@webpieces/rules-config 0.4.609 → 0.4.610
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/state-dir.d.ts +1 -1
- package/src/state-dir.js +5 -6
- package/src/state-dir.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/rules-config",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.610",
|
|
4
4
|
"description": "Shared webpieces.config.json loader. Single source of truth for validation rule configuration consumed by @webpieces/ai-hook-rules, @webpieces/code-rules, and @webpieces/nx-webpieces-rules.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
package/src/state-dir.d.ts
CHANGED
|
@@ -118,7 +118,7 @@ export declare class DotWebpieces {
|
|
|
118
118
|
* nothing else; a stale `hooks/` left by an older release is inert and can be deleted by hand.
|
|
119
119
|
*/
|
|
120
120
|
logs(startDir: string): string;
|
|
121
|
-
/** A path beneath the log directory — `dotWebpieces.logsFile(root,
|
|
121
|
+
/** A path beneath the log directory — `dotWebpieces.logsFile(root, CALLS_STREAM, writerFile)`. */
|
|
122
122
|
logsFile(startDir: string, ...segments: string[]): string;
|
|
123
123
|
/** True when `startDir` sits in a LINKED worktree rather than the primary clone. */
|
|
124
124
|
isLinkedWorktree(startDir: string): boolean;
|
package/src/state-dir.js
CHANGED
|
@@ -23,11 +23,10 @@ exports.WORKTREE_STATE_DIR = 'worktrees';
|
|
|
23
23
|
// reads or writes it.
|
|
24
24
|
//
|
|
25
25
|
// Every writer resolves its DIRECTORY through dotWebpieces.logs()/logsFile(), so the layout cannot
|
|
26
|
-
// drift apart again.
|
|
27
|
-
//
|
|
28
|
-
//
|
|
29
|
-
//
|
|
30
|
-
// them, which gives them the same one-writer-per-name property.
|
|
26
|
+
// drift apart again. What sits INSIDE it is ai-hook-rules' business (see its log-streams.ts and
|
|
27
|
+
// LogStream): one directory per LAYER, and inside that one file per WRITER, named
|
|
28
|
+
// <sessionId>-<agentId|coordinator>-<hook>.log — because Claude Code runs all matching PreToolUse
|
|
29
|
+
// hooks IN PARALLEL and subagents/windows share a tree, so writers must never share a file.
|
|
31
30
|
exports.LOGS_STATE_DIR = 'logs';
|
|
32
31
|
// git prints the shared git dir as `<primary>/.git` for a conventional clone. Anything else (a bare
|
|
33
32
|
// repo, `--separate-git-dir`) is a layout we decline to derive a working tree from.
|
|
@@ -175,7 +174,7 @@ let DotWebpieces = class DotWebpieces {
|
|
|
175
174
|
logs(startDir) {
|
|
176
175
|
return path.join(this.local(startDir), exports.LOGS_STATE_DIR);
|
|
177
176
|
}
|
|
178
|
-
/** A path beneath the log directory — `dotWebpieces.logsFile(root,
|
|
177
|
+
/** A path beneath the log directory — `dotWebpieces.logsFile(root, CALLS_STREAM, writerFile)`. */
|
|
179
178
|
logsFile(startDir, ...segments) {
|
|
180
179
|
return path.join(this.logs(startDir), ...segments);
|
|
181
180
|
}
|
package/src/state-dir.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state-dir.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/state-dir.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,2CAAgD;AAChD,+DAAyD;AAEzD,uGAAuG;AACvG,2FAA2F;AAC3F,8DAA8D;AACjD,QAAA,kBAAkB,GAAG,WAAW,CAAC;AAE9C,kGAAkG;AAClG,iGAAiG;AACjG,mGAAmG;AACnG,iEAAiE;AACjE,EAAE;AACF,0FAA0F;AAC1F,mGAAmG;AACnG,qGAAqG;AACrG,sBAAsB;AACtB,EAAE;AACF,mGAAmG;AACnG,oGAAoG;AACpG,sGAAsG;AACtG,kGAAkG;AAClG,qGAAqG;AACrG,gEAAgE;AACnD,QAAA,cAAc,GAAG,MAAM,CAAC;AAErC,oGAA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B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAQE,sCAAgB;GAP9C,YAAY,CA6IxB;AAED,sGAAsG;AACtG,sGAAsG;AACtG,uFAAuF;AAC1E,QAAA,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { WEBPIECES_TMP_DIR } from './constants';\nimport { StateDirMigrator } from './state-dir-migration';\n\n// The per-worktree namespace inside the primary clone's `.webpieces/`. A LINKED worktree's local state\n// lives at `<primary>/.webpieces/worktrees/<worktreeName>/`; the primary clone keeps using\n// `<primary>/.webpieces/` directly, exactly as it always has.\nexport const WORKTREE_STATE_DIR = 'worktrees';\n\n// The ONE and ONLY directory webpieces writes observability state into — `<state>/logs/`, for the\n// primary clone and for each worktree namespace alike. There is no second state directory and no\n// split: the L1 binary's logs, the L0 sh shim's log, and the rejection DETAIL files (which are not\n// `.log`s but belong to the log that indexes them) are all here.\n//\n// It used to be two directories — `hooks/`, holding the binary's logs mixed in with dated\n// `hooks/<YYYY-MM-DD>/writeInfo-*.md` rejection details, and `logs/`, where the sh shim wrote — so\n// \"where are the logs?\" had two answers and neither was complete. `hooks/` is gone entirely; nothing\n// reads or writes it.\n//\n// Every writer resolves its DIRECTORY through dotWebpieces.logs()/logsFile(), so the layout cannot\n// drift apart again. The FILENAME is a separate question: ai-hook-rules' LogStream prefixes it with\n// <sessionId>-<agentId|coordinator>-<hook>- so that concurrent writers (Claude Code runs all matching\n// PreToolUse hooks IN PARALLEL, and subagents/windows share a tree) never append to one file. The\n// rejection details sit in a DIRECTORY carrying that identical prefix, beside the log that points at\n// them, which gives them the same one-writer-per-name property.\nexport const LOGS_STATE_DIR = 'logs';\n\n// git prints the shared git dir as `<primary>/.git` for a conventional clone. Anything else (a bare\n// repo, `--separate-git-dir`) is a layout we decline to derive a working tree from.\nconst GIT_DIR_NAME = '.git';\n\n/**\n * Data-only carrier for the two paths git is asked for. Per CLAUDE.md: classes for data.\n *\n * `gitDir` is the PER-WORKTREE git dir (`<primary>/.git/worktrees/<name>` in a linked worktree,\n * `<primary>/.git` in the primary clone). `commonDir` is the SHARED one — always `<primary>/.git`.\n * They differ if and only if this is a linked worktree; that is git's own canonical test.\n */\nexport class GitDirs {\n readonly gitDir: string;\n readonly commonDir: string;\n\n constructor(gitDir: string, commonDir: string) {\n this.gitDir = gitDir;\n this.commonDir = commonDir;\n }\n\n get isLinkedWorktree(): boolean {\n return path.resolve(this.gitDir) !== path.resolve(this.commonDir);\n }\n}\n\n/**\n * WHERE a piece of `.webpieces/` state belongs — the ONE resolver every reader and writer must go\n * through, with TWO named methods because there are exactly two answers and a call site must DECLARE\n * which one it means.\n *\n * dotWebpieces.shared(dir) → <primary>/.webpieces (repo-wide facts)\n * dotWebpieces.local(dir) → <primary>/.webpieces/worktrees/<name> (this worktree only)\n * → <primary>/.webpieces (…in the primary clone)\n *\n * ─── The bug ───────────────────────────────────────────────────────────────────────────────────────\n * `.webpieces/` is gitignored, and it was anchored at the directory holding webpieces.config.json —\n * which in a linked worktree is the WORKTREE. So a repo with seven worktrees had SEVEN independent\n * copies of files that describe the WHOLE REPO. `merged-branches.json` holds verdicts for every branch\n * AND every worktree in the repo; N copies is N divergent truths, and the guards read them as fact.\n * Observed in the field: branch-creation-guard asserted \"8 parked local branches\" while\n * `git branch --list` showed ONE — it was reading a cache written before deletions performed from a\n * DIFFERENT worktree — and it then blocked a legitimate `git worktree add` on that fiction.\n *\n * ─── Why two explicit methods and not a symlink ────────────────────────────────────────────────────\n * A `<worktree>/.webpieces` → `<primary>/…/worktrees/<name>` symlink would have left every call site\n * untouched, which is seductive and wrong. Nothing hooks `git worktree add`, so the link needs LAZY\n * creation that also has to handle \"link already exists\", \"link points somewhere else\", and \"a real\n * directory is already there\" — invisible filesystem magic with a Windows failure mode. Worse, the safe\n * way to write a shared file under concurrency is temp-file-then-`rename()`, and `rename(2)` acts on\n * the PATH, not the link: it REPLACES a symlink with a real file. That silently works for one writer\n * and diverges for everyone else — the exact bug being fixed, but invisible. An explicit call is\n * greppable, testable, and forces each site to say which scope it means.\n *\n * ─── Which scope is which (the scope assignment is deliberate, not incidental) ─────────────────────\n * shared():\n * • merged-branches.json — verdicts for every branch and worktree in the repo. Atomically written.\n * • main-sync-status.json AND main-sync.lock.json — there is one `main` and one `.git`, so there is\n * one refresher. A lock inside a per-worktree directory locks nothing.\n * local():\n * • logs/*.log, INCLUDING branch-mutations.log. A shared append-only log genuinely corrupts:\n * `O_APPEND` writes are indivisible only under PIPE_BUF, which is 512 bytes on macOS, and a\n * `recover=git worktree add -b <branch> <abs-path> <tag>` line with real paths exceeds that. A\n * per-worktree log has exactly ONE writer and cannot tear, and under this layout it already\n * survives the worktree's deletion — recovery is one glob over\n * `<primary>/.webpieces/worktrees/*/logs/branch-mutations.log`.\n * • merge-info/staged|merged/<branch>/ and its index.json, pr-review/<branch>/, instruct-ai/, and\n * every other per-tree scratch file.\n *\n * ─── The boundary that must not be blurred ─────────────────────────────────────────────────────────\n * ONLY the gitignored `.webpieces/` STATE relocates. `webpieces.config.json` is TRACKED IN GIT and is\n * therefore part of the BRANCH: a branch may legitimately change its own rules and that must keep\n * working. Config resolution is untouched — still per-worktree, via findConfigFile /\n * RepoRootFinder.resolveRepoRoot. Nothing in this class reads or moves config.\n *\n * ─── Why `--git-dir` / `--git-common-dir`, and not one of the existing services ────────────────────\n * They are git's own answers, from any subdirectory, in one cheap local call, with no `.git`-file\n * parsing by hand (which gets `--separate-git-dir` and submodules wrong). Two existing mechanisms do\n * distinguish primary from linked, and neither is the right authority here:\n * • `WorktreeService` answers \"what worktrees exist and what do they hold\" — a repo-wide ENUMERATION\n * (`git worktree list --porcelain`) for the caps and the reaper. Using it for a path lookup would\n * run an enumeration on the hook's blocking path for every state access, and it fails SOFT to `[]`,\n * which here would read as \"there is no primary clone\" on exactly the degraded repo where the\n * answer matters most. It also does not expose the worktree's git NAME, which is the namespace key.\n * • `EffectiveTreeResolver` (#524) answers \"which tree does this COMMAND act on\" — it takes a command\n * string and is a policy input to the bash guards, not a filesystem-path resolver.\n * Both remain authoritative for their own questions. This asks the narrowest one — two path strings —\n * and lives in rules-config, UNDER both, which is where a primitive that pr-gate, ai-hook-rules and\n * code-rules all need has to sit.\n *\n * Fails CLOSED to the pre-change behaviour: when git cannot answer, every path here collapses to\n * `<startDir-root>/.webpieces` exactly as before. Degrading to merely-suboptimal beats throwing on a\n * hook's blocking path.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class DotWebpieces {\n // treeRoot → git's answer. One `git rev-parse` pair per root per process; every later path lookup\n // in that invocation is a Map hit.\n private readonly gitDirsByRoot = new Map<string, GitDirs | null>();\n // Roots whose legacy per-worktree `.webpieces/` has already been considered for migration.\n private readonly migrated = new Set<string>();\n\n constructor(private readonly migrator: StateDirMigrator = new StateDirMigrator()) {}\n\n /**\n * REPO-WIDE state: `<primary>/.webpieces`. Use ONLY for facts about the repo rather than about one\n * worktree — today that is merged-branches.json and the main-sync status + lock. Identical from\n * every worktree, and never behind an indirection, so an atomic `rename()` into it is safe.\n */\n shared(startDir: string): string {\n return path.join(this.primaryRoot(startDir), WEBPIECES_TMP_DIR);\n }\n\n /** A path beneath the repo-wide state dir. */\n sharedFile(startDir: string, ...segments: string[]): string {\n return path.join(this.shared(startDir), ...segments);\n }\n\n /**\n * THIS WORKTREE's private state: `<primary>/.webpieces/worktrees/<name>` for a linked worktree, and\n * `<primary>/.webpieces` for the primary clone, which keeps its state exactly where it has always\n * been. Fully isolated — two worktrees never write the same path, so nothing here needs a lock.\n *\n * The first call for a linked worktree also MIGRATES a legacy real `<worktree>/.webpieces/`\n * directory into the namespace, so in-flight merge / pr-review state written under the old scheme\n * (or by an older PUBLISHED build during the transition) is picked up rather than orphaned.\n */\n local(startDir: string): string {\n const dirs = this.gitDirs(startDir);\n if (dirs === null || !dirs.isLinkedWorktree) return this.shared(startDir);\n\n const target = path.join(this.shared(startDir), WORKTREE_STATE_DIR, path.basename(dirs.gitDir));\n this.migrateOnce(startDir, target);\n return target;\n }\n\n /** A path beneath this worktree's private state dir. */\n localFile(startDir: string, ...segments: string[]): string {\n return path.join(this.local(startDir), ...segments);\n }\n\n /**\n * THE log directory — `<local()>/logs` — and the only place webpieces writes a `.log` or a log's\n * detail files, in the primary clone and in every worktree namespace alike.\n *\n * There is NO migration here, deliberately. A lazy once-per-process relocation of an older\n * release's `hooks/*.log` used to run on this path, and it was itself the defect it claimed to\n * cure: it only fires in the trees a process happens to re-enter, so it guarantees two answers to\n * \"where are the logs\" indefinitely rather than converging on one. New writes go to `logs/` and\n * nothing else; a stale `hooks/` left by an older release is inert and can be deleted by hand.\n */\n logs(startDir: string): string {\n return path.join(this.local(startDir), LOGS_STATE_DIR);\n }\n\n /** A path beneath the log directory — `dotWebpieces.logsFile(root, 'guard-invocations.log')`. */\n logsFile(startDir: string, ...segments: string[]): string {\n return path.join(this.logs(startDir), ...segments);\n }\n\n /** True when `startDir` sits in a LINKED worktree rather than the primary clone. */\n isLinkedWorktree(startDir: string): boolean {\n const dirs = this.gitDirs(startDir);\n return dirs !== null && dirs.isLinkedWorktree;\n }\n\n /**\n * git's own name for this linked worktree — the basename of `<primary>/.git/worktrees/<name>`, and\n * the namespace key under `worktrees/`. Empty for the primary clone. git's name rather than the\n * directory's basename, so two worktrees checked out into same-named directories under different\n * parents cannot collide.\n */\n worktreeName(startDir: string): string {\n const dirs = this.gitDirs(startDir);\n if (dirs === null || !dirs.isLinkedWorktree) return '';\n return path.basename(dirs.gitDir);\n }\n\n /** The primary clone's root, from any worktree. Falls back to git's toplevel-less best guess. */\n primaryRoot(startDir: string): string {\n const dirs = this.gitDirs(startDir);\n if (dirs === null) return startDir;\n if (path.basename(dirs.commonDir) !== GIT_DIR_NAME) return startDir;\n const primary = path.dirname(dirs.commonDir);\n return fs.existsSync(primary) ? primary : startDir;\n }\n\n /**\n * The PRE-change location, `<treeRoot>/.webpieces` — what every call site used to compute. Public\n * because the migrator and its specs must be able to name the thing being migrated FROM, and\n * because the transition-window fallback readers need it.\n */\n legacyDir(treeRoot: string): string {\n return path.join(treeRoot, WEBPIECES_TMP_DIR);\n }\n\n // Drain a legacy per-worktree `.webpieces/` into this worktree's namespace, at most once per tree\n // per process. Migration is idempotent, but it touches the filesystem on the hook's blocking path.\n private migrateOnce(startDir: string, target: string): void {\n // Guard on the CHEAP key first. `local()` is called many times per invocation, and resolving the\n // worktree toplevel costs a `git rev-parse` — doing that before the once-check would put a\n // process spawn on the hook's blocking path for every single state-path lookup.\n if (this.migrated.has(startDir)) return;\n this.migrated.add(startDir);\n const toplevel = this.gitToplevel(startDir);\n if (toplevel === null) return;\n this.migrator.migrate(this.legacyDir(toplevel), target);\n }\n\n // Both git dirs for `startDir`, cached, or null when this is not a git repo / git is unavailable.\n // `status !== 0` IS the expected \"not a repo\" answer (spawnSync does not throw on a non-zero exit),\n // so there is no try/catch here swallowing a real git crash. Mirrors RepoRootFinder.gitToplevel.\n private gitDirs(startDir: string): GitDirs | null {\n const cached = this.gitDirsByRoot.get(startDir);\n if (cached !== undefined) return cached;\n\n const gitDir = this.revParse(startDir, '--git-dir');\n const commonDir = this.revParse(startDir, '--git-common-dir');\n const dirs = gitDir === null || commonDir === null ? null : new GitDirs(gitDir, commonDir);\n this.gitDirsByRoot.set(startDir, dirs);\n return dirs;\n }\n\n private gitToplevel(startDir: string): string | null {\n return this.revParse(startDir, '--show-toplevel');\n }\n\n // One `git rev-parse <flag>`, resolved to an absolute path (git prints a bare `.git`, relative to\n // the tree, in the primary clone, and an absolute path from a linked worktree).\n private revParse(cwd: string, flag: string): string | null {\n const result = spawnSync('git', ['-C', cwd, 'rev-parse', flag], { encoding: 'utf8' });\n if (result.status !== 0) return null;\n const printed = (result.stdout ?? '').trim();\n if (printed === '') return null;\n return path.resolve(cwd, printed);\n }\n}\n\n// Process-wide instance for the many non-DI call sites (hooks, detached refreshers, wp-* bins, eslint\n// rules). Sharing one instance is what makes the git-resolution cache and the once-per-tree migration\n// worth having; inversify still injects the singleton wherever a container is in play.\nexport const dotWebpieces = new DotWebpieces();\n"]}
|
|
1
|
+
{"version":3,"file":"state-dir.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/state-dir.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE3D,2CAAgD;AAChD,+DAAyD;AAEzD,uGAAuG;AACvG,2FAA2F;AAC3F,8DAA8D;AACjD,QAAA,kBAAkB,GAAG,WAAW,CAAC;AAE9C,kGAAkG;AAClG,iGAAiG;AACjG,mGAAmG;AACnG,iEAAiE;AACjE,EAAE;AACF,0FAA0F;AAC1F,mGAAmG;AACnG,qGAAqG;AACrG,sBAAsB;AACtB,EAAE;AACF,mGAAmG;AACnG,gGAAgG;AAChG,kFAAkF;AAClF,kGAAkG;AAClG,4FAA4F;AAC/E,QAAA,cAAc,GAAG,MAAM,CAAC;AAGrC,oGAAoG;AACpG,oFAAoF;AACpF,MAAM,YAAY,GAAG,MAAM,CAAC;AAE5B;;;;;;GAMG;AACH,MAAa,OAAO;IACP,MAAM,CAAS;IACf,SAAS,CAAS;IAE3B,YAAY,MAAc,EAAE,SAAiB;QACzC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC/B,CAAC;IAED,IAAI,gBAAgB;QAChB,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACtE,CAAC;CACJ;AAZD,0BAYC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmEG;AAEI,IAAM,YAAY,GAAlB,MAAM,YAAY;IAOQ;IAN7B,kGAAkG;IAClG,mCAAmC;IAClB,a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AAO,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,iBAAiB,CAAC,CAAC;IACtD,CAAC;IAED,kGAAkG;IAClG,gFAAgF;IACxE,QAAQ,CAAC,GAAW,EAAE,IAAY;QACtC,MAAM,MAAM,GAAG,IAAA,yBAAS,EAAC,KAAK,EAAE,CAAC,IAAI,EAAE,GAAG,EAAE,WAAW,EAAE,IAAI,CAAC,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;QACtF,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QACrC,MAAM,OAAO,GAAG,CAAC,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;QAC7C,IAAI,OAAO,KAAK,EAAE;YAAE,OAAO,IAAI,CAAC;QAChC,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IACtC,CAAC;CACJ,CAAA;AA7IY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAQE,sCAAgB;GAP9C,YAAY,CA6IxB;AAED,sGAAsG;AACtG,sGAAsG;AACtG,uFAAuF;AAC1E,QAAA,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC","sourcesContent":["import { spawnSync } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { WEBPIECES_TMP_DIR } from './constants';\nimport { StateDirMigrator } from './state-dir-migration';\n\n// The per-worktree namespace inside the primary clone's `.webpieces/`. A LINKED worktree's local state\n// lives at `<primary>/.webpieces/worktrees/<worktreeName>/`; the primary clone keeps using\n// `<primary>/.webpieces/` directly, exactly as it always has.\nexport const WORKTREE_STATE_DIR = 'worktrees';\n\n// The ONE and ONLY directory webpieces writes observability state into — `<state>/logs/`, for the\n// primary clone and for each worktree namespace alike. There is no second state directory and no\n// split: the L1 binary's logs, the L0 sh shim's log, and the rejection DETAIL files (which are not\n// `.log`s but belong to the log that indexes them) are all here.\n//\n// It used to be two directories — `hooks/`, holding the binary's logs mixed in with dated\n// `hooks/<YYYY-MM-DD>/writeInfo-*.md` rejection details, and `logs/`, where the sh shim wrote — so\n// \"where are the logs?\" had two answers and neither was complete. `hooks/` is gone entirely; nothing\n// reads or writes it.\n//\n// Every writer resolves its DIRECTORY through dotWebpieces.logs()/logsFile(), so the layout cannot\n// drift apart again. What sits INSIDE it is ai-hook-rules' business (see its log-streams.ts and\n// LogStream): one directory per LAYER, and inside that one file per WRITER, named\n// <sessionId>-<agentId|coordinator>-<hook>.log — because Claude Code runs all matching PreToolUse\n// hooks IN PARALLEL and subagents/windows share a tree, so writers must never share a file.\nexport const LOGS_STATE_DIR = 'logs';\n\n\n// git prints the shared git dir as `<primary>/.git` for a conventional clone. Anything else (a bare\n// repo, `--separate-git-dir`) is a layout we decline to derive a working tree from.\nconst GIT_DIR_NAME = '.git';\n\n/**\n * Data-only carrier for the two paths git is asked for. Per CLAUDE.md: classes for data.\n *\n * `gitDir` is the PER-WORKTREE git dir (`<primary>/.git/worktrees/<name>` in a linked worktree,\n * `<primary>/.git` in the primary clone). `commonDir` is the SHARED one — always `<primary>/.git`.\n * They differ if and only if this is a linked worktree; that is git's own canonical test.\n */\nexport class GitDirs {\n readonly gitDir: string;\n readonly commonDir: string;\n\n constructor(gitDir: string, commonDir: string) {\n this.gitDir = gitDir;\n this.commonDir = commonDir;\n }\n\n get isLinkedWorktree(): boolean {\n return path.resolve(this.gitDir) !== path.resolve(this.commonDir);\n }\n}\n\n/**\n * WHERE a piece of `.webpieces/` state belongs — the ONE resolver every reader and writer must go\n * through, with TWO named methods because there are exactly two answers and a call site must DECLARE\n * which one it means.\n *\n * dotWebpieces.shared(dir) → <primary>/.webpieces (repo-wide facts)\n * dotWebpieces.local(dir) → <primary>/.webpieces/worktrees/<name> (this worktree only)\n * → <primary>/.webpieces (…in the primary clone)\n *\n * ─── The bug ───────────────────────────────────────────────────────────────────────────────────────\n * `.webpieces/` is gitignored, and it was anchored at the directory holding webpieces.config.json —\n * which in a linked worktree is the WORKTREE. So a repo with seven worktrees had SEVEN independent\n * copies of files that describe the WHOLE REPO. `merged-branches.json` holds verdicts for every branch\n * AND every worktree in the repo; N copies is N divergent truths, and the guards read them as fact.\n * Observed in the field: branch-creation-guard asserted \"8 parked local branches\" while\n * `git branch --list` showed ONE — it was reading a cache written before deletions performed from a\n * DIFFERENT worktree — and it then blocked a legitimate `git worktree add` on that fiction.\n *\n * ─── Why two explicit methods and not a symlink ────────────────────────────────────────────────────\n * A `<worktree>/.webpieces` → `<primary>/…/worktrees/<name>` symlink would have left every call site\n * untouched, which is seductive and wrong. Nothing hooks `git worktree add`, so the link needs LAZY\n * creation that also has to handle \"link already exists\", \"link points somewhere else\", and \"a real\n * directory is already there\" — invisible filesystem magic with a Windows failure mode. Worse, the safe\n * way to write a shared file under concurrency is temp-file-then-`rename()`, and `rename(2)` acts on\n * the PATH, not the link: it REPLACES a symlink with a real file. That silently works for one writer\n * and diverges for everyone else — the exact bug being fixed, but invisible. An explicit call is\n * greppable, testable, and forces each site to say which scope it means.\n *\n * ─── Which scope is which (the scope assignment is deliberate, not incidental) ─────────────────────\n * shared():\n * • merged-branches.json — verdicts for every branch and worktree in the repo. Atomically written.\n * • main-sync-status.json AND main-sync.lock.json — there is one `main` and one `.git`, so there is\n * one refresher. A lock inside a per-worktree directory locks nothing.\n * local():\n * • logs/*.log, INCLUDING branch-mutations.log. A shared append-only log genuinely corrupts:\n * `O_APPEND` writes are indivisible only under PIPE_BUF, which is 512 bytes on macOS, and a\n * `recover=git worktree add -b <branch> <abs-path> <tag>` line with real paths exceeds that. A\n * per-worktree log has exactly ONE writer and cannot tear, and under this layout it already\n * survives the worktree's deletion — recovery is one glob over\n * `<primary>/.webpieces/worktrees/*/logs/branch-mutations.log`.\n * • merge-info/staged|merged/<branch>/ and its index.json, pr-review/<branch>/, instruct-ai/, and\n * every other per-tree scratch file.\n *\n * ─── The boundary that must not be blurred ─────────────────────────────────────────────────────────\n * ONLY the gitignored `.webpieces/` STATE relocates. `webpieces.config.json` is TRACKED IN GIT and is\n * therefore part of the BRANCH: a branch may legitimately change its own rules and that must keep\n * working. Config resolution is untouched — still per-worktree, via findConfigFile /\n * RepoRootFinder.resolveRepoRoot. Nothing in this class reads or moves config.\n *\n * ─── Why `--git-dir` / `--git-common-dir`, and not one of the existing services ────────────────────\n * They are git's own answers, from any subdirectory, in one cheap local call, with no `.git`-file\n * parsing by hand (which gets `--separate-git-dir` and submodules wrong). Two existing mechanisms do\n * distinguish primary from linked, and neither is the right authority here:\n * • `WorktreeService` answers \"what worktrees exist and what do they hold\" — a repo-wide ENUMERATION\n * (`git worktree list --porcelain`) for the caps and the reaper. Using it for a path lookup would\n * run an enumeration on the hook's blocking path for every state access, and it fails SOFT to `[]`,\n * which here would read as \"there is no primary clone\" on exactly the degraded repo where the\n * answer matters most. It also does not expose the worktree's git NAME, which is the namespace key.\n * • `EffectiveTreeResolver` (#524) answers \"which tree does this COMMAND act on\" — it takes a command\n * string and is a policy input to the bash guards, not a filesystem-path resolver.\n * Both remain authoritative for their own questions. This asks the narrowest one — two path strings —\n * and lives in rules-config, UNDER both, which is where a primitive that pr-gate, ai-hook-rules and\n * code-rules all need has to sit.\n *\n * Fails CLOSED to the pre-change behaviour: when git cannot answer, every path here collapses to\n * `<startDir-root>/.webpieces` exactly as before. Degrading to merely-suboptimal beats throwing on a\n * hook's blocking path.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class DotWebpieces {\n // treeRoot → git's answer. One `git rev-parse` pair per root per process; every later path lookup\n // in that invocation is a Map hit.\n private readonly gitDirsByRoot = new Map<string, GitDirs | null>();\n // Roots whose legacy per-worktree `.webpieces/` has already been considered for migration.\n private readonly migrated = new Set<string>();\n\n constructor(private readonly migrator: StateDirMigrator = new StateDirMigrator()) {}\n\n /**\n * REPO-WIDE state: `<primary>/.webpieces`. Use ONLY for facts about the repo rather than about one\n * worktree — today that is merged-branches.json and the main-sync status + lock. Identical from\n * every worktree, and never behind an indirection, so an atomic `rename()` into it is safe.\n */\n shared(startDir: string): string {\n return path.join(this.primaryRoot(startDir), WEBPIECES_TMP_DIR);\n }\n\n /** A path beneath the repo-wide state dir. */\n sharedFile(startDir: string, ...segments: string[]): string {\n return path.join(this.shared(startDir), ...segments);\n }\n\n /**\n * THIS WORKTREE's private state: `<primary>/.webpieces/worktrees/<name>` for a linked worktree, and\n * `<primary>/.webpieces` for the primary clone, which keeps its state exactly where it has always\n * been. Fully isolated — two worktrees never write the same path, so nothing here needs a lock.\n *\n * The first call for a linked worktree also MIGRATES a legacy real `<worktree>/.webpieces/`\n * directory into the namespace, so in-flight merge / pr-review state written under the old scheme\n * (or by an older PUBLISHED build during the transition) is picked up rather than orphaned.\n */\n local(startDir: string): string {\n const dirs = this.gitDirs(startDir);\n if (dirs === null || !dirs.isLinkedWorktree) return this.shared(startDir);\n\n const target = path.join(this.shared(startDir), WORKTREE_STATE_DIR, path.basename(dirs.gitDir));\n this.migrateOnce(startDir, target);\n return target;\n }\n\n /** A path beneath this worktree's private state dir. */\n localFile(startDir: string, ...segments: string[]): string {\n return path.join(this.local(startDir), ...segments);\n }\n\n /**\n * THE log directory — `<local()>/logs` — and the only place webpieces writes a `.log` or a log's\n * detail files, in the primary clone and in every worktree namespace alike.\n *\n * There is NO migration here, deliberately. A lazy once-per-process relocation of an older\n * release's `hooks/*.log` used to run on this path, and it was itself the defect it claimed to\n * cure: it only fires in the trees a process happens to re-enter, so it guarantees two answers to\n * \"where are the logs\" indefinitely rather than converging on one. New writes go to `logs/` and\n * nothing else; a stale `hooks/` left by an older release is inert and can be deleted by hand.\n */\n logs(startDir: string): string {\n return path.join(this.local(startDir), LOGS_STATE_DIR);\n }\n\n /** A path beneath the log directory — `dotWebpieces.logsFile(root, CALLS_STREAM, writerFile)`. */\n logsFile(startDir: string, ...segments: string[]): string {\n return path.join(this.logs(startDir), ...segments);\n }\n\n /** True when `startDir` sits in a LINKED worktree rather than the primary clone. */\n isLinkedWorktree(startDir: string): boolean {\n const dirs = this.gitDirs(startDir);\n return dirs !== null && dirs.isLinkedWorktree;\n }\n\n /**\n * git's own name for this linked worktree — the basename of `<primary>/.git/worktrees/<name>`, and\n * the namespace key under `worktrees/`. Empty for the primary clone. git's name rather than the\n * directory's basename, so two worktrees checked out into same-named directories under different\n * parents cannot collide.\n */\n worktreeName(startDir: string): string {\n const dirs = this.gitDirs(startDir);\n if (dirs === null || !dirs.isLinkedWorktree) return '';\n return path.basename(dirs.gitDir);\n }\n\n /** The primary clone's root, from any worktree. Falls back to git's toplevel-less best guess. */\n primaryRoot(startDir: string): string {\n const dirs = this.gitDirs(startDir);\n if (dirs === null) return startDir;\n if (path.basename(dirs.commonDir) !== GIT_DIR_NAME) return startDir;\n const primary = path.dirname(dirs.commonDir);\n return fs.existsSync(primary) ? primary : startDir;\n }\n\n /**\n * The PRE-change location, `<treeRoot>/.webpieces` — what every call site used to compute. Public\n * because the migrator and its specs must be able to name the thing being migrated FROM, and\n * because the transition-window fallback readers need it.\n */\n legacyDir(treeRoot: string): string {\n return path.join(treeRoot, WEBPIECES_TMP_DIR);\n }\n\n // Drain a legacy per-worktree `.webpieces/` into this worktree's namespace, at most once per tree\n // per process. Migration is idempotent, but it touches the filesystem on the hook's blocking path.\n private migrateOnce(startDir: string, target: string): void {\n // Guard on the CHEAP key first. `local()` is called many times per invocation, and resolving the\n // worktree toplevel costs a `git rev-parse` — doing that before the once-check would put a\n // process spawn on the hook's blocking path for every single state-path lookup.\n if (this.migrated.has(startDir)) return;\n this.migrated.add(startDir);\n const toplevel = this.gitToplevel(startDir);\n if (toplevel === null) return;\n this.migrator.migrate(this.legacyDir(toplevel), target);\n }\n\n // Both git dirs for `startDir`, cached, or null when this is not a git repo / git is unavailable.\n // `status !== 0` IS the expected \"not a repo\" answer (spawnSync does not throw on a non-zero exit),\n // so there is no try/catch here swallowing a real git crash. Mirrors RepoRootFinder.gitToplevel.\n private gitDirs(startDir: string): GitDirs | null {\n const cached = this.gitDirsByRoot.get(startDir);\n if (cached !== undefined) return cached;\n\n const gitDir = this.revParse(startDir, '--git-dir');\n const commonDir = this.revParse(startDir, '--git-common-dir');\n const dirs = gitDir === null || commonDir === null ? null : new GitDirs(gitDir, commonDir);\n this.gitDirsByRoot.set(startDir, dirs);\n return dirs;\n }\n\n private gitToplevel(startDir: string): string | null {\n return this.revParse(startDir, '--show-toplevel');\n }\n\n // One `git rev-parse <flag>`, resolved to an absolute path (git prints a bare `.git`, relative to\n // the tree, in the primary clone, and an absolute path from a linked worktree).\n private revParse(cwd: string, flag: string): string | null {\n const result = spawnSync('git', ['-C', cwd, 'rev-parse', flag], { encoding: 'utf8' });\n if (result.status !== 0) return null;\n const printed = (result.stdout ?? '').trim();\n if (printed === '') return null;\n return path.resolve(cwd, printed);\n }\n}\n\n// Process-wide instance for the many non-DI call sites (hooks, detached refreshers, wp-* bins, eslint\n// rules). Sharing one instance is what makes the git-resolution cache and the once-per-tree migration\n// worth having; inversify still injects the singleton wherever a container is in play.\nexport const dotWebpieces = new DotWebpieces();\n"]}
|