@webpieces/tooling-common 0.0.1
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 +31 -0
- package/src/atomic-file.d.ts +46 -0
- package/src/atomic-file.js +114 -0
- package/src/atomic-file.js.map +1 -0
- package/src/claude-config-dir.d.ts +62 -0
- package/src/claude-config-dir.js +87 -0
- package/src/claude-config-dir.js.map +1 -0
- package/src/index.d.ts +6 -0
- package/src/index.js +10 -0
- package/src/index.js.map +1 -0
- package/src/inform-ai-error.d.ts +6 -0
- package/src/inform-ai-error.js +13 -0
- package/src/inform-ai-error.js.map +1 -0
- package/src/state-dir-migration.d.ts +79 -0
- package/src/state-dir-migration.js +185 -0
- package/src/state-dir-migration.js.map +1 -0
- package/src/state-dir.d.ts +209 -0
- package/src/state-dir.js +349 -0
- package/src/state-dir.js.map +1 -0
- package/src/state-path-constants.d.ts +2 -0
- package/src/state-path-constants.js +6 -0
- package/src/state-path-constants.js.map +1 -0
- package/src/to-error.d.ts +1 -0
- package/src/to-error.js +10 -0
- package/src/to-error.js.map +1 -0
package/src/state-dir.js
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.dotWebpieces = exports.DotWebpieces = exports.GitDirs = exports.AI_WRITABLE_STATE_DIRS = exports.LOGS_STATE_DIR = exports.WORKTREE_STATE_DIR = void 0;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
const child_process_1 = require("child_process");
|
|
6
|
+
const fs = tslib_1.__importStar(require("fs"));
|
|
7
|
+
const path = tslib_1.__importStar(require("path"));
|
|
8
|
+
const inversify_1 = require("inversify");
|
|
9
|
+
const state_path_constants_1 = require("./state-path-constants");
|
|
10
|
+
const state_dir_migration_1 = require("./state-dir-migration");
|
|
11
|
+
// The per-worktree namespace inside the primary clone's `.webpieces/`. A LINKED worktree's local state
|
|
12
|
+
// lives at `<primary>/.webpieces/worktrees/<worktreeName>/`; the primary clone keeps using
|
|
13
|
+
// `<primary>/.webpieces/` directly, exactly as it always has.
|
|
14
|
+
exports.WORKTREE_STATE_DIR = 'worktrees';
|
|
15
|
+
// The ONE and ONLY directory webpieces writes observability state into — `<state>/logs/`, for the
|
|
16
|
+
// primary clone and for each worktree namespace alike. There is no second state directory and no
|
|
17
|
+
// split: the L1 binary's logs, the L0 sh shim's log, and the rejection DETAIL files (which are not
|
|
18
|
+
// `.log`s but belong to the log that indexes them) are all here.
|
|
19
|
+
//
|
|
20
|
+
// It used to be two directories — `hooks/`, holding the binary's logs mixed in with dated
|
|
21
|
+
// `hooks/<YYYY-MM-DD>/writeInfo-*.md` rejection details, and `logs/`, where the sh shim wrote — so
|
|
22
|
+
// "where are the logs?" had two answers and neither was complete. `hooks/` is gone entirely; nothing
|
|
23
|
+
// reads or writes it.
|
|
24
|
+
//
|
|
25
|
+
// Every writer resolves its DIRECTORY through dotWebpieces.logs()/logsFile(), so the layout cannot
|
|
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.
|
|
30
|
+
exports.LOGS_STATE_DIR = 'logs';
|
|
31
|
+
// The leaves of `.webpieces/` that resolve through `aiWritable()` and therefore live in the WORKTREE's
|
|
32
|
+
// own root rather than in the primary clone's namespace. Named here because TWO things must agree about
|
|
33
|
+
// them: `aiWritable()`, which puts them there, and `StateDirMigrator`, which must NOT sweep them out
|
|
34
|
+
// again (its whole job is draining `<worktree>/.webpieces` into the namespace, and these are the one
|
|
35
|
+
// part of that directory that is live rather than legacy).
|
|
36
|
+
exports.AI_WRITABLE_STATE_DIRS = [state_path_constants_1.PR_REVIEW_DIR];
|
|
37
|
+
// git prints the shared git dir as `<primary>/.git` for a conventional clone. Anything else (a bare
|
|
38
|
+
// repo, `--separate-git-dir`) is a layout we decline to derive a working tree from.
|
|
39
|
+
const GIT_DIR_NAME = '.git';
|
|
40
|
+
/**
|
|
41
|
+
* Data-only carrier for the two paths git is asked for. Per CLAUDE.md: classes for data.
|
|
42
|
+
*
|
|
43
|
+
* `gitDir` is the PER-WORKTREE git dir (`<primary>/.git/worktrees/<name>` in a linked worktree,
|
|
44
|
+
* `<primary>/.git` in the primary clone). `commonDir` is the SHARED one — always `<primary>/.git`.
|
|
45
|
+
* They differ if and only if this is a linked worktree; that is git's own canonical test.
|
|
46
|
+
*/
|
|
47
|
+
class GitDirs {
|
|
48
|
+
gitDir;
|
|
49
|
+
commonDir;
|
|
50
|
+
constructor(gitDir, commonDir) {
|
|
51
|
+
this.gitDir = gitDir;
|
|
52
|
+
this.commonDir = commonDir;
|
|
53
|
+
}
|
|
54
|
+
get isLinkedWorktree() {
|
|
55
|
+
return path.resolve(this.gitDir) !== path.resolve(this.commonDir);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
exports.GitDirs = GitDirs;
|
|
59
|
+
/**
|
|
60
|
+
* WHERE a piece of `.webpieces/` state belongs — the ONE resolver every reader and writer must go
|
|
61
|
+
* through, with THREE named methods because there are exactly three answers and a call site must DECLARE
|
|
62
|
+
* which one it means.
|
|
63
|
+
*
|
|
64
|
+
* dotWebpieces.shared(dir) → <primary>/.webpieces (repo-wide facts)
|
|
65
|
+
* dotWebpieces.local(dir) → <primary>/.webpieces/worktrees/<name> (this worktree only, tooling-written)
|
|
66
|
+
* → <primary>/.webpieces (…in the primary clone)
|
|
67
|
+
* dotWebpieces.aiWritable(dir) → <worktree>/.webpieces (this worktree only, AI-WRITTEN)
|
|
68
|
+
* → <primary>/.webpieces (…in the primary clone)
|
|
69
|
+
*
|
|
70
|
+
* ─── The bug ───────────────────────────────────────────────────────────────────────────────────────
|
|
71
|
+
* `.webpieces/` is gitignored, and it was anchored at the directory holding webpieces.config.json —
|
|
72
|
+
* which in a linked worktree is the WORKTREE. So a repo with seven worktrees had SEVEN independent
|
|
73
|
+
* copies of files that describe the WHOLE REPO. `merged-branches.json` holds verdicts for every branch
|
|
74
|
+
* AND every worktree in the repo; N copies is N divergent truths, and the guards read them as fact.
|
|
75
|
+
* Observed in the field: branch-creation-guard asserted "8 parked local branches" while
|
|
76
|
+
* `git branch --list` showed ONE — it was reading a cache written before deletions performed from a
|
|
77
|
+
* DIFFERENT worktree — and it then blocked a legitimate `git worktree add` on that fiction.
|
|
78
|
+
*
|
|
79
|
+
* ─── Why two explicit methods and not a symlink ────────────────────────────────────────────────────
|
|
80
|
+
* A `<worktree>/.webpieces` → `<primary>/…/worktrees/<name>` symlink would have left every call site
|
|
81
|
+
* untouched, which is seductive and wrong. Nothing hooks `git worktree add`, so the link needs LAZY
|
|
82
|
+
* creation that also has to handle "link already exists", "link points somewhere else", and "a real
|
|
83
|
+
* directory is already there" — invisible filesystem magic with a Windows failure mode. Worse, the safe
|
|
84
|
+
* way to write a shared file under concurrency is temp-file-then-`rename()`, and `rename(2)` acts on
|
|
85
|
+
* the PATH, not the link: it REPLACES a symlink with a real file. That silently works for one writer
|
|
86
|
+
* and diverges for everyone else — the exact bug being fixed, but invisible. An explicit call is
|
|
87
|
+
* greppable, testable, and forces each site to say which scope it means.
|
|
88
|
+
*
|
|
89
|
+
* ─── Which scope is which (the scope assignment is deliberate, not incidental) ─────────────────────
|
|
90
|
+
* shared():
|
|
91
|
+
* • merged-branches.json — verdicts for every branch and worktree in the repo. Atomically written.
|
|
92
|
+
* • main-sync-status.json AND main-sync.lock.json — there is one `main` and one `.git`, so there is
|
|
93
|
+
* one refresher. A lock inside a per-worktree directory locks nothing.
|
|
94
|
+
* local():
|
|
95
|
+
* • logs/*.log, INCLUDING branch-mutations.log. A shared append-only log genuinely corrupts:
|
|
96
|
+
* `O_APPEND` writes are indivisible only under PIPE_BUF, which is 512 bytes on macOS, and a
|
|
97
|
+
* `recover=git worktree add -b <branch> <abs-path> <tag>` line with real paths exceeds that. A
|
|
98
|
+
* per-worktree log has exactly ONE writer and cannot tear, and under this layout it already
|
|
99
|
+
* survives the worktree's deletion — recovery is one glob over
|
|
100
|
+
* `<primary>/.webpieces/worktrees/*/logs/branch-mutations.log`.
|
|
101
|
+
* • merge-info/staged|merged/<branch>/ and its index.json, instruct-ai/, and every other per-tree
|
|
102
|
+
* scratch file that the TOOLING writes.
|
|
103
|
+
* aiWritable():
|
|
104
|
+
* • pr-review/<branch>/ — and ONLY that, today. See the section below.
|
|
105
|
+
*
|
|
106
|
+
* ─── Why aiWritable() is a third scope and not a spelling of local() ──────────────────────────────
|
|
107
|
+
* `pr-review/<branch>/` is the one state directory a CODING AGENT writes into with its own file-write
|
|
108
|
+
* tool: `summary.json` is authored by the agent running the flow, and `review-round<N>-<id>.json` by each reviewer
|
|
109
|
+
* subagent. A worktree-isolated agent may write ONLY inside its own worktree — its harness refuses any
|
|
110
|
+
* Write/Edit whose path is under the shared checkout, with "This agent is isolated in the worktree …;
|
|
111
|
+
* edit the worktree copy of this file instead". That refusal is not ours to relax.
|
|
112
|
+
*
|
|
113
|
+
* So `local()` — correct for everything the tooling writes — is UNREACHABLE for the two files the flow
|
|
114
|
+
* asks an agent to write. Stage ② printed a `<primary>/.webpieces/worktrees/<name>/pr-review/…` path,
|
|
115
|
+
* the agent's Write was refused at exactly that path, and the only way through was `cp`/`>` from Bash
|
|
116
|
+
* (which is NOT blocked, so the refusal looks arbitrary rather than structural). Three separate agents
|
|
117
|
+
* hit it, each concluded the tooling was printing a path it did not use, and each invented its own
|
|
118
|
+
* workaround. Worse, the same refusal lands on every reviewer subagent's `review-round<N>-<id>.json`, and
|
|
119
|
+
* `wp-finish-upsert-pr` REFUSES the PR while a required checklist has no verdict — so this was a
|
|
120
|
+
* correctness bug, not an ergonomics one.
|
|
121
|
+
*
|
|
122
|
+
* The invariant, stated once: ANY `.webpieces/` path an AI AGENT is instructed to WRITE must resolve
|
|
123
|
+
* inside that agent's own working tree. `aiWritable()` is that rule, made greppable. Do not add a
|
|
124
|
+
* fourth scope; do not route a tooling-written file through this one.
|
|
125
|
+
*
|
|
126
|
+
* What it costs is what `local()` bought: a `pr-review/` under the worktree dies with the worktree.
|
|
127
|
+
* That is the right trade for THIS directory and only this one — a review is spent the moment the PR is
|
|
128
|
+
* posted, and `pnpm wp-review-upsert-pr` regenerates the whole directory from git in one run. An
|
|
129
|
+
* in-flight `merge-info/staged/<branch>/` is not regenerable, which is exactly why it stays on local().
|
|
130
|
+
*
|
|
131
|
+
* ─── The boundary that must not be blurred ─────────────────────────────────────────────────────────
|
|
132
|
+
* ONLY the gitignored `.webpieces/` STATE relocates. `webpieces.config.json` is TRACKED IN GIT and is
|
|
133
|
+
* therefore part of the BRANCH: a branch may legitimately change its own rules and that must keep
|
|
134
|
+
* working. Config resolution is untouched — still per-worktree, via findConfigFile /
|
|
135
|
+
* RepoRootFinder.resolveRepoRoot. Nothing in this class reads or moves config.
|
|
136
|
+
*
|
|
137
|
+
* ─── Why `--git-dir` / `--git-common-dir`, and not one of the existing services ────────────────────
|
|
138
|
+
* They are git's own answers, from any subdirectory, in one cheap local call, with no `.git`-file
|
|
139
|
+
* parsing by hand (which gets `--separate-git-dir` and submodules wrong). Two existing mechanisms do
|
|
140
|
+
* distinguish primary from linked, and neither is the right authority here:
|
|
141
|
+
* • `WorktreeService` answers "what worktrees exist and what do they hold" — a repo-wide ENUMERATION
|
|
142
|
+
* (`git worktree list --porcelain`) for the caps and the reaper. Using it for a path lookup would
|
|
143
|
+
* run an enumeration on the hook's blocking path for every state access, and it fails SOFT to `[]`,
|
|
144
|
+
* which here would read as "there is no primary clone" on exactly the degraded repo where the
|
|
145
|
+
* answer matters most. It also does not expose the worktree's git NAME, which is the namespace key.
|
|
146
|
+
* • `EffectiveTreeResolver` (#524) answers "which tree does this COMMAND act on" — it takes a command
|
|
147
|
+
* string and is a policy input to the bash guards, not a filesystem-path resolver.
|
|
148
|
+
* Both remain authoritative for their own questions. This asks the narrowest one — two path strings —
|
|
149
|
+
* and lives in rules-config, UNDER both, which is where a primitive that pr-gate, ai-hook-rules and
|
|
150
|
+
* code-rules all need has to sit.
|
|
151
|
+
*
|
|
152
|
+
* Fails CLOSED to the pre-change behaviour: when git cannot answer, every path here collapses to
|
|
153
|
+
* `<startDir-root>/.webpieces` exactly as before. Degrading to merely-suboptimal beats throwing on a
|
|
154
|
+
* hook's blocking path.
|
|
155
|
+
*/
|
|
156
|
+
let DotWebpieces = class DotWebpieces {
|
|
157
|
+
migrator;
|
|
158
|
+
// treeRoot → git's answer. One `git rev-parse` pair per root per process; every later path lookup
|
|
159
|
+
// in that invocation is a Map hit.
|
|
160
|
+
gitDirsByRoot = new Map();
|
|
161
|
+
// startDir → `git rev-parse --show-toplevel`, cached on the same terms as gitDirsByRoot.
|
|
162
|
+
treeRootByDir = new Map();
|
|
163
|
+
// Roots whose legacy per-worktree `.webpieces/` has already been considered for migration.
|
|
164
|
+
migrated = new Set();
|
|
165
|
+
constructor(migrator = new state_dir_migration_1.StateDirMigrator()) {
|
|
166
|
+
this.migrator = migrator;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* REPO-WIDE state: `<primary>/.webpieces`. Use ONLY for facts about the repo rather than about one
|
|
170
|
+
* worktree — today that is merged-branches.json and the main-sync status + lock. Identical from
|
|
171
|
+
* every worktree, and never behind an indirection, so an atomic `rename()` into it is safe.
|
|
172
|
+
*/
|
|
173
|
+
shared(startDir) {
|
|
174
|
+
return path.join(this.primaryRoot(startDir), state_path_constants_1.WEBPIECES_TMP_DIR);
|
|
175
|
+
}
|
|
176
|
+
/** A path beneath the repo-wide state dir. */
|
|
177
|
+
sharedFile(startDir, ...segments) {
|
|
178
|
+
return path.join(this.shared(startDir), ...segments);
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* THIS WORKTREE's private state: `<primary>/.webpieces/worktrees/<name>` for a linked worktree, and
|
|
182
|
+
* `<primary>/.webpieces` for the primary clone, which keeps its state exactly where it has always
|
|
183
|
+
* been. Fully isolated — two worktrees never write the same path, so nothing here needs a lock.
|
|
184
|
+
*
|
|
185
|
+
* The first call for a linked worktree also MIGRATES a legacy real `<worktree>/.webpieces/`
|
|
186
|
+
* directory into the namespace, so in-flight merge / pr-review state written under the old scheme
|
|
187
|
+
* (or by an older PUBLISHED build during the transition) is picked up rather than orphaned.
|
|
188
|
+
*/
|
|
189
|
+
local(startDir) {
|
|
190
|
+
const dirs = this.gitDirs(startDir);
|
|
191
|
+
if (dirs === null || !dirs.isLinkedWorktree)
|
|
192
|
+
return this.shared(startDir);
|
|
193
|
+
const target = path.join(this.shared(startDir), exports.WORKTREE_STATE_DIR, path.basename(dirs.gitDir));
|
|
194
|
+
this.migrateOnce(startDir, target);
|
|
195
|
+
return target;
|
|
196
|
+
}
|
|
197
|
+
/** A path beneath this worktree's private state dir. */
|
|
198
|
+
localFile(startDir, ...segments) {
|
|
199
|
+
return path.join(this.local(startDir), ...segments);
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* State an AI AGENT writes with its own file-write tool: `<worktree>/.webpieces` — the worktree's
|
|
203
|
+
* OWN root, which is the only place a worktree-isolated agent is permitted to write. Identical to
|
|
204
|
+
* `shared()`/`local()` in the primary clone, so nothing changes for a repo without worktrees.
|
|
205
|
+
*
|
|
206
|
+
* See the "Why aiWritable() is a third scope" section above before adding a call site: this is for
|
|
207
|
+
* files the flow ASKS AN AGENT TO WRITE, not for tooling output that an agent merely reads.
|
|
208
|
+
*/
|
|
209
|
+
aiWritable(startDir) {
|
|
210
|
+
const toplevel = this.treeRoot(startDir);
|
|
211
|
+
// Fails CLOSED to shared() when git cannot answer, on the same terms as every other path here.
|
|
212
|
+
if (toplevel === null)
|
|
213
|
+
return this.shared(startDir);
|
|
214
|
+
return path.join(toplevel, state_path_constants_1.WEBPIECES_TMP_DIR);
|
|
215
|
+
}
|
|
216
|
+
/** A path beneath the AI-writable state dir. */
|
|
217
|
+
aiWritableFile(startDir, ...segments) {
|
|
218
|
+
return path.join(this.aiWritable(startDir), ...segments);
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* THE log directory — `<local()>/logs` — and the only place webpieces writes a `.log` or a log's
|
|
222
|
+
* detail files, in the primary clone and in every worktree namespace alike.
|
|
223
|
+
*
|
|
224
|
+
* There is NO migration here, deliberately. A lazy once-per-process relocation of an older
|
|
225
|
+
* release's `hooks/*.log` used to run on this path, and it was itself the defect it claimed to
|
|
226
|
+
* cure: it only fires in the trees a process happens to re-enter, so it guarantees two answers to
|
|
227
|
+
* "where are the logs" indefinitely rather than converging on one. New writes go to `logs/` and
|
|
228
|
+
* nothing else; a stale `hooks/` left by an older release is inert and can be deleted by hand.
|
|
229
|
+
*/
|
|
230
|
+
logs(startDir) {
|
|
231
|
+
return path.join(this.local(startDir), exports.LOGS_STATE_DIR);
|
|
232
|
+
}
|
|
233
|
+
/** A path beneath the log directory — `dotWebpieces.logsFile(root, CALLS_STREAM, writerFile)`. */
|
|
234
|
+
logsFile(startDir, ...segments) {
|
|
235
|
+
return path.join(this.logs(startDir), ...segments);
|
|
236
|
+
}
|
|
237
|
+
/** True when `startDir` sits in a LINKED worktree rather than the primary clone. */
|
|
238
|
+
isLinkedWorktree(startDir) {
|
|
239
|
+
const dirs = this.gitDirs(startDir);
|
|
240
|
+
return dirs !== null && dirs.isLinkedWorktree;
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* git's two dir answers for `startDir`, memoized — null when it is not a git repo / git is
|
|
244
|
+
* unavailable.
|
|
245
|
+
*
|
|
246
|
+
* PUBLIC because TREE IDENTITY is decided from these two strings and nothing else. `commonDir`
|
|
247
|
+
* is the same for every checkout of ONE repo, so `commonDir(a) === commonDir(b)` is "same repo,
|
|
248
|
+
* different placement" — the test that tells a linked worktree (ours, wherever it sits, including
|
|
249
|
+
* inside the repo at `.claude/worktrees/**`) from a nested clone under `repositories/**` (not
|
|
250
|
+
* ours). `gitDirs.isLinkedWorktree` then separates primary from linked. See
|
|
251
|
+
* `EffectiveTreeResolver.classify`, the caller that runs this on the hook's blocking path, which is
|
|
252
|
+
* why it goes through this cache rather than spawning its own `rev-parse`.
|
|
253
|
+
*/
|
|
254
|
+
gitDirs(startDir) {
|
|
255
|
+
const cached = this.gitDirsByRoot.get(startDir);
|
|
256
|
+
if (cached !== undefined)
|
|
257
|
+
return cached;
|
|
258
|
+
const gitDir = this.revParse(startDir, '--git-dir');
|
|
259
|
+
const commonDir = this.revParse(startDir, '--git-common-dir');
|
|
260
|
+
const dirs = gitDir === null || commonDir === null ? null : new GitDirs(gitDir, commonDir);
|
|
261
|
+
this.gitDirsByRoot.set(startDir, dirs);
|
|
262
|
+
return dirs;
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* The WORKING TREE root containing `startDir` (`git rev-parse --show-toplevel`), memoized, or null
|
|
266
|
+
* when `startDir` is not in a git repo. In a linked worktree this is the WORKTREE's own root, which
|
|
267
|
+
* is exactly what a caller judging "which checkout am I standing in" needs.
|
|
268
|
+
*
|
|
269
|
+
* THE ONE tree-root resolver. There used to be three byte-identical `spawnSync … --show-toplevel`
|
|
270
|
+
* copies — this one, `RepoRootFinder`'s and `effective-tree.ts`'s — each commenting that it
|
|
271
|
+
* "mirrors" one of the others, and one of those comments was already stale. Both copies are deleted;
|
|
272
|
+
* everything that needs a tree root calls this. Do not add a fourth.
|
|
273
|
+
*/
|
|
274
|
+
treeRoot(startDir) {
|
|
275
|
+
const cached = this.treeRootByDir.get(startDir);
|
|
276
|
+
if (cached !== undefined)
|
|
277
|
+
return cached;
|
|
278
|
+
// `status !== 0` IS the expected "not a repo" answer (spawnSync does not throw on a non-zero
|
|
279
|
+
// exit), so nothing here swallows a real git crash.
|
|
280
|
+
const root = this.revParse(startDir, '--show-toplevel');
|
|
281
|
+
this.treeRootByDir.set(startDir, root);
|
|
282
|
+
return root;
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* git's own name for this linked worktree — the basename of `<primary>/.git/worktrees/<name>`, and
|
|
286
|
+
* the namespace key under `worktrees/`. Empty for the primary clone. git's name rather than the
|
|
287
|
+
* directory's basename, so two worktrees checked out into same-named directories under different
|
|
288
|
+
* parents cannot collide.
|
|
289
|
+
*/
|
|
290
|
+
worktreeName(startDir) {
|
|
291
|
+
const dirs = this.gitDirs(startDir);
|
|
292
|
+
if (dirs === null || !dirs.isLinkedWorktree)
|
|
293
|
+
return '';
|
|
294
|
+
return path.basename(dirs.gitDir);
|
|
295
|
+
}
|
|
296
|
+
/** The primary clone's root, from any worktree. Falls back to git's toplevel-less best guess. */
|
|
297
|
+
primaryRoot(startDir) {
|
|
298
|
+
const dirs = this.gitDirs(startDir);
|
|
299
|
+
if (dirs === null)
|
|
300
|
+
return startDir;
|
|
301
|
+
if (path.basename(dirs.commonDir) !== GIT_DIR_NAME)
|
|
302
|
+
return startDir;
|
|
303
|
+
const primary = path.dirname(dirs.commonDir);
|
|
304
|
+
return fs.existsSync(primary) ? primary : startDir;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* The PRE-change location, `<treeRoot>/.webpieces` — what every call site used to compute. Public
|
|
308
|
+
* because the migrator and its specs must be able to name the thing being migrated FROM, and
|
|
309
|
+
* because the transition-window fallback readers need it.
|
|
310
|
+
*/
|
|
311
|
+
legacyDir(treeRoot) {
|
|
312
|
+
return path.join(treeRoot, state_path_constants_1.WEBPIECES_TMP_DIR);
|
|
313
|
+
}
|
|
314
|
+
// Drain a legacy per-worktree `.webpieces/` into this worktree's namespace, at most once per tree
|
|
315
|
+
// per process. Migration is idempotent, but it touches the filesystem on the hook's blocking path.
|
|
316
|
+
migrateOnce(startDir, target) {
|
|
317
|
+
// Guard on the CHEAP key first. `local()` is called many times per invocation, and resolving the
|
|
318
|
+
// worktree toplevel costs a `git rev-parse` — doing that before the once-check would put a
|
|
319
|
+
// process spawn on the hook's blocking path for every single state-path lookup.
|
|
320
|
+
if (this.migrated.has(startDir))
|
|
321
|
+
return;
|
|
322
|
+
this.migrated.add(startDir);
|
|
323
|
+
const toplevel = this.treeRoot(startDir);
|
|
324
|
+
if (toplevel === null)
|
|
325
|
+
return;
|
|
326
|
+
this.migrator.migrate(this.legacyDir(toplevel), target, exports.AI_WRITABLE_STATE_DIRS);
|
|
327
|
+
}
|
|
328
|
+
// One `git rev-parse <flag>`, resolved to an absolute path (git prints a bare `.git`, relative to
|
|
329
|
+
// the tree, in the primary clone, and an absolute path from a linked worktree).
|
|
330
|
+
revParse(cwd, flag) {
|
|
331
|
+
const result = (0, child_process_1.spawnSync)('git', ['-C', cwd, 'rev-parse', flag], { encoding: 'utf8' });
|
|
332
|
+
if (result.status !== 0)
|
|
333
|
+
return null;
|
|
334
|
+
const printed = (result.stdout ?? '').trim();
|
|
335
|
+
if (printed === '')
|
|
336
|
+
return null;
|
|
337
|
+
return path.resolve(cwd, printed);
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
exports.DotWebpieces = DotWebpieces;
|
|
341
|
+
exports.DotWebpieces = DotWebpieces = tslib_1.__decorate([
|
|
342
|
+
(0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
|
|
343
|
+
tslib_1.__metadata("design:paramtypes", [state_dir_migration_1.StateDirMigrator])
|
|
344
|
+
], DotWebpieces);
|
|
345
|
+
// Process-wide instance for the many non-DI call sites (hooks, detached refreshers, wp-* bins, eslint
|
|
346
|
+
// rules). Sharing one instance is what makes the git-resolution cache and the once-per-tree migration
|
|
347
|
+
// worth having; inversify still injects the singleton wherever a container is in play.
|
|
348
|
+
exports.dotWebpieces = new DotWebpieces();
|
|
349
|
+
//# sourceMappingURL=state-dir.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"state-dir.js","sourceRoot":"","sources":["../../../../../packages/tooling/tooling-common/src/state-dir.ts"],"names":[],"mappings":";;;;AAAA,iDAA0C;AAC1C,+CAAyB;AACzB,mDAA6B;AAC7B,yCAA2D;AAE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AO,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IACtC,CAAC;CACJ,CAAA;AA5LY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAUE,sCAAgB;GAT9C,YAAY,CA4LxB;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 { PR_REVIEW_DIR, WEBPIECES_TMP_DIR } from './state-path-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// The leaves of `.webpieces/` that resolve through `aiWritable()` and therefore live in the WORKTREE's\n// own root rather than in the primary clone's namespace. Named here because TWO things must agree about\n// them: `aiWritable()`, which puts them there, and `StateDirMigrator`, which must NOT sweep them out\n// again (its whole job is draining `<worktree>/.webpieces` into the namespace, and these are the one\n// part of that directory that is live rather than legacy).\nexport const AI_WRITABLE_STATE_DIRS: readonly string[] = [PR_REVIEW_DIR];\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 THREE named methods because there are exactly three 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, tooling-written)\n * → <primary>/.webpieces (…in the primary clone)\n * dotWebpieces.aiWritable(dir) → <worktree>/.webpieces (this worktree only, AI-WRITTEN)\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, instruct-ai/, and every other per-tree\n * scratch file that the TOOLING writes.\n * aiWritable():\n * • pr-review/<branch>/ — and ONLY that, today. See the section below.\n *\n * ─── Why aiWritable() is a third scope and not a spelling of local() ──────────────────────────────\n * `pr-review/<branch>/` is the one state directory a CODING AGENT writes into with its own file-write\n * tool: `summary.json` is authored by the agent running the flow, and `review-round<N>-<id>.json` by each reviewer\n * subagent. A worktree-isolated agent may write ONLY inside its own worktree — its harness refuses any\n * Write/Edit whose path is under the shared checkout, with \"This agent is isolated in the worktree …;\n * edit the worktree copy of this file instead\". That refusal is not ours to relax.\n *\n * So `local()` — correct for everything the tooling writes — is UNREACHABLE for the two files the flow\n * asks an agent to write. Stage ② printed a `<primary>/.webpieces/worktrees/<name>/pr-review/…` path,\n * the agent's Write was refused at exactly that path, and the only way through was `cp`/`>` from Bash\n * (which is NOT blocked, so the refusal looks arbitrary rather than structural). Three separate agents\n * hit it, each concluded the tooling was printing a path it did not use, and each invented its own\n * workaround. Worse, the same refusal lands on every reviewer subagent's `review-round<N>-<id>.json`, and\n * `wp-finish-upsert-pr` REFUSES the PR while a required checklist has no verdict — so this was a\n * correctness bug, not an ergonomics one.\n *\n * The invariant, stated once: ANY `.webpieces/` path an AI AGENT is instructed to WRITE must resolve\n * inside that agent's own working tree. `aiWritable()` is that rule, made greppable. Do not add a\n * fourth scope; do not route a tooling-written file through this one.\n *\n * What it costs is what `local()` bought: a `pr-review/` under the worktree dies with the worktree.\n * That is the right trade for THIS directory and only this one — a review is spent the moment the PR is\n * posted, and `pnpm wp-review-upsert-pr` regenerates the whole directory from git in one run. An\n * in-flight `merge-info/staged/<branch>/` is not regenerable, which is exactly why it stays on local().\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 // startDir → `git rev-parse --show-toplevel`, cached on the same terms as gitDirsByRoot.\n private readonly treeRootByDir = new Map<string, string | 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 * State an AI AGENT writes with its own file-write tool: `<worktree>/.webpieces` — the worktree's\n * OWN root, which is the only place a worktree-isolated agent is permitted to write. Identical to\n * `shared()`/`local()` in the primary clone, so nothing changes for a repo without worktrees.\n *\n * See the \"Why aiWritable() is a third scope\" section above before adding a call site: this is for\n * files the flow ASKS AN AGENT TO WRITE, not for tooling output that an agent merely reads.\n */\n aiWritable(startDir: string): string {\n const toplevel = this.treeRoot(startDir);\n // Fails CLOSED to shared() when git cannot answer, on the same terms as every other path here.\n if (toplevel === null) return this.shared(startDir);\n return path.join(toplevel, WEBPIECES_TMP_DIR);\n }\n\n /** A path beneath the AI-writable state dir. */\n aiWritableFile(startDir: string, ...segments: string[]): string {\n return path.join(this.aiWritable(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 two dir answers for `startDir`, memoized — null when it is not a git repo / git is\n * unavailable.\n *\n * PUBLIC because TREE IDENTITY is decided from these two strings and nothing else. `commonDir`\n * is the same for every checkout of ONE repo, so `commonDir(a) === commonDir(b)` is \"same repo,\n * different placement\" — the test that tells a linked worktree (ours, wherever it sits, including\n * inside the repo at `.claude/worktrees/**`) from a nested clone under `repositories/**` (not\n * ours). `gitDirs.isLinkedWorktree` then separates primary from linked. See\n * `EffectiveTreeResolver.classify`, the caller that runs this on the hook's blocking path, which is\n * why it goes through this cache rather than spawning its own `rev-parse`.\n */\n 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 /**\n * The WORKING TREE root containing `startDir` (`git rev-parse --show-toplevel`), memoized, or null\n * when `startDir` is not in a git repo. In a linked worktree this is the WORKTREE's own root, which\n * is exactly what a caller judging \"which checkout am I standing in\" needs.\n *\n * THE ONE tree-root resolver. There used to be three byte-identical `spawnSync … --show-toplevel`\n * copies — this one, `RepoRootFinder`'s and `effective-tree.ts`'s — each commenting that it\n * \"mirrors\" one of the others, and one of those comments was already stale. Both copies are deleted;\n * everything that needs a tree root calls this. Do not add a fourth.\n */\n treeRoot(startDir: string): string | null {\n const cached = this.treeRootByDir.get(startDir);\n if (cached !== undefined) return cached;\n // `status !== 0` IS the expected \"not a repo\" answer (spawnSync does not throw on a non-zero\n // exit), so nothing here swallows a real git crash.\n const root = this.revParse(startDir, '--show-toplevel');\n this.treeRootByDir.set(startDir, root);\n return root;\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.treeRoot(startDir);\n if (toplevel === null) return;\n this.migrator.migrate(this.legacyDir(toplevel), target, AI_WRITABLE_STATE_DIRS);\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"]}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PR_REVIEW_DIR = exports.WEBPIECES_TMP_DIR = void 0;
|
|
4
|
+
exports.WEBPIECES_TMP_DIR = '.webpieces';
|
|
5
|
+
exports.PR_REVIEW_DIR = 'pr-review';
|
|
6
|
+
//# sourceMappingURL=state-path-constants.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"state-path-constants.js","sourceRoot":"","sources":["../../../../../packages/tooling/tooling-common/src/state-path-constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,iBAAiB,GAAG,YAAY,CAAC;AACjC,QAAA,aAAa,GAAG,WAAW,CAAC","sourcesContent":["export const WEBPIECES_TMP_DIR = '.webpieces';\nexport const PR_REVIEW_DIR = 'pr-review';\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function toError(err: unknown): Error;
|
package/src/to-error.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.toError = toError;
|
|
4
|
+
// webpieces-disable no-any-unknown -- toError intentionally accepts unknown to safely convert any thrown value to Error
|
|
5
|
+
function toError(err) {
|
|
6
|
+
if (err instanceof Error)
|
|
7
|
+
return err;
|
|
8
|
+
return new Error(String(err));
|
|
9
|
+
}
|
|
10
|
+
//# sourceMappingURL=to-error.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"to-error.js","sourceRoot":"","sources":["../../../../../packages/tooling/tooling-common/src/to-error.ts"],"names":[],"mappings":";;AACA,0BAGC;AAJD,wHAAwH;AACxH,SAAgB,OAAO,CAAC,GAAY;IAChC,IAAI,GAAG,YAAY,KAAK;QAAE,OAAO,GAAG,CAAC;IACrC,OAAO,IAAI,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;AAClC,CAAC","sourcesContent":["// webpieces-disable no-any-unknown -- toError intentionally accepts unknown to safely convert any thrown value to Error\nexport function toError(err: unknown): Error { // webpieces-disable no-function-outside-class -- existing stateless error adapter moved intact; this leaf must load without filesystem services\n if (err instanceof Error) return err;\n return new Error(String(err));\n}\n"]}
|