Skip to content

fix(sync): never rewrite a user-owned AGENTS.md or write a machine-specific scripts/dev symlink (absorbs #991) #990

Closed

Description

@admarble

Epic: W2 Blocked by: — Tier: mechanical Doc: W2 PLAN §4 (template sync seam), §5 I-2, §7 D1/D2/D3/D6, Lab §1

Why

Two file classes from the 2026-09-06 downstream incident that #988 (v2.13.1)
did not close, because an explicit sequant sync still does both:

  • AGENTS.md — src/commands/sync.ts:498-512 regenerates it whenever it
    exists; it is not in CUSTOMIZABLE_FILES (src/lib/templates.ts:238) and
    sync has no --no-agents-md (only init does, bin/cli.ts:189). A
    deliberate 73-line pointer file was replaced with a 1,079-line copy of
    CLAUDE.md because generateAgentsMd inlines getPortableInstructions()
    (src/lib/agents-md.ts:100).
  • scripts/dev/*.sh — symlink target is
    relative(dirname(dest), <templates dir of whichever sequant ran>)
    (src/lib/templates.ts:499-507): an npx cache path (evicted → dead links), an
    npm link sibling or a global prefix (machine-specific). Only a local
    devDependency target survives git clone && npm install. The links are
    tracked (GITIGNORE_ENTRIES is .sequant/ only, src/commands/init.ts:101),
    so every re-sync from a different runner is churn on three files.
  • Found in Phase 0 (Lab §1): src/commands/doctor.ts:320-360 tells the
    owner of a pointer-style AGENTS.md to run sequant sync --force — the
    command that destroys it.

One contract (PLAN §5 I-2): sequant never rewrites a tracked file the user owns,
never writes a machine-specific one, and shows every such decision before
writing.

Scope

  • may touch: src/lib/templates.ts, src/lib/agents-md.ts,
    src/commands/sync.ts, src/commands/init.ts, src/commands/doctor.ts,
    bin/cli.ts (one .option() line on sync), README.md (sync-section
    lines), CHANGELOG.md ([Unreleased], one bullet); tests:
    src/lib/templates.test.ts, src/lib/agents-md.test.ts,
    src/commands/sync.test.ts, src/commands/init.test.ts,
    src/commands/doctor.test.ts.
  • not in scope: populating Manifest.files (PLAN §10); gitignoring
    scripts/dev (OQ-1); the Windows copy path (unchanged); any hook or skill
    file (I-4).
  • real filesystem only: symlink/copy tests run in a temp project with
    SEQUANT_TEMPLATES_DIR; no fs mocking (I-8).

Acceptance criteria

  • AC-1: a generated AGENTS.md begins with the marker line <!-- sequant:agents-md v=<package version> h=<sha1 of everything after the marker line> -->, written by generateAgentsMd and therefore present in init output — Verify: npx vitest run src/lib/agents-md.test.ts -t "AC-1" → first line matches ^<!-- sequant:agents-md v=\S+ h=[0-9a-f]{40} -->$ and h recomputes from the body.
  • AC-2: sequant sync leaves an AGENTS.md byte-identical when it has no marker or its body hash ≠ the marker's h=, lists it under Customizable (preserved), and rewrites it only with --force; a marked file whose hash matches is regenerated as today — Verify: npx vitest run src/commands/sync.test.ts -t "AC-2" → three cases: unmarked file unchanged + preserved line; marked-and-matching regenerated; --force rewrites both. Mutation: delete the marker/hash guard → the first case fails; restore.
  • AC-3: sequant sync --no-agents-md skips AGENTS.md entirely (parity with init) — Verify: npx vitest run src/commands/sync.test.ts -t "AC-3" → generateAgentsMd not called, file untouched; node dist/bin/cli.js sync --help | grep -c -- '--no-agents-md' → 1.
  • AC-4: when <project>/node_modules/sequant/templates/scripts/ exists, every scripts/dev/*.sh link targets it (relative path) regardless of which sequant binary ran the command — Verify: npx vitest run src/lib/templates.test.ts -t "AC-4" → with SEQUANT_TEMPLATES_DIR pointing at a sibling dir and a fake node_modules/sequant/templates/scripts present, readlink of each link resolves inside node_modules/sequant. Mutation: remove the node_modules preference → fails; restore.
  • AC-5: with no local node_modules/sequant, a templates dir under a /_npx/ path segment or outside the project tree yields copies, not links, plus exactly one stdout line that says why and names --no-symlinks — Verify: npx vitest run src/lib/templates.test.ts -t "AC-5" → two cases (the _npx case uses the verbatim field target ../../../../.npm/_npx/38ae72183b73fa32/node_modules/sequant/templates/scripts/new-feature.sh, observed committed in sequant-io/sequant-landing on 2026-09-09 — PLAN D13; the second is a sibling dir): no symlinks under scripts/dev, files present, exactly one line matching --no-symlinks. Mutation: drop the _npx/outside-tree detection → links appear; restore.
  • AC-6: sequant sync --dry-run prints the AGENTS.md decision (runner amendment 2026-09-10, W2 D16: the sequant update --dry-run clause moves to fix(sync): dry-run lists files apply never writes — the template walk maps templates/opencode/** to .claude/opencode/** (phantom drift nag in serve; update plants unrendered {{PHASE}} files) #1030 — update never regenerates AGENTS.md nor re-links scripts/dev, so printing those decisions there would make dry-run ≠ apply, the I-2 violation fix(sync): dry-run lists files apply never writes — the template walk maps templates/opencode/** to .claude/opencode/** (phantom drift nag in serve; update plants unrendered {{PHASE}} files) #1030 owns; update.ts is also outside this node's may-touch list) (regenerate | preserved | skipped (--no-agents-md)) and, for each scripts/dev link whose target would change, old → new, and write nothing — Verify: npx vitest run src/commands/sync.test.ts -t "AC-6" → stdout assertions; project tree hash identical before and after.
  • AC-7: sequant doctor (a) warns on a scripts/dev/*.sh link whose target is missing or resolves outside both node_modules/sequant and the project tree, naming the fix command, and (b) reports an unmarked or hash-mismatched AGENTS.md as user-owned (preserved by sync) and never recommends sync --force for it — Verify: npx vitest run src/commands/doctor.test.ts -t "AC-7" → dead-link case warns with the fix text; user-owned case's message contains no --force. Mutation: restore the old --force hint → (b) fails; restore.
  • AC-8: the behavior change is documented — CHANGELOG.md [Unreleased] and the README sync section state the ownership rule, the marker, and that pre-existing AGENTS.md files without a marker are treated as user-owned until sync --force once — Verify: grep -c "sequant:agents-md" README.md CHANGELOG.md → both ≥ 1.
  • AC-9: suite green — Verify: npm run build && npm test → pass.

Done when

sequant sync/update never rewrite an AGENTS.md the user owns and never
write a scripts/dev link that only works on the machine that ran the command,
and every such decision is visible in --dry-run and doctor before any
write.

Activity

  1. added
    bug
    cli
    on Sep 7, 2026
  2. admarble commented on Sep 7, 2026

    @admarble
    ContributorAuthor

    Sibling from the same 2026-09-06 downstream sync: #991 (scripts/dev symlink targets). Both are file classes the #988 fix leaves untouched on an explicit sequant sync.

  3. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    Runner context — opencode dogfood sample (graph-2026-09 node 16, #997). This issue is being run spec→exec→qa twice as a sample for the opencode promotion gate: once with --agent opencode (base branch dogfood/opencode-2026-09, which carries the generated .opencode/ wrappers and hook shim), then once with the default claude-code driver. The resulting PRs are samples and will not be merged; the owner reads them for defects and the runner records verdict, skill-marker presence, fan-out, cost and wall time in docs/investigations/multi-backend-2026-07.md ("Dogfood 2026-09"). Work the issue exactly as you would for real — same ACs, same PR body discipline, mutation records for gate tests — but do not file any issue and do not merge. Commit a WIP within 5 minutes and every ~10 minutes; targeted tests in the foreground only; a phase silent for 30 minutes is killed. Cost cap for the opencode arm across all three sample issues: $30.

  4. changed the title [-]fix(sync): AGENTS.md is regenerated unconditionally — a hand-maintained file is silently replaced with a CLAUDE.md copy (no opt-out, not a customizable file)[/-] [+]fix(sync): never rewrite a user-owned AGENTS.md or write a machine-specific scripts/dev symlink (absorbs #991)[/+] on Sep 9, 2026
  5. added
    graph-2026-09-w2
    on Sep 9, 2026
  6. admarble commented on Sep 10, 2026

    @admarble
    ContributorAuthor

    Runner context — W2 wave 1 launch (2026-09-10). This supersedes the 2026-09-08 "opencode dogfood sample" comment above: the #997 gate was deferred and this issue was re-scoped as wave-2 node 01. This is a real run on the default claude-code driver; the PR is for the owner's merge review (stop-at-PR — do not merge). Work the ACs and verify commands in the body exactly.

  7. admarble commented on Sep 10, 2026

    @admarble
    ContributorAuthor

    Complexity: Complex (9 ACs, 4 directories)

    AC Quality Check

    9/9 pass the standard lint (no vague/unmeasurable/incomplete/open-ended/title-body-tension flags). Two non-blocking format notes:

    • Every AC uses — Verify: <command> rather than the constitution's Evidence: clause format. extractAcceptanceCriteria only recognizes a literal Evidence: clause (feat(spec/qa): explicit Evidence: clause on ACs — declared verification replaces keyword inference #938) for declared-evidence verification-method inference, so all 9 ACs resolved to verificationMethod: "manual" programmatically even though each names an exact vitest run ... -t "AC-N" command. Doesn't block planning (methods assigned manually below from the Verify text), but worth knowing before trusting /spec's auto-inference on this issue.
    • The scope tool's Non-Goals parser looks for a ## Non-Goals heading and reports it missing; the issue's ## Scope → not in scope: bullets serve the same purpose in different words. Treated as present for the assessment below.

    Scope Assessment

    Non-Goals (from ## Scope → not in scope): populating Manifest.files (PLAN §10); gitignoring scripts/dev (OQ-1); the Windows copy path (unchanged); any hook or skill file (I-4).

    Metric Value Status
    Feature count 3 (keyword clusters: "test", "api", "docs") ❌
    AC items 9 ❌
    Directory spread 4 (src, bin, scripts, tests) ⚠️

    Verdict: ❌ SCOPE_SPLIT_RECOMMENDED (programmatic)

    Assessment: the keyword clustering doesn't track a real feature seam here — AC-1/2/3 (AGENTS.md ownership marker) and AC-4/5 (symlink target ownership) are the two halves of one contract ("never rewrite a tracked file the user owns, never write a machine-specific one"), and AC-6/7/8/9 (visibility, docs, tests) apply to both halves together. Recommend proceeding as one issue, as already scoped by the issue author (explicit file list, absorbed sibling #991, single PLAN §5 I-2 citation) — see Open Questions.


    Acceptance Criteria

    AC-1: Generated AGENTS.md begins with a versioned, self-verifying marker line

    Verification: Unit Test
    Scenario: Given generateAgentsMd(config) → When called → Then output's first line matches ^<!-- sequant:agents-md v=\S+ h=[0-9a-f]{40} -->$, and h is the sha1 of everything after that line.
    Assumptions: The hash must cover the exact bytes written to disk (including the trailing newline generateAgentsMd appends at agents-md.ts:116), not a re-trimmed copy — see Open Question 3.

    AC-2: sequant sync never rewrites an AGENTS.md it doesn't recognize as its own

    Verification: Integration Test
    Scenario: Given an AGENTS.md with no marker, or a marker whose h= doesn't match the recomputed body hash → When sequant sync runs (no --force) → Then the file is byte-identical and reported under "Customizable (preserved)"; given a marked file whose hash matches → Then it regenerates as today; given --force → Then both cases rewrite.
    Assumptions: Reuses the existing preservedCustomizable reporting pattern (sync.ts:478-492) built for CUSTOMIZABLE_FILES/constitution.md (#814) rather than inventing a second mechanism.

    AC-3: sequant sync --no-agents-md skips AGENTS.md entirely

    Verification: Integration Test
    Scenario: Given --no-agents-md → When sequant sync runs → Then generateAgentsMd is never called and the file is untouched; node dist/bin/cli.js sync --help contains --no-agents-md exactly once.
    Assumptions: Mirrors init's existing --no-agents-md (bin/cli.ts:189, init.ts:88/643/808) — same flag semantics, new command.

    AC-4: A local node_modules/sequant/templates/scripts/ always wins as the symlink target

    Verification: Integration Test
    Scenario: Given node_modules/sequant/templates/scripts exists in the project → When scripts/dev/*.sh links are (re)created, regardless of which getTemplatesDir() value produced the copy → Then every link's readlink resolves inside node_modules/sequant.
    Assumptions: New preference check sits beside getTemplatesDir() (templates.ts:122-140) and feeds symlinkDir's call site in copyTemplates (templates.ts:662-682), which today always targets whatever templatesDir resolved to.

    AC-5: A _npx or outside-project-tree templates dir produces copies, not links

    Verification: Integration Test
    Scenario: Given no local node_modules/sequant and a templates dir under /_npx/ (using the verbatim PLAN D13 fixture path) or outside process.cwd() → When scripts/dev is populated → Then no symlinks are created, files are present, and exactly one stdout line names --no-symlinks.
    Assumptions: Extends the existing useSymlinks gate (templates.ts:663, currently only !options.noSymlinks && !isNativeWindows()) with a third condition; the Windows copy path itself is explicitly out of scope (unchanged).

    AC-6: --dry-run previews both decisions before any write

    Verification: Integration Test
    Scenario: Given sequant sync --dry-run → When run → Then it prints the AGENTS.md decision (regenerate | preserved | skipped (--no-agents-md)) and, per changed scripts/dev link, old → new, and the project tree hash is identical before/after.
    Assumptions: See Open Question 1 — the AC also names sequant update --dry-run, but the Verify command only exercises sync.test.ts, and update.ts has no AGENTS.md awareness today at all (confirmed: zero references in src/commands/update.ts).

    AC-7: sequant doctor warns correctly on both artifact classes

    Verification: Integration Test
    Scenario: Given a scripts/dev/*.sh link whose target is missing or resolves outside both node_modules/sequant and the project tree → When doctor runs → Then it warns and names the fix command; given an unmarked/hash-mismatched AGENTS.md → Then it reports user-owned (preserved by sync) and the message contains no --force.
    Assumptions: Part (b) replaces the current doctor.ts:331-336 branch, which today recommends sync --force for exactly this case — the bug the issue's "Found in Phase 0" note calls out.

    AC-8: Behavior is documented

    Verification: Integration Test
    Scenario: Given the implementation lands → When grep -c "sequant:agents-md" README.md CHANGELOG.md runs → Then both counts are ≥ 1.
    Assumptions: CHANGELOG [Unreleased] is currently empty (one bullet to add); README already documents sync --dry-run/update --dry-run near line 69 — natural place to extend.

    AC-9: Suite green

    Verification: Integration Test
    Scenario: Given the full change set → When npm run build && npm test runs → Then it passes.
    Assumptions: None beyond the above.


    Implementation Plan

    Phase 1: AGENTS.md ownership marker (AC-1, AC-2, AC-3)

    1. Add marker build/parse helpers to src/lib/agents-md.ts (buildMarkerLine, parseMarkerLine, sha1 via crypto); prepend the marker to generateAgentsMd's output (agents-md.ts:112-116).
    2. In sync.ts's regenerate block (sync.ts:498-521), read the existing file first; skip-and-report when unmarked or hash-mismatched (unless --force); regenerate when marked-and-matching or --force.
    3. Add --no-agents-md to the sync command in bin/cli.ts (one .option() line, matching init's at line 189) and thread agentsMd through SyncOptions.

    Phase 2: Machine-specific symlink targeting (AC-4, AC-5)

    1. Add a target-resolution helper in templates.ts near getTemplatesDir (lines 122-140): prefer <project>/node_modules/sequant/templates/scripts when present; else, if the resolved dir is under _npx or outside process.cwd(), signal "copy" with a one-line reason naming --no-symlinks; else symlink as today.
    2. Wire the helper into copyTemplates's scripts branch (templates.ts:662-682), replacing the current unconditional useSymlinks gate.

    Phase 3: Visibility — dry-run and doctor (AC-6, AC-7)

    1. In sync.ts's dry-run branch (sync.ts:366-441), print the AGENTS.md decision line and per-link old → new lines using the Phase 1/2 helpers, writing nothing.
    2. In doctor.ts: add a scripts/dev dead/foreign-target link check (new); replace the AGENTS.md consistency branch (doctor.ts:320-364) with the marker/hash-aware "user-owned (preserved by sync)" message, removing the --force hint for that case.

    Phase 4: Docs and verification (AC-8, AC-9)

    1. Add the CHANGELOG [Unreleased] bullet and extend the README sync section (~line 69) with the ownership rule, the marker, and the one-time --force note for pre-existing unmarked files.
    2. npm run build && npm test.

    Design Review

    1. Where does this logic belong? Marker/hash helpers live in agents-md.ts beside generation; symlink-target preference lives in templates.ts beside getTemplatesDir. Both are consumed by sync.ts (write + dry-run) and doctor.ts (read-only check) — no new module needed.
    2. What's the simplest correct approach? One marker line + one hash function + one target-preference helper. Reject a broader "ownership registry" — the existing CUSTOMIZABLE_FILES/isCustomizableFile split (fix(sync): plain sync overwrites CUSTOMIZABLE_FILES (constitution) — copyDir ignores force and never consults isCustomizableFile #814) already proves the minimal shape for exactly this kind of decision.
    3. What existing pattern does this follow? Directly mirrors fix(sync): plain sync overwrites CUSTOMIZABLE_FILES (constitution) — copyDir ignores force and never consults isCustomizableFile #814's constitution.md protection: "diverges from what sequant would generate → preserved unless explicit --force." The only structural difference is how divergence is detected — constitution.md diffs against a stored template, but AGENTS.md content varies per-project (name, stack, conventions), so there's no template to diff against; the self-describing marker+hash is the substitute for a stored baseline.
    4. What would a senior reviewer challenge? "Why hash instead of just diffing like constitution.md?" — because AGENTS.md has no canonical expected content to diff against. A reviewer might also ask why not skip AGENTS.md sync entirely by default — rejected because that would regress the working case (sequant-generated, untouched files) for every existing user, not just the incident case.

    Feature Quality Planning

    Most standard checks pass. Notable items:

    • update.ts/update.test.ts are not in the issue's file list but AC-6's prose names sequant update --dry-run — see Open Question 1; recommend descoping that clause from this PR.
    • The Windows copy path is explicitly unchanged (scope note) — Phase 2's new helper must only gate the target selection, not the existing isNativeWindows() fallback.
    • No derived ACs — the 9 ACs already cover generation, sync, CLI flag, symlink targeting, dry-run visibility, doctor, docs, and the full suite for both artifact classes.

    Derived ACs

    None.


    Open Questions

    1. AC-6 names sequant update --dry-run, but update.ts has no AGENTS.md awareness today and isn't in the file scope. Confirmed: zero AGENTS.md/agents-md references anywhere in src/commands/update.ts — its apply path only ever writes files computeTemplateChanges diffs from the templates/ tree, which never routes to AGENTS.md. The AC's own Verify command only runs sync.test.ts -t "AC-6", so it doesn't gate an update assertion either. Recommendation: implement AC-6 for sync --dry-run only (fully covered by the stated Verify command); call out in the PR body that the update --dry-run clause is descoped because it requires giving update a capability it doesn't have today, which is a bigger change than this issue's mechanical scope implies. Impact if wrong: a literal reading of the issue body could read this as incomplete even though the verify command is green — worth a one-line flag in the PR so QA doesn't treat it as silently dropped.
    2. Scope tool recommends a split; issue framing says one contract. Recommendation: keep as one issue per the author's explicit single-contract framing (PLAN §5 I-2) and the absorbed-sibling history (fix(templates): scripts/dev symlinks target whichever sequant package ran the command — npx-cache targets get evicted, npm-link targets are machine-specific #991). Impact if wrong: split at the first sign the two halves (AGENTS.md marker vs. symlink targeting) actually conflict during implementation — they touch disjoint functions except for the shared sync.ts dry-run block and doctor.ts.
    3. Does AC-1's hash include the trailing newline generateAgentsMd appends? Recommendation: hash the exact bytes written to disk (post-trimEnd()+"\n"), so "byte-identical" in AC-2 is unambiguous. Impact if wrong: a differently-trimmed hash would make freshly-generated files register as "user-owned" on the very next sync — a false positive that reproduces this issue's own bug class in the fix itself.

    Recommended Workflow

    Phases: spec → testgen → exec → qa
    Quality Loop: enabled
    Reasoning: Correctness-critical file-ownership logic (the exact bug class behind the 2026-09-06 downstream incident, #988/#990/#991) with 4 mutation-gated ACs (2, 4, 5, 7) across 5 files; testgen because every AC names a specific -t "AC-N" test that doesn't exist yet, spanning templates.test.ts, agents-md.test.ts, sync.test.ts, init.test.ts, doctor.test.ts.


    Label Review

    Current: bug, cli, graph-2026-09-w2
    Recommended: bug, cli, graph-2026-09-w2, planned
    Reason: Standard post-spec marker; no complexity/UI labels apply (no .tsx/.jsx involved, no browser testing needed).
    Quality Loop: Enabled — see Recommended Workflow reasoning above.

    → gh issue edit 990 --add-label planned

  8. added
    planned
    on Sep 10, 2026
  9. admarble commented on Sep 10, 2026

    @admarble
    ContributorAuthor

    Runner context — exec resumed (2026-09-10 14:02Z). The first exec attempt was killed by the orchestrator's hard 30-minute per-phase budget with no commit. The worktree kept the work: bin/cli.ts, src/commands/{doctor,sync}.ts (+tests), src/lib/{agents-md,templates}.ts (+tests, snapshot) are modified and uncommitted. On resume: read git status and git diff first, commit what is there as a WIP within the first 5 minutes, then continue from where it left off. Commit every ~10 minutes — every phase has a hard 30-minute wall and uncommitted work is only preserved by luck.

  10. admarble commented on Sep 10, 2026

    @admarble
    ContributorAuthor

    Runner context — exec resumed again (2026-09-10 15:20Z). The second attempt ended the same way as several other runs (#1032): the agent started npm test in the background and ended its turn "waiting for the notification" — under sequant run that ends the phase, and the 12 files were left uncommitted. The runner has checkpointed them as 4daf25ea chore(#990): wip checkpoint. On resume: git log --oneline main..HEAD + git show --stat HEAD first, then continue from that commit.

    Foreground only. Run every check in the foreground with a timeout, e.g. timeout 600 npm test 2>&1 | tail -80. Do not use run_in_background, a Monitor, or any "wait for the notification" pattern — nothing will wake you; the phase simply ends. Commit every ~10 minutes; every phase has a hard 30-minute wall.

  11. added a commit that references this issue on Sep 10, 2026
  12. admarble commented on Sep 10, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugcligraph-2026-09-w2planned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions