@lifeaitools/rdc-skills 0.37.2 → 0.37.5
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/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +23 -0
- package/clauth-plugin.json +1 -1
- package/commands/flow.md +12 -3
- package/git-sha.json +1 -1
- package/guides/lessons-learned-spec.md +16 -14
- package/hooks/gate-watchdog-selfcheck.js +93 -5
- package/hooks/require-work-item-on-commit.js +15 -1
- package/package.json +3 -3
- package/scripts/acceptance.mjs +5 -2
- package/scripts/install-rdc-skills.js +34 -11
- package/scripts/rdc-release.mjs +91 -0
- package/scripts/validate-publish-manifests.js +41 -8
- package/skills/build/SKILL.md +4 -0
- package/skills/collab/SKILL.md +2 -0
- package/skills/edit/SKILL.md +8 -0
- package/skills/fixit/SKILL.md +24 -4
- package/skills/housekeeping/SKILL.md +8 -5
- package/skills/plan/SKILL.md +2 -0
- package/skills/release/SKILL.md +25 -10
- package/skills/rpms-filemap/SKILL.cloud.md +1 -1
- package/skills/rpms-filemap/SKILL.md +1 -1
- package/skills/status/SKILL.md +3 -5
- package/skills/terminal-config/SKILL.md +5 -0
- package/tests/harness-gates.test.mjs +24 -172
- package/tests/install-stale-checkout.test.mjs +42 -0
- package/tests/publish-manifest-staging-gates.test.mjs +30 -0
- package/tests/release-guard.test.mjs +93 -0
- package/tests/release-skill-contract.test.mjs +14 -0
- package/tests/require-work-item-on-commit.test.mjs +13 -0
- package/hooks/post-tool-batch-gate.js +0 -203
- package/hooks/task-completed-gate.js +0 -274
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { test } from 'node:test';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
|
|
7
|
+
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
8
|
+
const skill = readFileSync(path.join(ROOT, 'skills', 'release', 'SKILL.md'), 'utf8');
|
|
9
|
+
|
|
10
|
+
test('release skill routes the scoped commit and tag through the executable guard', () => {
|
|
11
|
+
assert.match(skill, /node scripts\/rdc-release\.mjs --repo <repo-path>/);
|
|
12
|
+
assert.match(skill, /--allow package\.json --allow package-lock\.json/);
|
|
13
|
+
assert.match(skill, /staged paths.*before creating either a commit or a tag/is);
|
|
14
|
+
});
|
|
@@ -45,6 +45,19 @@ assert('isGitCommit: false for --help',
|
|
|
45
45
|
hook.isGitCommit('git commit --help') === false);
|
|
46
46
|
assert('isGitCommit: false for unrelated',
|
|
47
47
|
hook.isGitCommit('git status') === false);
|
|
48
|
+
// LIFEAI/regen-root#243: git must be the command word, not a substring anywhere.
|
|
49
|
+
for (const [cmd, want] of [
|
|
50
|
+
['( cd /repo && git add a.js && git commit -q -F - <<\'EOF\'\nfix(x): y\nEOF\n)', true],
|
|
51
|
+
['git -C "C:/Dev/my repo" commit -m "fix: x"', true],
|
|
52
|
+
['GIT_AUTHOR_NAME=x git -c user.email=a@b commit -m "fix: x"', true],
|
|
53
|
+
['cd a; git --no-pager commit --amend --no-edit', true],
|
|
54
|
+
['node rdc-lesson.mjs submit --what "the git hook fired before commit ran"', false],
|
|
55
|
+
['git log --oneline --grep commit', false],
|
|
56
|
+
['gh issue create --body "run git commit after staging"', false],
|
|
57
|
+
['echo git && echo commit', false],
|
|
58
|
+
]) {
|
|
59
|
+
assert(`isGitCommit(${JSON.stringify(cmd).slice(0, 60)}) === ${want}`, hook.isGitCommit(cmd) === want);
|
|
60
|
+
}
|
|
48
61
|
assert('commitSucceeded: false on nothing-to-commit',
|
|
49
62
|
hook.commitSucceeded({ stdout: 'nothing to commit, working tree clean' }) === false);
|
|
50
63
|
assert('commitSucceeded: true on exit 0',
|
|
@@ -1,203 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,274 +0,0 @@
|
|
|
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) — but the
|
|
25
|
-
* DB check is OPT-IN: it only runs when RDC_TRUTHGATE_TASKCOMPLETED_DB
|
|
26
|
-
* is in {1,true,on,yes}. This keeps the default-OFF path ZERO-COST: an
|
|
27
|
-
* unset env flag returns false with NO Supabase/clauth round-trip, so a
|
|
28
|
-
* dormant gate never makes a network call on every TaskCompleted.
|
|
29
|
-
*
|
|
30
|
-
* Offline test seam: when RDC_TASKCOMPLETED_CLOSURE_SINK points at a JSON file,
|
|
31
|
-
* the hook reads the closure row from that file instead of Supabase. This lets
|
|
32
|
-
* the gate be proven without a live DB. The sink shape is a single work_items
|
|
33
|
-
* row: { id, status, item_type, implementation_report }.
|
|
34
|
-
*/
|
|
35
|
-
'use strict';
|
|
36
|
-
|
|
37
|
-
const fs = require('fs');
|
|
38
|
-
const path = require('path');
|
|
39
|
-
const hookLog = require('./hook-logger');
|
|
40
|
-
|
|
41
|
-
const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
|
|
42
|
-
const WITNESS_ALLOWLIST = new Set(['validator-rerun', 'ci', 'human-review']);
|
|
43
|
-
const DEFAULT_SUPABASE_URL = 'https://uvojezuorjgqzmhhgluu.supabase.co';
|
|
44
|
-
|
|
45
|
-
function readStdin() {
|
|
46
|
-
return new Promise((resolve) => {
|
|
47
|
-
let input = '';
|
|
48
|
-
process.stdin.setEncoding('utf8');
|
|
49
|
-
process.stdin.on('data', (chunk) => { input += chunk; });
|
|
50
|
-
process.stdin.on('end', () => resolve(input));
|
|
51
|
-
process.stdin.resume();
|
|
52
|
-
});
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/** Block the TaskCompleted with exit code 2 (the blocking semantics for this event). */
|
|
56
|
-
function block(reason, details = {}) {
|
|
57
|
-
hookLog('task-completed-gate', 'TaskCompleted', 'block', { reason, ...details });
|
|
58
|
-
process.stdout.write(JSON.stringify({
|
|
59
|
-
decision: 'block',
|
|
60
|
-
reason: `TASK COMPLETION BLOCKED — Truth Gate Layer 5 (TaskCompleted).\n\n${reason}`,
|
|
61
|
-
}));
|
|
62
|
-
process.stderr.write(`TASK COMPLETION BLOCKED: ${reason}\n`);
|
|
63
|
-
process.exit(2);
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
function pass(details = {}) {
|
|
67
|
-
hookLog('task-completed-gate', 'TaskCompleted', 'pass', details);
|
|
68
|
-
process.exit(0);
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* Is the Layer-5 TaskCompleted gate enabled? Default OFF (returns false).
|
|
73
|
-
* Mirrors work-item-exit-gate.js truthGateFlagEnabled — env is the authoritative,
|
|
74
|
-
* test-stable switch; a DB toggle is an optional deploy-time enable.
|
|
75
|
-
*/
|
|
76
|
-
function flagEnabledEnv() {
|
|
77
|
-
const v = String(process.env.RDC_TRUTHGATE_TASKCOMPLETED || '').trim().toLowerCase();
|
|
78
|
-
return v === '1' || v === 'true' || v === 'on' || v === 'yes';
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* Is the optional DB flag check opted into? Default OFF (returns false).
|
|
83
|
-
* The DB check is a Supabase/clauth round-trip; gating it behind this explicit
|
|
84
|
-
* env opt-in keeps the default-OFF path zero-cost (no network on every
|
|
85
|
-
* TaskCompleted). Only when this is set do we consult truthgate_flags.
|
|
86
|
-
*/
|
|
87
|
-
function flagDbOptIn() {
|
|
88
|
-
const v = String(process.env.RDC_TRUTHGATE_TASKCOMPLETED_DB || '').trim().toLowerCase();
|
|
89
|
-
return v === '1' || v === 'true' || v === 'on' || v === 'yes';
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
async function getServiceKey() {
|
|
93
|
-
if (process.env.SUPABASE_SERVICE_ROLE_KEY) return process.env.SUPABASE_SERVICE_ROLE_KEY;
|
|
94
|
-
if (process.env.SUPABASE_SERVICE_KEY) return process.env.SUPABASE_SERVICE_KEY;
|
|
95
|
-
for (const endpoint of ['supabase-service', 'supabase-service-role']) {
|
|
96
|
-
try {
|
|
97
|
-
const res = await fetch(`http://127.0.0.1:52437/v/${endpoint}`, { signal: AbortSignal.timeout(2000) });
|
|
98
|
-
if (res.ok) {
|
|
99
|
-
const text = (await res.text()).trim();
|
|
100
|
-
if (text && !text.startsWith('{')) return text;
|
|
101
|
-
}
|
|
102
|
-
} catch (_) {}
|
|
103
|
-
}
|
|
104
|
-
return null;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
async function supabaseGet(pathname) {
|
|
108
|
-
const key = await getServiceKey();
|
|
109
|
-
if (!key) throw new Error('clauth/env did not provide a Supabase service key');
|
|
110
|
-
const base = (process.env.SUPABASE_URL || process.env.NEXT_PUBLIC_SUPABASE_URL || DEFAULT_SUPABASE_URL).replace(/\/$/, '');
|
|
111
|
-
const res = await fetch(`${base}/rest/v1/${pathname}`, {
|
|
112
|
-
headers: { apikey: key, Authorization: `Bearer ${key}`, Accept: 'application/json' },
|
|
113
|
-
signal: AbortSignal.timeout(3500),
|
|
114
|
-
});
|
|
115
|
-
if (!res.ok) throw new Error(`Supabase HTTP ${res.status}`);
|
|
116
|
-
return res.json();
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
/** Best-effort DB flag toggle. Absence/error → false (stays OFF). */
|
|
120
|
-
async function flagEnabledDb() {
|
|
121
|
-
try {
|
|
122
|
-
const rows = await supabaseGet('truthgate_flags?flag=eq.taskcompleted&select=enabled&limit=1');
|
|
123
|
-
return Array.isArray(rows) && rows[0] && rows[0].enabled === true;
|
|
124
|
-
} catch (_) {
|
|
125
|
-
return false;
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
/**
|
|
130
|
-
* Extract the work-item UUID a task is bound to from the TaskCompleted payload.
|
|
131
|
-
* Looks in the common task fields and falls back to the first UUID anywhere in
|
|
132
|
-
* the serialized payload (the closure ref the agent recorded against the task).
|
|
133
|
-
* Returns the lowercased UUID or null.
|
|
134
|
-
*/
|
|
135
|
-
function extractWorkItemId(raw) {
|
|
136
|
-
const candidates = [
|
|
137
|
-
raw && raw.work_item_id,
|
|
138
|
-
raw && raw.task && raw.task.work_item_id,
|
|
139
|
-
raw && raw.task && raw.task.metadata && raw.task.metadata.work_item_id,
|
|
140
|
-
raw && raw.metadata && raw.metadata.work_item_id,
|
|
141
|
-
];
|
|
142
|
-
for (const c of candidates) {
|
|
143
|
-
if (typeof c === 'string' && UUID_RE.test(c)) return c.match(UUID_RE)[0].toLowerCase();
|
|
144
|
-
}
|
|
145
|
-
let blob = '';
|
|
146
|
-
try { blob = JSON.stringify(raw); } catch (_) { blob = String(raw || ''); }
|
|
147
|
-
const m = blob.match(UUID_RE);
|
|
148
|
-
return m ? m[0].toLowerCase() : null;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* Is the work-item closure SOUND for completion? Pure + unit-testable; returns
|
|
153
|
-
* { ok:true } or { ok:false, reason } — never throws. A sound closure for an
|
|
154
|
-
* implementation task requires (mirrors the L2/L3 contract the exit gate proves
|
|
155
|
-
* at `done` time):
|
|
156
|
-
* - the row exists
|
|
157
|
-
* - status === 'done' (the exit gate admitted it; epics are exempt below)
|
|
158
|
-
* - implementation_report.codeflow_post exists
|
|
159
|
-
* - codeflow_post.witness ∈ allow-list (never 'agent' / self-witness, D5)
|
|
160
|
-
* - codeflow_post.commit is present (a captured SHA the exit gate matched)
|
|
161
|
-
* - codeflow_post.files_changed is a non-empty array
|
|
162
|
-
* - codeflow_post.verification is a non-empty array
|
|
163
|
-
* Epics are not implementation tasks — an epic row is considered sound on
|
|
164
|
-
* status alone (the exit gate exempts epics from L2/L3).
|
|
165
|
-
*/
|
|
166
|
-
function closureIsSound(row) {
|
|
167
|
-
if (!row || typeof row !== 'object') {
|
|
168
|
-
return { ok: false, reason: 'no work-item closure row found for this task — cannot confirm a sound, Layer 2–3-admitted `done`.' };
|
|
169
|
-
}
|
|
170
|
-
if (row.item_type === 'epic') {
|
|
171
|
-
return row.status === 'done'
|
|
172
|
-
? { ok: true }
|
|
173
|
-
: { ok: false, reason: `linked epic ${row.id} is status "${row.status}", not "done".` };
|
|
174
|
-
}
|
|
175
|
-
if (row.status !== 'done') {
|
|
176
|
-
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.` };
|
|
177
|
-
}
|
|
178
|
-
const report = row.implementation_report;
|
|
179
|
-
if (!report || typeof report !== 'object') {
|
|
180
|
-
return { ok: false, reason: `work item ${row.id} has no implementation_report — a sound closure must carry one.` };
|
|
181
|
-
}
|
|
182
|
-
const post = report.codeflow_post;
|
|
183
|
-
if (!post || typeof post !== 'object') {
|
|
184
|
-
return { ok: false, reason: `work item ${row.id} has no implementation_report.codeflow_post — Layer 2–3 evidence absent.` };
|
|
185
|
-
}
|
|
186
|
-
const witness = String(post.witness || '');
|
|
187
|
-
if (!WITNESS_ALLOWLIST.has(witness)) {
|
|
188
|
-
return { ok: false, reason: `closure witness "${witness || '<missing>'}" is not in {validator-rerun, ci, human-review} — the doer cannot self-witness (D5).` };
|
|
189
|
-
}
|
|
190
|
-
if (typeof post.commit !== 'string' || !post.commit.trim()) {
|
|
191
|
-
return { ok: false, reason: `closure codeflow_post.commit is missing — no captured commit to bind the closure to.` };
|
|
192
|
-
}
|
|
193
|
-
if (!Array.isArray(post.files_changed) || post.files_changed.length === 0) {
|
|
194
|
-
return { ok: false, reason: `closure codeflow_post.files_changed is empty — a sound closure names the files it changed.` };
|
|
195
|
-
}
|
|
196
|
-
if (!Array.isArray(post.verification) || post.verification.length === 0) {
|
|
197
|
-
return { ok: false, reason: `closure codeflow_post.verification is empty — a sound closure carries a captured verification artifact.` };
|
|
198
|
-
}
|
|
199
|
-
return { ok: true };
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
/** Load the closure row: offline sink first (test seam), else Supabase. */
|
|
203
|
-
async function loadClosureRow(workItemId) {
|
|
204
|
-
const sink = process.env.RDC_TASKCOMPLETED_CLOSURE_SINK;
|
|
205
|
-
if (sink) {
|
|
206
|
-
const txt = fs.readFileSync(sink, 'utf8');
|
|
207
|
-
const parsed = JSON.parse(txt);
|
|
208
|
-
return Array.isArray(parsed) ? parsed[0] : parsed;
|
|
209
|
-
}
|
|
210
|
-
const rows = await supabaseGet(
|
|
211
|
-
`work_items?id=eq.${encodeURIComponent(workItemId)}&select=id,status,item_type,implementation_report&limit=1`,
|
|
212
|
-
);
|
|
213
|
-
return Array.isArray(rows) ? rows[0] : null;
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
async function main() {
|
|
217
|
-
let raw;
|
|
218
|
-
try { raw = JSON.parse(await readStdin()); } catch { process.exit(0); }
|
|
219
|
-
|
|
220
|
-
// Default-OFF: a no-op until the flag is flipped at deploy. The env flag is
|
|
221
|
-
// checked first and short-circuits — when it is unset, the DB check runs ONLY
|
|
222
|
-
// if explicitly opted in via RDC_TRUTHGATE_TASKCOMPLETED_DB, so the dormant
|
|
223
|
-
// path is zero-cost (no Supabase/clauth round-trip on every TaskCompleted).
|
|
224
|
-
let enabled = flagEnabledEnv();
|
|
225
|
-
if (!enabled && flagDbOptIn()) {
|
|
226
|
-
enabled = await flagEnabledDb().catch(() => false);
|
|
227
|
-
}
|
|
228
|
-
if (!enabled) return pass({ reason: 'flag-off' });
|
|
229
|
-
|
|
230
|
-
// FAIL-CLOSED from here: any inability to confirm a sound closure is a BLOCK.
|
|
231
|
-
const workItemId = extractWorkItemId(raw);
|
|
232
|
-
if (!workItemId) {
|
|
233
|
-
block(
|
|
234
|
-
'This task completion carries no work-item reference, so its closure cannot be verified against the ' +
|
|
235
|
-
'Layer 2–3 exit gate. Bind the task to its work item (record the work-item UUID on the task/closure) and retry.',
|
|
236
|
-
);
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
let row;
|
|
240
|
-
try {
|
|
241
|
-
row = await loadClosureRow(workItemId);
|
|
242
|
-
} catch (e) {
|
|
243
|
-
block(
|
|
244
|
-
`Could not load the work-item closure for ${workItemId} (${e && e.message ? e.message : String(e)}). ` +
|
|
245
|
-
`Fail-closed: not completing the task until the closure can be verified.`,
|
|
246
|
-
{ workItemId },
|
|
247
|
-
);
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
const verdict = closureIsSound(row);
|
|
251
|
-
if (!verdict.ok) {
|
|
252
|
-
block(
|
|
253
|
-
`${verdict.reason}\n\n` +
|
|
254
|
-
`A task may only complete once its work item has reached a sound, Layer 2–3-admitted \`done\` ` +
|
|
255
|
-
`(HMAC-valid, witnessed codeflow_post via the validator path). Move the work item through review → validator ` +
|
|
256
|
-
`\`done\` first, then complete the task.`,
|
|
257
|
-
{ workItemId },
|
|
258
|
-
);
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
pass({ workItemId });
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
if (require.main === module) {
|
|
265
|
-
main().catch((e) => block(`task-completed-gate crashed: ${e.message}`));
|
|
266
|
-
} else {
|
|
267
|
-
module.exports = {
|
|
268
|
-
flagEnabledEnv,
|
|
269
|
-
flagDbOptIn,
|
|
270
|
-
extractWorkItemId,
|
|
271
|
-
closureIsSound,
|
|
272
|
-
WITNESS_ALLOWLIST,
|
|
273
|
-
};
|
|
274
|
-
}
|