@webpieces/rules-config 0.4.836 → 0.4.838

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.
Files changed (129) hide show
  1. package/package.json +4 -2
  2. package/src/builds-log.d.ts +1 -1
  3. package/src/builds-log.js +3 -3
  4. package/src/builds-log.js.map +1 -1
  5. package/src/checklist-docs-validator.js +1 -1
  6. package/src/checklist-docs-validator.js.map +1 -1
  7. package/src/checklist-override.js +1 -1
  8. package/src/checklist-override.js.map +1 -1
  9. package/src/config-file.js +3 -3
  10. package/src/config-file.js.map +1 -1
  11. package/src/config-pruner.d.ts +1 -1
  12. package/src/config-pruner.js +2 -2
  13. package/src/config-pruner.js.map +1 -1
  14. package/src/constants.d.ts +0 -2
  15. package/src/constants.js +1 -3
  16. package/src/constants.js.map +1 -1
  17. package/src/diff-scope.js +1 -1
  18. package/src/diff-scope.js.map +1 -1
  19. package/src/exclude-hook-paths.js +2 -2
  20. package/src/exclude-hook-paths.js.map +1 -1
  21. package/src/home-config-doc-keys.js +2 -2
  22. package/src/home-config-doc-keys.js.map +1 -1
  23. package/src/home-config.js +9 -9
  24. package/src/home-config.js.map +1 -1
  25. package/src/index.d.ts +2 -21
  26. package/src/index.js +7 -129
  27. package/src/index.js.map +1 -1
  28. package/src/instruct-ai-docs.d.ts +1 -1
  29. package/src/instruct-ai-docs.js +3 -3
  30. package/src/instruct-ai-docs.js.map +1 -1
  31. package/src/load-config.js +2 -2
  32. package/src/load-config.js.map +1 -1
  33. package/src/load-template.d.ts +2 -2
  34. package/src/load-template.js +5 -5
  35. package/src/load-template.js.map +1 -1
  36. package/src/orphan-dir-archive.js +3 -3
  37. package/src/orphan-dir-archive.js.map +1 -1
  38. package/src/pr-gate-config.js +4 -4
  39. package/src/pr-gate-config.js.map +1 -1
  40. package/src/pr-gate-section-validators.js +7 -7
  41. package/src/pr-gate-section-validators.js.map +1 -1
  42. package/src/repo-root.d.ts +1 -1
  43. package/src/repo-root.js +5 -5
  44. package/src/repo-root.js.map +1 -1
  45. package/src/repo-scratch-dirs.d.ts +1 -1
  46. package/src/repo-scratch-dirs.js +3 -3
  47. package/src/repo-scratch-dirs.js.map +1 -1
  48. package/src/review-json.d.ts +1 -1
  49. package/src/review-json.js +11 -11
  50. package/src/review-json.js.map +1 -1
  51. package/src/review-provenance.js +4 -4
  52. package/src/review-provenance.js.map +1 -1
  53. package/src/reviewer-instructions.js +2 -2
  54. package/src/reviewer-instructions.js.map +1 -1
  55. package/src/rules-config-design.d.ts +2 -2
  56. package/src/rules-config-design.js +4 -4
  57. package/src/rules-config-design.js.map +1 -1
  58. package/src/skip-rule.d.ts +2 -8
  59. package/src/skip-rule.js +24 -61
  60. package/src/skip-rule.js.map +1 -1
  61. package/src/spec-temp-dirs.js +2 -1
  62. package/src/spec-temp-dirs.js.map +1 -1
  63. package/src/stale-bin-sweep.js +1 -1
  64. package/src/stale-bin-sweep.js.map +1 -1
  65. package/src/subagent-provenance.js +7 -7
  66. package/src/subagent-provenance.js.map +1 -1
  67. package/src/tmp-scratch-sweep.js +1 -1
  68. package/src/tmp-scratch-sweep.js.map +1 -1
  69. package/src/validate-config.js +1 -1
  70. package/src/validate-config.js.map +1 -1
  71. package/src/verdict-schema-renderer.js +2 -2
  72. package/src/verdict-schema-renderer.js.map +1 -1
  73. package/src/agent-worktree-lock.d.ts +0 -21
  74. package/src/agent-worktree-lock.js +0 -77
  75. package/src/agent-worktree-lock.js.map +0 -1
  76. package/src/atomic-file.d.ts +0 -46
  77. package/src/atomic-file.js +0 -114
  78. package/src/atomic-file.js.map +0 -1
  79. package/src/branch-archiver.d.ts +0 -70
  80. package/src/branch-archiver.js +0 -157
  81. package/src/branch-archiver.js.map +0 -1
  82. package/src/branch-mutation-log.d.ts +0 -77
  83. package/src/branch-mutation-log.js +0 -221
  84. package/src/branch-mutation-log.js.map +0 -1
  85. package/src/branch-reaper.d.ts +0 -121
  86. package/src/branch-reaper.js +0 -260
  87. package/src/branch-reaper.js.map +0 -1
  88. package/src/claude-config-dir.d.ts +0 -62
  89. package/src/claude-config-dir.js +0 -87
  90. package/src/claude-config-dir.js.map +0 -1
  91. package/src/harness-agent-activity.d.ts +0 -154
  92. package/src/harness-agent-activity.js +0 -346
  93. package/src/harness-agent-activity.js.map +0 -1
  94. package/src/inform-ai-error.d.ts +0 -6
  95. package/src/inform-ai-error.js +0 -13
  96. package/src/inform-ai-error.js.map +0 -1
  97. package/src/main-sync-file.d.ts +0 -121
  98. package/src/main-sync-file.js +0 -281
  99. package/src/main-sync-file.js.map +0 -1
  100. package/src/main-sync-status.d.ts +0 -197
  101. package/src/main-sync-status.js +0 -555
  102. package/src/main-sync-status.js.map +0 -1
  103. package/src/merged-branch-verdicts.d.ts +0 -189
  104. package/src/merged-branch-verdicts.js +0 -251
  105. package/src/merged-branch-verdicts.js.map +0 -1
  106. package/src/merged-branches.d.ts +0 -140
  107. package/src/merged-branches.js +0 -521
  108. package/src/merged-branches.js.map +0 -1
  109. package/src/review-identity-stamp.d.ts +0 -82
  110. package/src/review-identity-stamp.js +0 -172
  111. package/src/review-identity-stamp.js.map +0 -1
  112. package/src/state-dir-migration.d.ts +0 -79
  113. package/src/state-dir-migration.js +0 -185
  114. package/src/state-dir-migration.js.map +0 -1
  115. package/src/state-dir.d.ts +0 -209
  116. package/src/state-dir.js +0 -349
  117. package/src/state-dir.js.map +0 -1
  118. package/src/to-error.d.ts +0 -1
  119. package/src/to-error.js +0 -10
  120. package/src/to-error.js.map +0 -1
  121. package/src/worktree-lock-verdicts.d.ts +0 -149
  122. package/src/worktree-lock-verdicts.js +0 -225
  123. package/src/worktree-lock-verdicts.js.map +0 -1
  124. package/src/worktree-reaper.d.ts +0 -116
  125. package/src/worktree-reaper.js +0 -318
  126. package/src/worktree-reaper.js.map +0 -1
  127. package/src/worktrees.d.ts +0 -113
  128. package/src/worktrees.js +0 -260
  129. package/src/worktrees.js.map +0 -1
@@ -1,281 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MainSyncFileStore = exports.PullRequestIndex = exports.MainSyncStatusFile = exports.MainSyncStatus = exports.MAIN_SYNC_STATUS_VERSION = void 0;
4
- const tslib_1 = require("tslib");
5
- const fs = tslib_1.__importStar(require("fs"));
6
- const inversify_1 = require("inversify");
7
- const atomic_file_1 = require("./atomic-file");
8
- const to_error_1 = require("./to-error");
9
- /**
10
- * The ON-DISK SHAPE of `<primary>/.webpieces/main-sync-status.json`, and nothing else.
11
- *
12
- * WHY this is its own module rather than more of main-sync-status.ts: that file already owns the lock
13
- * state machine plus the whole slow git/gh computation, and adding the map shape to it pushed it past
14
- * the 700-line cap. The split is along a real seam — everything here is pure parse/serialise with no
15
- * process spawning, so it is also the cheap half to test.
16
- *
17
- * WHY the file is a MAP of branch -> status (v2) rather than one status (v1): the cache is SHARED by
18
- * every worktree of the repo (one `.git`, one `origin/main`, one single-flight refresher), but a v1
19
- * file described exactly ONE branch — whichever tree won the lock. Every guard fails open when the
20
- * cached branch is not the branch it is judging, so with N worktrees at most one worktree's guards
21
- * were armed and the rest abstained, thrashing as the lock changed hands. Keeping the payload per
22
- * branch identical and only changing the LOOKUP means no guard's field access changed.
23
- */
24
- // Bumped when the shape changes. v1 = one bare status; v2 = branch map; v3 = cached commit distance.
25
- exports.MAIN_SYNC_STATUS_VERSION = 3;
26
- // Data-only (per CLAUDE.md, classes for data). The per-branch payload — unchanged from v1.
27
- class MainSyncStatus {
28
- branch;
29
- branchAlreadyMerged;
30
- mergedPr;
31
- hasForkPoint;
32
- forkPoint;
33
- originMain;
34
- featureHead;
35
- conflict;
36
- conflictFiles;
37
- timestamp;
38
- // An OPEN (not merged) PR tracking this branch, if any — '' = none or not-yet-known. Advisory.
39
- // Kept OUT of the positional constructor (a defaulted field) so existing call sites don't churn.
40
- openPr = '';
41
- // The LOCAL refs/heads/main hash — '' = main does not exist locally (fresh clone / worktree) or
42
- // could not be read. Paired with `originMain`, this is what tells the read-stale-guard whether a
43
- // checked-out `main` is behind its remote. Defaulted field for the same reason as `openPr`.
44
- localMain = '';
45
- // Computed by the detached refresher as local main..origin/main. Null means an older cache or git
46
- // could not establish the distance; stale-main threshold checks fail open in that state.
47
- commitsBehind = null;
48
- /**
49
- * Did the forge answer when this entry was computed? See PullRequestIndex.forgeReachable.
50
- *
51
- * `branchAlreadyMerged: false` is produced BOTH by "this branch has no merged PR" and by "we could
52
- * not ask", and the three guards that act on the merged state took the ordinary ALLOW path in both.
53
- * Carrying the distinction into the cache is what lets them say ALLOW_FAIL_OPEN / `no-forge`
54
- * instead — the typed verdict exists precisely so abstentions are countable.
55
- *
56
- * Defaults TRUE, matching `openPr`/`localMain` as a non-positional field: an entry written before
57
- * this field existed (or hand-edited) is read as "the forge answered", which preserves today's
58
- * verdicts exactly rather than retro-labelling old caches as abstentions.
59
- */
60
- forgeReachable = true;
61
- constructor(branch, branchAlreadyMerged, mergedPr, hasForkPoint, forkPoint, originMain, featureHead, conflict, conflictFiles, timestamp) {
62
- this.branch = branch;
63
- this.branchAlreadyMerged = branchAlreadyMerged;
64
- this.mergedPr = mergedPr;
65
- this.hasForkPoint = hasForkPoint;
66
- this.forkPoint = forkPoint;
67
- this.originMain = originMain;
68
- this.featureHead = featureHead;
69
- this.conflict = conflict;
70
- this.conflictFiles = conflictFiles;
71
- this.timestamp = timestamp;
72
- }
73
- }
74
- exports.MainSyncStatus = MainSyncStatus;
75
- // Data-only. The whole document: every branch the last refresh could see, written as one unit.
76
- class MainSyncStatusFile {
77
- version;
78
- // When the map as a whole was written. Each entry also carries its own timestamp.
79
- timestamp;
80
- branches;
81
- constructor(version, timestamp, branches) {
82
- this.version = version;
83
- this.timestamp = timestamp;
84
- this.branches = branches;
85
- }
86
- }
87
- exports.MainSyncStatusFile = MainSyncStatusFile;
88
- /**
89
- * The repo's pull requests indexed by head branch — ONE `gh pr list` for the whole refresh.
90
- *
91
- * WHY it exists: the per-branch status needs a merged-PR and an open-PR answer, and the old code asked
92
- * `gh` twice PER BRANCH. Recording N branches per refresh would have meant 2N network round trips and
93
- * made the refresher scale with worktree count. One repo-wide query indexed locally is 1 call for any N.
94
- */
95
- class PullRequestIndex {
96
- // branch -> PR number, as a string ('' means "no such PR"), for MERGED and OPEN respectively.
97
- merged;
98
- open;
99
- /**
100
- * Did the forge actually ANSWER?
101
- *
102
- * `mergedFor()` returning '' has always meant two completely different things — "this branch has no
103
- * merged PR" and "we could not ask" (`gh` missing, unauthenticated, rate-limited, offline, or the
104
- * response unparseable). Both produced the same empty index, so from the decision log you could not
105
- * tell whether the merged-branch policy was PROTECTING anything or quietly abstaining. This flag is
106
- * the difference, and it is what lets the guards emit ALLOW_FAIL_OPEN instead of a plain ALLOW.
107
- *
108
- * REQUIRED, not defaulted: an index built on a failure path must say so out loud, and a default of
109
- * `true` would make "we asked and got an answer" the thing you get by forgetting.
110
- */
111
- forgeReachable;
112
- constructor(merged, open, forgeReachable) {
113
- this.merged = merged;
114
- this.open = open;
115
- this.forgeReachable = forgeReachable;
116
- }
117
- // A merged PR for this branch, or '' — the same value the old per-branch `gh` call produced.
118
- mergedFor(branch) {
119
- if (branch === '' || branch === 'main')
120
- return '';
121
- return hasOwn(this.merged, branch) ? (this.merged[branch] ?? '') : '';
122
- }
123
- openFor(branch) {
124
- if (branch === '' || branch === 'main')
125
- return '';
126
- return hasOwn(this.open, branch) ? (this.open[branch] ?? '') : '';
127
- }
128
- }
129
- exports.PullRequestIndex = PullRequestIndex;
130
- // Own-property lookup only: a branch literally named `constructor` or `toString` must not resolve to
131
- // something off Object.prototype and be mistaken for a cached status.
132
- // webpieces-disable no-function-outside-class -- one-line own-property predicate used by the classes in this module
133
- function hasOwn(record, key) {
134
- return Object.prototype.hasOwnProperty.call(record, key);
135
- }
136
- /**
137
- * Reads and writes the branch-keyed status document. Every read fails SOFT to null (or to an empty
138
- * map) — the guards above this treat null as `no-sync-cache (fail-open)`, so a missing, truncated or
139
- * malformed file must never throw and must never block an edit.
140
- */
141
- let MainSyncFileStore = class MainSyncFileStore {
142
- atomicFile;
143
- constructor(atomicFile = new atomic_file_1.AtomicFile()) {
144
- this.atomicFile = atomicFile;
145
- }
146
- /**
147
- * Parse the document at `statusPath`, adapting a v1 file on the way. Returns null when there is
148
- * nothing readable there — missing file, unreadable file, or JSON that does not parse.
149
- */
150
- readFile(statusPath) {
151
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
152
- try {
153
- if (!fs.existsSync(statusPath))
154
- return null;
155
- // The cast is the trust boundary: every field of RawFile is optional and every read of it
156
- // below is defaulted, so a document of any other shape degrades to an empty map.
157
- const parsed = JSON.parse(fs.readFileSync(statusPath, 'utf8'));
158
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
159
- return null;
160
- return this.adapt(parsed);
161
- }
162
- catch (err) {
163
- const error = (0, to_error_1.toError)(err);
164
- void error;
165
- return null;
166
- }
167
- }
168
- /**
169
- * ATOMIC write (temp file + `rename()` in the same directory). The refresher writes this while
170
- * guards on the blocking path read it, from other worktrees; a plain `writeFileSync` truncates
171
- * first, so a reader landing in that window gets a torn document. Writing the map WHOLE also means
172
- * a reader never sees half of one refresh's branches and half of the previous refresh's.
173
- */
174
- writeFile(statusPath, file) {
175
- this.atomicFile.writeJsonAtomic(statusPath, file);
176
- }
177
- /**
178
- * READ-MODIFY-WRITE a single branch's entry, leaving every sibling entry untouched.
179
- *
180
- * This is what any writer that is NOT the single-flight refresher must use. `stampCleanMainSyncStatus`
181
- * (pr-gate's post-merge stamp) runs without the lock and knows about exactly one branch; if it wrote
182
- * a whole document it would silently erase every other worktree's entry and disarm their guards
183
- * until the next refresh.
184
- */
185
- mergeBranch(statusPath, status) {
186
- const existing = this.readFile(statusPath);
187
- const branches = existing === null ? {} : existing.branches;
188
- branches[status.branch] = status;
189
- this.writeFile(statusPath, new MainSyncStatusFile(exports.MAIN_SYNC_STATUS_VERSION, new Date().toISOString(), branches));
190
- }
191
- // The entry for one branch, or null when this refresh never saw that branch.
192
- branchStatus(file, branch) {
193
- if (file === null)
194
- return null;
195
- // Defensive: readFile always produces a map, but this method is public and sits on the
196
- // blocking path — a caller handing it a raw document must get null, not a throw.
197
- if (file.branches === null || file.branches === undefined)
198
- return null;
199
- if (!hasOwn(file.branches, branch))
200
- return null;
201
- return file.branches[branch] ?? null;
202
- }
203
- /**
204
- * Index `gh pr list --state all --json number,headRefName,state` output by head branch.
205
- *
206
- * Newest-first is gh's order, so the FIRST row for a branch wins — matching the old per-branch
207
- * `--jq .[0].number`. Anything unparseable yields an empty index, i.e. "no PR", which is the same
208
- * answer the old code produced when `gh` was missing or offline: fail-open.
209
- */
210
- indexPullRequests(json) {
211
- const merged = {};
212
- const open = {};
213
- // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
214
- try {
215
- const parsed = JSON.parse(json);
216
- // Parsed but not an array: `gh` answered with something we do not understand, which is
217
- // not the same as it answering "no PRs". Unreachable, so the guards abstain rather than allow.
218
- if (!Array.isArray(parsed))
219
- return new PullRequestIndex(merged, open, false);
220
- for (const row of parsed) {
221
- if (row !== null && typeof row === 'object')
222
- this.indexOne(row, merged, open);
223
- }
224
- }
225
- catch (err) {
226
- const error = (0, to_error_1.toError)(err);
227
- void error;
228
- return new PullRequestIndex(merged, open, false);
229
- }
230
- return new PullRequestIndex(merged, open, true);
231
- }
232
- indexOne(row, merged, open) {
233
- const branch = row.headRefName ?? '';
234
- const number = typeof row.number === 'number' ? String(row.number) : '';
235
- if (branch === '' || number === '')
236
- return;
237
- const state = (row.state ?? '').toUpperCase();
238
- // First row wins per branch+state — gh lists newest first, matching the old `.[0].number`.
239
- if (state === 'MERGED' && !hasOwn(merged, branch))
240
- merged[branch] = number;
241
- if (state === 'OPEN' && !hasOwn(open, branch))
242
- open[branch] = number;
243
- }
244
- // v2 documents pass through; a v1 document becomes a one-entry map keyed by its own `branch`.
245
- adapt(raw) {
246
- const branches = {};
247
- const rawBranches = raw.branches;
248
- if (rawBranches !== undefined && rawBranches !== null && typeof rawBranches === 'object') {
249
- for (const [name, entry] of Object.entries(rawBranches)) {
250
- if (entry !== null && typeof entry === 'object')
251
- branches[name] = this.toStatus(entry);
252
- }
253
- return new MainSyncStatusFile(raw.version ?? exports.MAIN_SYNC_STATUS_VERSION, raw.timestamp ?? '', branches);
254
- }
255
- // v1: one bare status at the top level. Key it by the branch it was computed for, so the
256
- // guard for THAT branch stays armed across the upgrade and every other branch simply misses
257
- // (null → `no-sync-cache (fail-open)`), which is what it did under v1 anyway.
258
- if (typeof raw.branch === 'string' && raw.branch !== '')
259
- branches[raw.branch] = this.toStatus(raw);
260
- return new MainSyncStatusFile(1, raw.timestamp ?? '', branches);
261
- }
262
- // Every field defaulted: a truncated or hand-edited entry degrades to a benign status rather
263
- // than to a throw. `hasForkPoint` defaults TRUE because false is the BLOCKING value.
264
- toStatus(raw) {
265
- const status = new MainSyncStatus(raw.branch ?? '', raw.branchAlreadyMerged ?? false, raw.mergedPr ?? '', raw.hasForkPoint ?? true, raw.forkPoint ?? null, raw.originMain ?? '', raw.featureHead ?? '', raw.conflict ?? false, raw.conflictFiles ?? [], raw.timestamp ?? '');
266
- status.openPr = raw.openPr ?? '';
267
- status.localMain = raw.localMain ?? '';
268
- status.commitsBehind = typeof raw.commitsBehind === 'number'
269
- && Number.isInteger(raw.commitsBehind) && raw.commitsBehind >= 0
270
- ? raw.commitsBehind
271
- : null;
272
- status.forgeReachable = raw.forgeReachable ?? true;
273
- return status;
274
- }
275
- };
276
- exports.MainSyncFileStore = MainSyncFileStore;
277
- exports.MainSyncFileStore = MainSyncFileStore = tslib_1.__decorate([
278
- (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
279
- tslib_1.__metadata("design:paramtypes", [atomic_file_1.AtomicFile])
280
- ], MainSyncFileStore);
281
- //# sourceMappingURL=main-sync-file.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"main-sync-file.js","sourceRoot":"","sources":["../../../../../packages/tooling/rules-config/src/main-sync-file.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,yCAA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AAG,CAAC,SAAS,IAAI,EAAE,CACtB,CAAC;QACF,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,EAAE,CAAC;QACjC,MAAM,CAAC,SAAS,GAAG,GAAG,CAAC,SAAS,IAAI,EAAE,CAAC;QACvC,MAAM,CAAC,aAAa,GAAG,OAAO,GAAG,CAAC,aAAa,KAAK,QAAQ;eACrD,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,GAAG,CAAC,aAAa,IAAI,CAAC;YAChE,CAAC,CAAC,GAAG,CAAC,aAAa;YACnB,CAAC,CAAC,IAAI,CAAC;QACX,MAAM,CAAC,cAAc,GAAG,GAAG,CAAC,cAAc,IAAI,IAAI,CAAC;QACnD,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ,CAAA;AAzIY,8CAAiB;4BAAjB,iBAAiB;IAD7B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEI,wBAAU;GAD1C,iBAAiB,CAyI7B","sourcesContent":["import * as fs from 'fs';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { AtomicFile } from './atomic-file';\nimport { toError } from './to-error';\n\n/**\n * The ON-DISK SHAPE of `<primary>/.webpieces/main-sync-status.json`, and nothing else.\n *\n * WHY this is its own module rather than more of main-sync-status.ts: that file already owns the lock\n * state machine plus the whole slow git/gh computation, and adding the map shape to it pushed it past\n * the 700-line cap. The split is along a real seam — everything here is pure parse/serialise with no\n * process spawning, so it is also the cheap half to test.\n *\n * WHY the file is a MAP of branch -> status (v2) rather than one status (v1): the cache is SHARED by\n * every worktree of the repo (one `.git`, one `origin/main`, one single-flight refresher), but a v1\n * file described exactly ONE branch — whichever tree won the lock. Every guard fails open when the\n * cached branch is not the branch it is judging, so with N worktrees at most one worktree's guards\n * were armed and the rest abstained, thrashing as the lock changed hands. Keeping the payload per\n * branch identical and only changing the LOOKUP means no guard's field access changed.\n */\n\n// Bumped when the shape changes. v1 = one bare status; v2 = branch map; v3 = cached commit distance.\nexport const MAIN_SYNC_STATUS_VERSION = 3;\n\n// Data-only (per CLAUDE.md, classes for data). The per-branch payload — unchanged from v1.\nexport class MainSyncStatus {\n branch: string;\n branchAlreadyMerged: boolean;\n mergedPr: string;\n hasForkPoint: boolean;\n forkPoint: string | null;\n originMain: string;\n featureHead: string;\n conflict: boolean;\n conflictFiles: string[];\n timestamp: string;\n // An OPEN (not merged) PR tracking this branch, if any — '' = none or not-yet-known. Advisory.\n // Kept OUT of the positional constructor (a defaulted field) so existing call sites don't churn.\n openPr: string = '';\n // The LOCAL refs/heads/main hash — '' = main does not exist locally (fresh clone / worktree) or\n // could not be read. Paired with `originMain`, this is what tells the read-stale-guard whether a\n // checked-out `main` is behind its remote. Defaulted field for the same reason as `openPr`.\n localMain: string = '';\n // Computed by the detached refresher as local main..origin/main. Null means an older cache or git\n // could not establish the distance; stale-main threshold checks fail open in that state.\n commitsBehind: number | null = null;\n /**\n * Did the forge answer when this entry was computed? See PullRequestIndex.forgeReachable.\n *\n * `branchAlreadyMerged: false` is produced BOTH by \"this branch has no merged PR\" and by \"we could\n * not ask\", and the three guards that act on the merged state took the ordinary ALLOW path in both.\n * Carrying the distinction into the cache is what lets them say ALLOW_FAIL_OPEN / `no-forge`\n * instead — the typed verdict exists precisely so abstentions are countable.\n *\n * Defaults TRUE, matching `openPr`/`localMain` as a non-positional field: an entry written before\n * this field existed (or hand-edited) is read as \"the forge answered\", which preserves today's\n * verdicts exactly rather than retro-labelling old caches as abstentions.\n */\n forgeReachable: boolean = true;\n\n constructor(\n branch: string,\n branchAlreadyMerged: boolean,\n mergedPr: string,\n hasForkPoint: boolean,\n forkPoint: string | null,\n originMain: string,\n featureHead: string,\n conflict: boolean,\n conflictFiles: string[],\n timestamp: string,\n ) {\n this.branch = branch;\n this.branchAlreadyMerged = branchAlreadyMerged;\n this.mergedPr = mergedPr;\n this.hasForkPoint = hasForkPoint;\n this.forkPoint = forkPoint;\n this.originMain = originMain;\n this.featureHead = featureHead;\n this.conflict = conflict;\n this.conflictFiles = conflictFiles;\n this.timestamp = timestamp;\n }\n}\n\n// Data-only. The whole document: every branch the last refresh could see, written as one unit.\nexport class MainSyncStatusFile {\n version: number;\n // When the map as a whole was written. Each entry also carries its own timestamp.\n timestamp: string;\n branches: Record<string, MainSyncStatus>;\n\n constructor(version: number, timestamp: string, branches: Record<string, MainSyncStatus>) {\n this.version = version;\n this.timestamp = timestamp;\n this.branches = branches;\n }\n}\n\n/**\n * The repo's pull requests indexed by head branch — ONE `gh pr list` for the whole refresh.\n *\n * WHY it exists: the per-branch status needs a merged-PR and an open-PR answer, and the old code asked\n * `gh` twice PER BRANCH. Recording N branches per refresh would have meant 2N network round trips and\n * made the refresher scale with worktree count. One repo-wide query indexed locally is 1 call for any N.\n */\nexport class PullRequestIndex {\n // branch -> PR number, as a string ('' means \"no such PR\"), for MERGED and OPEN respectively.\n merged: Record<string, string>;\n open: Record<string, string>;\n /**\n * Did the forge actually ANSWER?\n *\n * `mergedFor()` returning '' has always meant two completely different things — \"this branch has no\n * merged PR\" and \"we could not ask\" (`gh` missing, unauthenticated, rate-limited, offline, or the\n * response unparseable). Both produced the same empty index, so from the decision log you could not\n * tell whether the merged-branch policy was PROTECTING anything or quietly abstaining. This flag is\n * the difference, and it is what lets the guards emit ALLOW_FAIL_OPEN instead of a plain ALLOW.\n *\n * REQUIRED, not defaulted: an index built on a failure path must say so out loud, and a default of\n * `true` would make \"we asked and got an answer\" the thing you get by forgetting.\n */\n forgeReachable: boolean;\n\n constructor(merged: Record<string, string>, open: Record<string, string>, forgeReachable: boolean) {\n this.merged = merged;\n this.open = open;\n this.forgeReachable = forgeReachable;\n }\n\n // A merged PR for this branch, or '' — the same value the old per-branch `gh` call produced.\n mergedFor(branch: string): string {\n if (branch === '' || branch === 'main') return '';\n return hasOwn(this.merged, branch) ? (this.merged[branch] ?? '') : '';\n }\n\n openFor(branch: string): string {\n if (branch === '' || branch === 'main') return '';\n return hasOwn(this.open, branch) ? (this.open[branch] ?? '') : '';\n }\n}\n\n// Raw JSON shapes for the cast at the parse boundary.\ninterface RawStatus {\n branch?: string;\n branchAlreadyMerged?: boolean;\n mergedPr?: string;\n hasForkPoint?: boolean;\n forkPoint?: string | null;\n originMain?: string;\n featureHead?: string;\n conflict?: boolean;\n conflictFiles?: string[];\n timestamp?: string;\n openPr?: string;\n localMain?: string;\n commitsBehind?: number | null;\n forgeReachable?: boolean;\n}\n\n// v2 has `branches`; a v1 document instead has the RawStatus fields at the top level.\ninterface RawFile extends RawStatus {\n version?: number;\n branches?: Record<string, RawStatus>;\n}\n\n// One row of `gh pr list --json number,headRefName,state`.\ninterface RawPullRequest {\n number?: number;\n headRefName?: string;\n state?: string;\n}\n\n// Own-property lookup only: a branch literally named `constructor` or `toString` must not resolve to\n// something off Object.prototype and be mistaken for a cached status.\n// webpieces-disable no-function-outside-class -- one-line own-property predicate used by the classes in this module\nfunction hasOwn(record: object, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(record, key);\n}\n\n/**\n * Reads and writes the branch-keyed status document. Every read fails SOFT to null (or to an empty\n * map) — the guards above this treat null as `no-sync-cache (fail-open)`, so a missing, truncated or\n * malformed file must never throw and must never block an edit.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class MainSyncFileStore {\n constructor(private readonly atomicFile: AtomicFile = new AtomicFile()) {}\n\n /**\n * Parse the document at `statusPath`, adapting a v1 file on the way. Returns null when there is\n * nothing readable there — missing file, unreadable file, or JSON that does not parse.\n */\n readFile(statusPath: string): MainSyncStatusFile | null {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n if (!fs.existsSync(statusPath)) return null;\n // The cast is the trust boundary: every field of RawFile is optional and every read of it\n // below is defaulted, so a document of any other shape degrades to an empty map.\n const parsed = JSON.parse(fs.readFileSync(statusPath, 'utf8')) as RawFile | null;\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null;\n return this.adapt(parsed);\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return null;\n }\n }\n\n /**\n * ATOMIC write (temp file + `rename()` in the same directory). The refresher writes this while\n * guards on the blocking path read it, from other worktrees; a plain `writeFileSync` truncates\n * first, so a reader landing in that window gets a torn document. Writing the map WHOLE also means\n * a reader never sees half of one refresh's branches and half of the previous refresh's.\n */\n writeFile(statusPath: string, file: MainSyncStatusFile): void {\n this.atomicFile.writeJsonAtomic(statusPath, file);\n }\n\n /**\n * READ-MODIFY-WRITE a single branch's entry, leaving every sibling entry untouched.\n *\n * This is what any writer that is NOT the single-flight refresher must use. `stampCleanMainSyncStatus`\n * (pr-gate's post-merge stamp) runs without the lock and knows about exactly one branch; if it wrote\n * a whole document it would silently erase every other worktree's entry and disarm their guards\n * until the next refresh.\n */\n mergeBranch(statusPath: string, status: MainSyncStatus): void {\n const existing = this.readFile(statusPath);\n const branches: Record<string, MainSyncStatus> = existing === null ? {} : existing.branches;\n branches[status.branch] = status;\n this.writeFile(statusPath, new MainSyncStatusFile(\n MAIN_SYNC_STATUS_VERSION, new Date().toISOString(), branches));\n }\n\n // The entry for one branch, or null when this refresh never saw that branch.\n branchStatus(file: MainSyncStatusFile | null, branch: string): MainSyncStatus | null {\n if (file === null) return null;\n // Defensive: readFile always produces a map, but this method is public and sits on the\n // blocking path — a caller handing it a raw document must get null, not a throw.\n if (file.branches === null || file.branches === undefined) return null;\n if (!hasOwn(file.branches, branch)) return null;\n return file.branches[branch] ?? null;\n }\n\n /**\n * Index `gh pr list --state all --json number,headRefName,state` output by head branch.\n *\n * Newest-first is gh's order, so the FIRST row for a branch wins — matching the old per-branch\n * `--jq .[0].number`. Anything unparseable yields an empty index, i.e. \"no PR\", which is the same\n * answer the old code produced when `gh` was missing or offline: fail-open.\n */\n indexPullRequests(json: string): PullRequestIndex {\n const merged: Record<string, string> = {};\n const open: Record<string, string> = {};\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const parsed = JSON.parse(json) as RawPullRequest[] | null;\n // Parsed but not an array: `gh` answered with something we do not understand, which is\n // not the same as it answering \"no PRs\". Unreachable, so the guards abstain rather than allow.\n if (!Array.isArray(parsed)) return new PullRequestIndex(merged, open, false);\n for (const row of parsed) {\n if (row !== null && typeof row === 'object') this.indexOne(row, merged, open);\n }\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n return new PullRequestIndex(merged, open, false);\n }\n return new PullRequestIndex(merged, open, true);\n }\n\n private indexOne(row: RawPullRequest, merged: Record<string, string>, open: Record<string, string>): void {\n const branch = row.headRefName ?? '';\n const number = typeof row.number === 'number' ? String(row.number) : '';\n if (branch === '' || number === '') return;\n const state = (row.state ?? '').toUpperCase();\n // First row wins per branch+state — gh lists newest first, matching the old `.[0].number`.\n if (state === 'MERGED' && !hasOwn(merged, branch)) merged[branch] = number;\n if (state === 'OPEN' && !hasOwn(open, branch)) open[branch] = number;\n }\n\n // v2 documents pass through; a v1 document becomes a one-entry map keyed by its own `branch`.\n private adapt(raw: RawFile): MainSyncStatusFile {\n const branches: Record<string, MainSyncStatus> = {};\n const rawBranches = raw.branches;\n if (rawBranches !== undefined && rawBranches !== null && typeof rawBranches === 'object') {\n for (const [name, entry] of Object.entries(rawBranches)) {\n if (entry !== null && typeof entry === 'object') branches[name] = this.toStatus(entry);\n }\n return new MainSyncStatusFile(raw.version ?? MAIN_SYNC_STATUS_VERSION, raw.timestamp ?? '', branches);\n }\n // v1: one bare status at the top level. Key it by the branch it was computed for, so the\n // guard for THAT branch stays armed across the upgrade and every other branch simply misses\n // (null → `no-sync-cache (fail-open)`), which is what it did under v1 anyway.\n if (typeof raw.branch === 'string' && raw.branch !== '') branches[raw.branch] = this.toStatus(raw);\n return new MainSyncStatusFile(1, raw.timestamp ?? '', branches);\n }\n\n // Every field defaulted: a truncated or hand-edited entry degrades to a benign status rather\n // than to a throw. `hasForkPoint` defaults TRUE because false is the BLOCKING value.\n private toStatus(raw: RawStatus): MainSyncStatus {\n const status = new MainSyncStatus(\n raw.branch ?? '',\n raw.branchAlreadyMerged ?? false,\n raw.mergedPr ?? '',\n raw.hasForkPoint ?? true,\n raw.forkPoint ?? null,\n raw.originMain ?? '',\n raw.featureHead ?? '',\n raw.conflict ?? false,\n raw.conflictFiles ?? [],\n raw.timestamp ?? '',\n );\n status.openPr = raw.openPr ?? '';\n status.localMain = raw.localMain ?? '';\n status.commitsBehind = typeof raw.commitsBehind === 'number'\n && Number.isInteger(raw.commitsBehind) && raw.commitsBehind >= 0\n ? raw.commitsBehind\n : null;\n status.forgeReachable = raw.forgeReachable ?? true;\n return status;\n }\n}\n"]}
@@ -1,197 +0,0 @@
1
- import { AtomicFile } from './atomic-file';
2
- import { MAIN_SYNC_STATUS_VERSION, MainSyncFileStore, MainSyncStatus, MainSyncStatusFile, PullRequestIndex } from './main-sync-file';
3
- import { DotWebpieces } from './state-dir';
4
- import { WorktreeService } from './worktrees';
5
- export { MainSyncStatus, MainSyncStatusFile, PullRequestIndex, MAIN_SYNC_STATUS_VERSION };
6
- export declare const DEFAULT_HANG_TIMEOUT_MINUTES = 5;
7
- export declare class MainSyncLock {
8
- state: string;
9
- started: number;
10
- pid: number;
11
- constructor(state: string, started: number, pid?: number);
12
- }
13
- /**
14
- * Reads/writes the main-sync cache + lock and computes the slow "is my branch healthy vs origin/main?"
15
- * status. `@injectable(bindingScopeValues.Singleton)` so it's injectable and drawn in the rules-config DI design.
16
- */
17
- export declare class MainSyncStatusService {
18
- private readonly dotDir;
19
- private readonly atomicFile;
20
- private readonly store;
21
- private readonly worktrees;
22
- constructor(dotDir?: DotWebpieces, atomicFile?: AtomicFile, store?: MainSyncFileStore, worktrees?: WorktreeService);
23
- /**
24
- * SHARED scope: `<primary>/.webpieces/main-sync-status.json`, one per repo.
25
- *
26
- * It is the OUTPUT of the single-flight refresher below, so it has to live where the lock lives —
27
- * one `.git`, one `origin/main`, one fetch, one answer. A per-worktree copy under single-flight
28
- * would only ever be written for whichever worktree won the lock anyway.
29
- *
30
- * FORMERLY a known defect, now fixed: the file's CONTENT used to be keyed to ONE branch, and every
31
- * reader fails OPEN when the cached branch is not the branch being judged (`stale-cross-branch-cache
32
- * (fail-open)`). With several worktrees on several branches, only the winner of the lock was ever
33
- * described, so every other worktree's guards abstained — and which one was armed thrashed as the
34
- * lock changed hands. The file is now a MAP of branch -> status (see MainSyncStatusFile): the single
35
- * winning refresher enumerates every worktree and records all of their branches in one atomic write,
36
- * so one fetch arms everyone. Single-flight is unchanged; only what the winner writes changed.
37
- */
38
- mainSyncStatusPath(repoRoot: string): string;
39
- /**
40
- * SHARED scope — the single-flight lock for the whole repo.
41
- *
42
- * This is the fix for the filed bug "the detached main-sync refresher's `git fetch` races the
43
- * agent's foreground `git fetch`/`git pull` and corrupts `.git/FETCH_HEAD`". The lock was already
44
- * atomic (O_CREAT|O_EXCL) and already serialised refreshers against each other — but only WITHIN
45
- * one worktree, so N worktrees meant N locks and up to N concurrent `git fetch`es against the ONE
46
- * shared `.git`, which is exactly how a duplicate `for-merge` line lands in FETCH_HEAD. There is
47
- * one `.git`, so there is now one lock: at most one refresher in flight across all worktrees.
48
- *
49
- * Stale-lock handling is unchanged and still required (a lock nobody can clear is worse than the
50
- * race): the holder records pid + start epoch, and `tryAcquireMainSyncLock` reclaims it once
51
- * `isRefreshInProgress` proves the holder is finished, hung past hangTimeoutMinutes, or dead.
52
- */
53
- mainSyncLockPath(repoRoot: string): string;
54
- /**
55
- * The cached status FOR ONE BRANCH — the only read the four main-sync guards perform.
56
- *
57
- * `branch` is mandatory and is the branch being judged. A branch the last refresh never saw
58
- * returns null, which every guard already treats as `no-sync-cache (fail-open)`, so an unknown
59
- * branch degrades exactly as a missing file did. Any error (missing, truncated, malformed JSON)
60
- * also returns null — this must never throw on the blocking path.
61
- */
62
- readMainSyncStatus(repoRoot: string, branch: string): MainSyncStatus | null;
63
- readMainSyncStatusFile(repoRoot: string): MainSyncStatusFile | null;
64
- /**
65
- * Merge ONE branch's entry into the existing map, atomically, leaving siblings untouched.
66
- *
67
- * Read-modify-write rather than replace: this is the writer used by everyone who is NOT the
68
- * single-flight refresher (notably pr-gate's post-merge stamp, which holds no lock and knows about
69
- * exactly one branch). Replacing the document from there would erase every other worktree's entry
70
- * and silently disarm their guards until the next refresh.
71
- */
72
- writeMainSyncStatus(repoRoot: string, status: MainSyncStatus): void;
73
- /**
74
- * Replace the WHOLE document — only the winning refresher may do this.
75
- *
76
- * ATOMIC (temp file + `rename()` in the same directory). The refresher writes this file while
77
- * guards on the blocking path read it, possibly from another worktree; a plain `writeFileSync`
78
- * truncates first, so a reader landing in that window gets a torn document. See AtomicFile.
79
- */
80
- writeMainSyncStatusFile(repoRoot: string, file: MainSyncStatusFile): void;
81
- readMainSyncLock(repoRoot: string): MainSyncLock | null;
82
- writeMainSyncLock(repoRoot: string, lock: MainSyncLock): void;
83
- isLockStale(lock: MainSyncLock, hangTimeoutMinutes: number, now?: number): boolean;
84
- isRefreshInProgress(repoRoot: string, hangTimeoutMinutes: number, now?: number): boolean;
85
- /**
86
- * ATOMICALLY take the refresher lock. Returns the held lock, or null when someone else holds it.
87
- *
88
- * Replaces the check-then-write pair (`isRefreshInProgress` then `writeMainSyncLock`), whose gap
89
- * let two detached refreshers both pass the check and then both run `git fetch` at once — the
90
- * concurrency this lock exists to prevent. The create uses the `wx` flag (O_CREAT|O_EXCL), so of
91
- * N racing refreshers exactly one creates the file.
92
- *
93
- * A lock file left behind by a FINISHED, hung, or killed refresher is reclaimed: we only unlink
94
- * and re-take it once `isRefreshInProgress` says the holder is provably not running, and we
95
- * re-read afterwards to confirm the entry we see is ours before claiming the lock.
96
- */
97
- tryAcquireMainSyncLock(repoRoot: string, hangTimeoutMinutes: number, now?: number, pid?: number): MainSyncLock | null;
98
- private createExclusive;
99
- inProcessLock(now?: number, pid?: number): MainSyncLock;
100
- finishedLock(started: number): MainSyncLock;
101
- /**
102
- * The SLOW path for ONE branch: the branch checked out in `repoRoot`. Runs its own fetch and its
103
- * own `gh` query, so it is the right entry point for a single-worktree caller and for tests.
104
- * The refresher uses computeAllMainSyncStatuses instead — see there for why.
105
- */
106
- computeMainSyncStatus(repoRoot: string): MainSyncStatus;
107
- /**
108
- * The SLOW path for EVERY branch this repo has checked out — what the detached refresher runs.
109
- *
110
- * The cache is shared by all worktrees but was written for one branch, so only one worktree's
111
- * guards were ever armed. Enumerating the worktrees here and writing all of their branches in one
112
- * atomic map arms every worktree off a single refresh.
113
- *
114
- * NETWORK COST DOES NOT SCALE WITH BRANCH COUNT, which is the whole reason this is a separate
115
- * method: ONE `git fetch` and ONE repo-wide `gh pr list` for all N branches (the old code asked
116
- * `gh` twice per branch, so looping it would have cost 2N round trips). Everything after that is
117
- * local git in each worktree — merge-base, rev-parse, diff, ls-files.
118
- *
119
- * The map is rebuilt from the LIVE worktree set every refresh, so a deleted branch or removed
120
- * worktree simply stops appearing. No pruning pass, no unbounded growth.
121
- */
122
- computeAllMainSyncStatuses(repoRoot: string): MainSyncStatusFile;
123
- private hasBranch;
124
- /**
125
- * One branch's status, computed in `worktreePath` (the tree that has it checked out — the
126
- * working-tree overlap signals are only correct from there). Does NOT fetch and does NOT call
127
- * `gh`: both are done once per refresh by the caller.
128
- */
129
- private computeBranchStatus;
130
- private stampForge;
131
- private computeBranchStatusInner;
132
- squashRecoverySteps(currentBranch: string): string[];
133
- /**
134
- * Synchronously stamp a clean "up to date with main" status — call right after a successful merge.
135
- *
136
- * This is the one writer that takes NO lock, and it knows about exactly one branch. It therefore
137
- * goes through writeMainSyncStatus, which MERGES its entry into the existing map; writing a whole
138
- * document from here would wipe every other worktree's entry.
139
- */
140
- stampCleanMainSyncStatus(repoRoot: string): void;
141
- /**
142
- * Refresh `origin/main` WITHOUT writing `.git/FETCH_HEAD`.
143
- *
144
- * WHY the flag is not optional: this runs in a DETACHED background process while the agent is
145
- * running its own foreground `git fetch` / `git pull` in the very same repo. `.git/FETCH_HEAD` is
146
- * a single file that git takes no lock on, so two overlapping fetches interleave their writes and
147
- * can leave the SAME `for-merge` line twice. `git pull` then reads two for-merge entries and dies
148
- * with `fatal: Cannot fast-forward to multiple branches` — wedging the exact command the
149
- * read-stale-guard tells the agent to run. `--no-write-fetch-head` (git >= 2.29) still updates the
150
- * remote-tracking ref, which is all anything downstream reads (`origin/main`, merge-base), so
151
- * nothing here needs FETCH_HEAD written at all.
152
- *
153
- * Older git rejects the flag; only then do we retry the plain form, accepting the old behaviour
154
- * rather than losing the refresh entirely on a pre-2020 git.
155
- */
156
- private fetchOriginMain;
157
- private isUnknownGitOption;
158
- private ensureDir;
159
- private isProcessAlive;
160
- private capture;
161
- private gitBranch;
162
- private localMainHash;
163
- private commitDistance;
164
- private changedFiles;
165
- private featureChangedFiles;
166
- /**
167
- * ONE repo-wide `gh pr list` giving every branch's merged/open PR — replaces the two per-branch
168
- * `--head <branch>` queries. `--limit 200` bounds it; a branch whose only PR is older than that
169
- * falls out of the index and reads as "no PR", which is the fail-OPEN direction (no merged PR =
170
- * no block), the same way a missing `gh` or an offline machine already degraded.
171
- */
172
- private loadPullRequestIndex;
173
- /**
174
- * A `main` entry synthesised WITHOUT a worktree standing on main. Carries only the two hashes
175
- * read-stale-guard / stale-main-bash-guard actually compare (originMain vs the live tree's
176
- * ancestry) — never merged, never conflicting, so it can only ever produce the stale-main verdict.
177
- */
178
- private mainOnlyStatus;
179
- private benignStatus;
180
- }
181
- export declare function mainSyncStatusPath(repoRoot: string): string;
182
- export declare function mainSyncLockPath(repoRoot: string): string;
183
- export declare function readMainSyncStatus(repoRoot: string, branch: string): MainSyncStatus | null;
184
- export declare function readMainSyncStatusFile(repoRoot: string): MainSyncStatusFile | null;
185
- export declare function writeMainSyncStatus(repoRoot: string, status: MainSyncStatus): void;
186
- export declare function writeMainSyncStatusFile(repoRoot: string, file: MainSyncStatusFile): void;
187
- export declare function readMainSyncLock(repoRoot: string): MainSyncLock | null;
188
- export declare function writeMainSyncLock(repoRoot: string, lock: MainSyncLock): void;
189
- export declare function isLockStale(lock: MainSyncLock, hangTimeoutMinutes: number, now?: number): boolean;
190
- export declare function isRefreshInProgress(repoRoot: string, hangTimeoutMinutes: number, now?: number): boolean;
191
- export declare function tryAcquireMainSyncLock(repoRoot: string, hangTimeoutMinutes: number, now?: number, pid?: number): MainSyncLock | null;
192
- export declare function inProcessLock(now?: number, pid?: number): MainSyncLock;
193
- export declare function finishedLock(started: number): MainSyncLock;
194
- export declare function computeMainSyncStatus(repoRoot: string): MainSyncStatus;
195
- export declare function computeAllMainSyncStatuses(repoRoot: string): MainSyncStatusFile;
196
- export declare function squashRecoverySteps(currentBranch: string): string[];
197
- export declare function stampCleanMainSyncStatus(repoRoot: string): void;