Skip to content

fix(writers): update/init/sync write through an existing symlink at a sequant-owned destination (#1053 class) #1122

Closed

Description

@admarble

Found by the writer-state matrix in #1097. Real filesystem, temp project, SEQUANT_TEMPLATES_DIR = the repo's templates/.

What happens

When the destination of a sequant-owned file is an existing symlink, several writers call writeFile on it. writeFile follows the link, so the link stays and its target is overwritten with template content. #1053 fixed this for scripts/dev in copyTemplates' copyDir; the other write sites still do it.

Destination Writers that write through a local or foreign symlink
.claude/settings.json init, init --force, sync, sync --force, update, update --force (copyTemplates writes it directly, outside copyDir; update writes every file with a bare writeFile)
.claude/skills/spec/SKILL.md and every other copyDir destination update, update --force only (sync/init replace the link)
scripts/dev/<x>.sh (copy and link routes) update, update --force only

Repro (foreign symlink): ln -s /somewhere/else/file .claude/settings.json && sequant sync. /somewhere/else/file now holds the template; .claude/settings.json is still a symlink.

Expected

Same rule as #1053: an existing symlink is replaced, never written through, and its target is left alone.

The matrix pins the current behaviour (letter W in src/lib/__tests__/writer-state-matrix.test.ts) and lists this under KNOWN_DEFECTS. Fixing it fails those cells until the grid is updated.

Also in scope: a directory at the destination (folded from #1124)

Same writer-state matrix (#1097), same code paths. When a directory sits where a template file goes, the writers reject with a raw EISDIR (or EEXIST from symlinkDir on the link route) and abort partway, dry-runs included: computeTemplateChanges reads the path as a file, so sync --dry-run and update --dry-run crash instead of reporting the collision. Affected destinations: .claude/settings.json, .claude/skills/*/SKILL.md, .claude/memory/constitution.md (every writer); .sequant/settings.json, .mcp.json, .gitignore (init, init --force); scripts/dev/<x>.sh (init --force, sync, update).

Expected: a named, actionable error per destination (<path> is a directory; move it aside) or a documented skip, and a dry-run that reports the collision instead of throwing. The matrix pins this as letter X under KNOWN_DEFECTS; the fix updates those cells alongside the W cells above.

Acceptance criteria

Tier: judgment · Graph: 2026-09-w3 (docs/internal/graph-2026-09-w3/issue-graph.md)

  • AC-1: no writer (init, sync, update, with and without --force) writes through an existing symlink at a sequant-owned destination; the link is replaced and its target stays byte-identical — Verify: npx vitest run src/lib/__tests__/writer-state-matrix.test.ts with symlink-written-through-at-sequant-owned removed from KNOWN_DEFECTS
  • AC-2: a directory at a template destination yields the named error <path> is a directory; move it aside (or a documented skip) with no partial write, and sync --dry-run / update --dry-run report the collision instead of throwing — Verify: npx vitest run src/lib/__tests__/writer-state-matrix.test.ts with directory-crashes-writer removed from KNOWN_DEFECTS
  • AC-3: the foreign-symlink repro above (ln -s <outside file> .claude/settings.json && sequant sync) leaves the outside file's content unchanged — Verify: a named case in src/lib/__tests__/writer-state-matrix.test.ts asserting the foreign file's bytes survive sync and update
  • AC-4: build and full suite green — Verify: npm run build && npm test

Activity

  1. admarble commented on Sep 25, 2026

    @admarble
    ContributorAuthor

    Runner context (graph 2026-09-w3, docs/internal/graph-2026-09-w3/issue-graph.md, PR #1154) — these rules apply to the spec, exec AND qa phases:

    • qa phase: do not run the full npm test. Verify each AC with its own verify command and run only the named test files. The runner runs the full suite once per PR, serially — three phase agents share this machine and a full-suite call inside a phase can hit the 30-minute no-progress wall.
    • exec phase: commit WIP before any long command; run the full suite at most once, in the foreground, with a timeout; never run_in_background.
    • Gate-test ACs: the PR body's <!-- SEQUANT_MUTATION: {...} --> marker needs failedTest to start with the test file path (src/.../x.test.ts > describe > case), or /qa §6i floors it to AC_NOT_MET.
    • CHANGELOG: add exactly one [Unreleased] line.
    • Stop at the PR — do not merge.
  2. admarble commented on Sep 25, 2026

    @admarble
    ContributorAuthor

    /spec — Plan (#1122)

    Complexity: Standard (4 ACs, 4 directories)

    AC Quality Check

    lintAcceptanceCriteria → 4/4 pass, 0 flagged. Two parser-level notes:

    Scope Assessment

    Non-Goals: not present in the issue body.

    Metric Value Status
    Feature count 2 warn
    AC items 4 ok
    Directory spread 4 warn

    Verdict: SCOPE_WARNING — clustering artifact: the detector split AC-3 into "config" and AC-4 ("build and full suite green") into "ui". Real spread is src/lib/ + src/commands/ + one test file.


    The two defects, located

    AC-1 (symlink write-through), 24 pinned cells — two call sites:

    Both go through src/lib/fs.ts:51 writeFile = ensureDir + fsWriteFile, and fsWriteFile follows the link.

    AC-2 (directory at destination), 32 pinned cells: fileExists uses access, which returns true for a directory, so every guard gated on it falls into a readFile/writeFile that throws EISDIR:

    • templates.ts:1040 (copyDir user-owned check -> readFile), templates.ts:1060 (writeFile)
    • templates.ts:830 (symlinkDir copy fallback; createSymlink gives EEXIST on the link route)
    • templates.ts:643 — computeTemplateChanges is the dry-run crash: fileExists true -> readFile -> EISDIR, before any preview is printed
    • init.ts:132 (updateGitignore's readFile), settings.ts:1276 (createDefaultSettings)

    Implementation Plan

    Phase 1 — symlink replacement (AC-1, AC-3)

    1. src/lib/fs.ts: make writeFile replace an existing symlink instead of following it — lstat, unlink when isSymbolicLink(), then fsWriteFile. One site fixes both AC-1 call paths and cannot be regressed by a future writer. (Alternative: a writeFileReplacingSymlink helper applied at templates.ts:1127 + update.ts:308 only — Open Question 1.)
    2. Drop the now-redundant pre-unlink at templates.ts:1051, or keep it with a comment pointing at the fs.ts guarantee. Keep symlinkDir's removeFileOrSymlink — it precedes createSymlink, not writeFile.
    3. Add the AC-3 named case next to the existing #1053: foreign symlink in copy mode block: foreign symlink at .claude/settings.json, run sync and update, assert the outside file's bytes are unchanged and the destination ends as a regular file with template content.

    Phase 2 — directory collision (AC-2)

    1. Add an lstat-based isDirectory(path) to src/lib/fs.ts (fileExists cannot answer this).
    2. computeTemplateChanges: check before readFile; emit a new TemplateChange.status value "directory-collision" (union at templates.ts:454).
    3. sync.ts / update.ts: filter that status out of the applySet and report it in its own block with the exact string <path> is a directory; move it aside. Do not list it under Modified files: / New files: — printedDecision would read that as o and break the DECISIONS rows.
    4. Same guard + same message in copyDir, symlinkDir's copy fallback, updateGitignore and createDefaultSettings, each skipping the destination rather than throwing.

    Phase 3 — re-pin the grid (AC-1, AC-2)

    1. Remove both entries from KNOWN_DEFECTS (writer-state-matrix.test.ts:456).
    2. Update GRID. With the fs.ts fix these are the exact deltas; localSymlink and foreignSymlink are identical in every row:
    Dest before after
    settings W W W W W W T T T T T T
    skill T T T T W W T T T T T T
    constitution = = = T = W = = = T = T
    sequantSettings = W = = = = = T = = = =
    agentsMd = W = W = = = T = T = =
    scriptsCopy T T T T W W T T T T T T
    scriptsLink L L L L W W L L L L T T

    gitignore and mcpJson stay M M = = = = (classify returns M for a merged regular file too). All directory rows become = = = = = =.

    1. Extend the letter legend in the file header if a distinct letter for "skipped, named message" is preferred over =.

    Phase 4 — verification

    1. npx vitest run src/lib/__tests__/writer-state-matrix.test.ts (63 cells x 2 suites — run this file alone, not npm test, per the runner-context comment).
    2. npm run build && npm test once, foreground, with a timeout.

    Design Review

    1. Where does this logic belong? src/lib/fs.ts for the symlink rule (36 writeFile call sites across 14 files inherit it); computeTemplateChanges for the directory rule, the single reader both dry-run paths share.
    2. What's the simplest correct approach? AC-2's two branches are not equivalent. The matrix asserts expect(dry.threw === null).toBe(apply.threw === null), and AC-2 requires the dry-run not to throw — so apply must not throw either. Further, classify returns X whenever a writer threw with a directory before and after, so throwing keeps all 32 cells at X and directory-crashes-writer cannot be removed from KNOWN_DEFECTS. Only the skip branch satisfies AC-2 as written: print the exact message, skip the destination, continue.
    3. What existing pattern does this follow? fix(init): --yes init replaces a user-modified AGENTS.md and an unparseable .mcp.json that sync would preserve #1123 (28bc0748), which made createProjectMcpJson return early without writing and report the file untouched — which is why mcpJson's directory row already reads = = = = = = while every other destination reads X.
    4. What would a senior reviewer challenge? "Why change writeFile for everyone?" The 24 cells span two unrelated call sites and the class already recurred once after fix(sync): copy-mode sync leaves existing machine-specific scripts/dev symlinks in place, and doctor's hint loops back to sync #1053 fixed it locally; a local fix leaves .sequant/settings.json, AGENTS.md and the constitution still writing through links.

    Feature Quality Planning

    • Sibling sites the fix reaches for free. 8 further W cells sit at user-owned destinations (constitution x2, sequantSettings x2, agentsMd x4) — same data-loss bug, uncounted because the symlink-written-through-at-sequant-owned invariant filters on ownershipPolicy() === "sequant-owned". The fs.ts fix flips all 8; the grid deltas above already include them.
    • Sibling site the fix does NOT reach. .mcp.json uses fs.writeFileSync directly (mcp-config.ts:243,356,471), so its M cells at symlink states stay write-throughs. Outside AC-1's literal scope (merge policy) and no invariant counts it — recommend a follow-up issue rather than widening scope here.
    • Gate-test marker. AC-3's named case should carry a SEQUANT_MUTATION record — mutation: restore the bare fsWriteFile in fs.ts; failedTest must start with src/lib/__tests__/writer-state-matrix.test.ts > ... or /qa §6i floors it to AC_NOT_MET.

    Derived AC

    Source Derived AC Priority
    Gate-test discipline AC-5: the PR body carries a SEQUANT_MUTATION marker for AC-3, failedTest starting with the test file path High

    Conflict Risk Analysis

    No file overlap. feature/1122-... exists at aa865de3 with an empty diff. In-flight siblings touch templates/scripts/new-feature.sh + a new test (#1145) and .github/workflows/upstream-assessment.yml (#1153). Shared merge point is CHANGELOG.md [Unreleased] only — one line, merge main in rather than rebasing.

    #1145 edits templates/scripts/new-feature.sh, which the matrix reads at test time as a fixture. Content-agnostic (it compares against that same template), so no ordering constraint.


    Open Questions

    1. Fix fs.writeFile globally, or a helper at two sites? Recommendation: globally. Impact if wrong: a caller that intends to follow a symlink starts replacing it — I found none among the 36 sites, and the alternative's failure mode is another fix(sync): copy-mode sync leaves existing machine-specific scripts/dev symlinks in place, and doctor's hint loops back to sync #1053-class recurrence.
    2. Does "documented skip" need a new grid letter, or is = enough? Recommendation: =, with a legend note that a named skip leaves the destination byte-identical. Impact: cosmetic.
    3. File the .mcp.json write-through follow-up now or after merge? Recommendation: after, referencing this PR.

    Recommended Workflow

    Phases: exec -> qa
    Quality Loop: enabled
    Reasoning: Nothing for testgen to stub — AC-1/2 modify an existing 1,137-line matrix test and AC-3 adds a case to it. Quality loop on: SCOPE_WARNING, and Phase 3 re-derives 63 grid cells by hand, exactly what a second pass catches. Per the runner-context comment, qa verifies each AC with its own command and must not run npm test.

  3. added
    planned
    bug
    on Sep 25, 2026
  4. added 2 commits that reference this issue on Sep 25, 2026
  5. admarble commented on Sep 25, 2026

    @admarble
    ContributorAuthor

    Runner note (resume): the first exec phase hit the MCP 30-minute no-progress wall. Its work is on origin/feature/1122-… (4 commits, head aef6c9db), and the worktree was reaped. The resumed exec should build on those commits rather than start over. Finish the remaining ACs, run only the named test files (src/lib/__tests__/writer-state-matrix.test.ts, the canary project npx vitest run --project canary), and open the PR. Do not run the full npm test in exec or qa; the runner runs it once per PR. Note: #1145 depends on this PR, because the required canary check needs sync to replace the scripts/dev/*.sh symlink.

  6. admarble commented on Sep 25, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    Gaps:

    • The .mcp.json symlink write-through is a live instance of the same data-loss class this PR fixes, deliberately scoped out but with no follow-up issue filed
    • Spreading the real fs.js module removes the previous loud-failure guard in two test files, so a future code path could silently mutate the real filesystem from a unit test
  7. added a commit that references this issue on Sep 25, 2026
  8. admarble commented on Sep 25, 2026

    @admarble
    ContributorAuthor

    Runner verification (PR #1157, head aef6c9db) — QA: AC_MET_BUT_NOT_A_PLUS.

    • AC-1/AC-2: KNOWN_DEFECTS is empty in writer-state-matrix.test.ts. npx vitest run src/lib/__tests__/writer-state-matrix.test.ts → 649 passed.
    • AC-3: the named case runs inside that test file and passes.
    • AC-4: CI at aef6c9db shows test, typecheck and canary all success. npx vitest run --project canary locally → 4 passed.
    • QA gap 1: .mcp.json writes bypass the new guard. Filed as fix(mcp-config): .mcp.json writes still follow an existing symlink (#1122 follow-up) #1160, out of scope here.
    • QA gap 2 (importOriginal spread in init.test.ts/sync.test.ts): noted, not changed.
  9. added a commit that references this issue on Sep 25, 2026
  10. added a commit that references this issue on Sep 25, 2026
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

    bugplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions