Repository navigation
Description
Summary
getTemplatesDir() (src/lib/templates.ts:26-39) resolves the bundled templates as join(__dirname, "..", "..", "..", "templates"), calibrated for the compiled layout (dist/src/lib/templates.js → 3 up = package root). Run from source via tsx (npx tsx bin/cli.ts sync), __dirname is <repo>/src/lib, so 3 up lands one directory above the repo root and the templates path does not exist.
The failure is silent-success: copyTemplates()'s copyDir treats ENOENT as "skip if source doesn't exist" (templates.ts:435-439), so every copy (skills, agents, hooks, memory) no-ops, the version marker is still written, and sync prints ✔ Synced to v2.9.0 / "Skills, hooks, and memory files have been updated." having installed nothing but .claude/skills/.sequant-version. init and the drift check (computeTemplateChanges) share the same resolution, so any template operation from an uncompiled source tree is affected.
Field observation (#813 QA, 2026-07-26)
While validating #813's sequant sync remedy in a scratch project:
npx tsx <repo>/bin/cli.ts sync→✔ Synced to v2.9.0, but.claude/skills/contained only.sequant-version— the feat(run): pre-flight the skills install — missing .claude/skills/ should fail fast, not flail for 30 minutes as a spec retry #813 skills pre-flight then correctly failed the very runsyncclaimed to have fixed (missing skills: exec, qa)node <repo>/dist/bin/cli.js sync→ all skills installed, pre-flight passed
Dev-invocation only — consumers run the compiled binary — but it is a trap for contributors testing sync/init from source, and the version marker it writes then makes the next sync hit the skillsVersion === packageVersion fast path and report "already up to date" against an empty tree (the #708 drift check compares against the same wrong templates dir, so it sees no drift).
Proposed fix
Existence-probe the two known layouts in getTemplatesDir(): try the compiled offset (../../../templates), fall back to the source offset (../../templates), and keep the SEQUANT_TEMPLATES_DIR env override as the first choice (already present, used by tests). Independently, a missing templates root should fail loudly rather than ride copyDir's per-directory ENOENT skip — that skip is fine for optional subdirs, not for the whole source tree.
Acceptance criteria
- AC-1:
getTemplatesDir()resolves the bundledtemplates/correctly from both the compiled layout (dist/src/lib) and a source-treetsxinvocation (src/lib), with a unit test pinning both offsets. - AC-2:
syncandinitexit non-zero naming the missing path when the resolved templates root does not exist, instead of printing✔ Syncedafter copyDir's silent ENOENT skip; per-subdir skips (e.g. a stack withoutmemory/) remain non-fatal. - AC-3: A regression test asserts that a source-invoked
syncagainst a bare project installs the core skills (spec, exec, qa), not just the.sequant-versionmarker.
Non-Goals
- Changing the plugin or npm distribution layout, or the
SEQUANT_TEMPLATES_DIRoverride semantics. - The fix(sync): plain sync overwrites CUSTOMIZABLE_FILES (constitution) — copyDir ignores force and never consults isCustomizableFile #814 customizable-files handling (already merged in PR fix(#814): plain sync preserves CUSTOMIZABLE_FILES (constitution) #815) — untouched.
Activity
admarble commentedon Jul 27, 2026
Plan (
/spec)Complexity: Standard (3 ACs, 2 directories)
Reproduction (evidence, not theory)
Both layouts are unambiguous and non-overlapping, so a compiled-first ordered probe is deterministic.
AC Quality Check
Scope Assessment
Non-Goals (from issue): distribution layout,
SEQUANT_TEMPLATES_DIRsemantics, #814 customizable-files handling.src/lib,src/commands)Verdict: ✅ SCOPE_OK
Acceptance Criteria
AC-1 —
getTemplatesDir()resolves from both layouts, unit test pins both offsets.Verification: Unit Test
Scenario: Given module dir
dist/src/lib(compiled) orsrc/lib(tsx) → WhengetTemplatesDir()runs → Then it returns the package-roottemplates/in both cases.Design note:
__dirnamecannot be faked in-process, so the offset table is extracted into a pure, injectable helperresolveTemplatesDirFrom(baseDir, exists).getTemplatesDir()becomesenv override ?? resolveTemplatesDirFrom(__dirname, existsSync). This makes "pinning both offsets" a real assertion rather than a tautology that only exercises whichever layout vitest happens to run under.AC-2 —
sync/initexit non-zero naming the missing path; per-subdir skips stay non-fatal.Verification: Unit Test (error message) + Integration Test (CLI exit code)
Scenario: Given
SEQUANT_TEMPLATES_DIR=/nope→ Whensequant syncruns → Then exit ≠ 0 and output contains/nope, and no✔ Syncedis printed. Given a templates tree withskills/but nomemory/→ WhencopyTemplatesruns → Then it succeeds (per-subdir ENOENT skip preserved).Assumption: the guard must run before sync's
skillsVersion === packageVersionfast path — that path callscomputeTemplateChangesagainst the same wrong dir, sees no drift, and prints "already up to date" against an empty tree (the second-run trap in the issue).AC-3 — Regression test: source-invoked
syncon a bare project installs spec/exec/qa.Verification: Integration Test
Scenario: Given a temp project with a seeded manifest and an empty
.claude/skills/→ Whennode_modules/.bin/tsx bin/cli.ts syncruns withSEQUANT_TEMPLATES_DIRunset → Then exit 0 and.claude/skills/{spec,exec,qa}/SKILL.mdall exist.Assumption: the env override must be left unset or the test is vacuous — it would pass today.
Implementation Plan
Phase 1 — Resolution (AC-1)
src/lib/templates.ts: extractresolveTemplatesDirFrom(baseDir, exists)with an ordered candidate list —["..","..",".."](compiled:dist/src/lib→ package root) then["..",".."](source:src/lib→ repo root). First hit wins; when neither exists, return the compiled candidate so AC-2's error names the canonical expected path rather than a bare-source guess.getTemplatesDir()keepsSEQUANT_TEMPLATES_DIRas the unconditional first choice (Non-Goal: semantics unchanged — no existence probe on the override at resolution time).src/lib/templates.test.ts: compiled base, source base, neither-exists fallback, env override precedence, plus one live check that the realgetTemplatesDir()points at a dir containingskills/.Phase 2 — Loud failure (AC-2)
4.
src/lib/templates.ts: addassertTemplatesDirExists(): Promise<string>— resolves, checks the root exists, throws anErrornaming the path and mentioningSEQUANT_TEMPLATES_DIR. Throwing (not printing) keeps presentation out of the lib layer.5.
src/commands/sync.ts: call it immediately after the manifest check — i.e. ahead of the version fast path — catch,chalk.red(message),process.exitCode = 1; return;(matches the existing not-initialized branch;.action(syncCommand)has no rejection handler, so throwing out of the command is not an option).6.
src/commands/init.ts: same guard right after the banner, before any prompt or write, so a broken install fails before it half-provisions a project.7.
copyDir's per-directory ENOENT skip is left alone — that is the "per-subdir skips remain non-fatal" half of AC-2. Add a test pinning it so a future tightening can't silently break stacks withoutmemory/.Phase 3 — Regression (AC-3)
8. New
src/commands/sync-source-invocation.integration.test.ts(.integration.test.ts→ subprocess-heavy integration project,fileParallelism: false), following thespawnSync(tsxBin, [cliSource, ...])pattern fromsrc/lib/workflow/phase-registry.integration.test.ts. Two cases: the AC-3 happy path, and the AC-2 negative path (SEQUANT_TEMPLATES_DIR=<nonexistent>→ non-zero + path in output).Design Review
src/lib/templates.ts— it already owns resolution; both commands are thin consumers. No new module.getTemplatesDirin the codebase's other idiom (see Q3) — a walk-up would, in a consumer project whosenode_modules/sequant/templatesis genuinely missing, climb out of the package and bind to the consumer's owntemplates/directory. Silently wrong beats loudly broken only until it doesn't; the bounded probe cannot over-reach, and it is what the issue proposes.fileURLToPath(import.meta.url)acrosssrc/,bin/):version.ts,manifest.ts,bin/preflight.tswalk up to apackage.jsonnamedsequant;relay/frame.tsandrelay/activation.tswalk up 6 levels probing for the template.getTemplatesDiris the only fixed-offset resolver in the repo — which is exactly why it is the only one that broke. Those siblings are already robust to the tsx layout, so this is a consistency observation, not additional scope: no follow-up issue recommended. The probe adopts their existence-check spirit while staying bounded.doctor/pre-flight throw?" — no:checkAndWarnSkillsOutdatedandcomputeDriftFingerprintalready swallow failures and are out of AC-2's scope; onlysyncandinitget the hard gate.Feature Quality Planning
All standard checks pass. Notable:
src/commands/sync.test.tsmocksgetTemplatesDir → "/pkg/templates"(a path that does not exist). Adding the guard tosyncCommandwill trip it unlessassertTemplatesDirExistsis added to thatvi.mockfactory. Known blast radius — must be handled in exec, not discovered in CI.syncbails early with "not initialized" otherwise, which would pass for the wrong reason.Open Questions
dist/templatesdoes not exist (verified above), so the two candidates never both resolve. Compiled-first additionally guarantees byte-identical behavior for every consumer today.Recommended Workflow
Phases: spec → exec → qa
Quality Loop: disabled (SCOPE_OK)
Reasoning:
buglabel with no UI labels → no/test.bug-only → no/testgenper the auto-detection table (the AC-1/AC-3 tests are written inline during exec). Exec should capture the before/after CLI transcript fornpx tsx bin/cli.ts syncas AC-2/AC-3 evidence.Label Review
Current:
bug,cliRecommended: unchanged (+
planned)Reason: no
.tsx/.jsxreferences and no UI labels, so browser testing is already skipped —no-browser-testwould add noise without changing behavior.test(#822): cover init's templates-root guard, not just sync's
admarble commentedon Jul 27, 2026
QA Review for Issue #822
AC Coverage
getTemplatesDir()resolves from compiled + source layouts, unit test pinning both offsetsTEMPLATES_DIR_OFFSETSand are pinned by 6 unit tests via an injectable ranker (import.meta.urlcannot be relocated in-process, so injection is what makes the assertion real rather than "whichever layout vitest happens to use"). Live:tsx bin/cli.ts sync→ 21 skills;node dist/bin/cli.js sync→ 21 skillssync/initexit non-zero naming the missing path; per-subdir skips stay non-fatal1naming/nope/templates, no✔ Synced. Both commands now have integration coverage (init's was added during this review — see Adversarial Re-Read). Second clause pinned byskips absent template subdirectories without failingsyncinstalls spec/exec/qa, not just the markersync-source-invocation.integration.test.tsspawns the real CLI undertsxwithSEQUANT_TEMPLATES_DIRcleared (with the override set the test would pass against the old code)Coverage: 3/3 AC items fully met. Derived ACs: none in spec comment.
AC Literal Verification
Each AC's technical claims were checked against the code, not inferred:
TEMPLATES_DIR_OFFSETS; "unit test pinning both" → separate test per offset, not one test covering the runner's layout.syncandinit→ both verified independently; names "exit non-zero" → exit code1captured from a real process, not inferred from athrow; names "per-subdir skips remain non-fatal" → verified as a preserved behavior with its own test.not.toEqual([".sequant-version"]).Mutation Verification (every new test)
A passing test proves nothing until it can fail. Each was inverted against the code it guards:
TEMPLATES_DIR_OFFSETSexpected [ '.sequant-version' ] to not deeply equal [ '.sequant-version' ]— the exact signature from the issueinit's guard0without it)CI Status
build (22.x)typecheckvalidate-skillsvalidate-pluginnode-floor-guardCI Summary: 5 passed, 0 pending, 0 failed.
mergeStateStatus: CLEAN,mergeable: MERGEABLE. No CI-gated ACs pending.Quality Metrics
any)Test Coverage Analysis
src/lib/templates.tstemplates.test.ts(+175 lines)src/commands/sync.tssync.test.ts+sync-source-invocation.integration.test.tssrc/commands/init.tsinit.test.ts+ integration case added this reviewCoverage: 3/3 changed source files have tests. No critical-path (auth/payment/security) files touched.
Call-Site Review
New exported functions: 2
resolveTemplatesDirFromtemplates.ts:134(insidegetTemplatesDir)assertTemplatesDirExistssync.ts:282,init.ts:130Ordering was verified rather than assumed:
sync's guard sits at line 282, ahead of theskillsVersion === packageVersionfast path — that path diffs against the same missing directory, sees no drift, and would report "already up to date" over an empty tree.init's sits ahead of the--upgrade-skillsbranch, which reads the same directory. Neither export is dead.Execution Evidence
tsx bin/cli.ts syncin a bare projectnode dist/bin/cli.js syncSEQUANT_TEMPLATES_DIR=/nope … sync✔ SyncedSEQUANT_TEMPLATES_DIR=/nope … init --yesEvidence status: Complete. These are post-fix validations, not pre-fix bug reproductions.
Anti-Pattern Detection
No
any, no empty catches masking control flow (both catches are deliberate: a missing/unparseablepackage.jsonlegitimately means "not a positively identified package root", andstatfailure means "not a directory" — each is commented). No hardcoded secrets, no SQL/eval/network patterns.package.jsonunchanged → dependency audit N/A.Performance
getTemplatesDirbecame stat-backed, andgetTemplateContentcalls it once per template file during a drift scan — a path #708 deliberately keeps in the 2–5ms range. Measured before memoizing: 2.10ms per 56-file scan. After: 0.02ms. Mitigated within this PR rather than left as a silent regression.Risk Assessment
templates/exists but its parent holds nopackage.jsonnamedsequant. This does not hard-fail — such a candidate still ranksexistsand is accepted — so the fallback tier is what keeps unknown layouts working. If that tier were ever removed, plugin-style layouts would break.path.join/dirnamethroughout with no path regexes, per the cross-platform guidance.fileURLToPath(import.meta.url)resolver insrc/andbin/—version.ts,manifest.ts,bin/preflight.tswalk up to apackage.jsonnamedsequant;relay/frame.tsandrelay/activation.tswalk up 6 levels probing for their template. All are already robust to thetsxlayout.getTemplatesDirwas the only fixed-offset resolver in the repo — which is precisely why it was the only one that broke. No follow-up issue warranted.templates.ts(join(templatesDir, "skills"|"agents"|"hooks"|"memory"|"scripts"),getTemplateContent) derives fromgetTemplatesDir(), so fixing the root fixes all of them.SKILLS_VERSION_PATHis a cwd-relative constant, unrelated.Adversarial Re-Read
Findings — three surfaced, all resolved:
<repo>/src/libthe compiled offset resolves to<repo>/../templates— so a bare probe would bind to any unrelatedtemplates/sitting beside the checkout. Replaced with a ranked probe anchored on apackage.jsonnamedsequant, keeping a merely-exists fallback for back-compat. Pinned by theignores a stray templates/ beside the repotest. The plan's Design Review had rejected walk-up for over-reach; that reasoning was wrong (the other resolvers gate on the package name), and the ranked probe adopts the correct half of it.syncandinit, but onlysync's failure branch had a regression test —init's was covered solely by the unit mock, which stubs the guard out entirely. Verified by mutation that deletinginit's guard left the suite green. Added a source-invokedinitcase (asserts exit code, the named path, and that nosettings.jsonwas written). Now fails without the guard.bin/cli.tsfor source invocations. With resolution fixed, a source-invoked command in a project with a stale version marker now performs a real auto-sync where it previously no-opped and only bumped the marker — verified live (1 → 22 entries, marker1.0.0→2.9.0). This is restored parity with the compiled binary, which has always done this, not a new risk class. Because it writes, I verified the destructive case explicitly: a customizedconstitution.mdsurvives untouched, so fix(sync): plain sync overwrites CUSTOMIZABLE_FILES (constitution) — copyDir ignores force and never consults isCustomizableFile #814's protection holds on this newly-live path.Process state inspected: worktree clean, 0 commits behind
origin/main, 2 commits ahead, no stray untracked files. Non-Goals checked: distribution layout untouched; #814 handling untouched;SEQUANT_TEMPLATES_DIRstill the unconditional first choice, returned verbatim and never probed — the new guard validates whatever root was resolved (override included), which is what AC-2's "the resolved templates root" asks for. Flagging that as a deliberate, narrow reading rather than leaving it implicit.Status: Clean
CHANGELOG Verification
CHANGELOG.mdexistsfix(#822):)[Unreleased]entry### Fixed, includes(#822)Sections Not Applicable
Skill command / detection-pattern verification (no skill markdown changed), CLI registration verification (no option interfaces touched), browser testing (no
.tsx), manual-test ACs (none in the spec plan), behavior-rule survival check (detector triggered on no AC — AC-2 hits onlyskip, below the 2-keyword threshold), script/verify(noscripts/changes).Verdict: READY_FOR_MERGE
All 3 ACs literally verified with runtime evidence, not code reading alone. Every new test is mutation-proven to fail against the bug it guards, including a full-bug mutation that reproduced the issue's exact signature. Both invocation layouts verified live, CI green across 5 checks, and the one performance regression the fix introduced was measured and mitigated inside the PR. The adversarial pass found three real items — a flaw in the original plan, a test gap on the
inithalf of AC-2, and an unexamined write-path consequence — all closed before this verdict rather than deferred.Documentation
Next Steps
./scripts/cleanup-worktree.sh feature/822-fix-templates-gettemplatesdir-resolves-one-levfix(#822): getTemplatesDir resolves from both compiled and source lay…
fix(#834): anchor AC attribution on the checkbox form — AC-6 routing …
fix(#834): scope AC attribution and drop the gawk-only IGNORECASE
fix(#834): §7 gates must be reachable — lint /qa's own enforcement ch…
fix(#842): tsx-spawning integration tests blow vitest's 5s default — …