@lifeaitools/rdc-skills 0.24.4 → 0.24.6
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/git-sha.json +1 -1
- package/hooks/gate-watchdog-selfcheck.js +245 -0
- package/hooks/post-tool-batch-gate.js +203 -0
- package/hooks/task-completed-gate.js +252 -0
- package/hooks/work-item-exit-gate.js +293 -0
- package/package.json +2 -2
- package/scripts/install-rdc-skills.js +11 -0
- package/tests/harness-gates.test.mjs +265 -0
- package/tests/work-item-exit-gate-l3.test.mjs +197 -0
package/git-sha.json
CHANGED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* gate-watchdog-selfcheck.js — Truth Gate 3.0 Layer 6 (gate watchdog).
|
|
4
|
+
*
|
|
5
|
+
* Registered on `SessionStart`. Per the Claude Code hooks reference,
|
|
6
|
+
* `SessionStart` CANNOT block — so this watchdog is ADVISORY: it prints a loud
|
|
7
|
+
* STOP-banner (like the existing agent-startup guard) when a Truth-Gate
|
|
8
|
+
* component is missing or unregistered, but it always exits 0. A disabled or
|
|
9
|
+
* absent gate is the ultimate bypass (R4); this watchdog surfaces that the
|
|
10
|
+
* moment a session starts, before any work trusts the gate chain.
|
|
11
|
+
*
|
|
12
|
+
* It asserts three things are present + registered:
|
|
13
|
+
* 1. work-item-exit-gate.js — exists in the installed rdc-skills hooks AND is
|
|
14
|
+
* referenced by a registered hook command (PreToolUse).
|
|
15
|
+
* 2. truth-gate.mjs — exists in the repo's .claude/hooks AND is
|
|
16
|
+
* registered on Stop and SubagentStop in .claude/settings.json.
|
|
17
|
+
* 3. the LIVE hookify plugin hooks.json — the plugin's OWN hooks manifest under
|
|
18
|
+
* ~/.claude/plugins/cache/.../hookify/<hash>/hooks/hooks.json.
|
|
19
|
+
* ⛔ It deliberately does NOT trust the dead ~/.claude/hooks/hookify-*.js
|
|
20
|
+
* wrappers — those point at an ORPHANED cache hash and are not the live
|
|
21
|
+
* enforcement path. The watchdog resolves the live manifest and (when both
|
|
22
|
+
* exist) warns if the dead wrappers point at a cache hash that differs from
|
|
23
|
+
* the live one (the exact drift that silently disables hookify).
|
|
24
|
+
*
|
|
25
|
+
* Test seam: the pure decision is `evaluateWatchdog(facts)` where `facts` is a
|
|
26
|
+
* plain object of booleans/paths gathered by the side-effecting probes. The
|
|
27
|
+
* banner text is produced by `renderBanner(findings)`. Both are exported and
|
|
28
|
+
* have no filesystem/process dependency, so the missing-gate banner and the
|
|
29
|
+
* all-present silent path are provable offline.
|
|
30
|
+
*/
|
|
31
|
+
'use strict';
|
|
32
|
+
|
|
33
|
+
const fs = require('fs');
|
|
34
|
+
const os = require('os');
|
|
35
|
+
const path = require('path');
|
|
36
|
+
|
|
37
|
+
const REPO_ROOT = process.env.RDC_TRUTH_GATE_REPO || 'C:/Dev/regen-root';
|
|
38
|
+
const HOOKS_DIR = __dirname; // installed rdc-skills hooks dir (where this file lives)
|
|
39
|
+
|
|
40
|
+
function readJsonSafe(p) {
|
|
41
|
+
try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch (_) { return null; }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Serialize all hook command strings in a settings.json hooks object. */
|
|
45
|
+
function settingsCommandText(settings) {
|
|
46
|
+
if (!settings || !settings.hooks || typeof settings.hooks !== 'object') return '';
|
|
47
|
+
const parts = [];
|
|
48
|
+
for (const event of Object.keys(settings.hooks)) {
|
|
49
|
+
const groups = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : [];
|
|
50
|
+
for (const g of groups) {
|
|
51
|
+
for (const h of Array.isArray(g.hooks) ? g.hooks : []) {
|
|
52
|
+
if (h && typeof h.command === 'string') parts.push(`${event}::${h.command}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return parts.join('\n');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Is a hook command referenced for the given event in the serialized text? */
|
|
60
|
+
function registeredForEvent(commandText, event, needle) {
|
|
61
|
+
return commandText.split('\n').some((line) => line.startsWith(`${event}::`) && line.includes(needle));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Locate the LIVE hookify plugin hooks.json under the plugins cache. Returns the
|
|
66
|
+
* resolved manifest path (the plugin's OWN hooks/hooks.json), or null. NEVER
|
|
67
|
+
* returns one of the dead ~/.claude/hooks/hookify-*.js wrappers.
|
|
68
|
+
*/
|
|
69
|
+
function findLiveHookifyManifest(home) {
|
|
70
|
+
const cacheRoot = path.join(home, '.claude', 'plugins', 'cache');
|
|
71
|
+
const found = [];
|
|
72
|
+
const walk = (dir, depth) => {
|
|
73
|
+
if (depth > 6) return;
|
|
74
|
+
let entries;
|
|
75
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch (_) { return; }
|
|
76
|
+
for (const e of entries) {
|
|
77
|
+
const full = path.join(dir, e.name);
|
|
78
|
+
if (e.isDirectory()) {
|
|
79
|
+
walk(full, depth + 1);
|
|
80
|
+
} else if (e.isFile() && e.name === 'hooks.json' && /hookify/i.test(full)) {
|
|
81
|
+
found.push(full);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
walk(cacheRoot, 0);
|
|
86
|
+
return found.length > 0 ? found[0] : null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Read the cache-hash a dead hookify wrapper points at (its PLUGIN_ROOT). null if none. */
|
|
90
|
+
function deadWrapperPluginRoot(home) {
|
|
91
|
+
const wrapper = path.join(home, '.claude', 'hooks', 'hookify-stop.js');
|
|
92
|
+
try {
|
|
93
|
+
const src = fs.readFileSync(wrapper, 'utf8');
|
|
94
|
+
const m = src.match(/PLUGIN_ROOT\s*=\s*['"]([^'"]+)['"]/);
|
|
95
|
+
return m ? m[1] : null;
|
|
96
|
+
} catch (_) {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Gather the watchdog facts via side-effecting probes. Returns a plain facts
|
|
103
|
+
* object consumed by the pure evaluator. Kept separate from evaluateWatchdog so
|
|
104
|
+
* the decision logic is unit-testable without a filesystem.
|
|
105
|
+
*/
|
|
106
|
+
function gatherFacts({ home = os.homedir(), repoRoot = REPO_ROOT, hooksDir = HOOKS_DIR } = {}) {
|
|
107
|
+
const exitGatePath = path.join(hooksDir, 'work-item-exit-gate.js');
|
|
108
|
+
const truthGatePath = path.join(repoRoot, '.claude', 'hooks', 'truth-gate.mjs');
|
|
109
|
+
const settingsPath = path.join(repoRoot, '.claude', 'settings.json');
|
|
110
|
+
const settings = readJsonSafe(settingsPath);
|
|
111
|
+
const commandText = settingsCommandText(settings);
|
|
112
|
+
|
|
113
|
+
const liveHookifyManifest = findLiveHookifyManifest(home);
|
|
114
|
+
const deadRoot = deadWrapperPluginRoot(home);
|
|
115
|
+
// The live manifest's plugin-root dir (the parent of /hooks/hooks.json).
|
|
116
|
+
const liveRoot = liveHookifyManifest
|
|
117
|
+
? path.dirname(path.dirname(liveHookifyManifest))
|
|
118
|
+
: null;
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
exitGateFileExists: fs.existsSync(exitGatePath),
|
|
122
|
+
exitGateRegistered: registeredForEvent(commandText, 'PreToolUse', 'work-item-exit-gate.js'),
|
|
123
|
+
truthGateFileExists: fs.existsSync(truthGatePath),
|
|
124
|
+
truthGateOnStop: registeredForEvent(commandText, 'Stop', 'truth-gate.mjs'),
|
|
125
|
+
truthGateOnSubagentStop: registeredForEvent(commandText, 'SubagentStop', 'truth-gate.mjs'),
|
|
126
|
+
liveHookifyManifestExists: Boolean(liveHookifyManifest),
|
|
127
|
+
liveHookifyManifestPath: liveHookifyManifest,
|
|
128
|
+
// Drift: a dead wrapper that points at a different cache hash than the live one.
|
|
129
|
+
deadWrapperRoot: deadRoot,
|
|
130
|
+
liveHookifyRoot: liveRoot,
|
|
131
|
+
deadWrapperPointsAtStaleCache: Boolean(
|
|
132
|
+
deadRoot && liveRoot &&
|
|
133
|
+
path.normalize(deadRoot).toLowerCase() !== path.normalize(liveRoot).toLowerCase(),
|
|
134
|
+
),
|
|
135
|
+
// paths for the banner / log
|
|
136
|
+
exitGatePath,
|
|
137
|
+
truthGatePath,
|
|
138
|
+
settingsPath,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Pure decision over the gathered facts. Returns an array of finding strings
|
|
144
|
+
* (empty = all gates healthy). The live hookify check is explicitly the PLUGIN
|
|
145
|
+
* manifest, not the dead wrappers.
|
|
146
|
+
*/
|
|
147
|
+
function evaluateWatchdog(facts = {}) {
|
|
148
|
+
const findings = [];
|
|
149
|
+
if (!facts.exitGateFileExists) {
|
|
150
|
+
findings.push(`work-item-exit-gate.js is MISSING from the installed hooks (${facts.exitGatePath || '?'}).`);
|
|
151
|
+
}
|
|
152
|
+
if (!facts.exitGateRegistered) {
|
|
153
|
+
findings.push('work-item-exit-gate.js is NOT registered on a PreToolUse hook in .claude/settings.json.');
|
|
154
|
+
}
|
|
155
|
+
if (!facts.truthGateFileExists) {
|
|
156
|
+
findings.push(`truth-gate.mjs is MISSING from the repo (${facts.truthGatePath || '?'}).`);
|
|
157
|
+
}
|
|
158
|
+
if (!facts.truthGateOnStop) {
|
|
159
|
+
findings.push('truth-gate.mjs is NOT registered on the Stop event in .claude/settings.json.');
|
|
160
|
+
}
|
|
161
|
+
if (!facts.truthGateOnSubagentStop) {
|
|
162
|
+
findings.push('truth-gate.mjs is NOT registered on the SubagentStop event in .claude/settings.json.');
|
|
163
|
+
}
|
|
164
|
+
if (!facts.liveHookifyManifestExists) {
|
|
165
|
+
findings.push(
|
|
166
|
+
'The LIVE hookify plugin hooks.json could not be found under ~/.claude/plugins/cache/**/hookify/**/hooks/hooks.json. ' +
|
|
167
|
+
'Hookify enforcement may be disabled. (The dead ~/.claude/hooks/hookify-*.js wrappers are NOT the live path and are not trusted here.)',
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
if (facts.deadWrapperPointsAtStaleCache) {
|
|
171
|
+
findings.push(
|
|
172
|
+
`The dead ~/.claude/hooks/hookify-*.js wrappers point at an ORPHANED cache hash (${facts.deadWrapperRoot}) ` +
|
|
173
|
+
`that differs from the live plugin (${facts.liveHookifyRoot}). The wrappers are stale; the live plugin manifest is authoritative.`,
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
return findings;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Render the loud STOP-banner from findings. Empty findings → empty string. */
|
|
180
|
+
function renderBanner(findings) {
|
|
181
|
+
if (!Array.isArray(findings) || findings.length === 0) return '';
|
|
182
|
+
const lines = findings.map((f) => ` ⛔ ${f}`).join('\n');
|
|
183
|
+
return (
|
|
184
|
+
'\n' +
|
|
185
|
+
'════════════════════════════════════════════════════════════════════════\n' +
|
|
186
|
+
'⛔⛔ TRUTH GATE WATCHDOG — A GATE IS MISSING OR UNREGISTERED ⛔⛔\n' +
|
|
187
|
+
'════════════════════════════════════════════════════════════════════════\n' +
|
|
188
|
+
'The Truth Gate enforcement chain is INCOMPLETE for this session. A disabled\n' +
|
|
189
|
+
'or unregistered gate is the ultimate closure bypass. Findings:\n\n' +
|
|
190
|
+
lines + '\n\n' +
|
|
191
|
+
'Repair before trusting any work-item closure this session:\n' +
|
|
192
|
+
' node C:/Dev/rdc-skills/scripts/install-rdc-skills.js (reinstall the hooks)\n' +
|
|
193
|
+
' then verify .claude/settings.json registers truth-gate.mjs on Stop+SubagentStop\n' +
|
|
194
|
+
' and work-item-exit-gate.js on PreToolUse.\n' +
|
|
195
|
+
'════════════════════════════════════════════════════════════════════════\n'
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function main() {
|
|
200
|
+
// Drain stdin if present (SessionStart delivers JSON); we don't need its body.
|
|
201
|
+
try {
|
|
202
|
+
const chunks = [];
|
|
203
|
+
process.stdin.on('data', (c) => chunks.push(c));
|
|
204
|
+
process.stdin.on('end', () => finish());
|
|
205
|
+
process.stdin.resume();
|
|
206
|
+
// If no stdin arrives quickly, finish anyway (SessionStart may pass nothing).
|
|
207
|
+
setTimeout(finish, 1500);
|
|
208
|
+
} catch (_) {
|
|
209
|
+
finish();
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
let _finished = false;
|
|
214
|
+
function finish() {
|
|
215
|
+
if (_finished) return;
|
|
216
|
+
_finished = true;
|
|
217
|
+
let findings = [];
|
|
218
|
+
try {
|
|
219
|
+
findings = evaluateWatchdog(gatherFacts());
|
|
220
|
+
} catch (e) {
|
|
221
|
+
// Even the watchdog crashing must not block the session — advisory only.
|
|
222
|
+
findings = [`gate-watchdog self-check crashed: ${e && e.message ? e.message : String(e)}`];
|
|
223
|
+
}
|
|
224
|
+
const banner = renderBanner(findings);
|
|
225
|
+
if (banner) {
|
|
226
|
+
// SessionStart context output via systemMessage; also emit to stderr so it
|
|
227
|
+
// is visible like the agent-startup guard. ADVISORY — always exit 0.
|
|
228
|
+
process.stdout.write(JSON.stringify({ systemMessage: banner }));
|
|
229
|
+
process.stderr.write(banner);
|
|
230
|
+
}
|
|
231
|
+
process.exit(0); // SessionStart cannot block — never exit non-zero.
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
if (require.main === module) {
|
|
235
|
+
main();
|
|
236
|
+
} else {
|
|
237
|
+
module.exports = {
|
|
238
|
+
evaluateWatchdog,
|
|
239
|
+
renderBanner,
|
|
240
|
+
gatherFacts,
|
|
241
|
+
findLiveHookifyManifest,
|
|
242
|
+
settingsCommandText,
|
|
243
|
+
registeredForEvent,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* post-tool-batch-gate.js — Truth Gate 3.0 Layer 5 (per-wave batch gate).
|
|
4
|
+
*
|
|
5
|
+
* Registered on the `PostToolBatch` event — it fires after a full batch of
|
|
6
|
+
* parallel tool calls resolves, BEFORE the next model call. Per the Claude Code
|
|
7
|
+
* hooks reference, `PostToolBatch` CAN block (exit code 2 stops the agentic
|
|
8
|
+
* loop). After a parallel build wave (multiple Agent dispatches into isolated
|
|
9
|
+
* worktrees), this gate asserts the wave's worktree bases are sane — every agent
|
|
10
|
+
* worktree must be based on the current `develop` HEAD — so a stale-base wave
|
|
11
|
+
* cannot feed fabricated/diverged closures into the next model turn.
|
|
12
|
+
*
|
|
13
|
+
* ⛔ FLAG-GATED, DEFAULT OFF. Until the flag is flipped at deploy this hook is a
|
|
14
|
+
* pure no-op (exit 0) so the in-flight build session is NOT disrupted. When the
|
|
15
|
+
* flag is ON it is FAIL-CLOSED: an inability to confirm worktree-base sanity is
|
|
16
|
+
* a BLOCK, never a silent pass.
|
|
17
|
+
*
|
|
18
|
+
* Flag (default OFF):
|
|
19
|
+
* - env RDC_TRUTHGATE_POSTTOOLBATCH in {1,true,on,yes}.
|
|
20
|
+
*
|
|
21
|
+
* Worktree-base sanity, per worktree:
|
|
22
|
+
* - resolve develop HEAD: `git rev-parse refs/heads/develop` in the main repo.
|
|
23
|
+
* - for each linked worktree (`git worktree list --porcelain`), its base must
|
|
24
|
+
* equal develop HEAD — i.e. develop is an ancestor of the worktree HEAD
|
|
25
|
+
* (`git merge-base --is-ancestor <developHead> <worktreeHead>`), OR the
|
|
26
|
+
* worktree HEAD already IS develop HEAD. A worktree whose base predates the
|
|
27
|
+
* current develop HEAD is STALE and the wave is flagged.
|
|
28
|
+
*
|
|
29
|
+
* Test seam: inject the git surface via the exported pure `evaluateWave({
|
|
30
|
+
* developHead, worktrees, isAncestor })`, where `worktrees` is
|
|
31
|
+
* [{ path, head }] and `isAncestor(a,b)` returns whether a is an ancestor of b.
|
|
32
|
+
* The pure evaluator has no process/network dependency, so the flag-OFF no-op
|
|
33
|
+
* and the stale-base FLAG branches are provable offline.
|
|
34
|
+
*/
|
|
35
|
+
'use strict';
|
|
36
|
+
|
|
37
|
+
const { execFileSync } = require('child_process');
|
|
38
|
+
const hookLog = require('./hook-logger');
|
|
39
|
+
|
|
40
|
+
const FULL_SHA_RE = /^[0-9a-f]{40}$/i;
|
|
41
|
+
const MAIN_REPO = process.env.RDC_TRUTH_GATE_REPO || 'C:/Dev/regen-root';
|
|
42
|
+
|
|
43
|
+
function readStdin() {
|
|
44
|
+
return new Promise((resolve) => {
|
|
45
|
+
let input = '';
|
|
46
|
+
process.stdin.setEncoding('utf8');
|
|
47
|
+
process.stdin.on('data', (chunk) => { input += chunk; });
|
|
48
|
+
process.stdin.on('end', () => resolve(input));
|
|
49
|
+
process.stdin.resume();
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Block the batch with exit code 2 (the blocking semantics for PostToolBatch). */
|
|
54
|
+
function block(reason, details = {}) {
|
|
55
|
+
hookLog('post-tool-batch-gate', 'PostToolBatch', 'block', { reason, ...details });
|
|
56
|
+
process.stdout.write(JSON.stringify({
|
|
57
|
+
decision: 'block',
|
|
58
|
+
reason: `BUILD WAVE FLAGGED — Truth Gate Layer 5 (PostToolBatch).\n\n${reason}`,
|
|
59
|
+
}));
|
|
60
|
+
process.stderr.write(`BUILD WAVE FLAGGED: ${reason}\n`);
|
|
61
|
+
process.exit(2);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function pass(details = {}) {
|
|
65
|
+
hookLog('post-tool-batch-gate', 'PostToolBatch', 'pass', details);
|
|
66
|
+
process.exit(0);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Default OFF. Only the env switch enables it (test-stable, deploy-flippable). */
|
|
70
|
+
function flagEnabledEnv() {
|
|
71
|
+
const v = String(process.env.RDC_TRUTHGATE_POSTTOOLBATCH || '').trim().toLowerCase();
|
|
72
|
+
return v === '1' || v === 'true' || v === 'on' || v === 'yes';
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function git(args, { cwd = MAIN_REPO, allowFail = false } = {}) {
|
|
76
|
+
try {
|
|
77
|
+
return execFileSync('git', args, {
|
|
78
|
+
cwd,
|
|
79
|
+
encoding: 'utf8',
|
|
80
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
81
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
82
|
+
}).trim();
|
|
83
|
+
} catch (e) {
|
|
84
|
+
if (allowFail) return null;
|
|
85
|
+
throw e;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Resolve develop's HEAD SHA in the main repo, or null. */
|
|
90
|
+
function developHead() {
|
|
91
|
+
const sha = git(['rev-parse', '--verify', '--quiet', 'refs/heads/develop'], { allowFail: true });
|
|
92
|
+
return sha && FULL_SHA_RE.test(sha) ? sha.toLowerCase() : null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Parse `git worktree list --porcelain` into [{ path, head }] (linked only). */
|
|
96
|
+
function listWorktrees() {
|
|
97
|
+
const out = git(['worktree', 'list', '--porcelain'], { allowFail: true });
|
|
98
|
+
if (out == null) return null;
|
|
99
|
+
const worktrees = [];
|
|
100
|
+
let cur = null;
|
|
101
|
+
for (const line of out.split('\n')) {
|
|
102
|
+
if (line.startsWith('worktree ')) {
|
|
103
|
+
if (cur) worktrees.push(cur);
|
|
104
|
+
cur = { path: line.slice('worktree '.length).trim(), head: null, bare: false };
|
|
105
|
+
} else if (line.startsWith('HEAD ')) {
|
|
106
|
+
if (cur) cur.head = line.slice('HEAD '.length).trim().toLowerCase();
|
|
107
|
+
} else if (line.trim() === 'bare') {
|
|
108
|
+
if (cur) cur.bare = true;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
if (cur) worktrees.push(cur);
|
|
112
|
+
// Linked worktrees only: drop the bare entry and the primary checkout (== MAIN_REPO).
|
|
113
|
+
const norm = (p) => String(p || '').replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase();
|
|
114
|
+
const mainNorm = norm(MAIN_REPO);
|
|
115
|
+
return worktrees.filter((w) => !w.bare && w.head && norm(w.path) !== mainNorm);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** True when `git merge-base --is-ancestor a b` (a is an ancestor of b). */
|
|
119
|
+
function isAncestor(a, b) {
|
|
120
|
+
if (!a || !b) return false;
|
|
121
|
+
if (a === b) return true;
|
|
122
|
+
// exit 0 = ancestor, exit 1 = not. allowFail captures the non-zero exit.
|
|
123
|
+
try {
|
|
124
|
+
execFileSync('git', ['merge-base', '--is-ancestor', a, b], {
|
|
125
|
+
cwd: MAIN_REPO,
|
|
126
|
+
stdio: ['ignore', 'ignore', 'ignore'],
|
|
127
|
+
});
|
|
128
|
+
return true;
|
|
129
|
+
} catch (_) {
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Pure wave evaluator (unit-testable, no process/network). Returns
|
|
136
|
+
* { stale: [{ path, head }], ok: boolean }. A worktree is STALE when develop
|
|
137
|
+
* HEAD is NOT an ancestor of its HEAD (its base predates current develop), and
|
|
138
|
+
* its HEAD is not develop HEAD itself.
|
|
139
|
+
*
|
|
140
|
+
* @param {object} surface
|
|
141
|
+
* @param {string|null} surface.developHead develop HEAD SHA (null → cannot evaluate)
|
|
142
|
+
* @param {Array<{path,head}>} surface.worktrees linked worktrees
|
|
143
|
+
* @param {(a:string,b:string)=>boolean} surface.isAncestor
|
|
144
|
+
*/
|
|
145
|
+
function evaluateWave({ developHead, worktrees, isAncestor: anc }) {
|
|
146
|
+
if (!developHead) {
|
|
147
|
+
return { ok: false, cannotEvaluate: true, stale: [] };
|
|
148
|
+
}
|
|
149
|
+
const list = Array.isArray(worktrees) ? worktrees : [];
|
|
150
|
+
const stale = [];
|
|
151
|
+
for (const w of list) {
|
|
152
|
+
if (!w || !w.head) continue;
|
|
153
|
+
const based = w.head === developHead || anc(developHead, w.head);
|
|
154
|
+
if (!based) stale.push({ path: w.path, head: w.head });
|
|
155
|
+
}
|
|
156
|
+
return { ok: stale.length === 0, cannotEvaluate: false, stale };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function main() {
|
|
160
|
+
// Drain stdin (PostToolBatch payload) — we don't need its body, but the event
|
|
161
|
+
// delivers JSON on stdin and the process should consume it cleanly.
|
|
162
|
+
try { await readStdin(); } catch (_) {}
|
|
163
|
+
|
|
164
|
+
// Default-OFF: a no-op until the flag is flipped at deploy.
|
|
165
|
+
if (!flagEnabledEnv()) return pass({ reason: 'flag-off' });
|
|
166
|
+
|
|
167
|
+
// FAIL-CLOSED from here.
|
|
168
|
+
const head = developHead();
|
|
169
|
+
const worktrees = listWorktrees();
|
|
170
|
+
if (head == null || worktrees == null) {
|
|
171
|
+
block(
|
|
172
|
+
`Could not read git state in ${MAIN_REPO} (develop HEAD or worktree list unavailable). ` +
|
|
173
|
+
`Fail-closed: cannot confirm the build wave's worktree bases are current.`,
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const verdict = evaluateWave({ developHead: head, worktrees, isAncestor });
|
|
178
|
+
if (verdict.cannotEvaluate) {
|
|
179
|
+
block(`develop HEAD could not be resolved; fail-closed — cannot confirm worktree-base sanity for this wave.`);
|
|
180
|
+
}
|
|
181
|
+
if (!verdict.ok) {
|
|
182
|
+
const lines = verdict.stale.map((s) => ` - ${s.path} @ ${s.head.slice(0, 9)} (base predates develop ${head.slice(0, 9)})`).join('\n');
|
|
183
|
+
block(
|
|
184
|
+
`One or more build-wave worktrees are NOT based on the current develop HEAD ${head.slice(0, 9)}:\n${lines}\n\n` +
|
|
185
|
+
`A wave built on a stale base can feed diverged/fabricated closures into the next turn. ` +
|
|
186
|
+
`Rebase each worktree onto develop (git fetch && git rebase origin/develop), re-run its verification, then continue.`,
|
|
187
|
+
{ developHead: head, stale: verdict.stale },
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
pass({ developHead: head, worktreeCount: worktrees.length });
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (require.main === module) {
|
|
195
|
+
main().catch((e) => block(`post-tool-batch-gate crashed: ${e.message}`));
|
|
196
|
+
} else {
|
|
197
|
+
module.exports = {
|
|
198
|
+
flagEnabledEnv,
|
|
199
|
+
evaluateWave,
|
|
200
|
+
listWorktrees,
|
|
201
|
+
developHead,
|
|
202
|
+
};
|
|
203
|
+
}
|