Skip to content

bug(init): init --agent <name> on an initialized repo overwrites .sequant/settings.json with defaults #1071

Closed

Description

@admarble

What happens

sequant init --agent <name> on an already-initialized repo overwrites .sequant/settings.json with defaults, discarding every tuned value.

initCommand notices the existing install and warns:

!  Sequant appears to be already initialized (.claude/settings.json exists)
   Use --force to reinitialize

but with --yes (or after confirming the prompt) it continues, and further down calls createDefaultSettings(options.agent) unconditionally — src/commands/init.ts, the "Create default settings + reference doc" block. createDefaultSettings writes generateSettingsJsonc(DEFAULT_SETTINGS) straight over SETTINGS_PATH.

Impact

Anything the user tuned is lost without a diff, a backup or a mention: run.phases model policy, run.timeout, agents.*, scopeAssessment.*. In this repo that means the per-phase routing (spec: sonnet, exec: sonnet/medium, qa: opus, timeout: 5400) would silently revert to defaults.

Found while provisioning this repo for the #1060 Codex gate — the documented setup step is sequant init --agent codex on an existing checkout, i.e. exactly the path that eats the settings. The provisioning was done by hand instead (symlink + .codex/config.toml copied from templates/codex/config.toml).

Expected

An init over an existing install should preserve .sequant/settings.json, merging in only what the flags actually change (here: run.agent). The precedent already exists — #990 gave AGENTS.md a marker-and-hash check so sync only regenerates what it wrote, preserves user-owned files, and reports the decision, with --force as the explicit override.

Note

The run.agent persistence itself is correct and wanted (#1059): init --agent codex must record the driver or doctor runs none of that driver's checks. The bug is the blast radius around it.

Prior art — this class has been fixed three times, never as a rule

Issue What got clobbered Fix shape
#708 in-place customizations on update diff/write variable sets unified so a customized file stops reading as "modified"
#814 .claude/memory/constitution.md on a plain sync CUSTOMIZABLE_FILES + isCustomizableFile() (src/lib/templates.ts:239), honored by sync/update, overridden only by --force
#990 a user-owned AGENTS.md on sync <!-- sequant:agents-md v= h= --> marker + body hash; regenerate only if sequant wrote it, else preserve and report

Each fix protected one file for one command. .sequant/settings.json is on none of those lists, and init never reaches the mechanism at all — it calls createDefaultSettings() directly rather than going through copyTemplates, so isCustomizableFile is never consulted.

The guard even exists already and is dead: settingsExist() is exported from src/lib/settings.ts:1225 and nothing calls it — doctor checks .claude/settings.json via fileExists instead. A three-line guard in createDefaultSettings (skip when the file exists unless force, or merge only the keys the flags set) would close this, and it is the same contract #814 and #990 already established.

Worth considering whether the real fix is a single preservation rule that every writer consults, rather than a fourth per-file patch.


Release-graph plan — pre-2.16.0 blockers (2026-09-17)

Graph: pre-2.16.0 release blockers, node 2 of 4 Tier: judgment Wave: 1
May touch: src/commands/init.ts, src/lib/settings.ts, src/commands/init.test.ts, CHANGELOG.md

Reproduced end-to-end 2026-09-17 — and it is worse than filed

Scratch repo, .claude/settings.json present, .sequant/settings.json tuned
(timeout: 5400, per-phase spec/exec/qa policy), then
sequant init --agent codex --yes:

  • timeout: 5400 → 1800
  • the entire run.phases block — deleted
  • only agent: "codex" survived (what the flag set)
  • init printed its success banner; the overwrite was never mentioned

Not in the original report: the "already initialized" guard checks
.claude/settings.json (init.ts:689), but the file destroyed is
.sequant/settings.json. A repo with tuned sequant settings and no
.claude/settings.json is clobbered with no warning at all.

Pre-dates v2.15.1 — not a regression from the codex batch. It blocks 2.16.0 because
2.16.0 is the release whose README tells people to run sequant init --agent codex on
an existing checkout.

Fix shape (graph D-3; open to challenge in spec)

Guard inside createDefaultSettings (src/lib/settings.ts:1238): when SETTINGS_PATH
exists and force is not set, read it, apply only the keys the flags set (today:
run.agent), write that back, and report the decision on stdout. --force keeps
today's overwrite. This is the contract #814 and #990 already established. It is
deliberately NOT the unified preservation rule — that is a follow-up, out of scope.

Acceptance Criteria

  • AC-1: init on a repo with an existing .sequant/settings.json preserves every key the flags did not set (run.timeout, run.phases survive) — Evidence: npx vitest run src/commands/init.test.ts -t "1071" 2>&1 | grep -E "Tests +([5-9]|[1-9][0-9]+) passed" prints a passed line (AC-1..AC-5 are five distinct cases named with 1071; zero matches or any failure prints nothing)
  • AC-2: init --agent codex on that same repo still records run.agent: "codex" while preserving the rest (feat(#497): sequant init --agent codex — .agents/skills symlink, .codex hooks wrapper, doctor, README #1059 behavior kept) — Evidence: covered by the AC-1 command, as its own case
  • AC-3: init --force still overwrites with defaults — the documented escape hatch — Evidence: covered by the AC-1 command, as its own case
  • AC-4: init reports what it preserved instead of succeeding silently — Evidence: covered by the AC-1 command, as a case asserting captured stdout names .sequant/settings.json as preserved
  • AC-5: the clobber is impossible with no .claude/settings.json present either (the guard keys off the file it actually writes) — Evidence: covered by the AC-1 command, as a case whose fixture has .sequant/settings.json but no .claude/settings.json
  • AC-6: settingsExist() is either used by the new guard or deleted — no exported dead code left — Evidence: bash -c 'grep -q settingsExist src/commands/init.ts || ! grep -q "export async function settingsExist" src/lib/settings.ts' && echo PASS prints PASS
  • AC-7: the manual end-to-end repro below, run against the worktree's own build, prints PRESERVED — Evidence: gh pr view --json body -q .body | grep -c "RESULT: PRESERVED" prints 1

AC-1 and AC-5 are gate tests: mutation-verify (remove the exists-guard → AC-1 fails;
key the guard off .claude/settings.json → AC-5 fails) and record the markers.

Manual end-to-end repro (run from the worktree root — the global sequant points at main's dist, not yours)

npm run build >/dev/null 2>&1 && CLI="$PWD/dist/bin/cli.js"
SC=$(mktemp -d); mkdir -p "$SC/.claude" "$SC/.sequant"; cd "$SC"; git init -q .
echo '{}' > .claude/settings.json
printf '%s\n' '{' '  "version": 1,' '  "run": { "agent": "claude-code", "timeout": 5400, "phases": { "spec": "sonnet", "exec": "sonnet", "qa": "opus" } }' '}' > .sequant/settings.json
B=$(shasum .sequant/settings.json | cut -d' ' -f1)
node "$CLI" init --agent codex --yes >/dev/null 2>&1
grep -q '"agent": "codex"' .sequant/settings.json && grep -q '"timeout": 5400' .sequant/settings.json && grep -q '"qa": "opus"' .sequant/settings.json \
  && echo "RESULT: PRESERVED (agent recorded, tuned keys intact)" || echo "RESULT: CLOBBERED"

Note the check is not a byte-for-byte hash — run.agent is supposed to change. It
asserts the flag's key landed and the tuned keys survived.

Out of scope

The "single preservation rule every writer consults" this issue speculates about. File
it as a follow-up after this merges.

Activity

  1. added
    bug
    on Sep 16, 2026
  2. added a commit that references this issue on Sep 16, 2026
  3. admarble commented on Sep 18, 2026

    @admarble
    ContributorAuthor

    Runner context (2026-09-18, wave 1 of the pre-2.16.0 graph)

    • Base: main at f776158f. The files in May touch are unchanged since this plan was written, so the line references above still hold.
    • Hard 30-minute wall per MCP-dispatched phase. Commit WIP before running the suite. Run the suite once, in the foreground, with a timeout. Never background it.
    • Gate-test ACs must carry the Mutation-verified: AC-N — <mutation>; <test> failed; restored. marker in the PR body (CLAUDE.md format, machine-anchored as <!-- SEQUANT_MUTATION: ... -->). /qa §6i enforces it.
    • Keep every existing CHANGELOG.md Unreleased entry; add yours alongside.
    • Stop at PR. Do not merge. Merge order is decided by the human.
    • settingsExist() now sits at src/lib/settings.ts:1242 (the issue says 1225). Still zero callers; doctor.ts:496 uses a local variable of the same name, not the export.
    • chore(doctor/templates): timeout the codex+opencode CLI probes; add the missing templates/codex routing test #1075 (running in parallel) adds a case to src/lib/templates.test.ts. Prefer not to touch templates.ts/templates.test.ts here unless the fix requires it, so the two PRs merge cleanly.
  4. admarble commented on Sep 18, 2026

    @admarble
    ContributorAuthor

    Plan — #1071 (preserve .sequant/settings.json on re-init)

    Complexity: Standard (7 ACs, 2 directories)

    AC Quality Check

    7 ACs parsed, all single-line, all carrying Evidence:. Declared evidence resolves AC-1 → unit_test, AC-4/AC-6/AC-7 → integration_test. No vague/unmeasurable/open-ended patterns. Two notes, neither blocking:

    • AC-6's evidence command constrains the design, not just the check. grep -q settingsExist src/commands/init.ts || ! grep -q "export async function settingsExist" src/lib/settings.ts passes only if (a) init.ts names settingsExist, or (b) the export is gone from settings.ts. A guard that lives inside createDefaultSettings and calls settingsExist() satisfies the AC's text but fails its command. Compliant shape recommended below.
    • AC-7's grep -c "RESULT: PRESERVED" must print exactly 1. The repro script in the issue body contains that literal string inside its own echo. Pasting the script into the PR body makes the count 2 and the gate fails. Paste the captured output line only.

    Scope Assessment

    Non-Goals: present as "### Out of scope" — the unified preservation rule every writer consults. Parser reports the Non-Goals section as empty (heading name mismatch); the boundary is stated and honoured here.

    Metric Value Status
    Feature count 1 (guard + report) ✅
    AC items 7 (AC-2..AC-5 are cases of AC-1's one command) ⚠️
    Directory spread 2 (src/commands, src/lib) ✅

    Verdict: ⚠️ SCOPE_WARNING — driven entirely by AC count; the real change is ~2 source files. Quality loop enabled per the SCOPE_WARNING rule.


    Acceptance Criteria

    AC-1: existing .sequant/settings.json survives init; run.timeout / run.phases intact
    Verification: Unit Test (src/commands/init.test.ts, describe 1071 …)
    Scenario: Given .sequant/settings.json with timeout: 5400 and a run.phases block → When createDefaultSettings runs without force → Then the file is not rewritten with defaults and both keys survive.
    Assumptions: the real createDefaultSettings is exercised, not the file-level mock (see Risk R3).

    AC-2: --agent codex still records run.agent while preserving the rest (#1059 kept)
    Verification: Unit Test — same describe, own case.
    Scenario: Given the same tuned file → When init runs with agent: "codex" → Then written content has agent: "codex" and timeout: 5400 and the phases block.

    AC-3: --force still overwrites with defaults
    Verification: Unit Test — same describe, own case.
    Scenario: Given the same tuned file → When force is set → Then the file is the freshly generated default JSONC (timeout back to 1800).

    AC-4: init reports what it preserved
    Verification: Integration Test (init-level, consoleLogSpy).
    Scenario: Given an existing settings file → When initCommand runs → Then captured stdout contains .sequant/settings.json and says it was preserved.
    Assumptions: the line goes through console.log, not spinner.succeed — cli-ui's spinner is mocked in that suite and its text never reaches consoleLogSpy (Risk R5).

    AC-5: no .claude/settings.json present → still preserved
    Verification: Unit Test — same describe, own case.
    Scenario: Given fileExists(".claude/settings.json") === false and .sequant/settings.json tuned → When init runs → Then the tuned keys survive. This is the guard keying off the file it writes, not the one it checks.

    AC-6: settingsExist() used by the guard or deleted
    Verification: Integration Test (the grep, run in CI/QA).
    Scenario: see AC Quality Check — recommended shape: drop export, call it from the guard.

    AC-7: manual end-to-end repro prints PRESERVED
    Verification: Manual Test, output pasted once into the PR body.
    Scenario: build the worktree, run the issue's script against dist/bin/cli.js, paste the single RESULT: line.


    Implementation Plan

    Phase 1 — the guard (src/lib/settings.ts)

    1. createDefaultSettings(agent?: string, force = false). When force is false and settingsExist() (now module-local, no export — AC-6), take the preserve path; otherwise today's behaviour verbatim (AC-3).
    2. Preserve path: read the file, JSON.parse(stripJsoncComments(content)) on the raw object. If no flag key needs changing, do not write at all — the file stays byte-identical, JSONC comments included. If agent must change, set run.agent on the raw object and write JSON.stringify(merged, null, 2).
    3. ⚠️ Do not re-serialize through generateSettingsJsonc. It emits neither run.phases nor scopeAssessment nor run.modelRoles (settings.ts:1272+) — round-tripping through it reproduces the exact data loss this issue reports and fails AC-1. Merge on the raw parsed object; nested Zod schemas strip unknown keys too, so don't route the write through validateSettings either.
    4. Unparseable existing file → preserve, don't write, warn, point at --force (derived AC below).
    5. Return a result ({ action: "created" | "preserved" | "updated", path }) so the caller can report.

    Phase 2 — the report (src/commands/init.ts)
    6. Pass options.force through; render the result. console.log a line naming .sequant/settings.json and what was preserved (AC-4), alongside the existing spinner.
    7. Update the #1059 test at init.test.ts:868 — toHaveBeenCalledWith("codex") breaks once the signature gains a second argument.

    Phase 3 — tests + evidence
    8. describe("1071: …") in src/commands/init.test.ts with ≥5 cases (AC-1's grep needs Tests 5 passed; format confirmed as Tests N passed | M skipped (T) under -t).
    9. Drive the real implementation via await vi.importActual("../lib/settings.js") inside that describe — ../lib/fs.js stays mocked, so the assertions are on readFile/writeFile calls. No temp cwd, no process.cwd spy (#870).
    10. Mutation-verify AC-1 (remove the exists-guard → the AC-1 case fails) and AC-5 (key the guard off .claude/settings.json → the AC-5 case fails); record both <!-- SEQUANT_MUTATION: … --> markers in the PR body.
    11. CHANGELOG entry alongside the existing Unreleased ones.

    Design Review

    1. Where does this belong? In createDefaultSettings — the only writer of SETTINGS_PATH on this path, and init never reaches copyTemplates/isCustomizableFile. Confirms graph D-3.
    2. Simplest correct approach? Don't-write-when-nothing-changes, plus a raw-object merge when --agent sets a key. Rejected: a surgical JSONC line patch that would also keep comments on the merge path — two code paths and a regex against user-formatted JSONC, for a comment-fidelity gain on one branch. Rejected: the unified preservation rule — explicitly out of scope here.
    3. Existing pattern? fix(sync): plain sync overwrites CUSTOMIZABLE_FILES (constitution) — copyDir ignores force and never consults isCustomizableFile #814 / fix(sync): never rewrite a user-owned AGENTS.md or write a machine-specific scripts/dev symlink (absorbs #991) #990: preserve user-owned content, report the decision, --force as the single override. Writing plain JSON over JSONC on the merge branch already has precedent in saveSettings.
    4. What would a reviewer challenge? "You merged through the generator and lost run.phases anyway" (step 3 exists to prevent exactly that), and "the new tests mock createDefaultSettings and assert nothing" — which the mutation record is there to disprove.

    Feature Quality Planning

    • Derived AC (Medium): an existing settings file that is invalid JSON must be preserved untouched with a warning, never silently replaced by defaults. Currently unspecified; the guard's read step makes it a one-line branch.
    • Sibling sites, same class, same command — not proposed for this PR: writeCodexConfig (init.ts:579) overwrites .codex/config.toml unconditionally, and saveConfig overwrites .claude/.sequant/config.json. Recommend a follow-up issue rather than widening scope, since the unified rule is declared out of scope.

    Open Questions

    1. Does an explicit --agent claude-code clear a recorded run.agent: "codex"? Today createDefaultSettings skips writing agent when it equals claude-code, so under the guard a user switching back would silently stay on codex. Recommendation: treat an explicitly-passed --agent as a key the flag set and write it, per the AC's own "only the keys the flags actually set". Impact if wrong: a switch-back is a silent no-op.
    2. Include the invalid-JSON derived AC in this PR? Recommendation: yes — it's a branch of the same read, and without it the corrupt-file path still clobbers.

    Conflict Risk

    No overlap. #1075 (in flight) touches templates.ts/templates.test.ts — untouched here, per the runner note. PR #1085 touches MCP/doctor/serve, no shared files. Both worktrees sit at f776158f.

    Recommended Workflow

    Phases: exec → qa
    Quality Loop: enabled (SCOPE_WARNING)
    Reasoning: bug label, one localized fix with the test design already pinned by AC-1's evidence command. testgen skipped despite declared unit/integration evidence — the evidence names one existing test file and an exact case count, so generated stubs would be replaced immediately; overriding the declared-evidence default deliberately.

  5. added
    planned
    on Sep 18, 2026
  6. admarble commented on Sep 19, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    AC coverage: 0/2 met

    Gaps:

    • The follow-up issue for the two sibling unconditional writers that spec recommended and the PR acknowledges was never filed, leaving the class untracked
    • The blank-existing-file branch of preserveExistingSettings has no automated test coverage
    • AC-1's test contains two assertions on a test constant that read as coverage but cannot discriminate
    • JSONC comments in the user's settings file are lost on the update path, on the very file this change exists to protect

    Suggestions:

    • The blank-file branch (settings.ts:1318, if (!content.trim())) is new production code with no automated test. I exercised it manually (empty file → 1836-byte default JSONC written, no "Preserved" line) and it is correct, but it has no regression guard.
    • AC-1's test includes expect(onDisk.run.timeout).toBe(5400) on a re-parse of the TUNED test constant — those two lines cannot fail regardless of implementation. The discriminating assertions (result.action === "preserved", writtenSettings() is null) are present and mutation-verified, so this is cosmetic, but it reads as coverage it is not.
  7. added a commit that references this issue on Sep 19, 2026
  8. added a commit that references this issue on Sep 20, 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