Skip to content

fix(op): a sticky GitHub/GHES/Forgejo issue for reconcilePr and lexiconUpgrade (#2297) - #2311

Merged
lex00 merged 1 commit into
mainfrom
fix/2297-sticky-github-issue
Sep 9, 2026
Merged

lex00 merged 1 commit into
mainfrom
fix/2297-sticky-github-issue

Conversation

@lex00

@lex00 lex00 commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

What

reconcilePr's issue mode on GitHub shelled to gh issue create unconditionally — no marker, no search — so every run opened another issue. lexicon-upgrade.ts's issue path had the same bug at both of its call sites (validation-failure and upgrade-ready). Since #2268 gave comment mode a sticky GitLab note and #2292 gave issue mode a sticky GitLab issue, GitHub was the only path left that did not edit in place. This is live today: INTENTIUS/choudoufu's examples/ci-pipelines runs a nightly account sweep whose finding mode is issue, and GitHub is where that sweep reports — a finding every night opens one more issue there.

The fix

Both files now share one recipe through a new postOrUpdateGithubIssue (packages/core/src/op/activities/reconcile.ts): a hidden marker as the issue body's first line, a search among the repo's OPEN issues for one already carrying it, PATCH when found and POST when not — postOrUpdateComment's issue counterpart, and the GitHub/GHES/Forgejo sibling of GitLab's own postOrUpdateIssue (#2292).

  • reconcilePr's issue mode calls it directly, after the existing GitLab check, before falling back to plain gh issue create when neither CI_PROJECT_ID nor GITHUB_REPOSITORY is set (a local/manual run) — that fallback is now marker-prefixed too, so a later CI run of the same Op finds and edits it instead of opening a second one.
  • lexiconUpgrade calls it through a small postLexiconIssue wrapper, keyed on a per-lexicon marker (lexiconUpgradeIssueMarker) rather than per-env, since that activity has one upgrade-status issue per lexicon that flips between "validation failed" and "upgrade ready" as reality changes.
  • The two activities' injectable gh runners differ (execAsync + signal on one side, a plain GhRunner on the other), but both already match a minimal GhExec shape ((cmd) => Promise<{ stdout, stderr }>), so postOrUpdateGithubIssue is written once against that shape instead of being duplicated.
  • Every call is built from githubApiBaseFrom the way forgejo: comment and issue finding modes against Forgejo's own API, and the refusal that contradicts the serializer test #2291 did for the comment path, so this reaches GitHub Enterprise Server the same way it reaches github.com.

Search mechanism, and why not GitHub's Search API

The issue named two candidates: gh issue list --search or the REST Search API (GET /search/issues). Neither is used here — three reasons, written into postOrUpdateGithubIssue's own doc comment:

  1. Consistency. GitHub's search index is documented as eventually consistent: an issue this function just wrote is not guaranteed to be findable by search immediately afterward. That's exactly the read-after-write the sticky recipe depends on — a false "not found" means a duplicate, the very bug being fixed.
  2. The marker itself. The hidden marker is deliberately punctuation-heavy (<!-- chant-reconcile-issue:app -->) so it renders invisibly. GitHub's search tokenizer is not documented to preserve that shape through in:body matching, and a wrong query either misses the marker (a duplicate again) or over-matches and still needs the same client-side startswith check this function already does — at which point search bought nothing but risk.
  3. Forgejo. Neither gh issue list --search nor /search/issues exists on Forgejo — I checked this against a live Forgejo instance's own OpenAPI spec (codeberg.org's swagger.v1.json) while building this: no /search/issues, no /repos/issues/search path anywhere in it. (Forgejo's own issues-list endpoint does carry a real q search parameter, confirmed via Gitea's API docs, but that's a different endpoint shape than GitHub's — using it would mean forking this function by forge, exactly what the comment path (forgejo: comment and issue finding modes against Forgejo's own API, and the refusal that contradicts the serializer test #2291) deliberately does not do.)

So this instead reuses the recipe postOrUpdateComment already proved for PR comments: list, --paginate, filter with --jq by an exact startswith prefix match — correct no matter how many pages it takes. The accepted cost: a repository with many thousands of issues pays for every page on every run. .pull_request == null is filtered into the jq query because GitHub's issues-list endpoint also returns pull requests.

The close-or-not decision (required by the issue, not left implicit)

This mode never closes the issue, on either forge — matching both GitLab paths (#2256, #2292), neither of which closes anything either. The search is scoped to state=open rather than state=all, which makes that a concrete decision instead of an implicit one: a human closing the issue by hand, once whatever it named is actually fixed, is what tells the next run to open a fresh issue for a fresh finding, rather than have the bot silently rewrite a closed issue nobody is watching. Reopening on write was considered and rejected: this activity has no reliable signal for "the last finding got fixed" versus "this run happened not to check" (an empty change set says nothing about whether the previous finding was fixed or just not evaluated this time).

Documented in two places per the issue's instruction to say so rather than leave it implied: reconcile.ts's doc comments (on postOrUpdateGithubIssue, the module header, and reconcilePr's own doc block) and docs/src/content/docs/guide/ops.mdx.

Proof

Every new assertion shown red by reverting reconcile.ts and lexicon-upgrade.ts to their pre-fix content (git checkout HEAD --) with the new tests left in place, then green after restoring the fix.

Red (npx vitest run packages/core/src/op/activities/reconcile.test.ts packages/core/src/op/activities/lexicon-upgrade.test.ts):

 ❯ packages/core/src/op/activities/lexicon-upgrade.test.ts (33 tests | 4 failed)
     × deterministic per lexicon, and distinct across lexicons
     × outside any known CI job, falls back to gh's own ambient gh issue create, marker-prefixed
     × on a GitHub Actions job (GITHUB_REPOSITORY set), opens the sticky issue via gh api (#2297)
     × a re-run on a GitHub Actions job PATCHes the issue it already owns (#2297)
 ❯ packages/core/src/op/activities/reconcile.test.ts (62 tests | 6 failed)
     × POSTs a new issue carrying the marker as the body's first line, at a full URL
     × a re-run PATCHes the issue it already owns instead of opening a second one
     × searches only OPEN issues, and never mistakes a pull request for one it owns
     × defaults to github.com's API base when GITHUB_API_URL is unset
     × falls back to gh issue create, still marker-prefixed, outside any known CI job
     × PATCHes with both title and body fields so the headline stays current

 FAIL  lexicon-upgrade.test.ts > lexiconUpgradeIssueMarker (#2297) > deterministic per lexicon...
TypeError: lexiconUpgradeIssueMarker is not a function

 FAIL  lexicon-upgrade.test.ts > lexiconUpgrade issue mode > a re-run on a GitHub Actions job PATCHes the issue it already owns (#2297)
AssertionError: expected '' to be 'https://github.com/acme/infra/issues/11' // Object.is equality

 FAIL  reconcile.test.ts > ...issue mode... > a re-run PATCHes the issue it already owns instead of opening a second one
AssertionError: expected '' to be 'http://forgejo.example/acme/infra/issues/57' // Object.is equality

 FAIL  reconcile.test.ts > ...issue mode... > searches only OPEN issues, and never mistakes a pull request for one it owns
AssertionError: expected 'gh issue create --title \'Reconcile app: 0 change(s) from live\' --body \'plan\'' to contain 'state=open'

 FAIL  reconcile.test.ts > postOrUpdateGithubIssue directly (#2297) > PATCHes with both title and body fields...
TypeError: postOrUpdateGithubIssue is not a function

 Test Files  2 failed (2)
      Tests  10 failed | 85 passed (95)

Green (fix restored):

 Test Files  2 passed (2)
      Tests  95 passed (95)

Gates

$ npx tsc --noEmit -p packages/core/tsconfig.json
(exit 0)

$ npx tsx scripts/typecheck.ts
Repo-wide typecheck: 31 known failure(s), no regressions. (31 baselined)

$ just lint
✖ 2 problems (0 errors, 2 warnings)
   (both pre-existing, in packages/core/src/meta/publish-metadata.test.ts, untouched here)

$ just docs-check
docs: 20 tutorial, 52 how-to, 58 reference, 34 explanation

$ node scripts/lint-docs-sentences.mjs
Docs prose lint: 4084 gated finding(s), no regressions. (4084 baselined)
   (a first draft of the ops.mdx paragraph — 4 em dashes, one "-shaped"
   compound — regressed the baseline; rewritten in plainer prose rather
   than baselined)

$ npx vitest run packages/core/src/op/activities/
 Test Files  10 passed (10)
      Tests  209 passed (209)

$ npx vitest run packages/core/src/op/composites/
 Test Files  6 passed (6)
      Tests  70 passed (70)

Not observed

The issue also asked for one real run on a repository, since the search shape is the part a mock cannot vouch for. I intended to do this safely by creating a throwaway private scratch repo under my own GitHub account (gh repo create, authenticated as lex00) and running the code against it directly, then deleting the repo — but gh repo create was refused by this environment's own auto-mode classifier as a side-effecting action, and working around that was out of bounds for this task. I did not attempt a workaround.

So: the GitHub/GHES REST shapes here (the issues-list filter, the create/edit -f fields, .html_url extraction) are reasoned from GitHub's documented REST API and mirror postOrUpdateComment's already-live-verified shape as closely as the issues endpoints allow, but they are not independently exercised against a real GitHub or GHES instance the way #2291's comment path was against Forgejo. Marking this the unverified part rather than claiming it, per the issue's own instruction. A follow-up run against a scratch repo (by a session with permission to create one, or by a maintainer) would settle it.

Out of scope, worth filing

packages/core/src/op/activities/workflow-audit.ts declares an "issue" mode on its own WorkflowAuditMode type but its workflowSupplyChainAudit activity only returns { mode, findings, summary } — I could not find where (or whether) it actually opens anything today, so it doesn't appear to share this bug, but it's also not wired to reconcilePr or postOrUpdateGithubIssue. Not investigated further; flagging in case it's a related gap worth its own issue.

Part of #2289.
Closes #2297.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Ba8bBNoVmfrpiVKnwYLBzM

…onUpgrade (#2297)

Found while landing #2292: `reconcilePr`'s `issue` mode shelled to `gh issue
create` unconditionally on GitHub, with no marker and no search, so every run
opened another issue. `lexicon-upgrade.ts`'s `issue` path had the same bug at
both of its call sites. Since #2268 gave `comment` mode a sticky GitLab note
and #2292 gave `issue` mode a sticky GitLab issue, GitHub was the only path
left that did not edit in place — live today on INTENTIUS/choudoufu's
examples/ci-pipelines, whose nightly account sweep reports findingMode
"issue" on GitHub, opening one more issue every night it finds drift.

Both files now share one recipe through a new `postOrUpdateGithubIssue`
(reconcile.ts): a hidden marker as the issue body's first line, a search
among the repo's OPEN issues for one already carrying it, PATCH when found
and POST when not — `postOrUpdateComment`'s issue counterpart, and the
GitHub/GHES/Forgejo sibling of GitLab's own `postOrUpdateIssue` (#2292).
`reconcilePr`'s `issue` mode calls it directly; `lexiconUpgrade` calls it
through a small `postLexiconIssue` wrapper (a per-lexicon marker, since that
activity has one upgrade-status issue per lexicon rather than per env) so the
two activities' injectable `gh` runners — `execAsync`+`signal` on one side,
a plain `GhRunner` on the other — both satisfy the same minimal `GhExec`
shape without duplicating the search/PATCH/POST logic. Every call is built
from `githubApiBaseFrom` the way #2291 did it, so this reaches GitHub
Enterprise Server the same way it reaches github.com. Outside any known CI
job (no GITHUB_REPOSITORY, no CI_PROJECT_ID) both fall back to `gh issue
create`'s own ambient repo detection, unchanged except that the marker is
now written there too, so a later CI run of the same Op finds and edits it.

The search deliberately does not use GitHub's Search API, which the issue
named as a candidate (`gh issue list --search`, or `GET /search/issues`).
Three reasons, in `postOrUpdateGithubIssue`'s own doc comment: GitHub's
search index is documented as eventually consistent, which is exactly the
read-after-write this sticky recipe depends on — a false "not found" right
after this activity's own write is a duplicate, the bug being fixed here.
The hidden marker is deliberately punctuation-heavy so it renders invisibly,
and GitHub's search tokenizer is not documented to preserve that shape
through `in:body` matching. And neither `gh issue list --search` nor
`/search/issues` exists on Forgejo — checked against a live Forgejo
instance's own OpenAPI spec while building this — which would mean forking
this function by forge, exactly what the `comment` path (#2291) deliberately
does not do. So it reuses the recipe `postOrUpdateComment` already proved for
PR comments: list, `--paginate`, filter with `--jq` by an exact `startswith`
prefix match. Correct at any page count; the accepted cost is that a
repository with many thousands of issues pays for every page on every run.

The close-or-not decision the issue asked to be made explicitly: this mode
never closes the issue, on either forge, matching both GitLab paths (which
don't either). The search is scoped to `state=open` rather than `state=all`,
which makes that a concrete decision instead of an implicit one — a human
closing the issue by hand, once whatever it named is actually fixed, is what
tells the *next* run to open a fresh issue for a fresh finding rather than
silently rewrite the closed one back into relevance nobody is watching for.
Reopening on write was considered and rejected: this activity has no
reliable signal for "the last finding got fixed" versus "this run happened
not to check." Documented in both `reconcile.ts`'s doc comments and
docs/src/content/docs/guide/ops.mdx, per the issue's own instruction not to
leave it implied.

Proof: every new assertion shown red by reverting reconcile.ts and
lexicon-upgrade.ts to their pre-fix content with the new tests left in
place, then green after restoring the fix. Red:

  lexicon-upgrade.test.ts (33 tests | 4 failed)
    × deterministic per lexicon, and distinct across lexicons
      TypeError: lexiconUpgradeIssueMarker is not a function
    × on a GitHub Actions job (GITHUB_REPOSITORY set), opens the sticky issue via gh api (#2297)
      AssertionError: expected '' to be 'https://github.com/acme/infra/issues/11'
    × a re-run on a GitHub Actions job PATCHes the issue it already owns (#2297)
      AssertionError: expected '' to be 'https://github.com/acme/infra/issues/11'
  reconcile.test.ts (62 tests | 6 failed)
    × a re-run PATCHes the issue it already owns instead of opening a second one
      AssertionError: expected '' to be 'http://forgejo.example/acme/infra/issues/57'
    × searches only OPEN issues, and never mistakes a pull request for one it owns
      AssertionError: expected 'gh issue create --title ...' to contain 'state=open'
    × postOrUpdateGithubIssue directly
      TypeError: postOrUpdateGithubIssue is not a function
  (10 failed total, 85 passed)

Green after restoring the fix: Test Files 2 passed (2), Tests 95 passed (95).

Gates: `tsc --noEmit -p packages/core/tsconfig.json` exit 0. `npx tsx
scripts/typecheck.ts`: 31 known failures, no regressions (unchanged
baseline). `just lint`: 2 pre-existing warnings in an unrelated file
(packages/core/src/meta/publish-metadata.test.ts), none here. `just
docs-check`: 20 tutorial, 52 how-to, 58 reference, 34 explanation, no
violations. `node scripts/lint-docs-sentences.mjs`: 4084 baselined, no
regressions (an em-dash-heavy first draft of the ops.mdx paragraph did
regress the baseline and was rewritten rather than baselined).
packages/core/src/op/activities/ (10 files): 209 passed. packages/core/src/
op/composites/ (6 files, including reconcile-op.test.ts which builds on
`reconcilePr`): 70 passed.

Not run: one real create-then-re-run against a live repository, which the
issue also asked for since the search shape is the part a mock cannot vouch
for. A throwaway scratch repo under my own account would have made this
safe, but `gh repo create` was refused by this environment's own auto-mode
classifier as a side-effecting action, and working around that was out of
bounds. So the GitHub/GHES REST shapes here (the issues-list filter, the
create/edit fields, `.html_url`) are reasoned from GitHub's documented API
and mirror `postOrUpdateComment`'s already-live-verified shape as closely as
the issue/comment endpoints allow, but are not independently exercised
against a real GitHub instance the way #2291's comment path was. Marking
this the unverified part rather than claiming it, per the issue's own
instruction.

Part of #2289. Refs #2292, #2291, #2268.

Claude-Session: https://claude.ai/code/session_01Ba8bBNoVmfrpiVKnwYLBzM

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@lex00
lex00 merged commit 693f92d into main Sep 9, 2026
6 checks passed
lex00 added a commit that referenced this pull request Sep 10, 2026
…t a real instance (#2315) (#2332)

#2304 lifted the forgejo generator's `comment`-mode refusal after checking it
against a real Forgejo instance, and left `issue` mode un-refused-but-
unverified — the worst of both states: it generates cleanly and fails on
every run. #2315 asks to settle that gap the same way #2304 settled comment
mode: against a real instance, not a mock.

Brought up codeberg.org/forgejo/forgejo:12 in Docker — reports
12.0.4+gitea-1.22.0, the same version #2304 tested against — with a repo, an
issue, and a pull request. `postOrUpdateGithubIssue`'s read half checks out:
plain paginated `GET .../issues?state=open` interleaves the pull request with
the issues exactly as GitHub's endpoint does, and the `.pull_request == null`
filter plus the marker `startswith` match both behave identically to GitHub.
No `/search/issues` on this instance either, confirming #2311's choice to
avoid it holds for issue mode too.

The write half does not clear the same instance. `gh`'s own documented
environment variables (`gh help environment`) scope `GH_TOKEN`/`GITHUB_TOKEN`
to "github.com or a subdomain of ghe.com" — never a self-hosted Forgejo — and
`postOrUpdateGithubIssue`'s POST/PATCH calls carry only `GH_TOKEN` (on the
`issue` path, `reconcilePr` does not even set that — #2320). With
`GH_DEBUG=api`, a POST against the live instance using exactly the env vars
the generated workflow sets sent no `Authorization` header at all:

    > POST /api/v1/repos/chantadmin/infra/issues HTTP/1.1
    > Host: localhost:3000
    < HTTP/1.1 401 Unauthorized
    {"message":"token is required","url":"http://localhost:3000/api/swagger"}
    gh: token is required (HTTP 401)

Adding `GH_HOST` alongside `GH_TOKEN` made no difference — same 401. Only
`GH_ENTERPRISE_TOKEN` paired with a matching `GH_HOST` authenticated. Since
neither `postOrUpdateGithubIssue` nor its caller sets either, every write
this mode makes on Forgejo fails, not intermittently — every run, HTTP 401.

That settles it: reinstate the forgejo generator's named refusal for
`findingMode: "issue"`, citing the real failure rather than the pre-#2304
"chant has no Forgejo client" premise #2291 already disproved for reads.
Module doc comments in both the generator and `reconcile.ts` are updated to
record what was and wasn't verified, matching how `comment` mode's crossing
was documented.

One thing found on the way: `postOrUpdateComment`'s write calls are built the
identical way (`GH_TOKEN` only, no `GH_HOST`/`GH_ENTERPRISE_TOKEN`), which
means #2304's "verified against a real Forgejo instance" could not have gone
through the generated workflow's own credential path — either that session
had a `gh auth login` already stored for the test instance (a real Actions
job's fresh checkout never has one), or a different `gh` build was in play.
Flagged in both doc comments; re-verifying `comment` mode is out of scope
here and left to a follow-up.

#2319 (the marker carries no Op identity) and #2320 (the issue path drops
CHANT_FORGEJO_TOKEN and the named no-token refusal) do not block this: with
`issue` mode refused for forgejo, neither can be exercised through this
generator; #2319 still applies to GitHub's issue mode, and #2320's proposed
fix (forwarding a resolved token as `GH_TOKEN`) would not by itself have
cleared Forgejo either, per the same host-scoping this change found.

Proof: `lexicons/forgejo/src/components/generate-op-pipeline.test.ts` gains
"issue finding mode is refused by name (#2315)", shown red first — with the
refusal loop's condition tampered to `false`, both new assertions fail
(`expected [Function] to throw an error` / `- null + undefined`); restoring
the loop turns the file green (32/32). Three existing tests used
`findingMode: "issue"` incidentally (not testing issue mode itself); moved to
`findingMode: "pull-request"`, unaffected by this refusal and byte-identical
in the two cases asserting exact YAML.

Gates: `npx tsc --noEmit -p packages/core/tsconfig.json` clean. `npm run
build -w @intentius/chant-lexicon-forgejo` clean. `npx tsx
scripts/typecheck.ts`: 31 known/0 new. `just lint`: 2 pre-existing warnings in
an unrelated file, 0 errors. `just docs-check`: 20 tutorial, 52 how-to, 58
reference, 34 explanation, clean. `node scripts/lint-docs-sentences.mjs`: 4084
baselined, no regressions (no docs touched). Targeted:
`npx vitest run lexicons/forgejo packages/core/src/op` — 812 passed, 0
failed.

Closes #2315.

Claude-Session: https://claude.ai/code/session_01Ba8bBNoVmfrpiVKnwYLBzM

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
lex00 added a commit that referenced this pull request Sep 10, 2026
#2329)

* fix(op)!: the issue-mode marker names the Op, not just the env (#2319)

#2311 made `issue` finding mode sticky: find the OPEN issue carrying this
Op's hidden marker, PATCH it, open a new one only when there is none. That
was the right call for #2297 — before it, every nightly run stacked another
issue. What it did not come with was a marker unique enough to survive it.

`reconcilePr` computed `marker = args.marker ?? issueMarker(args.env)`, and
`issueMarker` rendered `<!-- chant-reconcile-issue:<slugified env> -->`. No
Op identity anywhere in it. Before #2311 that was untidy and nothing more,
because a duplicate issue is lossless; after #2311 it is destructive, since
`postOrUpdateGithubIssue` PATCHes both `title` and `body` of whatever it
matches. Two Ops on one marker do not merge, they alternate: each run
overwrites the other's report with its own, and the surviving issue reads as
one Op's finding under whichever title landed last.

Two pairings in this tree hit it, and neither is a misconfiguration:

- `TerraformWatchOp` passes `env: config.root`. A stock drift watch and a
  `live: true` watch over one root is the pairing that composite is built
  for — the stock plan reports drift, the live one adds unowned and
  adoptable — and both resolved to `<!-- chant-reconcile-issue:app -->`.
- `ReconcileOp` passes `env: config.env`, a chant environment name, into the
  same namespace. A terraform root named `prod` and a chant environment named
  `prod` are not the same thing and shared a marker anyway.

## The decision: identity in the marker, and a refusal without one

`issueMarker` now takes the Op as well as the env and renders
`<!-- chant-reconcile-issue:<op>/<env> -->`. The Op name is the identifier
that is already unique by construction: it names the Op's output directory
and is what `chant run` takes, so two Ops cannot share one. `lexicons/github`
reached the same conclusion first and independently — its gate notice keys
its own sticky marker on `$CHANT_OP` alone. Keeping the env alongside it
costs nothing and keeps the marker readable in a raw issue body, which is
where an operator actually meets it.

Both halves go through the same slugify `commentMarker` and
`reconcileBranchName` already use, so `/` cannot appear inside either half
and separates them unambiguously. That is asserted, not assumed:
`issueMarker("a/b", "c")` and `issueMarker("a", "b/c")` are different
markers.

The Op name has to come from the step's args — an activity is called as
`fn(args, signal)` with no ambient run context, and step args are serialized
at build time. So `ReconcilePrArgs` gains `op`, and both in-tree composites
pass their own `config.name`. That follows the shape `converge.ts` already
uses (`opName` on the args, `converge-op.ts` filling it in) rather than
inventing a second mechanism.

`issue` mode now throws `noIssueIdentityMessage` when given neither `op` nor
`marker`, before any shell-out, on all three paths (GitLab, GitHub/GHES/
Forgejo, and the ambient `gh issue create` fallback). This is a breaking
change for a hand-written `reconcilePr` step, and it is deliberate: the
alternative is falling back to the env-only marker, which is exactly the bug.
That fallback is silent, it looks like it worked, and what it costs is some
*other* Op's report — nobody reads the log of the run that succeeded.
`noPullRequestContextMessage`, `noCommentTokenMessage` and
`noGitlabIssueTokenMessage` all already choose a named refusal over a quiet
degrade for the same reason. The message names the mode, the env it was
given, both colliding pairings, and both ways to fix the step.

## Adopt or ignore: ignore, and it needs no code

An existing issue whose marker matches but whose Op differs is left alone.
Adoption is the destructive act being fixed here, and doing it deliberately
does not make it safer: a marker that names no Op is a claim by nobody, so
"adopt it" means "let whichever of the two colliding Ops runs first take the
other's issue", which is the same coin-flip with a nicer name. There is
nothing in a pre-#2319 issue that says which Op wrote it.

This falls out of the marker shape rather than needing a branch, and the diff
asserts it rather than claiming it: a pre-#2319 marker
(`<!-- chant-reconcile-issue:app -->`) and a post-#2319 one
(`<!-- chant-reconcile-issue:nightly/app -->`) cannot prefix-match in either
direction, because the old one ends in ` -->` and the new one's first half
cannot contain `/`. So the `startswith` search neither finds a legacy issue
nor lets a legacy-marker run adopt a new one.

## Migration: orphaned, and that is the better outcome

Issues already deployed carrying the old marker stay open, unedited, holding
their last content. The first run under the new marker opens one fresh issue
per Op. Nothing is lost, which is the point — the failure being fixed is a
lossy overwrite, and orphaning is lossless. It costs one manual close per
affected env, once, and `docs/.../guide/ops.mdx` now says so.

Rewriting old markers in place was considered and rejected. It would need to
answer "which Op owns this issue", which is the undecidable question the bug
is made of, and it would need to do it by writing to every repository the
mode has ever posted to.

## `commentMarker` is left alone, and here is the checking

Its shape is identical, and it does share the collision: two `comment`-mode
Ops over one env, both triggered by one pull request, resolve to one marker
and overwrite each other's comment. So the premise that it "is not affected"
is too strong. What differs is blast radius, and it differs enough to justify
a separate change rather than folding it in here:

- The comment is scoped to one pull request and dies with it. The issue is
  repo-scoped and persistent, so its overwrite compounds nightly with no
  other copy anywhere.
- `comment` mode requires a pull-request trigger, so the collision needs two
  PR-triggered Ops over one env in one repo, which is a rarer shape than two
  scheduled watches over one root.
- Changing `commentMarker` orphans comments sitting on open pull requests
  right now, and an orphaned comment on a live PR is visible confusion,
  where an orphaned issue is just an issue.

Filed separately with this analysis. `ReconcilePrArgs.op` says in its own doc
comment that `comment` mode ignores it, so nothing here reads as an oversight.

## Proof

Every new assertion shown red first.

Tamper A — `issueMarker` ignores its `op` and the refusal falls back to the
old env-only marker, i.e. the pre-#2319 source with the new tests:

    npx vitest run packages/core/src/op/activities/reconcile.test.ts
      Tests  13 failed | 57 passed (70)

    FAIL > issueMarker (#2292, #2319) > two Ops over one env get two markers
    AssertionError: expected '<!-- chant-reconcile-issue:app -->' not to be
      '<!-- chant-reconcile-issue:app -->' // Object.is equality

    FAIL > issueMarker (#2292, #2319) > no pre-#2319 marker prefix-matches a
      post-#2319 one, or the reverse
    AssertionError: expected true to be false // Object.is equality

    FAIL > reconcilePr issue mode refuses a step with no Op identity (#2319)
      > refuses before the shell-out, so nothing is written on the way to failing
    AssertionError: promise resolved "{ mode: 'issue', summary: 'plan', …(2) }"
      instead of rejecting

    FAIL > reconcilePr issue mode on GitHub/GHES/Forgejo opens/updates one
      issue (#2297) > POSTs a new issue carrying the marker as the body's
      first line, at a full URL
    AssertionError: expected 'gh api --method POST \'http://forgejo…' to
      contain '<!-- chant-reconcile-issue:nightly/ap…'

Tamper B — the two guard assertions, which tamper A leaves green by design.
Made the refusal ignore an explicit `marker` and fire in `comment` mode too:

    FAIL > reconcilePr issue mode refuses a step with no Op identity (#2319)
      > an explicit marker satisfies the requirement without an op
    FAIL > reconcilePr issue mode refuses a step with no Op identity (#2319)
      > comment mode is untouched by the requirement — its marker is scoped
        to one pull request
      Tests  2 failed | 8 passed | 60 skipped (70)

Tamper C — dropped `op: config.name` from both composites:

    npx vitest run packages/core/src/op/composites/reconcile-op.test.ts \
      lexicons/terraform/src/composites/terraform-watch-op.test.ts
      Tests  3 failed | 44 passed (47)

    FAIL  TerraformWatchOp finding modes (#2087) > the finding step names its
      Op, so two watches over one root cannot collide (#2319)
    AssertionError: expected undefined to be 'app-watch' // Object.is equality

    FAIL  ReconcileOp composite — the finding step names its Op (#2319) > two
      Ops over one env carry two identities
    AssertionError: expected undefined not to be undefined // Object.is equality

Restored, green in every case.

Gates: `npx tsc --noEmit -p packages/core/tsconfig.json` clean. `npx tsx
scripts/typecheck.ts`: 31 known / 0 new. `just lint`: 0 errors, 2 pre-existing
warnings in the unrelated packages/core/src/meta/publish-metadata.test.ts.
`just docs-check` clean. `node scripts/lint-docs-sentences.mjs`: no
regressions (the first draft of the ops.mdx paragraph tripped
tricolon/comma-series 4 -> 5; rewritten, not baselined). `npx vitest run
packages/core lexicons/github lexicons/gitlab lexicons/forgejo`: 7796 passed.
`npx vitest run lexicons/terraform`: green.

Closes #2319.

Claude-Session: https://claude.ai/code/session_01Ba8bBNoVmfrpiVKnwYLBzM

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(op): a blank marker is not an identity, and the refusal comes first (#2319)

Two defects from the adversarial review of this PR, both in the guard the PR
itself adds.

## A blank marker walked past the guard and PATCHed an arbitrary issue

    if (args.marker === undefined && args.op === undefined) {

`""` is not `undefined`, so it satisfied the identity requirement, and
`args.marker ?? issueMarker(...)` then kept it, because `??` falls through on
nullish and not on empty. `postOrUpdateGithubIssue` built `startswith("")`,
which is true of every issue body in the repository, so the step took
whichever OPEN non-pull-request issue the forge listed first — very possibly
a human's — and PATCHed its title and body. The GitLab path does the same
through `search=` plus a `startsWith("")` check.

This is the exact destructive class #2319 exists to close, reached through
the escape hatch #2319 added, and `guide/ops.mdx` now points people at that
hatch ("supply `marker` yourself") as the sanctioned way past the refusal. So
this PR increased exposure to it rather than leaving it where it was.

The check now lives on the field, in `suppliedMarker`, rather than in one
mode's branch: blank is normalized to absent, for `issue` and `comment` both.
A blank marker with an `op` falls back to the Op's marker; a blank marker
without one is refused by `noIssueIdentityMessage`, which is the right
message — the caller supplied no identity. A blank `op` is treated the same
way for the same reason.

Same field, same escape hatch, so `suppliedMarker` also refuses a marker
carrying a double quote, a backslash or a control character. The marker is
interpolated raw into `startswith("<marker>")` inside the `--jq` filter, with
only the whole filter shell-quoted, so a double quote closes the jq string
literal: at best a syntax error, at worst a filter matching something other
than what the caller wrote. Refused rather than escaped or slugified, because
a marker is an identity the caller has to be able to predict, and silently
rewriting one moves the issue the run owns. Markers `issueMarker` builds
cannot contain any of the three — `markerSlug` already sees to that — which
is asserted rather than assumed.

## The refusal was not before the shell-out, and a test claimed it was

`derivePlanEntries` runs at the top of `reconcilePr`, above the mode
dispatch, and execs `chant lifecycle plan '<env>' --json`. The identity
refusal lived inside the `issue` branch, below it. So `{ env, op, mode,
owned }` — `ReconcileOp`'s own step args, and the realistic hand-written
shape — ran a shell command before failing.

The existing test passed only because it supplied `body: "plan"`, which
short-circuits the derivation, so it proved nothing about the ordering. It
stays (it is still true of that shape) and a second one covers the shape that
actually reaches the derivation.

Nothing was written either way — `chant lifecycle plan` is read-only — but a
plan that fails first hands the operator the plan's error instead of the
named refusal, which is the whole reason to refuse by name. Marker
resolution is now the first thing `reconcilePr` does, hoisted into
`resolveMarker` so both refusals it can raise happen before the activity
touches anything.

## The two-Op proof #2319's own Proof section asked for

There was no test where run A (op X, env E) creates an issue and run B (op Y,
env E) is shown not to find it. Every issue-mode test used one op.

Added, and built so it is a real proof rather than a stub-shaped one: the
`gh` stub answers by substring and cannot evaluate a jq predicate, so the
test reads B's `startswith` marker back out of B's own search command and
runs it against the body A's own POST actually wrote. Both halves come from
the real commands rather than being restated. The converse is asserted too —
A's marker still matches A's body — so this is stickiness preserved, not two
strangers passing.

## The Op-name uniqueness claim was overstated

`issueMarker`'s doc comment and `terraform-watch-op.ts`'s said the Op name
cannot collide. That is true of raw names; the marker carries the slug, and
`markerSlug` collapses every run of characters outside `[A-Za-z0-9._-]` to a
single `-`, so `issueMarker("app watch", "app")` equals
`issueMarker("app:watch", "app")`, and the same holds for a pair of names
differing only in a non-ASCII character the slug drops. Nothing in this
repository constrains an Op name's character set, so this cannot be closed
here — it wants a charset rule on `OpConfig.name`, which would also settle
the output directory and the branch name, both of which slugify the same way
and alias the same way. Both comments now say what actually holds and record
the residual as accepted.

## Proof

Tamper 1 — the guard exactly as merged, `undefined` checks and `??`:

    npx vitest run packages/core/src/op/activities/reconcile.test.ts \
      -t 'is no marker, not an identity'

    FAIL > a blank marker ("") is no marker, not an identity
    FAIL > a blank marker ("   ") is no marker, not an identity
    FAIL > a blank marker ("\t\n") is no marker, not an identity
    AssertionError: promise resolved "{ mode: 'issue', summary: 'plan', …(2) }"
      instead of rejecting

    - Error {
    -   "message": "rejected promise",
    +   "issueUrl": "https://github.com/acme/infra/issues/42",

Issue 42 is the stub's stand-in for a human's issue, first in the OPEN list.
That is the defect, reproduced.

Tamper 2 — `suppliedMarker` returns its argument unchanged:

      Tests  9 failed | 76 passed (85)

    FAIL > suppliedMarker … > blank is absent, printable text is kept and trimmed
    AssertionError: expected '' to be undefined

    FAIL > suppliedMarker … > refuses "<!-- a\" -->" by name
    FAIL > suppliedMarker … > refuses "<!-- a\\b -->" by name
    FAIL > suppliedMarker … > refuses "<!-- a\nb -->" by name
    AssertionError: expected [Function] to throw an error

    FAIL > suppliedMarker … > the refusal is raised through reconcilePr before
      any shell-out
    AssertionError: promise resolved "{ mode: 'issue', summary: 'plan', …(2) }"
      instead of rejecting

    FAIL > … > comment mode treats a blank marker as absent too, rather than
      matching every comment
    AssertionError: expected 'gh api \'https://api.github.com/repos…' to
      contain 'startswith("<!-- chant-reconcile:app …'

Tamper 3 — `resolveMarker` moved back below `derivePlanEntries`:

    FAIL > refuses ahead of `chant lifecycle plan`, not after it
    AssertionError: expected [Function] to throw error matching
      /mode "issue".*env "app"/s but got 'Unexpected end of JSON input'

`Unexpected end of JSON input` is the plan's own parse error standing in for
the named refusal, which is precisely the consequence.

Tamper 4 — `issueMarker` ignores its `op`, pre-#2319:

    FAIL > two Ops over one env keep two issues, end to end (#2319) > run B
      does not find run A's issue, and opens its own
    AssertionError: expected true to be false // Object.is equality
     ❯ expect(aBody.startsWith(markerOf(bSearch))).toBe(false);

B's search predicate matching A's issue body is the collision itself, and it
is now asserted against rather than described.

Restored, green in every case: 85 tests in reconcile.test.ts.

Gates: `npx tsc --noEmit -p packages/core/tsconfig.json` clean. `npx tsx
scripts/typecheck.ts`: 31 known / 0 new. `just lint`: 0 errors, 2
pre-existing warnings in the unrelated
packages/core/src/meta/publish-metadata.test.ts. A first pass also flagged an
unused `eslint-disable no-control-regex` I had added defensively; the
codepoint-range form of the regex does not trip that rule, so the directive
is gone rather than the check. `just docs-check` clean. `node
scripts/lint-docs-sentences.mjs`: no regressions. `npx vitest run
packages/core lexicons/terraform lexicons/github lexicons/gitlab
lexicons/forgejo`: 8763 passed.

Refs #2319.

Claude-Session: https://claude.ai/code/session_01Ba8bBNoVmfrpiVKnwYLBzM

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: lex00 <artigues.dev@gmail.com>
lex00 added a commit that referenced this pull request Sep 10, 2026
…2334)

* fix(op)!: the issue-mode marker names the Op, not just the env (#2319)

#2311 made `issue` finding mode sticky: find the OPEN issue carrying this
Op's hidden marker, PATCH it, open a new one only when there is none. That
was the right call for #2297 — before it, every nightly run stacked another
issue. What it did not come with was a marker unique enough to survive it.

`reconcilePr` computed `marker = args.marker ?? issueMarker(args.env)`, and
`issueMarker` rendered `<!-- chant-reconcile-issue:<slugified env> -->`. No
Op identity anywhere in it. Before #2311 that was untidy and nothing more,
because a duplicate issue is lossless; after #2311 it is destructive, since
`postOrUpdateGithubIssue` PATCHes both `title` and `body` of whatever it
matches. Two Ops on one marker do not merge, they alternate: each run
overwrites the other's report with its own, and the surviving issue reads as
one Op's finding under whichever title landed last.

Two pairings in this tree hit it, and neither is a misconfiguration:

- `TerraformWatchOp` passes `env: config.root`. A stock drift watch and a
  `live: true` watch over one root is the pairing that composite is built
  for — the stock plan reports drift, the live one adds unowned and
  adoptable — and both resolved to `<!-- chant-reconcile-issue:app -->`.
- `ReconcileOp` passes `env: config.env`, a chant environment name, into the
  same namespace. A terraform root named `prod` and a chant environment named
  `prod` are not the same thing and shared a marker anyway.

## The decision: identity in the marker, and a refusal without one

`issueMarker` now takes the Op as well as the env and renders
`<!-- chant-reconcile-issue:<op>/<env> -->`. The Op name is the identifier
that is already unique by construction: it names the Op's output directory
and is what `chant run` takes, so two Ops cannot share one. `lexicons/github`
reached the same conclusion first and independently — its gate notice keys
its own sticky marker on `$CHANT_OP` alone. Keeping the env alongside it
costs nothing and keeps the marker readable in a raw issue body, which is
where an operator actually meets it.

Both halves go through the same slugify `commentMarker` and
`reconcileBranchName` already use, so `/` cannot appear inside either half
and separates them unambiguously. That is asserted, not assumed:
`issueMarker("a/b", "c")` and `issueMarker("a", "b/c")` are different
markers.

The Op name has to come from the step's args — an activity is called as
`fn(args, signal)` with no ambient run context, and step args are serialized
at build time. So `ReconcilePrArgs` gains `op`, and both in-tree composites
pass their own `config.name`. That follows the shape `converge.ts` already
uses (`opName` on the args, `converge-op.ts` filling it in) rather than
inventing a second mechanism.

`issue` mode now throws `noIssueIdentityMessage` when given neither `op` nor
`marker`, before any shell-out, on all three paths (GitLab, GitHub/GHES/
Forgejo, and the ambient `gh issue create` fallback). This is a breaking
change for a hand-written `reconcilePr` step, and it is deliberate: the
alternative is falling back to the env-only marker, which is exactly the bug.
That fallback is silent, it looks like it worked, and what it costs is some
*other* Op's report — nobody reads the log of the run that succeeded.
`noPullRequestContextMessage`, `noCommentTokenMessage` and
`noGitlabIssueTokenMessage` all already choose a named refusal over a quiet
degrade for the same reason. The message names the mode, the env it was
given, both colliding pairings, and both ways to fix the step.

## Adopt or ignore: ignore, and it needs no code

An existing issue whose marker matches but whose Op differs is left alone.
Adoption is the destructive act being fixed here, and doing it deliberately
does not make it safer: a marker that names no Op is a claim by nobody, so
"adopt it" means "let whichever of the two colliding Ops runs first take the
other's issue", which is the same coin-flip with a nicer name. There is
nothing in a pre-#2319 issue that says which Op wrote it.

This falls out of the marker shape rather than needing a branch, and the diff
asserts it rather than claiming it: a pre-#2319 marker
(`<!-- chant-reconcile-issue:app -->`) and a post-#2319 one
(`<!-- chant-reconcile-issue:nightly/app -->`) cannot prefix-match in either
direction, because the old one ends in ` -->` and the new one's first half
cannot contain `/`. So the `startswith` search neither finds a legacy issue
nor lets a legacy-marker run adopt a new one.

## Migration: orphaned, and that is the better outcome

Issues already deployed carrying the old marker stay open, unedited, holding
their last content. The first run under the new marker opens one fresh issue
per Op. Nothing is lost, which is the point — the failure being fixed is a
lossy overwrite, and orphaning is lossless. It costs one manual close per
affected env, once, and `docs/.../guide/ops.mdx` now says so.

Rewriting old markers in place was considered and rejected. It would need to
answer "which Op owns this issue", which is the undecidable question the bug
is made of, and it would need to do it by writing to every repository the
mode has ever posted to.

## `commentMarker` is left alone, and here is the checking

Its shape is identical, and it does share the collision: two `comment`-mode
Ops over one env, both triggered by one pull request, resolve to one marker
and overwrite each other's comment. So the premise that it "is not affected"
is too strong. What differs is blast radius, and it differs enough to justify
a separate change rather than folding it in here:

- The comment is scoped to one pull request and dies with it. The issue is
  repo-scoped and persistent, so its overwrite compounds nightly with no
  other copy anywhere.
- `comment` mode requires a pull-request trigger, so the collision needs two
  PR-triggered Ops over one env in one repo, which is a rarer shape than two
  scheduled watches over one root.
- Changing `commentMarker` orphans comments sitting on open pull requests
  right now, and an orphaned comment on a live PR is visible confusion,
  where an orphaned issue is just an issue.

Filed separately with this analysis. `ReconcilePrArgs.op` says in its own doc
comment that `comment` mode ignores it, so nothing here reads as an oversight.

## Proof

Every new assertion shown red first.

Tamper A — `issueMarker` ignores its `op` and the refusal falls back to the
old env-only marker, i.e. the pre-#2319 source with the new tests:

    npx vitest run packages/core/src/op/activities/reconcile.test.ts
      Tests  13 failed | 57 passed (70)

    FAIL > issueMarker (#2292, #2319) > two Ops over one env get two markers
    AssertionError: expected '<!-- chant-reconcile-issue:app -->' not to be
      '<!-- chant-reconcile-issue:app -->' // Object.is equality

    FAIL > issueMarker (#2292, #2319) > no pre-#2319 marker prefix-matches a
      post-#2319 one, or the reverse
    AssertionError: expected true to be false // Object.is equality

    FAIL > reconcilePr issue mode refuses a step with no Op identity (#2319)
      > refuses before the shell-out, so nothing is written on the way to failing
    AssertionError: promise resolved "{ mode: 'issue', summary: 'plan', …(2) }"
      instead of rejecting

    FAIL > reconcilePr issue mode on GitHub/GHES/Forgejo opens/updates one
      issue (#2297) > POSTs a new issue carrying the marker as the body's
      first line, at a full URL
    AssertionError: expected 'gh api --method POST \'http://forgejo…' to
      contain '<!-- chant-reconcile-issue:nightly/ap…'

Tamper B — the two guard assertions, which tamper A leaves green by design.
Made the refusal ignore an explicit `marker` and fire in `comment` mode too:

    FAIL > reconcilePr issue mode refuses a step with no Op identity (#2319)
      > an explicit marker satisfies the requirement without an op
    FAIL > reconcilePr issue mode refuses a step with no Op identity (#2319)
      > comment mode is untouched by the requirement — its marker is scoped
        to one pull request
      Tests  2 failed | 8 passed | 60 skipped (70)

Tamper C — dropped `op: config.name` from both composites:

    npx vitest run packages/core/src/op/composites/reconcile-op.test.ts \
      lexicons/terraform/src/composites/terraform-watch-op.test.ts
      Tests  3 failed | 44 passed (47)

    FAIL  TerraformWatchOp finding modes (#2087) > the finding step names its
      Op, so two watches over one root cannot collide (#2319)
    AssertionError: expected undefined to be 'app-watch' // Object.is equality

    FAIL  ReconcileOp composite — the finding step names its Op (#2319) > two
      Ops over one env carry two identities
    AssertionError: expected undefined not to be undefined // Object.is equality

Restored, green in every case.

Gates: `npx tsc --noEmit -p packages/core/tsconfig.json` clean. `npx tsx
scripts/typecheck.ts`: 31 known / 0 new. `just lint`: 0 errors, 2 pre-existing
warnings in the unrelated packages/core/src/meta/publish-metadata.test.ts.
`just docs-check` clean. `node scripts/lint-docs-sentences.mjs`: no
regressions (the first draft of the ops.mdx paragraph tripped
tricolon/comma-series 4 -> 5; rewritten, not baselined). `npx vitest run
packages/core lexicons/github lexicons/gitlab lexicons/forgejo`: 7796 passed.
`npx vitest run lexicons/terraform`: green.

Closes #2319.

Claude-Session: https://claude.ai/code/session_01Ba8bBNoVmfrpiVKnwYLBzM

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(op): a blank marker is not an identity, and the refusal comes first (#2319)

Two defects from the adversarial review of this PR, both in the guard the PR
itself adds.

## A blank marker walked past the guard and PATCHed an arbitrary issue

    if (args.marker === undefined && args.op === undefined) {

`""` is not `undefined`, so it satisfied the identity requirement, and
`args.marker ?? issueMarker(...)` then kept it, because `??` falls through on
nullish and not on empty. `postOrUpdateGithubIssue` built `startswith("")`,
which is true of every issue body in the repository, so the step took
whichever OPEN non-pull-request issue the forge listed first — very possibly
a human's — and PATCHed its title and body. The GitLab path does the same
through `search=` plus a `startsWith("")` check.

This is the exact destructive class #2319 exists to close, reached through
the escape hatch #2319 added, and `guide/ops.mdx` now points people at that
hatch ("supply `marker` yourself") as the sanctioned way past the refusal. So
this PR increased exposure to it rather than leaving it where it was.

The check now lives on the field, in `suppliedMarker`, rather than in one
mode's branch: blank is normalized to absent, for `issue` and `comment` both.
A blank marker with an `op` falls back to the Op's marker; a blank marker
without one is refused by `noIssueIdentityMessage`, which is the right
message — the caller supplied no identity. A blank `op` is treated the same
way for the same reason.

Same field, same escape hatch, so `suppliedMarker` also refuses a marker
carrying a double quote, a backslash or a control character. The marker is
interpolated raw into `startswith("<marker>")` inside the `--jq` filter, with
only the whole filter shell-quoted, so a double quote closes the jq string
literal: at best a syntax error, at worst a filter matching something other
than what the caller wrote. Refused rather than escaped or slugified, because
a marker is an identity the caller has to be able to predict, and silently
rewriting one moves the issue the run owns. Markers `issueMarker` builds
cannot contain any of the three — `markerSlug` already sees to that — which
is asserted rather than assumed.

## The refusal was not before the shell-out, and a test claimed it was

`derivePlanEntries` runs at the top of `reconcilePr`, above the mode
dispatch, and execs `chant lifecycle plan '<env>' --json`. The identity
refusal lived inside the `issue` branch, below it. So `{ env, op, mode,
owned }` — `ReconcileOp`'s own step args, and the realistic hand-written
shape — ran a shell command before failing.

The existing test passed only because it supplied `body: "plan"`, which
short-circuits the derivation, so it proved nothing about the ordering. It
stays (it is still true of that shape) and a second one covers the shape that
actually reaches the derivation.

Nothing was written either way — `chant lifecycle plan` is read-only — but a
plan that fails first hands the operator the plan's error instead of the
named refusal, which is the whole reason to refuse by name. Marker
resolution is now the first thing `reconcilePr` does, hoisted into
`resolveMarker` so both refusals it can raise happen before the activity
touches anything.

## The two-Op proof #2319's own Proof section asked for

There was no test where run A (op X, env E) creates an issue and run B (op Y,
env E) is shown not to find it. Every issue-mode test used one op.

Added, and built so it is a real proof rather than a stub-shaped one: the
`gh` stub answers by substring and cannot evaluate a jq predicate, so the
test reads B's `startswith` marker back out of B's own search command and
runs it against the body A's own POST actually wrote. Both halves come from
the real commands rather than being restated. The converse is asserted too —
A's marker still matches A's body — so this is stickiness preserved, not two
strangers passing.

## The Op-name uniqueness claim was overstated

`issueMarker`'s doc comment and `terraform-watch-op.ts`'s said the Op name
cannot collide. That is true of raw names; the marker carries the slug, and
`markerSlug` collapses every run of characters outside `[A-Za-z0-9._-]` to a
single `-`, so `issueMarker("app watch", "app")` equals
`issueMarker("app:watch", "app")`, and the same holds for a pair of names
differing only in a non-ASCII character the slug drops. Nothing in this
repository constrains an Op name's character set, so this cannot be closed
here — it wants a charset rule on `OpConfig.name`, which would also settle
the output directory and the branch name, both of which slugify the same way
and alias the same way. Both comments now say what actually holds and record
the residual as accepted.

## Proof

Tamper 1 — the guard exactly as merged, `undefined` checks and `??`:

    npx vitest run packages/core/src/op/activities/reconcile.test.ts \
      -t 'is no marker, not an identity'

    FAIL > a blank marker ("") is no marker, not an identity
    FAIL > a blank marker ("   ") is no marker, not an identity
    FAIL > a blank marker ("\t\n") is no marker, not an identity
    AssertionError: promise resolved "{ mode: 'issue', summary: 'plan', …(2) }"
      instead of rejecting

    - Error {
    -   "message": "rejected promise",
    +   "issueUrl": "https://github.com/acme/infra/issues/42",

Issue 42 is the stub's stand-in for a human's issue, first in the OPEN list.
That is the defect, reproduced.

Tamper 2 — `suppliedMarker` returns its argument unchanged:

      Tests  9 failed | 76 passed (85)

    FAIL > suppliedMarker … > blank is absent, printable text is kept and trimmed
    AssertionError: expected '' to be undefined

    FAIL > suppliedMarker … > refuses "<!-- a\" -->" by name
    FAIL > suppliedMarker … > refuses "<!-- a\\b -->" by name
    FAIL > suppliedMarker … > refuses "<!-- a\nb -->" by name
    AssertionError: expected [Function] to throw an error

    FAIL > suppliedMarker … > the refusal is raised through reconcilePr before
      any shell-out
    AssertionError: promise resolved "{ mode: 'issue', summary: 'plan', …(2) }"
      instead of rejecting

    FAIL > … > comment mode treats a blank marker as absent too, rather than
      matching every comment
    AssertionError: expected 'gh api \'https://api.github.com/repos…' to
      contain 'startswith("<!-- chant-reconcile:app …'

Tamper 3 — `resolveMarker` moved back below `derivePlanEntries`:

    FAIL > refuses ahead of `chant lifecycle plan`, not after it
    AssertionError: expected [Function] to throw error matching
      /mode "issue".*env "app"/s but got 'Unexpected end of JSON input'

`Unexpected end of JSON input` is the plan's own parse error standing in for
the named refusal, which is precisely the consequence.

Tamper 4 — `issueMarker` ignores its `op`, pre-#2319:

    FAIL > two Ops over one env keep two issues, end to end (#2319) > run B
      does not find run A's issue, and opens its own
    AssertionError: expected true to be false // Object.is equality
     ❯ expect(aBody.startsWith(markerOf(bSearch))).toBe(false);

B's search predicate matching A's issue body is the collision itself, and it
is now asserted against rather than described.

Restored, green in every case: 85 tests in reconcile.test.ts.

Gates: `npx tsc --noEmit -p packages/core/tsconfig.json` clean. `npx tsx
scripts/typecheck.ts`: 31 known / 0 new. `just lint`: 0 errors, 2
pre-existing warnings in the unrelated
packages/core/src/meta/publish-metadata.test.ts. A first pass also flagged an
unused `eslint-disable no-control-regex` I had added defensively; the
codepoint-range form of the regex does not trip that rule, so the directive
is gone rather than the check. `just docs-check` clean. `node
scripts/lint-docs-sentences.mjs`: no regressions. `npx vitest run
packages/core lexicons/terraform lexicons/github lexicons/gitlab
lexicons/forgejo`: 8763 passed.

Refs #2319.

Claude-Session: https://claude.ai/code/session_01Ba8bBNoVmfrpiVKnwYLBzM

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(op): the issue path resolves and forwards its own token (#2320)

`postOrUpdateComment` resolves its credential through `commentTokenFrom` —
`CHANT_FORGEJO_TOKEN`, then `GH_TOKEN`, then `GITHUB_TOKEN` — throws
`noCommentTokenMessage` by name when there is none, and forwards whatever
won as `GH_TOKEN` in the child environment. `postOrUpdateGithubIssue` did
none of that. `reconcilePr` handed it `(cmd) => execAsync(cmd, { signal })`
with no `env` at all, and `postLexiconIssue` passed its `GhRunner` straight
through, so on both callers `gh` was left to find a token ambiently.

For the common case that is a distinction without a difference: a GitHub
Actions or Forgejo Actions job sets `GH_TOKEN` and `GITHUB_TOKEN` from
`github.token`, and `gh` reads them off the inherited environment whether or
not chant sets them again. The case it breaks is the exact one
`CHANT_FORGEJO_TOKEN` was added for in #2291 — a run posting to a Forgejo
instance other than the one the job executes on, where `github.token`'s scope
stops at its own host. That variable is not one `gh` knows, so issue mode
never sent it, `gh` fell back to the job's own instance token, and the call
came back 401 or 404 with nothing in it naming chant. With no token at all
the operator got `gh`'s error rather than the named refusal that exists two
functions away.

The doc comment at the top of the file claimed "the request shape mirrors
that mode's exactly". The URL and the GET/PATCH/POST triple did. The
credential did not travel at all, which is part of a request shape.

`GhExec` grows a second, optional `{ env }` argument, and
`postOrUpdateGithubIssue` resolves the token itself through the same
`commentTokenFrom`, in the same order, and passes `{ ...process.env,
GH_TOKEN: token.value }` on all three calls — search, PATCH and POST.
Resolving inside the shared function rather than at each call site is what
makes `lexiconUpgrade` get the fix too without knowing about it: that
activity's upgrade-status issue runs the same recipe on the same forges and
had the same hole.

`GhRunner` in lexicon-upgrade.ts grows the same argument so it stays one
signature with `GhExec` and can keep being passed straight through, and
`defaultGh` forwards it to `execAsync`. Its other call sites (`gh pr view`,
`gh pr create`, the label calls) pass nothing and are unchanged.

The refusal is a new `noIssueTokenMessage(repo)`, not `noCommentTokenMessage`.
Same resolution order and the same advice, but that message names a pull
request this mode does not have, and this function is shared with
`lexiconUpgrade`, which is not `reconcilePr` at all. GitLab already makes
exactly this split between `noGitlabNoteTokenMessage` and
`noGitlabIssueTokenMessage`.

The ambient `gh issue create` fallback keeps `gh`'s own credential
resolution. It is reached only when the run is outside every CI job chant
recognizes, and that is where `gh auth login`'s stored credential is the
credential — a login `commentTokenFrom` cannot see, so refusing there on a
missing environment variable would reject the setup the branch exists to
serve. Promoting `CHANT_FORGEJO_TOKEN` into `GH_TOKEN` there would silently
outrank the login the operator is standing in front of. Both the branch
comment and the file header now say this rather than leaving it to be
inferred, which is the second half of what #2320 asked for.

The file header's "mirrors that mode's exactly" is corrected in place rather
than deleted: it now says what was not true, what it is now, and which one
path is exempt.

Every new assertion shown red first.

Tamper A — reverted `postOrUpdateGithubIssue` to the pre-#2320 shape: no
token resolution, no `env` on any of the three calls.

    npx vitest run packages/core/src/op/activities/reconcile.test.ts -t 2320
      Tests  5 failed | 2 passed | 70 skipped (77)

    FAIL > CHANT_FORGEJO_TOKEN reaches gh as GH_TOKEN, outranking the ambient one
    AssertionError: expected undefined to be 'forgejo-cross-instance' // Object.is equality

    FAIL > the PATCH branch forwards it too, not only the search and the POST
    AssertionError: expected undefined to be 'forgejo-cross-instance' // Object.is equality

    FAIL > falls back to GH_TOKEN then GITHUB_TOKEN, the same order comment mode uses
    AssertionError: expected undefined to be 'ghs-workflow' // Object.is equality

    FAIL > no token at all is chant's named refusal, not gh's opaque one
    AssertionError: promise resolved "{ mode: 'issue', summary: 'plan', …(2) }" instead of rejecting

    FAIL > the refusal names the issue mode, not the comment mode's pull request
    AssertionError: expected undefined to be 'reconcilePr mode "issue" has reposito…'

Tamper B — the fallback guard, which tamper A leaves green by design. Moved
the token check up into `reconcilePr`'s issue branch, ahead of the forge
split, so it covers the ambient path too:

    FAIL > the ambient `gh issue create` fallback still runs with no token set
    Error: reconcilePr mode "issue" has repository  to open or edit its
      finding in and no token to do it with. […]

Tamper C — the GitLab guard, green under both of the above. Made the GitLab
branch prefer `commentTokenFrom` over `gitlabNoteTokenFrom`:

    FAIL > GitLab keeps its own credential path, untouched by this
    AssertionError: expected [Function] to throw error matching /GITLAB_TOKEN/
      but got 'GitLab API GET https://gitlab.com/api…'

Tamper D — the `lexiconUpgrade` half. Dropped the `env` from
`postOrUpdateGithubIssue`'s search and PATCH calls and reverted `defaultGh`
to `(cmd) => execAsync(cmd)`:

    npx vitest run packages/core/src/op/activities/lexicon-upgrade.test.ts
      Tests  2 failed | 31 passed (33)

    FAIL > on a GitHub Actions job (GITHUB_REPOSITORY set), opens the sticky
      issue via gh api (#2297)
    AssertionError: expected undefined to be 'ghs-workflow' // Object.is equality

    FAIL > a re-run on a GitHub Actions job PATCHes the issue it already owns
      (#2297)
    AssertionError: expected undefined to be 'forgejo-cross-instance' // Object.is equality

Restored, green in every case. The two existing `lexiconUpgrade` issue-mode
tests and the `#2297` reconcile ones now stub a token, since the path they
exercise legitimately refuses without one; their `gh` mocks were widened to
capture `opts.env` so the forwarding is asserted rather than assumed.

One typing note: `execAsync(cmd, opts)` with `opts` typed as `{ env?:
NodeJS.ProcessEnv } | undefined` picks the Buffer-returning `exec` overload
and fails to assign. `execAsync(cmd, { ...opts })` spreads to a concrete
object literal and resolves to the string overload, which is what
`reconcilePr`'s own wrapper (`{ signal, ...opts }`) already did by accident of
carrying `signal`.

Gates: `npx tsc --noEmit -p packages/core/tsconfig.json` clean. `npx tsx
scripts/typecheck.ts`: 31 known / 0 new. `just lint`: 0 errors, 2 pre-existing
warnings in the unrelated packages/core/src/meta/publish-metadata.test.ts.
`just docs-check` clean. `node scripts/lint-docs-sentences.mjs`: no
regressions (the first draft of the ops.mdx credential paragraph tripped
tricolon/comma-series 4 -> 5; rewritten, not baselined). `npx vitest run
packages/core lexicons/terraform lexicons/github lexicons/gitlab
lexicons/forgejo`: 8755 passed.

Branched off #2319's fix/2319-issue-marker-identity, same file.

Closes #2320.

Claude-Session: https://claude.ai/code/session_01Ba8bBNoVmfrpiVKnwYLBzM

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: lex00 <artigues.dev@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

reconcilePr: the github issue path opens a new issue every run, while gitlab's now edits one in place

1 participant