Skip to content

test(ownership-gate): register writeFile sites individually — per-function keying, await-only match and arrow-const writers let a new destination through (#1090 follow-up) #1106

Closed

Description

@admarble

What happens

#1090's ownership gate has two sides. Side (b) asserts that an explicit NON_TEMPLATE_DESTINATIONS list is exhaustive against the writeFile( targets in init.ts, sync.ts and update.ts. Its QA (PR #1105) found the scan is coarser than the claim, in three ways that are all latent today (verified 0 occurrences) but are exactly the recurrence paths for the clobbering class:

  1. Keyed by enclosing function, deduped by site. A second await writeFile( added inside an already-registered function, writing a new destination, passes silently. Today every registered function writes one destination (upgradeSkills's two both target .claude/skills/).
  2. Matches await writeFile( only. A non-awaited writeFile( (fire-and-forget, or void writeFile(...)) is not scanned.
  3. Enclosing-function regex matches top-level function declarations only. A writer added as const foo = async () => { … } inherits the previous function's key.

Deferred out of #1090 on the runner's call so that PR stays reviewable.

Fix shape (open to spec)

Register per write site, not per function: each writeFile( occurrence (awaited or not, in any function form) maps to the destination expression it writes, and every distinct destination must resolve to a declared policy. A fixture-driven test with a synthetic source string covering the three shapes above keeps the gate honest without touching the real writers.

Release-graph plan — guard-2026-09 (2026-09-20)

Graph: guard-2026-09 Tier: mechanical Wave: 1
May touch: new src/lib/ownership-gate.ts (the per-site scan helper) and new src/lib/ownership-gate.test.ts (the three synthetic cases + the real-writer run); src/lib/templates.test.ts only to delete the old side-(b) block (#1053 appends cases to this file in the same wave, PLAN D-9); CHANGELOG.md

The npm run build && npm test AC is verified by the runner from a clean shell after the PR opens (PLAN I-1); the agent runs only the test files its ACs name. Mutation markers use failedTest starting with the test file path (I-4). #1090 merged as PR #1105, so no blocker remains. The AC-1 command npx vitest run src/lib -t "1106" still matches the new file.

Acceptance Criteria

  • AC-1: gate side (b) registers every writeFile( call site individually, awaited or not — Evidence: npx vitest run src/lib -t "1106" 2>&1 | grep -E "Tests +([3-9]|[1-9][0-9]+) passed" prints a passed line (AC-1..AC-3 are three cases named with 1106, each feeding a synthetic source string to the scan and asserting the undeclared destination is named in the failure)
  • AC-2: a second write inside an already-registered function, to a new destination, fails the gate naming that destination — Evidence: covered by the AC-1 command, as its own case
  • AC-3: a writer declared as const name = async () => {…} is attributed to itself, not to the preceding function — Evidence: covered by the AC-1 command, as its own case
  • AC-4: the real three writers still pass the tightened gate unchanged, or every newly surfaced destination is declared — Evidence: npx vitest run src/lib/templates.test.ts -t "ownership policy covers" 2>&1 | grep -E "Tests +[2-9][0-9]* passed" prints a passed line

AC-1 is a gate test: mutation-verify (revert the scan to await writeFile( only → AC-1's non-awaited case fails) and record the marker with failedTest starting with the test file path.

Activity

  1. added
    enhancement
    on Sep 19, 2026
  2. admarble commented on Sep 20, 2026

    @admarble
    ContributorAuthor

    Runner context — guard-2026-09 launch, 2026-09-20. Base: origin/main at da9ed6e8 (2.16.0 plus the plan docs). These rules override the exec skill's defaults for this run:

    • No full npm test in the worktree. Run only the test files this issue's ACs name. The runner runs the full suite once per PR from a clean shell. Under sequant run the suite is not hermetic against SEQUANT_* (bug(test): suite isn't hermetic against the SEQUANT_* env phases inject — exec sees red tests it didn't cause and opens no PR #1086), so a full run shows red files you did not cause.
    • A named test file red before your change: re-run it as env -u SEQUANT_ORCHESTRATOR -u SEQUANT_WORKTREE -u SEQUANT_PHASE -u SEQUANT_ISSUE -u SEQUANT_RELAY -u SEQUANT_RELAY_FRAME npx vitest run <file>. If it is still red, the PR body names the issue number and the base-vs-head result for that test.
    • Mutation marker (gate-test ACs): <!-- SEQUANT_MUTATION: {"ac":"AC-N","mutation":"<what you deleted>","failedTest":"<test file path> > <describe> > <case>"} --> in the PR body. failedTest MUST start with the test file path, or the qa classifier reports it Failed. Commit before mutating.
    • 30-minute no-progress wall per phase. Commit a WIP checkpoint before any long command; every command foreground, with timeout.
    • Commits: single-line git commit -m "...", no Co-Authored-By. Never rebase or force-push after pushing. One AC per line in the PR body, ids AC-N only.
    • Stop at the PR. Do not merge.

    Issue-specific: In src/lib/templates.test.ts delete the old side-(b) block only; #1053 appends cases at the end of the same file concurrently, so touch nothing else there. The scan helper and its tests are new files (src/lib/ownership-gate.ts, src/lib/ownership-gate.test.ts).

  3. admarble commented on Sep 20, 2026

    @admarble
    ContributorAuthor

    Complexity: Standard (4 ACs, 2 directories)

    AC Quality Check

    No vague/unmeasurable/open-ended wording. AC-2 and AC-3 are "covered by the AC-1 command", so they have no independent count; AC-1's [3-9]|[1-9][0-9]+ passed floor is what proves all three cases exist. ⚠️ AC-4 cannot pass as written. See Open Question 1.


    Scope Assessment

    Non-Goals: not stated. Inferred from "May touch": no changes to the real writers (init.ts/sync.ts/update.ts), no changes to templates.ts, and nothing in templates.test.ts beyond removing side (b).

    Metric Value Status
    Feature count 1 (per-site write scan) ✅
    AC items 4 ✅
    Directory spread 2 (src/lib, root CHANGELOG.md) ✅

    Verdict: ✅ SCOPE_OK


    Acceptance Criteria

    AC-1: every writeFile( site registered individually, awaited or not

    Verification: Unit Test
    Scenario: Given a synthetic source with void writeFile(join(d,"x.json"), …) (no await) and no matching registry entry → When the scan + check run → Then the failure names x.json's destination expression.
    Assumptions: Case names contain 1106. The command runs -t "1106" across all of src/lib, so no other test there may carry that string.

    AC-2: second write in a registered function, to a new destination, fails

    Verification: Unit Test
    Scenario: Given a synthetic function registered for join(d,"a") that also writes join(d,"b") → Then the gate fails naming join(d,"b").

    AC-3: const name = async () => {…} attributed to itself

    Verification: Unit Test
    Scenario: Given a top-level function first(){…} followed by const second = async () => { await writeFile(…) } → Then the site key is …#second, not …#first.

    AC-4: real writers pass the tightened gate unchanged (or new destinations are declared)

    Verification: Integration Test (reads the real init.ts/sync.ts/update.ts)
    Scenario: Given the current sources → When the real-writer run executes → Then no undeclared site or destination, and the run is a test whose name matches ownership policy covers.
    Assumptions: ⚠️ see Open Question 1.


    Implementation Plan

    Phase 1: the scan helper — src/lib/ownership-gate.ts (new)

    1. scanWriteSites(source, file) → { site: "file#fn", destination: "<normalized first-arg expr>", line }[]. Match \bwriteFile\s*\( (awaited, void, bare, fs.writeFile). Parse the first argument with balanced parens/brackets, skipping string/template/comment contents. This also covers the multi-line calls at init.ts:294 and :953, where the destination is on the next line.
    2. Attribute each site to its enclosing named function with a brace-depth scope stack, not "last function line seen". Recognise function f, async function f, export …, and const|let f = [async] (…) => / = [async] function. Anonymous callbacks inherit the enclosing named scope. This fixes shape 3, and also a nested closure inheriting the wrong key after an inner function closes.
    3. checkWriteSites(sites, registry, declared) → { undeclaredSites, undeclaredDestinations }. The registry is keyed file#fn#destExpr → destination. A second write with a new expression in a registered function therefore has no entry and is reported by expression. Two sites with the same expression dedupe legitimately.

    Phase 2: tests — src/lib/ownership-gate.test.ts (new)

    1. Three #1106 cases (AC-1, AC-2, AC-3) on synthetic strings; each asserts the failure message names the destination/expression.
    2. Real-writer run: scan the three real files, then move the registry table, DECIDED and b3 assertions across from templates.test.ts unchanged in meaning. The registry is re-keyed per site (about 13 entries; upgradeSkills's two sites are already distinct expressions). Guard the guard: assert scanWriteSites finds exactly as many sites as a naive /\bwriteFile\(/g count of the same file, so a tokenizer mistake (e.g. a regex literal containing a quote) fails loudly rather than silently dropping sites.

    Phase 3: retire the old block, changelog

    1. In templates.test.ts remove only the side-(b) it(…) (lines ~232–354). fileURLToPath, NON_TEMPLATE_DESTINATIONS and OwnershipPolicy (lines 12, 27, 29) become unused; drop them so npm run lint --max-warnings 0 stays green. fix(sync): copy-mode sync leaves existing machine-specific scripts/dev symlinks in place, and doctor's hint loops back to sync #1053 only appends after line ~1215, so the two edits don't overlap textually.
    2. CHANGELOG.md Unreleased entry.

    Mutation record (AC-1, gate test): commit first, then revert the match to await writeFile( only → the AC-1 non-awaited case must fail. Marker: failedTest = src/lib/ownership-gate.test.ts > <describe> > <case>. Also mutate the enclosing-scope logic to last-function-line → AC-3 must fail; and remove one registry entry → the real-writer run must fail.


    Design Review

    1. Where does this logic belong? A pure helper in src/lib/ownership-gate.ts (string in → sites out), so synthetic fixtures need no filesystem. Only tests import it, so it ships in dist but has no runtime caller.
    2. Simplest correct approach? A small tokenizer + scope stack. Rejected: a TypeScript-AST walk (the typescript package is available, but this is a dev-time gate, and adding an AST dependency to src/lib is heavier than a ~80-line scanner with a count cross-check); keeping the line-regex and patching the three shapes one by one (the same class of hole returns at the next shape).
    3. Existing pattern? The current side-(b) static scan, made per-site; the two-sided gate design from fix(sync/init/update): one ownership rule for project files — the clobbering class fixed file-by-file in #708/#814/#990/#1042/#1071/#1078 #1090 is unchanged.
    4. What would a reviewer challenge? "Why not the TS compiler API?" (above). "Expression-keyed registry is brittle to renames." Deliberate: a renamed destination variable must be re-declared, which is the point of the gate.

    Feature Quality Planning

    Standard checks pass. Notable items:


    Open Questions

    1. AC-4 as written can't pass once the block is deleted. -t "ownership policy covers" matches by full name, including the describe ownership policy covers every destination sequant writes. Baseline is Tests 2 passed (side a + side b). After deleting side (b) only side (a) remains: Tests 1 passed, and the [2-9][0-9]* grep doesn't match (the command also runs templates.test.ts only, not the new file). Recommendation: in place of a bare deletion, leave a thin side-(b) it in that describe that calls the new helper on the real writers (same describe name, so the AC-4 command counts it) and keep the heavy fixtures in the new file. This adds a few lines inside the deleted block's range rather than touching anything else in that file. Alternative: amend AC-4 to point at src/lib/ownership-gate.test.ts -t "ownership policy covers" and require the real-writer run there to be named so. Impact if unresolved: /qa gets a false AC_NOT_MET or the exec agent silently games the count.
    2. Widen to other write primitives / other writer files? Recommendation: no, file a follow-up. Impact: latent hole remains for appendFile/writeFileSync, but 0 occurrences today.

    Recommended Workflow

    Phases: exec → qa
    Quality Loop: disabled
    Reasoning: Tests are the deliverable, so testgen stubs would duplicate what exec writes. Test-only change; no UI, no security surface. Runner context (comment above) applies: run only the named test files, no full suite in the worktree.

    Label Review

    Current: enhancement
    Recommended: enhancement, planned
    Quality Loop: won't auto-enable (SCOPE_OK)

  4. added
    planned
    on Sep 20, 2026
  5. admarble commented on Sep 20, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    AC coverage: 0/7 met

    Gaps:

    • The spec-directed follow-up issue for widening the ownership gate beyond writeFile( was never filed, leaving a latent (0 live occurrences today) coverage hole untracked
    • The guard-the-guard count cross-check can fail on a comment or string mentioning writeFile( in a real writer, with a message that blames the scanner instead
    • Residual silent-pass hole: same function plus same destination expression text but a different actual destination is not caught by the tightened gate
  6. added 3 commits that reference 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

    enhancementplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions