Skip to content

fix(templates): getTemplatesDir resolves one level too high under tsx — source-run sync/init prints "✔ Synced" while installing nothing #822

Closed

Description

@admarble

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:

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 bundled templates/ correctly from both the compiled layout (dist/src/lib) and a source-tree tsx invocation (src/lib), with a unit test pinning both offsets.
  • AC-2: sync and init exit non-zero naming the missing path when the resolved templates root does not exist, instead of printing ✔ Synced after copyDir's silent ENOENT skip; per-subdir skips (e.g. a stack without memory/) remain non-fatal.
  • AC-3: A regression test asserts that a source-invoked sync against a bare project installs the core skills (spec, exec, qa), not just the .sequant-version marker.

Non-Goals

Activity

  1. added
    bug
    cli
    on Jul 27, 2026
  2. admarble commented on Jul 27, 2026

    @admarble
    ContributorAuthor

    Plan (/spec)

    Complexity: Standard (3 ACs, 2 directories)

    Reproduction (evidence, not theory)

    src/lib     + ../../../templates → /Users/tony/Projects/templates          MISSING  ← the bug
    src/lib     + ../../templates    → /Users/tony/Projects/sequant/templates  exists
    dist/src/lib+ ../../../templates → /Users/tony/Projects/sequant/templates  exists
    dist/src/lib+ ../../templates    → /Users/tony/Projects/sequant/dist/templates  absent (build emits bin/, dashboard/, marketplace/, src/ only)
    

    Both layouts are unambiguous and non-overlapping, so a compiled-first ordered probe is deterministic.

    AC Quality Check

    AC Verdict
    AC-1 ⚠️ "correctly" is vague in isolation — but the parenthetical pins both concrete offsets, so it is measurable as written. No refinement needed.
    AC-2 ✅
    AC-3 ✅

    Scope Assessment

    Non-Goals (from issue): distribution layout, SEQUANT_TEMPLATES_DIR semantics, #814 customizable-files handling.

    Metric Value Status
    Feature count 1 (path resolution + loud failure) ✅
    AC items 3 ✅
    Directory spread 2 (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) or src/lib (tsx) → When getTemplatesDir() runs → Then it returns the package-root templates/ in both cases.
    Design note: __dirname cannot be faked in-process, so the offset table is extracted into a pure, injectable helper resolveTemplatesDirFrom(baseDir, exists). getTemplatesDir() becomes env 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/init exit 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 → When sequant sync runs → Then exit ≠ 0 and output contains /nope, and no ✔ Synced is printed. Given a templates tree with skills/ but no memory/ → When copyTemplates runs → Then it succeeds (per-subdir ENOENT skip preserved).
    Assumption: the guard must run before sync's skillsVersion === packageVersion fast path — that path calls computeTemplateChanges against 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 sync on a bare project installs spec/exec/qa.
    Verification: Integration Test
    Scenario: Given a temp project with a seeded manifest and an empty .claude/skills/ → When node_modules/.bin/tsx bin/cli.ts sync runs with SEQUANT_TEMPLATES_DIR unset → Then exit 0 and .claude/skills/{spec,exec,qa}/SKILL.md all 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)

    1. src/lib/templates.ts: extract resolveTemplatesDirFrom(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.
    2. getTemplatesDir() keeps SEQUANT_TEMPLATES_DIR as the unconditional first choice (Non-Goal: semantics unchanged — no existence probe on the override at resolution time).
    3. Unit tests in src/lib/templates.test.ts: compiled base, source base, neither-exists fallback, env override precedence, plus one live check that the real getTemplatesDir() points at a dir containing skills/.

    Phase 2 — Loud failure (AC-2)
    4. src/lib/templates.ts: add assertTemplatesDirExists(): Promise<string> — resolves, checks the root exists, throws an Error naming the path and mentioning SEQUANT_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 without memory/.

    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 the spawnSync(tsxBin, [cliSource, ...]) pattern from src/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

    1. Where does this logic belong? src/lib/templates.ts — it already owns resolution; both commands are thin consumers. No new module.
    2. Simplest correct approach? A two-entry ordered probe. Rejected: rewriting getTemplatesDir in the codebase's other idiom (see Q3) — a walk-up would, in a consumer project whose node_modules/sequant/templates is genuinely missing, climb out of the package and bind to the consumer's own templates/ directory. Silently wrong beats loudly broken only until it doesn't; the bounded probe cannot over-reach, and it is what the issue proposes.
    3. What existing pattern does this follow? Sibling scan (fileURLToPath(import.meta.url) across src/, bin/): version.ts, manifest.ts, bin/preflight.ts walk up to a package.json named sequant; relay/frame.ts and relay/activation.ts walk up 6 levels probing for the template. getTemplatesDir is 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.
    4. What would a senior reviewer challenge? (a) "Why not just fix the offset to 2-up?" — that breaks every compiled consumer. (b) "Isn't the unit test tautological?" — answered by the injectable-helper design in AC-1. (c) "Does the guard make doctor/pre-flight throw?" — no: checkAndWarnSkillsOutdated and computeDriftFingerprint already swallow failures and are out of AC-2's scope; only sync and init get the hard gate.

    Feature Quality Planning

    All standard checks pass. Notable:

    • src/commands/sync.test.ts mocks getTemplatesDir → "/pkg/templates" (a path that does not exist). Adding the guard to syncCommand will trip it unless assertTemplatesDirExists is added to that vi.mock factory. Known blast radius — must be handled in exec, not discovered in CI.
    • The new integration test must seed a manifest; sync bails early with "not initialized" otherwise, which would pass for the wrong reason.

    Open Questions

    1. Probe order — compiled first or source first? Recommendation: compiled first. Impact if wrong: none in practice — dist/templates does 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: bug label with no UI labels → no /test. bug-only → no /testgen per the auto-detection table (the AC-1/AC-3 tests are written inline during exec). Exec should capture the before/after CLI transcript for npx tsx bin/cli.ts sync as AC-2/AC-3 evidence.

    Label Review

    Current: bug, cli
    Recommended: unchanged (+ planned)
    Reason: no .tsx/.jsx references and no UI labels, so browser testing is already skipped — no-browser-test would add noise without changing behavior.

  3. added
    planned
    on Jul 27, 2026
  4. added a commit that references this issue on Jul 27, 2026
  5. admarble commented on Jul 27, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #822

    AC Coverage

    AC Source Description Status Notes
    AC-1 Original getTemplatesDir() resolves from compiled + source layouts, unit test pinning both offsets MET Both offsets live in TEMPLATES_DIR_OFFSETS and are pinned by 6 unit tests via an injectable ranker (import.meta.url cannot 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 skills
    AC-2 Original sync/init exit non-zero naming the missing path; per-subdir skips stay non-fatal MET Live: both exit 1 naming /nope/templates, no ✔ Synced. Both commands now have integration coverage (init's was added during this review — see Adversarial Re-Read). Second clause pinned by skips absent template subdirectories without failing
    AC-3 Original Regression test: source-invoked sync installs spec/exec/qa, not just the marker MET sync-source-invocation.integration.test.ts spawns the real CLI under tsx with SEQUANT_TEMPLATES_DIR cleared (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:

    • AC-1 names two concrete offsets → both present verbatim in TEMPLATES_DIR_OFFSETS; "unit test pinning both" → separate test per offset, not one test covering the runner's layout.
    • AC-2 names sync and init → both verified independently; names "exit non-zero" → exit code 1 captured from a real process, not inferred from a throw; names "per-subdir skips remain non-fatal" → verified as a preserved behavior with its own test.
    • AC-3 names spec, exec, qa specifically → asserted per-skill, plus the exact bug signature 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:

    Mutation Result
    Remove the source offset from TEMPLATES_DIR_OFFSETS 3 tests fail, incl. the live-filesystem one
    Restore the original one-line bug and remove the guard (full pre-fix state) AC-3 test fails with expected [ '.sequant-version' ] to not deeply equal [ '.sequant-version' ] — the exact signature from the issue
    Remove init's guard New init test fails (init exits 0 without it)

    CI Status

    Check State Conclusion Impact
    build (22.x) COMPLETED SUCCESS ✅ MET
    typecheck COMPLETED SUCCESS ✅ MET
    validate-skills COMPLETED SUCCESS ✅ MET
    validate-plugin COMPLETED SUCCESS ✅ MET
    node-floor-guard COMPLETED SUCCESS ✅ MET

    CI Summary: 5 passed, 0 pending, 0 failed. mergeStateStatus: CLEAN, mergeable: MERGEABLE. No CI-gated ACs pending.


    Quality Metrics

    Metric Value Status
    Type issues (any) 0 OK
    Deleted tests 0 OK
    Files changed 8 OK
    Lines added +479 -
    Lines deleted -8 -
    Build / Lint / Tests clean / clean / 4275 passed, 1 expected fail, 2 skipped (206 files) OK

    Test Coverage Analysis

    Changed File Tier Has Tests?
    src/lib/templates.ts Standard ✅ templates.test.ts (+175 lines)
    src/commands/sync.ts Standard ✅ sync.test.ts + sync-source-invocation.integration.test.ts
    src/commands/init.ts Standard ✅ init.test.ts + integration case added this review

    Coverage: 3/3 changed source files have tests. No critical-path (auth/payment/security) files touched.


    Call-Site Review

    New exported functions: 2

    Function Call Sites Loop? Conditions AC Match
    resolveTemplatesDirFrom templates.ts:134 (inside getTemplatesDir) No Behind the memo + env-override checks ✅ AC-1
    assertTemplatesDirExists sync.ts:282, init.ts:130 No Unconditional, before any read/write ✅ AC-2

    Ordering was verified rather than assumed: sync's guard sits at line 282, ahead of the skillsVersion === packageVersion fast 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-skills branch, which reads the same directory. Neither export is dead.


    Execution Evidence

    Test Command Result
    Source invocation (the bug) tsx bin/cli.ts sync in a bare project ✅ exit 0, 21 skills installed (was: marker only)
    Compiled invocation (regression guard) node dist/bin/cli.js sync ✅ exit 0, 21 skills — unregressed
    Missing root, sync SEQUANT_TEMPLATES_DIR=/nope … sync ✅ exit 1, path named, no ✔ Synced
    Missing root, init SEQUANT_TEMPLATES_DIR=/nope … init --yes ✅ exit 1, path named

    Evidence 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/unparseable package.json legitimately means "not a positively identified package root", and stat failure means "not a directory" — each is commented). No hardcoded secrets, no SQL/eval/network patterns. package.json unchanged → dependency audit N/A.


    Performance

    getTemplatesDir became stat-backed, and getTemplateContent calls 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

    • Likely failure mode: A distribution layout where templates/ exists but its parent holds no package.json named sequant. This does not hard-fail — such a candidate still ranks exists and is accepted — so the fallback tier is what keeps unknown layouts working. If that tier were ever removed, plugin-style layouts would break.
    • Not tested: Windows path behavior is unexercised (no CI runner). Risk is low — resolution uses path.join/dirname throughout with no path regexes, per the cross-platform guidance.
    • Sibling sites considered (cross-file): Audited every fileURLToPath(import.meta.url) resolver in src/ and bin/ — version.ts, manifest.ts, bin/preflight.ts walk up to a package.json named sequant; relay/frame.ts and relay/activation.ts walk up 6 levels probing for their template. All are already robust to the tsx layout. getTemplatesDir was the only fixed-offset resolver in the repo — which is precisely why it was the only one that broke. No follow-up issue warranted.
    • Sibling-line audit (intra-file): Every other path construction in templates.ts (join(templatesDir, "skills"|"agents"|"hooks"|"memory"|"scripts"), getTemplateContent) derives from getTemplatesDir(), so fixing the root fixes all of them. SKILLS_VERSION_PATH is a cwd-relative constant, unrelated.

    Adversarial Re-Read

    Findings — three surfaced, all resolved:

    1. Design flaw in my own plan, caught while writing the tests. The plan called for a bare existence probe. From <repo>/src/lib the compiled offset resolves to <repo>/../templates — so a bare probe would bind to any unrelated templates/ sitting beside the checkout. Replaced with a ranked probe anchored on a package.json named sequant, keeping a merely-exists fallback for back-compat. Pinned by the ignores a stray templates/ beside the repo test. 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.
    2. AC-2 test gap. AC-2 names sync and init, but only sync'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 deleting init's guard left the suite green. Added a source-invoked init case (asserts exit code, the named path, and that no settings.json was written). Now fails without the guard.
    3. Untested consequence of the fix. The same root cause silently disabled the post-command auto-sync in bin/cli.ts for 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, marker 1.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 customized constitution.md survives 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_DIR still 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

    Check Status
    CHANGELOG.md exists ✅ Found
    User-facing change ✅ Yes (fix(#822):)
    [Unreleased] entry ✅ Present under ### 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 only skip, below the 2-keyword threshold), script /verify (no scripts/ 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 init half of AC-2, and an unexamined write-path consequence — all closed before this verdict rather than deferred.

    Documentation

    • CHANGELOG entry added
    • N/A — no README/docs change needed: consumers were never affected, and no user-facing flag or command was added

    Next Steps

    1. Merge PR fix(#822): getTemplatesDir resolves from both compiled and source layouts #829
    2. ./scripts/cleanup-worktree.sh feature/822-fix-templates-gettemplatesdir-resolves-one-lev
  6. added
    ready-for-review
    on Jul 27, 2026
  7. added a commit that references this issue on Jul 27, 2026
  8. added 4 commits that reference this issue on Jul 28, 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

    bugcliplannedready-for-review

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions