@yeison.restrepo.r/code-conductor 1.24.1 → 1.31.0
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/README.md +17 -7
- package/bin/code-conductor.mjs +4 -4
- package/global/commands/cc-compact.md +17 -2
- package/global/hooks/graphify-ast-refresh.mjs +91 -0
- package/global/settings.json +0 -13
- package/lib/installer/config.mjs +0 -8
- package/lib/installer/deploy.mjs +45 -20
- package/lib/installer/host-owned.mjs +94 -0
- package/lib/installer/settings-merge.mjs +118 -0
- package/lib/installer/settings.mjs +27 -3
- package/package.json +1 -1
- package/project-template/.claude/commands/cc-implement.md +28 -0
- package/project-template/.claude/commands/cc-init.md +50 -18
- package/project-template/.claude/commands/cc-plan.md +142 -1
- package/project-template/.claude/hooks/pre-tool-use.mjs +509 -0
- package/project-template/.claude/settings.json +2 -2
- package/project-template/CLAUDE.md +3 -1
- package/scripts/claude-md-fields.mjs +42 -0
- package/scripts/conductor-db.mjs +93 -1
- package/scripts/detect-stack.mjs +5 -1
- package/scripts/init-wizard.mjs +195 -0
- package/scripts/resume-read.mjs +22 -12
- package/scripts/snap-build.mjs +4 -7
- package/scripts/snap-contract.mjs +39 -0
- package/scripts/snap-validate.mjs +8 -8
- package/project-template/.claude/hooks/pre-tool-use.sh +0 -81
package/scripts/conductor-db.mjs
CHANGED
|
@@ -15,6 +15,7 @@ import { execFileSync } from 'node:child_process';
|
|
|
15
15
|
import { mkdirSync, existsSync, renameSync, unlinkSync, statSync, readSync } from 'node:fs';
|
|
16
16
|
import { dirname, basename, join, resolve, relative, sep } from 'node:path';
|
|
17
17
|
import { fileURLToPath } from 'node:url';
|
|
18
|
+
import { PRE_PARSE_MAX_BYTES as MAX_SNAP_BYTES } from './snap-contract.mjs';
|
|
18
19
|
|
|
19
20
|
const PREFIX = 'CONDUCTOR_DB:';
|
|
20
21
|
const warn = (m) => process.stderr.write(`${PREFIX} ${m}\n`);
|
|
@@ -24,9 +25,17 @@ const MAX_KEY_LEN = 512;
|
|
|
24
25
|
const WALK_CAP = 40;
|
|
25
26
|
const USAGE = "usage: conductor-db.mjs record <plan_file> <task_id> <state> | init";
|
|
26
27
|
const SCHEMA_VERSION = 2;
|
|
27
|
-
const MAX_SNAP_BYTES = 10 * 1024 * 1024; // 10 MiB
|
|
28
28
|
const MAX_CONTENT_BYTES = 1024 * 1024; // 1 MiB
|
|
29
29
|
const STDIN_CHUNK = 65536;
|
|
30
|
+
|
|
31
|
+
// FEAT-025 retention bounds. Row counts, never the clock: an age window would
|
|
32
|
+
// evict the only snapshot for a long-idle HEAD and silently break /cc-resume.
|
|
33
|
+
const SNAPSHOT_KEEP_PER_HASH = 3;
|
|
34
|
+
const SNAPSHOT_SOFT_CAP = 200;
|
|
35
|
+
const SNAPSHOT_HARD_MAX = 500;
|
|
36
|
+
const HISTORY_KEEP_PER_SESSION = null; // an ordered log is truncated, never thinned
|
|
37
|
+
const HISTORY_SOFT_CAP = 1000;
|
|
38
|
+
const HISTORY_HARD_MAX = 2000;
|
|
30
39
|
const U_SESSION = 'usage: conductor-db.mjs session <session_id> <phase> <spec> <git_commit_hash>';
|
|
31
40
|
const U_GET_SESSION = 'usage: conductor-db.mjs get-session <session_id>';
|
|
32
41
|
const U_SNAPSHOT = 'usage: conductor-db.mjs snapshot <git_commit_hash>';
|
|
@@ -280,6 +289,61 @@ function upsertSession(db, sessionId, phase, spec, gitHash) {
|
|
|
280
289
|
).run({ $session_id: sessionId, $started_at: now, $updated_at: now, $phase: phase, $spec: spec, $git_commit_hash: gitHash });
|
|
281
290
|
}
|
|
282
291
|
|
|
292
|
+
// Bounded retention for the two append-only tables (FEAT-025). Bounds are
|
|
293
|
+
// applied in order and keyed on `id`; `table` and `key` are module constants,
|
|
294
|
+
// never user input, so interpolating them is safe where a bound parameter
|
|
295
|
+
// cannot be used.
|
|
296
|
+
//
|
|
297
|
+
// `id` is the rowid WITHOUT AUTOINCREMENT: SQLite assigns MAX(rowid) + 1, so
|
|
298
|
+
// deleting the highest row would let the next insert reuse its id and silently
|
|
299
|
+
// break `ORDER BY id DESC LIMIT 1` as a recency ordering. Every bound deletes
|
|
300
|
+
// oldest-first only, which is what keeps that ordering true.
|
|
301
|
+
function purgeTable(db, { table, key, keepPerKey, softCap, hardMax }) {
|
|
302
|
+
const count = () => db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get().n;
|
|
303
|
+
let n = count();
|
|
304
|
+
|
|
305
|
+
// Bound 1 — keep the newest `keepPerKey` rows per key. `null` skips it:
|
|
306
|
+
// thinning an ordered log in place would destroy it rather than bound it.
|
|
307
|
+
// `n <= keepPerKey` skips it too — a total at or under the per-key budget
|
|
308
|
+
// cannot have a key that exceeds it — so the ordinary write, which is every
|
|
309
|
+
// write on a healthy db, issues no DELETE at all rather than a windowed one
|
|
310
|
+
// matching zero rows. The recount runs only when the DELETE actually ran.
|
|
311
|
+
if (keepPerKey !== null && n > keepPerKey) {
|
|
312
|
+
db.prepare(
|
|
313
|
+
`DELETE FROM ${table} WHERE id IN (SELECT id FROM (` +
|
|
314
|
+
`SELECT id, ROW_NUMBER() OVER (PARTITION BY ${key} ORDER BY id DESC) AS rn FROM ${table}` +
|
|
315
|
+
`) WHERE rn > $keep)`
|
|
316
|
+
).run({ $keep: keepPerKey });
|
|
317
|
+
n = count();
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// Bound 2 — soft cap with a newest-per-key floor. `n` reflects bound 1's
|
|
321
|
+
// deletions: it was recounted iff bound 1 issued its DELETE, and is otherwise
|
|
322
|
+
// unchanged by definition. Only `n - distinctKeys` rows are eligible, so the
|
|
323
|
+
// table settles at max(softCap, distinctKeys) and every represented key keeps
|
|
324
|
+
// the row `get-snapshot` reads.
|
|
325
|
+
let excess = n - softCap;
|
|
326
|
+
if (excess > 0) {
|
|
327
|
+
db.prepare(
|
|
328
|
+
`DELETE FROM ${table} WHERE id IN (SELECT id FROM ${table} ` +
|
|
329
|
+
`WHERE id NOT IN (SELECT MAX(id) FROM ${table} GROUP BY ${key}) ` +
|
|
330
|
+
`ORDER BY id ASC LIMIT $excess)`
|
|
331
|
+
).run({ $excess: excess });
|
|
332
|
+
n = count();
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Bound 3 — hard ceiling, no floor. Same rule: `n` was recounted iff bound 2
|
|
336
|
+
// issued its DELETE. Reachable only when more than `hardMax` distinct keys
|
|
337
|
+
// each hold a floor row bound 2 could not touch; the oldest keys' rows go,
|
|
338
|
+
// recent ones never do.
|
|
339
|
+
excess = n - hardMax;
|
|
340
|
+
if (excess > 0) {
|
|
341
|
+
db.prepare(
|
|
342
|
+
`DELETE FROM ${table} WHERE id IN (SELECT id FROM ${table} ORDER BY id ASC LIMIT $excess)`
|
|
343
|
+
).run({ $excess: excess });
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
283
347
|
async function withDb(root, fn) {
|
|
284
348
|
let DatabaseSync;
|
|
285
349
|
try {
|
|
@@ -391,6 +455,21 @@ async function cmdSnapshot(args) {
|
|
|
391
455
|
await withDb(root, (db) => {
|
|
392
456
|
db.prepare('INSERT INTO snapshots (git_commit_hash, created_at, snap_json) VALUES ($h, $c, $j)')
|
|
393
457
|
.run({ $h: gitHash, $c: new Date().toISOString(), $j: snapJson });
|
|
458
|
+
// Same connection, statement immediately after the already-autocommitted
|
|
459
|
+
// INSERT — never a second withDb open, which would pay the checkpoint/close
|
|
460
|
+
// cost twice and re-enter the recovery ladder for a best-effort cleanup.
|
|
461
|
+
// The catch wraps the purge ALONE: a throw reaching withDb's catch would
|
|
462
|
+
// misreport this committed write as "skipping cache write".
|
|
463
|
+
try {
|
|
464
|
+
purgeTable(db, {
|
|
465
|
+
table: 'snapshots', key: 'git_commit_hash',
|
|
466
|
+
keepPerKey: SNAPSHOT_KEEP_PER_HASH,
|
|
467
|
+
softCap: SNAPSHOT_SOFT_CAP,
|
|
468
|
+
hardMax: SNAPSHOT_HARD_MAX,
|
|
469
|
+
});
|
|
470
|
+
} catch (e) {
|
|
471
|
+
warn(`retention purge skipped (snapshots): ${(e && e.code) || (e && e.message)}`);
|
|
472
|
+
}
|
|
394
473
|
});
|
|
395
474
|
}
|
|
396
475
|
|
|
@@ -424,6 +503,19 @@ async function cmdHistory(args) {
|
|
|
424
503
|
await withDb(root, (db) => {
|
|
425
504
|
db.prepare('INSERT INTO raw_history (session_id, created_at, kind, content) VALUES ($s, $c, $k, $ct)')
|
|
426
505
|
.run({ $s: sessionId, $c: new Date().toISOString(), $k: kind, $ct: content });
|
|
506
|
+
// Bound 1 is disabled for this table: keeping only the newest few rows per
|
|
507
|
+
// session would destroy an ordered log rather than bound it. Same
|
|
508
|
+
// connection, same scoped catch as the snapshots call site.
|
|
509
|
+
try {
|
|
510
|
+
purgeTable(db, {
|
|
511
|
+
table: 'raw_history', key: 'session_id',
|
|
512
|
+
keepPerKey: HISTORY_KEEP_PER_SESSION,
|
|
513
|
+
softCap: HISTORY_SOFT_CAP,
|
|
514
|
+
hardMax: HISTORY_HARD_MAX,
|
|
515
|
+
});
|
|
516
|
+
} catch (e) {
|
|
517
|
+
warn(`retention purge skipped (raw_history): ${(e && e.code) || (e && e.message)}`);
|
|
518
|
+
}
|
|
427
519
|
});
|
|
428
520
|
}
|
|
429
521
|
|
package/scripts/detect-stack.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { readdir, readFile, stat, realpath } from 'node:fs/promises';
|
|
3
3
|
import { join, resolve, basename, sep } from 'node:path';
|
|
4
4
|
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { FIELD_KEYS } from './claude-md-fields.mjs';
|
|
5
6
|
|
|
6
7
|
// ── Constants ────────────────────────────────────────────────────────────────
|
|
7
8
|
export const GLOBAL_IGNORE = new Set([
|
|
@@ -21,6 +22,10 @@ export const globDepth = (() => {
|
|
|
21
22
|
return Math.max(1, Math.min(MAX_DEPTH, v));
|
|
22
23
|
})();
|
|
23
24
|
|
|
25
|
+
// The CLAUDE.md fields come from the shared list, so detection and init-wizard can never
|
|
26
|
+
// disagree about what a field is. `goVersion` is detect-stack's own extra.
|
|
27
|
+
export const MERGE_FIELDS = [...FIELD_KEYS, 'goVersion'];
|
|
28
|
+
|
|
24
29
|
// ── Low-level helpers ─────────────────────────────────────────────────────────
|
|
25
30
|
export function stripBOM(s) { return s.replace(/^/, ''); }
|
|
26
31
|
|
|
@@ -575,7 +580,6 @@ async function main() {
|
|
|
575
580
|
];
|
|
576
581
|
|
|
577
582
|
const merged = {};
|
|
578
|
-
const MERGE_FIELDS = ['stack','build','test','lint','format','setup','name','goVersion'];
|
|
579
583
|
for (const d of detectorResults) {
|
|
580
584
|
for (const f of MERGE_FIELDS) {
|
|
581
585
|
if (merged[f] === undefined && d[f] !== undefined) merged[f] = d[f];
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// scripts/init-wizard.mjs
|
|
2
|
+
// report | check | apply over CLAUDE.md's canonical field lines.
|
|
3
|
+
//
|
|
4
|
+
// Mode-blind by construction: nothing here inspects whether stdin is a terminal, and
|
|
5
|
+
// nothing reads the CI environment variable — a test greps this source for both. The one
|
|
6
|
+
// caller that matters — /cc-init executed by Claude Code through Bash — never has a
|
|
7
|
+
// terminal, so such a probe would pin the interactive path into non-interactive mode
|
|
8
|
+
// forever. The split lives in the caller: cc-init.md asks and applies, CI runs report
|
|
9
|
+
// and stops.
|
|
10
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
11
|
+
import { join } from 'node:path';
|
|
12
|
+
import { fileURLToPath } from 'node:url';
|
|
13
|
+
import { FIELDS, FIELD_KEYS, fieldByKey, canonicalLine, unresolvedReason } from './claude-md-fields.mjs';
|
|
14
|
+
|
|
15
|
+
const USAGE = `usage:
|
|
16
|
+
node scripts/init-wizard.mjs report
|
|
17
|
+
node scripts/init-wizard.mjs check <field> --value-stdin
|
|
18
|
+
node scripts/init-wizard.mjs apply <field> --value-stdin
|
|
19
|
+
fields: ${FIELD_KEYS.join(', ')}`;
|
|
20
|
+
|
|
21
|
+
// Labels are fixed ASCII words from the shared module, never developer input, so no
|
|
22
|
+
// escaping is needed. No `g` flag: first occurrence is the whole rule.
|
|
23
|
+
export function lineMatcher(field) {
|
|
24
|
+
return new RegExp(`^- ${field.label}:(.*)$`, 'm');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function buildReport(text) {
|
|
28
|
+
const report = { unresolved: [], resolved: [], absent: [] };
|
|
29
|
+
for (const field of FIELDS) {
|
|
30
|
+
const m = text.match(lineMatcher(field));
|
|
31
|
+
if (!m) {
|
|
32
|
+
report.absent.push({ field: field.key, expected: canonicalLine(field) });
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
const reason = unresolvedReason(m[1]);
|
|
36
|
+
if (reason) report.unresolved.push({ field: field.key, raw: m[0], reason });
|
|
37
|
+
else report.resolved.push(field.key);
|
|
38
|
+
}
|
|
39
|
+
return report;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Exactly one trailing line terminator is stripped — the one the heredoc adds. CRLF
|
|
43
|
+
// counts as that one terminator; leaving the CR would write a stray carriage return into
|
|
44
|
+
// a single-line field. No other whitespace is touched: apply writes what it was given,
|
|
45
|
+
// and the predicate judges it trimmed.
|
|
46
|
+
export function stripOneTerminator(raw) {
|
|
47
|
+
if (raw.endsWith('\r\n')) return raw.slice(0, -2);
|
|
48
|
+
if (raw.endsWith('\n')) return raw.slice(0, -1);
|
|
49
|
+
return raw;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function applyToText(text, field, value) {
|
|
53
|
+
const re = lineMatcher(field);
|
|
54
|
+
if (!re.test(text)) {
|
|
55
|
+
const err = new Error(
|
|
56
|
+
`${canonicalLine(field)} is missing from CLAUDE.md — restore that line by hand, then re-run. apply never inserts.`,
|
|
57
|
+
);
|
|
58
|
+
err.code = 'LINE_ABSENT';
|
|
59
|
+
throw err;
|
|
60
|
+
}
|
|
61
|
+
// A function replacer: a value may legitimately contain `$&` or `$1`, which a
|
|
62
|
+
// replacement string would expand.
|
|
63
|
+
return text.replace(re, () => `${canonicalLine(field)} ${value}`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const NPM_RUN = /^(?:npm|pnpm)\s+run\s+(\S+)$/;
|
|
67
|
+
const YARN = /^yarn\s+(\S+)$/;
|
|
68
|
+
|
|
69
|
+
// Only the shapes a package.json can actually answer. Everything else — make, cargo, go,
|
|
70
|
+
// a bare binary — is not checkable, and not checkable is not suspicious.
|
|
71
|
+
export function scriptNameOf(value) {
|
|
72
|
+
const v = value.trim();
|
|
73
|
+
const m = v.match(NPM_RUN) ?? v.match(YARN);
|
|
74
|
+
return m ? m[1] : null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Returns one warning string, or null for silence. Never executes anything, never reaches
|
|
78
|
+
// the network. An absent or unparseable manifest is silence, not a warning: that is the
|
|
79
|
+
// normal case this whole feature exists to serve.
|
|
80
|
+
export function checkValue(value, pkgRaw) {
|
|
81
|
+
if (value.trim() === 'N/A') return null;
|
|
82
|
+
const script = scriptNameOf(value);
|
|
83
|
+
if (!script || pkgRaw === null) return null;
|
|
84
|
+
let pkg;
|
|
85
|
+
try {
|
|
86
|
+
pkg = JSON.parse(pkgRaw);
|
|
87
|
+
} catch {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
if (typeof pkg !== 'object' || pkg === null || Array.isArray(pkg)) return null;
|
|
91
|
+
const scripts = (typeof pkg.scripts === 'object' && pkg.scripts !== null && !Array.isArray(pkg.scripts))
|
|
92
|
+
? pkg.scripts
|
|
93
|
+
: {};
|
|
94
|
+
if (Object.prototype.hasOwnProperty.call(scripts, script)) return null;
|
|
95
|
+
return `no script named "${script}" in package.json`;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function fail(msg, code) {
|
|
99
|
+
process.stderr.write(`init-wizard: ${msg}\n`);
|
|
100
|
+
process.exit(code);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function requireField(name) {
|
|
104
|
+
const field = fieldByKey(name);
|
|
105
|
+
if (!field) fail(`unknown field ${name ? `"${name}"` : '(none)'}\n${USAGE}`, 2);
|
|
106
|
+
return field;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// argv is the wrong channel for a developer's answer: quotes, backticks and $(...) in an
|
|
110
|
+
// agent-composed command line are an injection surface. stdin has no such edge.
|
|
111
|
+
function requireValueStdin(argv) {
|
|
112
|
+
if (!argv.includes('--value-stdin')) fail(`the value must arrive on stdin via --value-stdin\n${USAGE}`, 2);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function readValue() {
|
|
116
|
+
try {
|
|
117
|
+
return stripOneTerminator(readFileSync(0, 'utf8'));
|
|
118
|
+
} catch (err) {
|
|
119
|
+
fail(`cannot read the value from stdin: ${err.message}`, 2);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function readClaudeMd(root) {
|
|
124
|
+
const path = join(root, 'CLAUDE.md');
|
|
125
|
+
try {
|
|
126
|
+
return { path, text: readFileSync(path, 'utf8') };
|
|
127
|
+
} catch (err) {
|
|
128
|
+
// A missing CLAUDE.md is a broken init, not an unresolved field.
|
|
129
|
+
fail(`cannot read ${path}: ${err.message}`, 1);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function main() {
|
|
134
|
+
const [sub] = process.argv.slice(2);
|
|
135
|
+
const root = process.cwd();
|
|
136
|
+
|
|
137
|
+
if (sub === 'report') {
|
|
138
|
+
const { text } = readClaudeMd(root);
|
|
139
|
+
const report = buildReport(text);
|
|
140
|
+
process.stdout.write(JSON.stringify(report, null, 2) + '\n');
|
|
141
|
+
// Advisory only; stdout stays pure JSON.
|
|
142
|
+
if (report.unresolved.length) {
|
|
143
|
+
process.stderr.write(`init-wizard: unresolved: ${report.unresolved.map(u => u.field).join(', ')}\n`);
|
|
144
|
+
}
|
|
145
|
+
if (report.absent.length) {
|
|
146
|
+
process.stderr.write(`init-wizard: absent from CLAUDE.md: ${report.absent.map(a => a.field).join(', ')}\n`);
|
|
147
|
+
}
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (sub === 'check') {
|
|
152
|
+
const rest = process.argv.slice(3);
|
|
153
|
+
const field = requireField(rest[0]);
|
|
154
|
+
requireValueStdin(rest);
|
|
155
|
+
const value = readValue();
|
|
156
|
+
let pkgRaw = null;
|
|
157
|
+
try {
|
|
158
|
+
pkgRaw = readFileSync(join(root, 'package.json'), 'utf8');
|
|
159
|
+
} catch {
|
|
160
|
+
pkgRaw = null;
|
|
161
|
+
}
|
|
162
|
+
const warning = checkValue(value, pkgRaw);
|
|
163
|
+
if (warning) process.stderr.write(`init-wizard: ${field.key}: ${warning}\n`);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
if (sub === 'apply') {
|
|
168
|
+
const rest = process.argv.slice(3);
|
|
169
|
+
const field = requireField(rest[0]);
|
|
170
|
+
requireValueStdin(rest);
|
|
171
|
+
const value = readValue();
|
|
172
|
+
if (value === '') fail(`refusing an empty value for "${field.key}" — a skipped question applies the literal N/A`, 3);
|
|
173
|
+
if (/[\r\n]/.test(value)) fail(`refusing a multi-line value for "${field.key}" — the canonical line is single-line`, 3);
|
|
174
|
+
const { path, text } = readClaudeMd(root);
|
|
175
|
+
let next;
|
|
176
|
+
try {
|
|
177
|
+
next = applyToText(text, field, value);
|
|
178
|
+
} catch (err) {
|
|
179
|
+
fail(err.message, 4);
|
|
180
|
+
}
|
|
181
|
+
try {
|
|
182
|
+
writeFileSync(path, next);
|
|
183
|
+
} catch (err) {
|
|
184
|
+
fail(`cannot write ${path}: ${err.message}`, 5);
|
|
185
|
+
}
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
fail(`unknown subcommand ${sub ? `"${sub}"` : '(none)'}\n${USAGE}`, 2);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Guard: run main() only when this file is the entry point, so the helpers above can be
|
|
193
|
+
// imported by tests without side effects.
|
|
194
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
195
|
+
if (process.argv[1] === __filename) main();
|
package/scripts/resume-read.mjs
CHANGED
|
@@ -57,10 +57,17 @@ function resolveHash() {
|
|
|
57
57
|
return SENTINEL;
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
-
//
|
|
60
|
+
// snap-validate writes one `SNAP_ERROR: ...` line per rejection; the first is the cause.
|
|
61
|
+
function reasonOf(r) {
|
|
62
|
+
const first = String(r.stderr || '').trim().split('\n')[0];
|
|
63
|
+
return first || ('validator exit ' + r.status);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Validate an existing file path via snap-validate. Returns the verdict AND the
|
|
67
|
+
// validator's own reason, so a degrade can name what was wrong (BUG-038).
|
|
61
68
|
function validateFile(p) {
|
|
62
69
|
const r = spawnSync(process.execPath, [VALIDATE, p], { encoding: 'utf8', env: process.env });
|
|
63
|
-
return r.status === 0;
|
|
70
|
+
return { ok: r.status === 0, reason: reasonOf(r) };
|
|
64
71
|
}
|
|
65
72
|
|
|
66
73
|
// Probe how to launch node:sqlite. Returns [] (no flag), ['--experimental-sqlite','--no-warnings'], or null (unavailable).
|
|
@@ -77,10 +84,10 @@ function probeSqliteFlags() {
|
|
|
77
84
|
function validateBlob(blob) {
|
|
78
85
|
const tmp = join(COND, 'resume-validate.' + process.pid + '.tmp.json');
|
|
79
86
|
try { mkdirSync(COND, { recursive: true }); writeFileSync(tmp, blob, 'utf8'); }
|
|
80
|
-
catch { return false; } // FS write error
|
|
87
|
+
catch { return { ok: false, reason: 'temp write failed' }; } // FS write error, blob unusable
|
|
81
88
|
try {
|
|
82
89
|
const r = spawnSync(process.execPath, [VALIDATE, tmp], { encoding: 'utf8', env: process.env });
|
|
83
|
-
return r.status === 0;
|
|
90
|
+
return { ok: r.status === 0, reason: reasonOf(r) };
|
|
84
91
|
} finally { tryUnlink(tmp); }
|
|
85
92
|
}
|
|
86
93
|
|
|
@@ -91,15 +98,17 @@ function queryDb(hash) {
|
|
|
91
98
|
return null;
|
|
92
99
|
}
|
|
93
100
|
const flags = probeSqliteFlags();
|
|
94
|
-
if (flags === null)
|
|
101
|
+
if (flags === null) { trace('db-unavailable degrade: node:sqlite absent'); return null; }
|
|
95
102
|
const args = flags.concat([CONDUCTOR_DB, 'get-snapshot', hash]);
|
|
96
103
|
const r = spawnSync(process.execPath, args, { encoding: 'utf8', timeout: 5000, env: process.env });
|
|
97
|
-
if (r.status !== 0
|
|
104
|
+
if (r.status !== 0) { trace('db-query degrade: get-snapshot exit ' + r.status); return null; }
|
|
105
|
+
if (!r.stdout) return null; // no row for this hash is an ordinary miss, not a rejection
|
|
98
106
|
const blob = r.stdout.trim();
|
|
99
107
|
if (blob === '') return null;
|
|
100
|
-
|
|
108
|
+
const verdict = validateBlob(blob);
|
|
109
|
+
if (!verdict.ok) { trace('db-invalid degrade: ' + verdict.reason); return null; }
|
|
101
110
|
const snap = parseJson(blob);
|
|
102
|
-
if (snap === undefined) { trace('db-invalid degrade'); return null; }
|
|
111
|
+
if (snap === undefined) { trace('db-invalid degrade: unparseable after validation'); return null; }
|
|
103
112
|
return snap;
|
|
104
113
|
}
|
|
105
114
|
|
|
@@ -141,12 +150,13 @@ function main() {
|
|
|
141
150
|
if (!existsSync(HANDOFF)) { trace('miss'); return { code: 3, out: '' }; }
|
|
142
151
|
let content;
|
|
143
152
|
try { content = readFileSync(HANDOFF, 'utf8'); }
|
|
144
|
-
catch { trace('file-unreadable degrade'); return { code: 3, out: '' }; } // leave file on disk
|
|
153
|
+
catch (e) { trace('file-unreadable degrade: ' + ((e && e.code) || 'unknown')); return { code: 3, out: '' }; } // leave file on disk
|
|
145
154
|
if (content.trim() === '') { trace('file-empty degrade'); tryUnlink(HANDOFF); return { code: 3, out: '' }; }
|
|
146
|
-
|
|
155
|
+
const fileVerdict = validateFile(HANDOFF);
|
|
156
|
+
if (!fileVerdict.ok) { trace('file-invalid halt: ' + fileVerdict.reason); return { code: 4, out: '' }; } // leave on disk
|
|
147
157
|
const snap = parseJson(content);
|
|
148
|
-
if (snap === undefined) { trace('file-invalid halt'); return { code: 4, out: '' }; }
|
|
149
|
-
if (snap.sys.c !== hash) { trace('file-stale-hash degrade'); tryUnlink(HANDOFF); return { code: 3, out: '' }; }
|
|
158
|
+
if (snap === undefined) { trace('file-invalid halt: unparseable after validation'); return { code: 4, out: '' }; }
|
|
159
|
+
if (snap.sys.c !== hash) { trace('file-stale-hash degrade: ' + snap.sys.c + ' != ' + hash); tryUnlink(HANDOFF); return { code: 3, out: '' }; }
|
|
150
160
|
// valid + hash matches → bind (content already captured), then unlink.
|
|
151
161
|
const out = buildHit('file', snap, hash);
|
|
152
162
|
trace('file-bind+unlink');
|
package/scripts/snap-build.mjs
CHANGED
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
import { readFileSync } from 'node:fs';
|
|
2
|
-
|
|
3
|
-
const MAX_SNAP_BYTES = 10485760; // 10 MiB (v2)
|
|
4
|
-
const V1_MAX_CHARS = 4096; // handoff-file contract (v1)
|
|
5
|
-
const CAPS = { n: [3, 200], f: [20, 300], d: [10, 300], x: [5, 200] };
|
|
2
|
+
import { CAPS, PRE_PARSE_MAX_BYTES as MAX_SNAP_BYTES, V1_MAX_CHARS } from './snap-contract.mjs';
|
|
6
3
|
|
|
7
4
|
const die = (msg) => { process.stderr.write(`SNAP_BUILD_ERROR: ${msg}\n`); process.exit(1); };
|
|
8
5
|
const byteLen = (s) => Buffer.byteLength(s, 'utf8');
|
|
@@ -48,12 +45,12 @@ for (const k of ['ph', 'c', 's']) {
|
|
|
48
45
|
}
|
|
49
46
|
|
|
50
47
|
const sys = { ph: obj.ph, c: obj.c, s: obj.s };
|
|
51
|
-
const ops = { n: normArray(obj.n, CAPS.n), f: normArray(obj.f, CAPS.f) };
|
|
52
|
-
const mem = { d: normArray(obj.d, CAPS.d), x: normArray(obj.x, CAPS.x) };
|
|
48
|
+
const ops = { n: normArray(obj.n, CAPS['ops.n']), f: normArray(obj.f, CAPS['ops.f']) };
|
|
49
|
+
const mem = { d: normArray(obj.d, CAPS['mem.d']), x: normArray(obj.x, CAPS['mem.x']) };
|
|
53
50
|
const pr = typeof obj.pr === 'string' ? obj.pr : '';
|
|
54
51
|
|
|
55
52
|
if (pr === '') {
|
|
56
|
-
// ---- v1:
|
|
53
|
+
// ---- v1: V1_MAX_CHARS cap, drop oldest of mem.d / ops.f ----
|
|
57
54
|
const snap = { v: 1, sys, ops, mem };
|
|
58
55
|
let line = JSON.stringify(snap);
|
|
59
56
|
while (line.length > V1_MAX_CHARS && (mem.d.length || ops.f.length)) {
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// scripts/snap-contract.mjs
|
|
2
|
+
// The handoff contract: every limit, array cap, field set and version the SNAP
|
|
3
|
+
// envelope is defined by. snap-build.mjs (writer), snap-validate.mjs (validator)
|
|
4
|
+
// and conductor-db.mjs (store) all import from here, so a literal on one side
|
|
5
|
+
// cannot drift from the other. Zero dependencies, node: builtins only.
|
|
6
|
+
|
|
7
|
+
// Hard pre-parse ceiling: the largest any version may legitimately be. Applied
|
|
8
|
+
// before JSON.parse, whatever version the payload claims, so a hostile or
|
|
9
|
+
// corrupt file cannot exhaust memory through the parser.
|
|
10
|
+
export const PRE_PARSE_MAX_BYTES = 10485760; // 10 MiB
|
|
11
|
+
|
|
12
|
+
// The v1 context budget for .claude/memory/session-snapshot.json, a file whose
|
|
13
|
+
// whole purpose is to be read into a session. Not a drifted literal: a real
|
|
14
|
+
// constraint, kept under its own name.
|
|
15
|
+
export const V1_MAX_CHARS = 4096;
|
|
16
|
+
|
|
17
|
+
// Post-parse, version-specific caps, applied once snap.v is known. For v2 the
|
|
18
|
+
// two tiers coincide; they separate the moment a v3 arrives with its own budget.
|
|
19
|
+
export const POST_PARSE_MAX = { 1: V1_MAX_CHARS, 2: PRE_PARSE_MAX_BYTES };
|
|
20
|
+
|
|
21
|
+
// Highest v this contract understands. Raising it here moves the
|
|
22
|
+
// SNAP_UNKNOWN_VERSION boundary with no edit anywhere else.
|
|
23
|
+
export const MAX_VERSION = 2;
|
|
24
|
+
|
|
25
|
+
// One array-cap table in ONE key scheme: dotted path to [count cap, element cap].
|
|
26
|
+
// Two schemes for one table is how a drift hides from every diff and grep.
|
|
27
|
+
export const CAPS = {
|
|
28
|
+
'ops.n': [3, 200],
|
|
29
|
+
'ops.f': [20, 300],
|
|
30
|
+
'mem.d': [10, 300],
|
|
31
|
+
'mem.x': [5, 200],
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
// Field sets. Top-level is per version; block members are version-invariant.
|
|
35
|
+
export const TOP_FIELDS = {
|
|
36
|
+
1: ['v', 'sys', 'ops', 'mem'],
|
|
37
|
+
2: ['v', 'sys', 'ops', 'mem', 'pr'],
|
|
38
|
+
};
|
|
39
|
+
export const BLOCK_FIELDS = { sys: ['ph', 'c', 's'], ops: ['n', 'f'], mem: ['d', 'x'] };
|
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
import { readFileSync } from 'node:fs';
|
|
1
|
+
import { readFileSync } from 'node:fs'; import { BLOCK_FIELDS, CAPS, MAX_VERSION, POST_PARSE_MAX, PRE_PARSE_MAX_BYTES, TOP_FIELDS } from './snap-contract.mjs';
|
|
2
2
|
const err = (m) => { process.stderr.write(`SNAP_ERROR: ${m}\n`); process.exit(1); };
|
|
3
3
|
const path = process.argv[2]; if (path === undefined) err('no path provided');
|
|
4
4
|
let raw; try { raw = readFileSync(path, 'utf8'); } catch (e) { err(e.code === 'ENOENT' ? 'file not found' : e.code); }
|
|
5
5
|
if (raw.includes('�')) err('encoding error');
|
|
6
6
|
const trimmed = raw.trim(); if (trimmed.includes('\n')) err('internal newline in payload');
|
|
7
|
-
if (trimmed === '') err('empty file');
|
|
7
|
+
if (trimmed === '') err('empty file');
|
|
8
|
+
if (raw.length > PRE_PARSE_MAX_BYTES) err(`payload too large: ${raw.length} > ${PRE_PARSE_MAX_BYTES} (pre-parse ceiling)`);
|
|
8
9
|
let snap; try { snap = JSON.parse(trimmed); } catch { err('malformed JSON'); }
|
|
9
10
|
if (typeof snap !== 'object' || snap === null || Array.isArray(snap)) err('root must be a plain object');
|
|
10
11
|
for (const b of ['sys', 'ops', 'mem']) if (typeof snap[b] !== 'object' || snap[b] === null || Array.isArray(snap[b])) err(`missing block: ${b}`);
|
|
11
12
|
const req = { v: snap.v, 'sys.ph': snap.sys.ph, 'sys.c': snap.sys.c, 'sys.s': snap.sys.s, 'ops.n': snap.ops.n, 'ops.f': snap.ops.f, 'mem.d': snap.mem.d, 'mem.x': snap.mem.x };
|
|
12
13
|
const missing = Object.entries(req).filter(([, v]) => v === undefined).map(([k]) => k);
|
|
13
14
|
if (missing.length) { for (const k of missing) process.stderr.write(`SNAP_ERROR: missing: ${k}\n`); process.exit(1); }
|
|
14
|
-
const topAllowed = snap.v
|
|
15
|
+
const topAllowed = TOP_FIELDS[snap.v] || TOP_FIELDS[1];
|
|
15
16
|
const topExtra = Object.keys(snap).find(k => !topAllowed.includes(k)); if (topExtra) err(`unexpected key: ${topExtra}`);
|
|
16
17
|
if (snap.pr !== undefined && typeof snap.pr !== 'string') err('pr must be a string');
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
if (
|
|
18
|
+
for (const b of ['sys', 'ops', 'mem']) { const extra = Object.keys(snap[b]).find(k => !BLOCK_FIELDS[b].includes(k)); if (extra) err(`unexpected key: ${b}.${extra}`); }
|
|
19
|
+
if (typeof snap.v !== 'number' || !Number.isInteger(snap.v) || snap.v < 1) err('v must be a positive integer'); if (snap.v > MAX_VERSION) err('SNAP_UNKNOWN_VERSION');
|
|
20
|
+
if (raw.length > POST_PARSE_MAX[snap.v]) err(`payload too large: ${raw.length} > ${POST_PARSE_MAX[snap.v]} (v${snap.v} cap)`);
|
|
20
21
|
if (!['spec', 'plan', 'impl', 'rev'].includes(snap.sys.ph)) err('ph must be spec|plan|impl|rev');
|
|
21
|
-
const
|
|
22
|
-
for (const [key, [cap, elemCap]] of Object.entries(caps)) {
|
|
22
|
+
for (const [key, [cap, elemCap]] of Object.entries(CAPS)) {
|
|
23
23
|
const [blk, sub] = key.split('.'); const arr = snap[blk][sub]; if (!Array.isArray(arr)) err(`${key} must be an array`); if (arr.length > cap) err(`${key} exceeds cap`);
|
|
24
24
|
arr.forEach((el, i) => { if (typeof el !== 'string' || el.trim() === '') err(`empty element in ${key}[${i}]`); if (JSON.stringify(el).slice(1, -1).length > elemCap) err(`element too long in ${key}[${i}]`); });
|
|
25
25
|
}
|
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env bash
|
|
2
|
-
# Guards: (1) large-file Read without limit, (2) duplicate file creation.
|
|
3
|
-
|
|
4
|
-
set -euo pipefail
|
|
5
|
-
|
|
6
|
-
# ── Guard 1: Large-file Read without limit ─────────────────────────────────────
|
|
7
|
-
if [ "${CLAUDE_TOOL_NAME:-}" = "Read" ]; then
|
|
8
|
-
READ_PATH=$(echo "${CLAUDE_TOOL_INPUT:-}" | grep -o '"file_path":"[^"]*"' | head -1 | sed 's/"file_path":"//;s/"//' || true)
|
|
9
|
-
if [ -n "$READ_PATH" ] && [ -f "$READ_PATH" ]; then
|
|
10
|
-
LINE_COUNT=$(wc -l < "$READ_PATH" 2>/dev/null || echo "0")
|
|
11
|
-
HAS_LIMIT=$(echo "${CLAUDE_TOOL_INPUT:-}" | grep -c '"limit"' || true)
|
|
12
|
-
if [ "$LINE_COUNT" -gt 150 ] && [ "$HAS_LIMIT" -eq 0 ]; then
|
|
13
|
-
echo ""
|
|
14
|
-
echo "⛔ LARGE FILE READ BLOCKED"
|
|
15
|
-
echo " File: $READ_PATH"
|
|
16
|
-
echo " Lines: $LINE_COUNT (>150 — no limit specified)"
|
|
17
|
-
echo ""
|
|
18
|
-
echo " Follow the orchestrator lookup chain:"
|
|
19
|
-
echo " 1. Check .claude/memory/project.md"
|
|
20
|
-
echo " 2. Query graphify for structural questions"
|
|
21
|
-
echo " 3. Use Grep/Glob for pattern searches"
|
|
22
|
-
echo " 4. Read with explicit offset + limit"
|
|
23
|
-
echo ""
|
|
24
|
-
exit 1
|
|
25
|
-
fi
|
|
26
|
-
fi
|
|
27
|
-
fi
|
|
28
|
-
|
|
29
|
-
# ── Guard 4 — block Read on graphify-out/ and node_modules/ (BUG-017) ─────────────────────
|
|
30
|
-
# To reset to GitHub upstream: delete .claude/hooks/pre-tool-use.sh, then re-run installer.
|
|
31
|
-
if [ "$CLAUDE_TOOL_NAME" = "Read" ]; then
|
|
32
|
-
_g4_result=$(printf '%s' "$CLAUDE_TOOL_INPUT" | python3 -c '
|
|
33
|
-
import json, sys, posixpath
|
|
34
|
-
raw = sys.stdin.buffer.read().decode("utf-8", errors="replace")
|
|
35
|
-
d = json.loads(raw)
|
|
36
|
-
fp = d.get("file_path", "").strip()
|
|
37
|
-
fp_n = posixpath.normpath(fp.replace("\\", "/"))
|
|
38
|
-
parts = [p.lower() for p in fp_n.split("/") if p and p != "."]
|
|
39
|
-
blocked = {"graphify-out", "node_modules"}
|
|
40
|
-
print("BLOCK" if any(p in blocked for p in parts) else "OK")
|
|
41
|
-
' 2>/dev/null) || true
|
|
42
|
-
if [ "$_g4_result" = "BLOCK" ]; then
|
|
43
|
-
echo '{"decision":"block","reason":"Guard 4: direct reads of graphify-out/ and node_modules/ are forbidden. Use Glob for existence checks or the graphify skill: /graphify query \"<question>\"."}'
|
|
44
|
-
exit 1
|
|
45
|
-
fi
|
|
46
|
-
# Debug: set CC_GUARD4_DEBUG=1 to log fail-open events to stderr for diagnostics.
|
|
47
|
-
if [ -n "${CC_GUARD4_DEBUG:-}" ] && [ "$_g4_result" != "OK" ]; then
|
|
48
|
-
printf '[Guard 4 debug] fail-open: _g4_result="%s"\n' "$_g4_result" >&2
|
|
49
|
-
fi
|
|
50
|
-
fi
|
|
51
|
-
|
|
52
|
-
# ── Guard 2: Duplicate file creation ──────────────────────────────────────────
|
|
53
|
-
FILE_PATH=""
|
|
54
|
-
if [ -n "${CLAUDE_TOOL_INPUT:-}" ]; then
|
|
55
|
-
FILE_PATH=$(echo "$CLAUDE_TOOL_INPUT" | grep -o '"path":"[^"]*"' | head -1 | sed 's/"path":"//;s/"//' || true)
|
|
56
|
-
fi
|
|
57
|
-
|
|
58
|
-
if [ -z "$FILE_PATH" ]; then
|
|
59
|
-
exit 0
|
|
60
|
-
fi
|
|
61
|
-
|
|
62
|
-
if [ ! -f "$FILE_PATH" ]; then
|
|
63
|
-
exit 0
|
|
64
|
-
fi
|
|
65
|
-
|
|
66
|
-
LINE_COUNT=$(wc -l < "$FILE_PATH" 2>/dev/null || echo "?")
|
|
67
|
-
LAST_MODIFIED=$(date -r "$FILE_PATH" "+%Y-%m-%d %H:%M" 2>/dev/null || stat -c "%y" "$FILE_PATH" 2>/dev/null | cut -d. -f1 || echo "unknown")
|
|
68
|
-
|
|
69
|
-
echo ""
|
|
70
|
-
echo "⚠️ FILE ALREADY EXISTS"
|
|
71
|
-
echo " Path: $FILE_PATH"
|
|
72
|
-
echo " Lines: $LINE_COUNT"
|
|
73
|
-
echo " Last modified: $LAST_MODIFIED"
|
|
74
|
-
echo ""
|
|
75
|
-
echo " Choose an action:"
|
|
76
|
-
echo " 1. Edit the existing file instead of overwriting"
|
|
77
|
-
echo " 2. Confirm you want to overwrite (re-issue the command)"
|
|
78
|
-
echo " 3. Cancel"
|
|
79
|
-
echo ""
|
|
80
|
-
|
|
81
|
-
exit 1
|