@lifeaitools/rdc-skills 0.24.5 → 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 CHANGED
@@ -1,3 +1,3 @@
1
1
  {
2
- "sha": "c8a28f6d5c90e94b2e2429b40ffb2752eda66887"
2
+ "sha": "c7ae6c2095cf0f711bf4740bc82adbdb805ab966"
3
3
  }
@@ -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
+ }
@@ -0,0 +1,252 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * task-completed-gate.js — Truth Gate 3.0 Layer 5 (harness completion gate).
4
+ *
5
+ * Registered on the `TaskCompleted` event. Per the Claude Code hooks reference,
6
+ * `TaskCompleted` CAN block (exit code 2 / decision "block" prevents the task
7
+ * from being marked completed). This hook makes a task completion structurally
8
+ * dependent on a SOUND work-item closure: a task cannot complete unless the
9
+ * work item it references is `done` AND that `done` was admitted by Layers 2–3
10
+ * (the FUSED evidence gate + the validator re-run receipt) — i.e. the work item
11
+ * carries an HMAC-valid, witnessed `implementation_report.codeflow_post` and is
12
+ * in status `done`. The exit gate (work-item-exit-gate.js) is what proves
13
+ * Layers 2–3 at `done` time; this gate refuses to let a TASK finish on a work
14
+ * item that never reached that sound `done` state.
15
+ *
16
+ * ⛔ FLAG-GATED, DEFAULT OFF. Until the flag is flipped at deploy this hook is a
17
+ * pure no-op (exit 0) so the in-flight build session is NOT disrupted — the
18
+ * blocking Stop/SubagentStop truth-gate is already live and gating capability
19
+ * claims; this layer is dormant until activation. When the flag is ON it is
20
+ * FAIL-CLOSED: an inability to verify a sound closure is a BLOCK, never a pass.
21
+ *
22
+ * Flag (default OFF), either enables it:
23
+ * - env RDC_TRUTHGATE_TASKCOMPLETED in {1,true,on,yes}, OR
24
+ * - DB public.truthgate_flags(flag='taskcompleted', enabled=true) (best-effort).
25
+ *
26
+ * Offline test seam: when RDC_TASKCOMPLETED_CLOSURE_SINK points at a JSON file,
27
+ * the hook reads the closure row from that file instead of Supabase. This lets
28
+ * the gate be proven without a live DB. The sink shape is a single work_items
29
+ * row: { id, status, item_type, implementation_report }.
30
+ */
31
+ 'use strict';
32
+
33
+ const fs = require('fs');
34
+ const path = require('path');
35
+ const hookLog = require('./hook-logger');
36
+
37
+ const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
38
+ const WITNESS_ALLOWLIST = new Set(['validator-rerun', 'ci', 'human-review']);
39
+ const DEFAULT_SUPABASE_URL = 'https://uvojezuorjgqzmhhgluu.supabase.co';
40
+
41
+ function readStdin() {
42
+ return new Promise((resolve) => {
43
+ let input = '';
44
+ process.stdin.setEncoding('utf8');
45
+ process.stdin.on('data', (chunk) => { input += chunk; });
46
+ process.stdin.on('end', () => resolve(input));
47
+ process.stdin.resume();
48
+ });
49
+ }
50
+
51
+ /** Block the TaskCompleted with exit code 2 (the blocking semantics for this event). */
52
+ function block(reason, details = {}) {
53
+ hookLog('task-completed-gate', 'TaskCompleted', 'block', { reason, ...details });
54
+ process.stdout.write(JSON.stringify({
55
+ decision: 'block',
56
+ reason: `TASK COMPLETION BLOCKED — Truth Gate Layer 5 (TaskCompleted).\n\n${reason}`,
57
+ }));
58
+ process.stderr.write(`TASK COMPLETION BLOCKED: ${reason}\n`);
59
+ process.exit(2);
60
+ }
61
+
62
+ function pass(details = {}) {
63
+ hookLog('task-completed-gate', 'TaskCompleted', 'pass', details);
64
+ process.exit(0);
65
+ }
66
+
67
+ /**
68
+ * Is the Layer-5 TaskCompleted gate enabled? Default OFF (returns false).
69
+ * Mirrors work-item-exit-gate.js truthGateFlagEnabled — env is the authoritative,
70
+ * test-stable switch; a DB toggle is an optional deploy-time enable.
71
+ */
72
+ function flagEnabledEnv() {
73
+ const v = String(process.env.RDC_TRUTHGATE_TASKCOMPLETED || '').trim().toLowerCase();
74
+ return v === '1' || v === 'true' || v === 'on' || v === 'yes';
75
+ }
76
+
77
+ async function getServiceKey() {
78
+ if (process.env.SUPABASE_SERVICE_ROLE_KEY) return process.env.SUPABASE_SERVICE_ROLE_KEY;
79
+ if (process.env.SUPABASE_SERVICE_KEY) return process.env.SUPABASE_SERVICE_KEY;
80
+ for (const endpoint of ['supabase-service', 'supabase-service-role']) {
81
+ try {
82
+ const res = await fetch(`http://127.0.0.1:52437/v/${endpoint}`, { signal: AbortSignal.timeout(2000) });
83
+ if (res.ok) {
84
+ const text = (await res.text()).trim();
85
+ if (text && !text.startsWith('{')) return text;
86
+ }
87
+ } catch (_) {}
88
+ }
89
+ return null;
90
+ }
91
+
92
+ async function supabaseGet(pathname) {
93
+ const key = await getServiceKey();
94
+ if (!key) throw new Error('clauth/env did not provide a Supabase service key');
95
+ const base = (process.env.SUPABASE_URL || process.env.NEXT_PUBLIC_SUPABASE_URL || DEFAULT_SUPABASE_URL).replace(/\/$/, '');
96
+ const res = await fetch(`${base}/rest/v1/${pathname}`, {
97
+ headers: { apikey: key, Authorization: `Bearer ${key}`, Accept: 'application/json' },
98
+ signal: AbortSignal.timeout(3500),
99
+ });
100
+ if (!res.ok) throw new Error(`Supabase HTTP ${res.status}`);
101
+ return res.json();
102
+ }
103
+
104
+ /** Best-effort DB flag toggle. Absence/error → false (stays OFF). */
105
+ async function flagEnabledDb() {
106
+ try {
107
+ const rows = await supabaseGet('truthgate_flags?flag=eq.taskcompleted&select=enabled&limit=1');
108
+ return Array.isArray(rows) && rows[0] && rows[0].enabled === true;
109
+ } catch (_) {
110
+ return false;
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Extract the work-item UUID a task is bound to from the TaskCompleted payload.
116
+ * Looks in the common task fields and falls back to the first UUID anywhere in
117
+ * the serialized payload (the closure ref the agent recorded against the task).
118
+ * Returns the lowercased UUID or null.
119
+ */
120
+ function extractWorkItemId(raw) {
121
+ const candidates = [
122
+ raw && raw.work_item_id,
123
+ raw && raw.task && raw.task.work_item_id,
124
+ raw && raw.task && raw.task.metadata && raw.task.metadata.work_item_id,
125
+ raw && raw.metadata && raw.metadata.work_item_id,
126
+ ];
127
+ for (const c of candidates) {
128
+ if (typeof c === 'string' && UUID_RE.test(c)) return c.match(UUID_RE)[0].toLowerCase();
129
+ }
130
+ let blob = '';
131
+ try { blob = JSON.stringify(raw); } catch (_) { blob = String(raw || ''); }
132
+ const m = blob.match(UUID_RE);
133
+ return m ? m[0].toLowerCase() : null;
134
+ }
135
+
136
+ /**
137
+ * Is the work-item closure SOUND for completion? Pure + unit-testable; returns
138
+ * { ok:true } or { ok:false, reason } — never throws. A sound closure for an
139
+ * implementation task requires (mirrors the L2/L3 contract the exit gate proves
140
+ * at `done` time):
141
+ * - the row exists
142
+ * - status === 'done' (the exit gate admitted it; epics are exempt below)
143
+ * - implementation_report.codeflow_post exists
144
+ * - codeflow_post.witness ∈ allow-list (never 'agent' / self-witness, D5)
145
+ * - codeflow_post.commit is present (a captured SHA the exit gate matched)
146
+ * - codeflow_post.files_changed is a non-empty array
147
+ * - codeflow_post.verification is a non-empty array
148
+ * Epics are not implementation tasks — an epic row is considered sound on
149
+ * status alone (the exit gate exempts epics from L2/L3).
150
+ */
151
+ function closureIsSound(row) {
152
+ if (!row || typeof row !== 'object') {
153
+ return { ok: false, reason: 'no work-item closure row found for this task — cannot confirm a sound, Layer 2–3-admitted `done`.' };
154
+ }
155
+ if (row.item_type === 'epic') {
156
+ return row.status === 'done'
157
+ ? { ok: true }
158
+ : { ok: false, reason: `linked epic ${row.id} is status "${row.status}", not "done".` };
159
+ }
160
+ if (row.status !== 'done') {
161
+ return { ok: false, reason: `linked work item ${row.id} is status "${row.status}", not "done" — the exit gate has not admitted a Layer 2–3 closure.` };
162
+ }
163
+ const report = row.implementation_report;
164
+ if (!report || typeof report !== 'object') {
165
+ return { ok: false, reason: `work item ${row.id} has no implementation_report — a sound closure must carry one.` };
166
+ }
167
+ const post = report.codeflow_post;
168
+ if (!post || typeof post !== 'object') {
169
+ return { ok: false, reason: `work item ${row.id} has no implementation_report.codeflow_post — Layer 2–3 evidence absent.` };
170
+ }
171
+ const witness = String(post.witness || '');
172
+ if (!WITNESS_ALLOWLIST.has(witness)) {
173
+ return { ok: false, reason: `closure witness "${witness || '<missing>'}" is not in {validator-rerun, ci, human-review} — the doer cannot self-witness (D5).` };
174
+ }
175
+ if (typeof post.commit !== 'string' || !post.commit.trim()) {
176
+ return { ok: false, reason: `closure codeflow_post.commit is missing — no captured commit to bind the closure to.` };
177
+ }
178
+ if (!Array.isArray(post.files_changed) || post.files_changed.length === 0) {
179
+ return { ok: false, reason: `closure codeflow_post.files_changed is empty — a sound closure names the files it changed.` };
180
+ }
181
+ if (!Array.isArray(post.verification) || post.verification.length === 0) {
182
+ return { ok: false, reason: `closure codeflow_post.verification is empty — a sound closure carries a captured verification artifact.` };
183
+ }
184
+ return { ok: true };
185
+ }
186
+
187
+ /** Load the closure row: offline sink first (test seam), else Supabase. */
188
+ async function loadClosureRow(workItemId) {
189
+ const sink = process.env.RDC_TASKCOMPLETED_CLOSURE_SINK;
190
+ if (sink) {
191
+ const txt = fs.readFileSync(sink, 'utf8');
192
+ const parsed = JSON.parse(txt);
193
+ return Array.isArray(parsed) ? parsed[0] : parsed;
194
+ }
195
+ const rows = await supabaseGet(
196
+ `work_items?id=eq.${encodeURIComponent(workItemId)}&select=id,status,item_type,implementation_report&limit=1`,
197
+ );
198
+ return Array.isArray(rows) ? rows[0] : null;
199
+ }
200
+
201
+ async function main() {
202
+ let raw;
203
+ try { raw = JSON.parse(await readStdin()); } catch { process.exit(0); }
204
+
205
+ // Default-OFF: a no-op until the flag is flipped at deploy.
206
+ const enabled = flagEnabledEnv() || (await flagEnabledDb().catch(() => false));
207
+ if (!enabled) return pass({ reason: 'flag-off' });
208
+
209
+ // FAIL-CLOSED from here: any inability to confirm a sound closure is a BLOCK.
210
+ const workItemId = extractWorkItemId(raw);
211
+ if (!workItemId) {
212
+ block(
213
+ 'This task completion carries no work-item reference, so its closure cannot be verified against the ' +
214
+ 'Layer 2–3 exit gate. Bind the task to its work item (record the work-item UUID on the task/closure) and retry.',
215
+ );
216
+ }
217
+
218
+ let row;
219
+ try {
220
+ row = await loadClosureRow(workItemId);
221
+ } catch (e) {
222
+ block(
223
+ `Could not load the work-item closure for ${workItemId} (${e && e.message ? e.message : String(e)}). ` +
224
+ `Fail-closed: not completing the task until the closure can be verified.`,
225
+ { workItemId },
226
+ );
227
+ }
228
+
229
+ const verdict = closureIsSound(row);
230
+ if (!verdict.ok) {
231
+ block(
232
+ `${verdict.reason}\n\n` +
233
+ `A task may only complete once its work item has reached a sound, Layer 2–3-admitted \`done\` ` +
234
+ `(HMAC-valid, witnessed codeflow_post via the validator path). Move the work item through review → validator ` +
235
+ `\`done\` first, then complete the task.`,
236
+ { workItemId },
237
+ );
238
+ }
239
+
240
+ pass({ workItemId });
241
+ }
242
+
243
+ if (require.main === module) {
244
+ main().catch((e) => block(`task-completed-gate crashed: ${e.message}`));
245
+ } else {
246
+ module.exports = {
247
+ flagEnabledEnv,
248
+ extractWorkItemId,
249
+ closureIsSound,
250
+ WITNESS_ALLOWLIST,
251
+ };
252
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lifeaitools/rdc-skills",
3
- "version": "0.24.5",
3
+ "version": "0.24.6",
4
4
  "description": "RDC typed-agent dispatch skill suite for Claude Code - plan, build, review, overnight builds",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -34,7 +34,7 @@
34
34
  "validate": "node tests/validate-skills.js",
35
35
  "rdc-design": "node scripts/rdc-design-cli.mjs",
36
36
  "test:hooks": "node scripts/test-rdc-hooks.mjs",
37
- "test:truth-gate": "node tests/run-evidence-gate.test.mjs && node tests/work-item-exit-gate-l2.test.mjs && node tests/work-item-exit-gate-l3.test.mjs && node tests/require-work-item-on-commit.test.mjs",
37
+ "test:truth-gate": "node tests/run-evidence-gate.test.mjs && node tests/work-item-exit-gate-l2.test.mjs && node tests/work-item-exit-gate-l3.test.mjs && node tests/require-work-item-on-commit.test.mjs && node tests/harness-gates.test.mjs",
38
38
  "test:mcp": "node tests/mcp.test.mjs",
39
39
  "test:mcp:remote": "node tests/mcp.test.mjs --remote",
40
40
  "mcp": "node bin/rdc-skills-mcp.mjs",
@@ -715,10 +715,21 @@ function buildHooksConfig(hooksDir, profile = 'core') {
715
715
  cmd('check-rdc-environment.js', 'Checking RDC skills runtime...'),
716
716
  cmd('check-cwd.js'),
717
717
  cmd('check-stale-work-items.js', 'Checking for stale work items...'),
718
+ // Truth Gate 3.0 Layer 6 — gate watchdog (ADVISORY; SessionStart cannot block).
719
+ cmd('gate-watchdog-selfcheck.js', 'Truth Gate watchdog: verifying gate registration...'),
718
720
  ]}];
719
721
  config.PreToolUse[0].hooks.push(
720
722
  cmd('work-item-exit-gate.js', 'Checking work item exit gates...'),
721
723
  );
724
+ // Truth Gate 3.0 Layer 5 — harness completion gates. Both blocking hooks are
725
+ // FLAG-GATED, default OFF (no-op until the env/DB flag is flipped at deploy),
726
+ // so registering them does NOT disrupt the in-flight build session.
727
+ config.TaskCompleted = [{ hooks: [
728
+ cmd('task-completed-gate.js', 'Truth Gate: verifying task closure...'),
729
+ ]}];
730
+ config.PostToolBatch = [{ hooks: [
731
+ cmd('post-tool-batch-gate.js', 'Truth Gate: checking build-wave worktree bases...'),
732
+ ]}];
722
733
  config.PreCompact = [{ hooks: [
723
734
  cmd('precompact-log.js'),
724
735
  ]}];
@@ -0,0 +1,265 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Truth Gate 3.0 — Layers 5+6 harness-gate tests (WP-5).
4
+ *
5
+ * Covers the three new hooks, fully offline (no DB, no brain, no clauth):
6
+ * task-completed-gate.js — flag OFF no-op; flag ON + no/unsound closure BLOCK;
7
+ * flag ON + sound closure PASS.
8
+ * post-tool-batch-gate.js — flag OFF no-op; flag ON + stale worktree base FLAG;
9
+ * flag ON + current base PASS.
10
+ * gate-watchdog-selfcheck — STOP-banner when a gate file/registration absent;
11
+ * silent when all present; checks the LIVE hookify
12
+ * hooks.json (plugin manifest), not the dead wrappers.
13
+ *
14
+ * Run: node tests/harness-gates.test.mjs
15
+ */
16
+ import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
17
+ import { tmpdir } from 'node:os';
18
+ import { join, resolve, dirname } from 'node:path';
19
+ import { fileURLToPath } from 'node:url';
20
+ import { spawnSync } from 'node:child_process';
21
+ import { createRequire } from 'node:module';
22
+
23
+ const __dirname = dirname(fileURLToPath(import.meta.url));
24
+ const REPO_ROOT = resolve(__dirname, '..');
25
+ const HOOKS = join(REPO_ROOT, 'hooks');
26
+ const require = createRequire(import.meta.url);
27
+
28
+ const failures = [];
29
+ function assert(name, condition, detail = '') {
30
+ if (!condition) failures.push(`${name}${detail ? `: ${detail}` : ''}`);
31
+ else process.stdout.write(` ok ${name}\n`);
32
+ }
33
+
34
+ function runHook(file, payload, extraEnv = {}) {
35
+ return spawnSync(process.execPath, [join(HOOKS, file)], {
36
+ input: JSON.stringify(payload),
37
+ encoding: 'utf8',
38
+ env: { ...process.env, ...extraEnv },
39
+ });
40
+ }
41
+
42
+ const WI = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';
43
+
44
+ // ===========================================================================
45
+ // 1. task-completed-gate.js
46
+ // ===========================================================================
47
+ {
48
+ const tcg = require(join(HOOKS, 'task-completed-gate.js'));
49
+
50
+ // pure: closureIsSound branches
51
+ assert('TCG closureIsSound: null row → not ok', tcg.closureIsSound(null).ok === false);
52
+ assert('TCG closureIsSound: not-done task → not ok',
53
+ tcg.closureIsSound({ id: WI, item_type: 'task', status: 'review' }).ok === false);
54
+ assert('TCG closureIsSound: done but witness:agent → not ok',
55
+ tcg.closureIsSound({ id: WI, item_type: 'task', status: 'done', implementation_report: { codeflow_post: { witness: 'agent', commit: 'x', files_changed: ['f'], verification: [{ exit_code: 0 }] } } }).ok === false);
56
+ const soundRow = {
57
+ id: WI, item_type: 'task', status: 'done',
58
+ implementation_report: { codeflow_post: { witness: 'validator-rerun', commit: 'c3189c9d58a37d648e9de4a6bcd7d46772053eea', files_changed: ['hooks/x.js'], verification: [{ exit_code: 0 }] } },
59
+ };
60
+ assert('TCG closureIsSound: full sound closure → ok', tcg.closureIsSound(soundRow).ok === true,
61
+ tcg.closureIsSound(soundRow).reason || '');
62
+ assert('TCG closureIsSound: epic done → ok',
63
+ tcg.closureIsSound({ id: WI, item_type: 'epic', status: 'done' }).ok === true);
64
+
65
+ // pure: extractWorkItemId
66
+ assert('TCG extractWorkItemId: from field', tcg.extractWorkItemId({ work_item_id: WI }) === WI);
67
+ assert('TCG extractWorkItemId: from blob', tcg.extractWorkItemId({ task: { note: `closes ${WI}` } }) === WI);
68
+ assert('TCG extractWorkItemId: none → null', tcg.extractWorkItemId({ task: { note: 'no uuid' } }) === null);
69
+
70
+ // pure: flagEnabledEnv default OFF
71
+ {
72
+ const prev = process.env.RDC_TRUTHGATE_TASKCOMPLETED;
73
+ delete process.env.RDC_TRUTHGATE_TASKCOMPLETED;
74
+ assert('TCG flag default OFF', tcg.flagEnabledEnv() === false);
75
+ process.env.RDC_TRUTHGATE_TASKCOMPLETED = 'true';
76
+ assert('TCG flag ON via env', tcg.flagEnabledEnv() === true);
77
+ if (prev === undefined) delete process.env.RDC_TRUTHGATE_TASKCOMPLETED;
78
+ else process.env.RDC_TRUTHGATE_TASKCOMPLETED = prev;
79
+ }
80
+
81
+ // process: flag OFF → no-op (exit 0, no block)
82
+ {
83
+ const r = runHook('task-completed-gate.js', { work_item_id: WI }, { RDC_TRUTHGATE_TASKCOMPLETED: '' });
84
+ assert('TCG flag OFF → exit 0 no-op', r.status === 0, `status=${r.status} ${r.stderr}`);
85
+ }
86
+
87
+ // process: flag ON + no closure ref → BLOCK (exit 2)
88
+ {
89
+ const r = runHook('task-completed-gate.js', { task: { note: 'no uuid here' } },
90
+ { RDC_TRUTHGATE_TASKCOMPLETED: '1' });
91
+ assert('TCG flag ON + no work-item ref → exit 2 BLOCK', r.status === 2, `status=${r.status}`);
92
+ assert('TCG block mentions no work-item reference', /no work-item reference/.test(r.stdout + r.stderr), r.stdout);
93
+ }
94
+
95
+ // process: flag ON + unsound closure (status review via sink) → BLOCK
96
+ {
97
+ const dir = mkdtempSync(join(tmpdir(), 'tcg-'));
98
+ const sink = join(dir, 'closure.json');
99
+ writeFileSync(sink, JSON.stringify({ id: WI, item_type: 'task', status: 'review', implementation_report: null }));
100
+ const r = runHook('task-completed-gate.js', { work_item_id: WI },
101
+ { RDC_TRUTHGATE_TASKCOMPLETED: '1', RDC_TASKCOMPLETED_CLOSURE_SINK: sink });
102
+ assert('TCG flag ON + unsound closure → exit 2 BLOCK', r.status === 2, `status=${r.status} ${r.stdout}`);
103
+ rmSync(dir, { recursive: true, force: true });
104
+ }
105
+
106
+ // process: flag ON + sound closure (via sink) → PASS (exit 0)
107
+ {
108
+ const dir = mkdtempSync(join(tmpdir(), 'tcg-'));
109
+ const sink = join(dir, 'closure.json');
110
+ writeFileSync(sink, JSON.stringify(soundRow));
111
+ const r = runHook('task-completed-gate.js', { work_item_id: WI },
112
+ { RDC_TRUTHGATE_TASKCOMPLETED: '1', RDC_TASKCOMPLETED_CLOSURE_SINK: sink });
113
+ assert('TCG flag ON + sound closure → exit 0 PASS', r.status === 0, `status=${r.status} ${r.stdout}${r.stderr}`);
114
+ rmSync(dir, { recursive: true, force: true });
115
+ }
116
+ }
117
+
118
+ // ===========================================================================
119
+ // 2. post-tool-batch-gate.js
120
+ // ===========================================================================
121
+ {
122
+ const ptb = require(join(HOOKS, 'post-tool-batch-gate.js'));
123
+ const DEV = 'c3189c9d58a37d648e9de4a6bcd7d46772053eea';
124
+ const STALE = 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef';
125
+ const FRESH = '1234567812345678123456781234567812345678';
126
+
127
+ // pure: evaluateWave — cannotEvaluate when no develop HEAD
128
+ {
129
+ const v = ptb.evaluateWave({ developHead: null, worktrees: [], isAncestor: () => true });
130
+ assert('PTB evaluateWave: no develop HEAD → cannotEvaluate', v.cannotEvaluate === true && v.ok === false);
131
+ }
132
+ // pure: current base (develop is ancestor of worktree HEAD) → ok
133
+ {
134
+ const v = ptb.evaluateWave({
135
+ developHead: DEV,
136
+ worktrees: [{ path: '/wt/a', head: FRESH }],
137
+ isAncestor: (a, b) => a === DEV && b === FRESH, // DEV is ancestor of FRESH
138
+ });
139
+ assert('PTB evaluateWave: current base → ok, no stale', v.ok === true && v.stale.length === 0);
140
+ }
141
+ // pure: worktree HEAD == develop HEAD → ok
142
+ {
143
+ const v = ptb.evaluateWave({
144
+ developHead: DEV,
145
+ worktrees: [{ path: '/wt/a', head: DEV }],
146
+ isAncestor: () => false,
147
+ });
148
+ assert('PTB evaluateWave: head==develop → ok', v.ok === true && v.stale.length === 0);
149
+ }
150
+ // pure: stale base (develop NOT an ancestor) → flagged
151
+ {
152
+ const v = ptb.evaluateWave({
153
+ developHead: DEV,
154
+ worktrees: [{ path: '/wt/stale', head: STALE }],
155
+ isAncestor: () => false, // DEV is NOT an ancestor of STALE
156
+ });
157
+ assert('PTB evaluateWave: stale base → not ok', v.ok === false, JSON.stringify(v));
158
+ assert('PTB evaluateWave: stale worktree listed', v.stale.length === 1 && v.stale[0].head === STALE);
159
+ }
160
+
161
+ // process: flag OFF → no-op (exit 0)
162
+ {
163
+ const r = runHook('post-tool-batch-gate.js', { hook_event_name: 'PostToolBatch' },
164
+ { RDC_TRUTHGATE_POSTTOOLBATCH: '' });
165
+ assert('PTB flag OFF → exit 0 no-op', r.status === 0, `status=${r.status} ${r.stderr}`);
166
+ }
167
+ }
168
+
169
+ // ===========================================================================
170
+ // 3. gate-watchdog-selfcheck.js
171
+ // ===========================================================================
172
+ {
173
+ const wd = require(join(HOOKS, 'gate-watchdog-selfcheck.js'));
174
+
175
+ const allPresent = {
176
+ exitGateFileExists: true, exitGateRegistered: true,
177
+ truthGateFileExists: true, truthGateOnStop: true, truthGateOnSubagentStop: true,
178
+ liveHookifyManifestExists: true, deadWrapperPointsAtStaleCache: false,
179
+ };
180
+ // all present → no findings, empty banner (silent)
181
+ {
182
+ const findings = wd.evaluateWatchdog(allPresent);
183
+ assert('WD all present → no findings', findings.length === 0, JSON.stringify(findings));
184
+ assert('WD all present → empty banner (silent)', wd.renderBanner(findings) === '');
185
+ }
186
+ // truth-gate missing → finding + STOP banner
187
+ {
188
+ const findings = wd.evaluateWatchdog({ ...allPresent, truthGateFileExists: false });
189
+ assert('WD truth-gate missing → finding', findings.some((f) => /truth-gate\.mjs is MISSING/.test(f)), JSON.stringify(findings));
190
+ const banner = wd.renderBanner(findings);
191
+ assert('WD truth-gate missing → STOP banner emitted', /TRUTH GATE WATCHDOG/.test(banner) && banner.length > 0);
192
+ }
193
+ // truth-gate unregistered on SubagentStop → finding
194
+ {
195
+ const findings = wd.evaluateWatchdog({ ...allPresent, truthGateOnSubagentStop: false });
196
+ assert('WD truth-gate not on SubagentStop → finding', findings.some((f) => /SubagentStop/.test(f)));
197
+ }
198
+ // exit gate missing → finding
199
+ {
200
+ const findings = wd.evaluateWatchdog({ ...allPresent, exitGateFileExists: false });
201
+ assert('WD exit-gate missing → finding', findings.some((f) => /work-item-exit-gate\.js is MISSING/.test(f)));
202
+ }
203
+ // LIVE hookify manifest absent → finding mentions plugin manifest, NOT dead wrappers as trusted
204
+ {
205
+ const findings = wd.evaluateWatchdog({ ...allPresent, liveHookifyManifestExists: false });
206
+ const f = findings.find((x) => /hookify/i.test(x));
207
+ assert('WD live hookify manifest absent → finding', Boolean(f), JSON.stringify(findings));
208
+ assert('WD finding names the LIVE plugin hooks.json (not dead wrappers as trusted)',
209
+ f && /plugins\/cache.*hookify.*hooks\.json/i.test(f) && /NOT the live path/i.test(f), f || '');
210
+ }
211
+ // dead wrapper points at stale cache → drift finding
212
+ {
213
+ const findings = wd.evaluateWatchdog({ ...allPresent, deadWrapperPointsAtStaleCache: true,
214
+ deadWrapperRoot: '/cache/hookify/OLDHASH', liveHookifyRoot: '/cache/hookify/NEWHASH' });
215
+ assert('WD stale-cache drift → finding', findings.some((f) => /ORPHANED cache hash/.test(f)));
216
+ }
217
+
218
+ // structural: gatherFacts inspects the LIVE plugins/cache hooks.json path, not the wrappers.
219
+ {
220
+ const home = mkdtempSync(join(tmpdir(), 'wd-home-'));
221
+ const repo = mkdtempSync(join(tmpdir(), 'wd-repo-'));
222
+ // Build a fake LIVE hookify plugin manifest under plugins/cache/.../hookify/<hash>/hooks/hooks.json
223
+ const live = join(home, '.claude', 'plugins', 'cache', 'official', 'hookify', 'NEWHASH', 'hooks');
224
+ mkdirSync(live, { recursive: true });
225
+ writeFileSync(join(live, 'hooks.json'), JSON.stringify({ hooks: {} }));
226
+ // Build a dead wrapper that points at a DIFFERENT (orphaned) hash.
227
+ const deadDir = join(home, '.claude', 'hooks');
228
+ mkdirSync(deadDir, { recursive: true });
229
+ writeFileSync(join(deadDir, 'hookify-stop.js'),
230
+ "const PLUGIN_ROOT = 'C:/cache/official/hookify/OLDHASH';\n");
231
+ // Minimal settings.json registering both gates so those facts are true.
232
+ mkdirSync(join(repo, '.claude', 'hooks'), { recursive: true });
233
+ writeFileSync(join(repo, '.claude', 'hooks', 'truth-gate.mjs'), '// stub');
234
+ writeFileSync(join(repo, '.claude', 'settings.json'), JSON.stringify({
235
+ hooks: {
236
+ PreToolUse: [{ hooks: [{ type: 'command', command: 'node hooks/work-item-exit-gate.js' }] }],
237
+ Stop: [{ hooks: [{ type: 'command', command: 'node .claude/hooks/truth-gate.mjs' }] }],
238
+ SubagentStop: [{ hooks: [{ type: 'command', command: 'node .claude/hooks/truth-gate.mjs' }] }],
239
+ },
240
+ }));
241
+
242
+ const manifest = wd.findLiveHookifyManifest(home);
243
+ assert('WD findLiveHookifyManifest resolves the plugin hooks.json',
244
+ typeof manifest === 'string' && /plugins[\\/]cache.*hookify.*hooks\.json$/i.test(manifest.replace(/\\/g, '/')), manifest || 'null');
245
+
246
+ const facts = wd.gatherFacts({ home, repoRoot: repo, hooksDir: HOOKS });
247
+ assert('WD gatherFacts: live hookify manifest detected', facts.liveHookifyManifestExists === true);
248
+ assert('WD gatherFacts: dead wrapper stale-cache drift detected', facts.deadWrapperPointsAtStaleCache === true,
249
+ `dead=${facts.deadWrapperRoot} live=${facts.liveHookifyRoot}`);
250
+ assert('WD gatherFacts: truth-gate registered on Stop+SubagentStop',
251
+ facts.truthGateOnStop === true && facts.truthGateOnSubagentStop === true);
252
+ assert('WD gatherFacts: exit gate registered on PreToolUse', facts.exitGateRegistered === true);
253
+
254
+ rmSync(home, { recursive: true, force: true });
255
+ rmSync(repo, { recursive: true, force: true });
256
+ }
257
+ }
258
+
259
+ // ===========================================================================
260
+ if (failures.length > 0) {
261
+ console.error('\nharness-gates tests — FAIL\n');
262
+ for (const f of failures) console.error(` - ${f}`);
263
+ process.exit(1);
264
+ }
265
+ console.log('\nharness-gates tests — PASS');