@yeison.restrepo.r/code-conductor 1.23.3 → 1.30.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.
@@ -27,6 +27,15 @@ const SCHEMA_VERSION = 2;
27
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
 
@@ -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();
@@ -1,3 +1,9 @@
1
+ ---
2
+ name: code-simplifier
3
+ description: "Always-active simplicity rules: no speculative abstractions, one job per function, max 30 lines, flat over nested with early returns, descriptive names, comments explain why"
4
+ type: skill
5
+ ---
6
+
1
7
  # Code Simplifier
2
8
 
3
9
  **Always active.** Apply these rules to every piece of code written or reviewed.
@@ -1,3 +1,9 @@
1
+ ---
2
+ name: verbosity
3
+ description: "Response verbosity protocol: reads the level from ~/.claude/memory/verbosity.md and applies the MIN, INFO or VERBOSE output rules to every reply"
4
+ type: skill
5
+ ---
6
+
1
7
  # Verbosity
2
8
 
3
9
  Read `~/.claude/memory/verbosity.md` once at the start of every session. Extract the value after `VERBOSITY:`. Default to MIN if the file is absent or the value is unrecognized.
@@ -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