@yeison.restrepo.r/code-conductor 1.43.0 → 1.44.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 +28 -3
- package/bin/code-conductor.mjs +6 -3
- package/global/commands/cc-compact.md +1 -1
- package/global/commands/cc-stack.md +31 -1
- package/lib/installer/deploy.mjs +13 -1
- package/package.json +1 -1
- package/project-template/.claude/agents/plan.md +3 -3
- package/project-template/.claude/agents/spec.md +3 -3
- package/project-template/.claude/commands/cc-orchestrate.md +6 -5
- package/project-template/.claude/commands/cc-resume.md +16 -2
- package/project-template/.claude/hooks/pre-tool-use.mjs +21 -2
- package/project-template/.claude/review-loop.settings.json +1 -1
- package/project-template/.opencode/plugin/conductor-guard.js +157 -0
- package/scripts/adopt-claude-md.mjs +229 -0
- package/scripts/detect-stack.mjs +38 -17
- package/scripts/doc-locations.mjs +193 -0
- package/scripts/orchestrate.mjs +45 -9
- package/scripts/snap-build.mjs +42 -6
- package/scripts/snap-contract.mjs +3 -0
- package/scripts/snap-validate.mjs +2 -2
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// scripts/adopt-claude-md.mjs (FEAT-040)
|
|
3
|
+
// Semantic adoption of a host CLAUDE.md, split so no judgment can change bytes:
|
|
4
|
+
// the model only classifies each host section into a slot; this script renders the
|
|
5
|
+
// resulting file deterministically and writes it only when handed the sha256 of the
|
|
6
|
+
// exact render the owner was shown.
|
|
7
|
+
//
|
|
8
|
+
// usage:
|
|
9
|
+
// adopt-claude-md.mjs sections <file> -> JSON for the model
|
|
10
|
+
// adopt-claude-md.mjs render <file> <plan.json> -> resulting file on stdout, token on stderr
|
|
11
|
+
// adopt-claude-md.mjs apply <file> <plan.json> <token> -> backup, then write
|
|
12
|
+
// plan.json maps a section id to a slot, e.g. {"0":"conventions","2":"keep"}.
|
|
13
|
+
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import crypto from 'node:crypto';
|
|
16
|
+
import { pathToFileURL } from 'node:url';
|
|
17
|
+
import { scanLines, SENTINEL_START, SENTINEL_END } from '../lib/installer/merge-md.mjs';
|
|
18
|
+
|
|
19
|
+
// Scaffold order of project-template/CLAUDE.md; a moved section lands in this order.
|
|
20
|
+
export const SLOTS = ['identity', 'commands', 'architecture', 'conventions', 'out-of-scope', 'keep'];
|
|
21
|
+
const KEEP = SLOTS.indexOf('keep');
|
|
22
|
+
|
|
23
|
+
// Parity-tested against project-template/CLAUDE.md. A line outside the managed block
|
|
24
|
+
// that is not one of these (or a field line) is host content.
|
|
25
|
+
export const SCAFFOLD_HEADINGS = [
|
|
26
|
+
'Project Identity', 'Development Commands', 'Architecture Notes',
|
|
27
|
+
'Conventions', 'Out of Scope', 'Active Stack Profiles',
|
|
28
|
+
];
|
|
29
|
+
export const SCAFFOLD_LINES = new Set([
|
|
30
|
+
'# Project Claude Configuration',
|
|
31
|
+
'Extends global CLAUDE.md. Project-specific rules take precedence over global ones.',
|
|
32
|
+
'<!-- Key architectural decisions for this project -->',
|
|
33
|
+
'<!-- Project-specific conventions that override global defaults -->',
|
|
34
|
+
'<!-- Things Claude should not touch in this project -->',
|
|
35
|
+
'<!-- cc-stack:managed: regenerated by /cc-stack, manual edits inside are overwritten -->',
|
|
36
|
+
'---',
|
|
37
|
+
]);
|
|
38
|
+
// Filled-in fields are conductor's own writes (/cc-stack, /cc-init), not host prose.
|
|
39
|
+
const FIELD_LINE = /^- (Name|Description|Stack|Language|Build|Test|Lint|Format|Setup|Specs|Plans):/;
|
|
40
|
+
const GENERATED_SECTION = 'Active Stack Profiles';
|
|
41
|
+
// /cc-stack 5b writes only `### stack` subsections and `- ` bullets there (prose is
|
|
42
|
+
// disallowed), so any other line in that section is the host's own.
|
|
43
|
+
const GENERATED_LINE = /^(- |### )/;
|
|
44
|
+
|
|
45
|
+
export class AdoptError extends Error {}
|
|
46
|
+
|
|
47
|
+
// Exact-byte pieces: lines keep their CR, so rejoining on '\n' reproduces the file.
|
|
48
|
+
export function splitManaged(text) {
|
|
49
|
+
const scan = scanLines(text);
|
|
50
|
+
if (scan.status === 'unbalanced') throw new AdoptError('unbalanced managed-block sentinels');
|
|
51
|
+
if (scan.openFence) throw new AdoptError('unclosed code fence');
|
|
52
|
+
if (scan.status === 'none') return { before: scan.lines, block: [], after: [] };
|
|
53
|
+
return {
|
|
54
|
+
before: scan.lines.slice(0, scan.start),
|
|
55
|
+
block: scan.lines.slice(scan.start, scan.end + 1),
|
|
56
|
+
after: scan.lines.slice(scan.end + 1),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// A preamble (heading null) plus one segment per fence-aware `## ` heading.
|
|
61
|
+
export function sectionsOf(lines) {
|
|
62
|
+
const cuts = scanLines(lines.join('\n')).headings.map((h) => h.index);
|
|
63
|
+
const bounds = [...new Set([0, ...cuts, lines.length])];
|
|
64
|
+
const out = [];
|
|
65
|
+
for (let i = 0; i < bounds.length - 1; i++) {
|
|
66
|
+
const segment = lines.slice(bounds[i], bounds[i + 1]);
|
|
67
|
+
const heading = segment[0].startsWith('## ') ? segment[0].replace(/\r$/, '').slice(3).trim() : null;
|
|
68
|
+
out.push({ heading, lines: segment });
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Scaffold-only files never trigger: the owner gets nothing to adopt.
|
|
74
|
+
export function hasHostContent(text) {
|
|
75
|
+
const parts = splitManaged(text);
|
|
76
|
+
let generated = false;
|
|
77
|
+
for (const raw of [...parts.before, ...parts.after]) {
|
|
78
|
+
const line = raw.replace(/\r$/, '').trim();
|
|
79
|
+
if (line.startsWith('## ')) generated = line.slice(3).trim() === GENERATED_SECTION;
|
|
80
|
+
const scaffold = line === '' || SCAFFOLD_LINES.has(line) || FIELD_LINE.test(line)
|
|
81
|
+
|| SCAFFOLD_HEADINGS.some((h) => line === `## ${h}`)
|
|
82
|
+
|| (generated && GENERATED_LINE.test(line));
|
|
83
|
+
if (!scaffold) return true;
|
|
84
|
+
}
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Host sections in file order, each tagged with its side of the block and whether its
|
|
89
|
+
// heading collides with another host section or the managed block.
|
|
90
|
+
export function listSections(text) {
|
|
91
|
+
const parts = splitManaged(text);
|
|
92
|
+
const blockHeadings = new Set(sectionsOf(parts.block).map((s) => s.heading));
|
|
93
|
+
const all = [
|
|
94
|
+
...sectionsOf(parts.before).map((s) => ({ ...s, where: 'before' })),
|
|
95
|
+
...sectionsOf(parts.after).map((s) => ({ ...s, where: 'after' })),
|
|
96
|
+
];
|
|
97
|
+
const seen = new Map();
|
|
98
|
+
all.forEach((s, id) => { s.id = id; seen.set(s.heading, (seen.get(s.heading) ?? 0) + 1); });
|
|
99
|
+
return all.map((s) => ({
|
|
100
|
+
...s,
|
|
101
|
+
duplicateInFile: s.heading !== null && seen.get(s.heading) > 1,
|
|
102
|
+
duplicateOfManagedBlock: s.heading !== null && blockHeadings.has(s.heading),
|
|
103
|
+
}));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function slotRank(plan, id) {
|
|
107
|
+
const slot = plan[id] ?? 'keep';
|
|
108
|
+
if (!SLOTS.includes(slot)) throw new AdoptError(`unknown slot "${slot}" for section ${id}`);
|
|
109
|
+
return SLOTS.indexOf(slot);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// The preamble anchors the file's title and intro; a slot for it is a mistake to surface.
|
|
113
|
+
function checkPlan(plan, sections) {
|
|
114
|
+
for (const id of Object.keys(plan)) {
|
|
115
|
+
const section = sections.find((s) => String(s.id) === id);
|
|
116
|
+
if (!section) throw new AdoptError(`plan names unknown section ${id}`);
|
|
117
|
+
if (section.heading === null && plan[id] !== 'keep') throw new AdoptError(`section ${id} has no heading and cannot be moved`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Pure function of (text, plan): same input, same bytes, so a hash is a sound approval
|
|
122
|
+
// token. The preamble never moves and the block is copied verbatim.
|
|
123
|
+
export function render(text, plan) {
|
|
124
|
+
const parts = splitManaged(text);
|
|
125
|
+
const sections = listSections(text);
|
|
126
|
+
checkPlan(plan, sections);
|
|
127
|
+
const moved = sections
|
|
128
|
+
.filter((s) => s.heading !== null && slotRank(plan, s.id) !== KEEP)
|
|
129
|
+
.sort((a, b) => slotRank(plan, a.id) - slotRank(plan, b.id) || a.id - b.id);
|
|
130
|
+
const stays = sections.filter((s) => !moved.includes(s));
|
|
131
|
+
const before = [...stays.filter((s) => s.where === 'before'), ...moved].flatMap((s) => s.lines);
|
|
132
|
+
const after = stays.filter((s) => s.where === 'after').flatMap((s) => s.lines);
|
|
133
|
+
return [before, parts.block, after].filter((a) => a.length).map((a) => a.join('\n')).join('\n');
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export const tokenOf = (rendered) => crypto.createHash('sha256').update(rendered).digest('hex');
|
|
137
|
+
|
|
138
|
+
// Acceptance criteria 2 and 3 as an independent check on the render, not on the plan.
|
|
139
|
+
// Host sections must survive as the same multiset, so a lost, duplicated or altered
|
|
140
|
+
// section is caught; substring matching would miss a duplicate. The preamble must
|
|
141
|
+
// still lead the file. Slot moves reorder sections by design, so order is otherwise free.
|
|
142
|
+
export function violations(original, rendered) {
|
|
143
|
+
const o = splitManaged(original);
|
|
144
|
+
const r = splitManaged(rendered);
|
|
145
|
+
const found = [];
|
|
146
|
+
if (o.block.join('\n') !== r.block.join('\n')) found.push('managed block changed');
|
|
147
|
+
const bytesOf = (parts) => [...sectionsOf(parts.before), ...sectionsOf(parts.after)].map((s) => s.lines.join('\n'));
|
|
148
|
+
const expected = bytesOf(o).sort();
|
|
149
|
+
const actual = bytesOf(r).sort();
|
|
150
|
+
if (expected.length !== actual.length || expected.some((s, i) => s !== actual[i])) found.push('host sections lost, duplicated or altered');
|
|
151
|
+
const lead = (parts) => sectionsOf(parts.before)[0];
|
|
152
|
+
if (lead(o)?.heading === null && lead(o).lines.join('\n') !== lead(r)?.lines.join('\n')) found.push('leading preamble moved');
|
|
153
|
+
return found;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Same name shape as the installer's backup so one prune/restore story covers both.
|
|
157
|
+
export function backupPath(file, now = new Date()) {
|
|
158
|
+
const stamp = now.toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z');
|
|
159
|
+
return `${file}.installer-backup.${stamp}`;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function applyPlan(file, plan, approvedToken) {
|
|
163
|
+
const text = readText(file, 'file');
|
|
164
|
+
const rendered = render(text, plan);
|
|
165
|
+
if (approvedToken !== tokenOf(rendered)) throw new AdoptError('token does not match the shown result; nothing written');
|
|
166
|
+
const bad = violations(text, rendered);
|
|
167
|
+
if (bad.length) throw new AdoptError(`refused: ${bad.join('; ')}`);
|
|
168
|
+
const backup = copyToFreshBackup(file);
|
|
169
|
+
fs.writeFileSync(file, rendered);
|
|
170
|
+
return backup;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const MAX_BACKUP_ATTEMPTS = 100;
|
|
174
|
+
|
|
175
|
+
// EXCL so a second apply in the same second can never overwrite the first backup, the
|
|
176
|
+
// only copy of the original. Any other failure aborts before the file is touched.
|
|
177
|
+
function copyToFreshBackup(file) {
|
|
178
|
+
const base = backupPath(file);
|
|
179
|
+
for (let n = 0; n < MAX_BACKUP_ATTEMPTS; n++) {
|
|
180
|
+
const candidate = n === 0 ? base : `${base}.${n}`;
|
|
181
|
+
try {
|
|
182
|
+
fs.copyFileSync(file, candidate, fs.constants.COPYFILE_EXCL);
|
|
183
|
+
return candidate;
|
|
184
|
+
} catch (err) {
|
|
185
|
+
if (err.code !== 'EEXIST') throw new AdoptError(`backup failed (${err.code ?? err.message}); nothing written`);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
throw new AdoptError('backup failed (no free backup name); nothing written');
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function describeSections(text) {
|
|
192
|
+
if (!hasHostContent(text)) return { trigger: false };
|
|
193
|
+
const sections = listSections(text).map(({ lines, ...rest }) => ({ ...rest, preview: lines.join('\n').slice(0, 80) }));
|
|
194
|
+
return { trigger: true, slots: SLOTS, sections };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function readText(path, what) {
|
|
198
|
+
if (!path) throw new AdoptError(`missing ${what} argument`);
|
|
199
|
+
try { return fs.readFileSync(path, 'utf8'); } catch (err) { throw new AdoptError(`cannot read ${what} ${path}: ${err.code ?? err.message}`); }
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function readPlan(planFile) {
|
|
203
|
+
let plan;
|
|
204
|
+
try { plan = JSON.parse(readText(planFile, 'plan')); } catch (err) {
|
|
205
|
+
if (err instanceof AdoptError) throw err;
|
|
206
|
+
throw new AdoptError(`plan ${planFile} is not valid JSON`);
|
|
207
|
+
}
|
|
208
|
+
if (plan === null || typeof plan !== 'object' || Array.isArray(plan)) throw new AdoptError('plan must be a JSON object of section id to slot');
|
|
209
|
+
return plan;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function main([command, file, planFile, token]) {
|
|
213
|
+
if (command === 'sections') return console.log(JSON.stringify(describeSections(readText(file, 'file')), null, 1));
|
|
214
|
+
if (command === 'render') {
|
|
215
|
+
const rendered = render(readText(file, 'file'), readPlan(planFile));
|
|
216
|
+
process.stdout.write(rendered);
|
|
217
|
+
return console.error(`approval token: ${tokenOf(rendered)}`);
|
|
218
|
+
}
|
|
219
|
+
if (command === 'apply') return console.log(`backup: ${applyPlan(file, readPlan(planFile), token)}`);
|
|
220
|
+
throw new AdoptError('usage: adopt-claude-md.mjs sections|render|apply <file> [plan.json] [token]');
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
|
|
224
|
+
try { main(process.argv.slice(2)); } catch (err) {
|
|
225
|
+
if (!(err instanceof AdoptError)) throw err;
|
|
226
|
+
console.error(`ERROR: ${err.message}`);
|
|
227
|
+
process.exit(2);
|
|
228
|
+
}
|
|
229
|
+
}
|
package/scripts/detect-stack.mjs
CHANGED
|
@@ -31,6 +31,9 @@ export function stripBOM(s) { return s.replace(/^/, ''); }
|
|
|
31
31
|
|
|
32
32
|
export function warn(msg) { process.stderr.write(`WARN: ${msg}\n`); }
|
|
33
33
|
|
|
34
|
+
// A package.json field counts only when it is a string; anything else reads as a missing key.
|
|
35
|
+
export function stringField(value) { return typeof value === 'string' ? value : undefined; }
|
|
36
|
+
|
|
34
37
|
export async function readdirSafe(dir) {
|
|
35
38
|
return Promise.race([
|
|
36
39
|
readdir(dir, { withFileTypes: true }),
|
|
@@ -53,6 +56,18 @@ export async function readManifest(filepath) {
|
|
|
53
56
|
} catch { return null; }
|
|
54
57
|
}
|
|
55
58
|
|
|
59
|
+
const SCRIPT_KEYS = ['build', 'test', 'lint', 'format'];
|
|
60
|
+
|
|
61
|
+
// One line per ignored field, emitted where a manifest is loaded so two detectors reading it cannot double it.
|
|
62
|
+
export function warnNonStringFields(pkg, filepath) {
|
|
63
|
+
if (!pkg) return;
|
|
64
|
+
const scripts = typeof pkg.scripts === 'object' && pkg.scripts !== null ? pkg.scripts : {};
|
|
65
|
+
const fields = [['name', pkg.name], ['description', pkg.description], ...SCRIPT_KEYS.map(k => [`scripts.${k}`, scripts[k]])];
|
|
66
|
+
for (const [field, value] of fields) {
|
|
67
|
+
if (value !== undefined && typeof value !== 'string') warn(`non-string package.json field ignored - ${field}: ${filepath}`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
56
71
|
export async function readText(filepath, maxLines = Infinity) {
|
|
57
72
|
try {
|
|
58
73
|
const s = await stat(filepath);
|
|
@@ -242,7 +257,7 @@ export async function detectAngular(pkg, workspacePkgs) {
|
|
|
242
257
|
const major = extractMajorVersion(v);
|
|
243
258
|
if (!major) continue;
|
|
244
259
|
const s = p.scripts ?? {};
|
|
245
|
-
return { stack: `Angular ${major}`, build: s.build ?? 'ng build', test: s.test ?? 'ng test', lint: s.lint ?? 'ng lint', format: 'prettier --write .', setup: 'npm install' };
|
|
260
|
+
return { stack: `Angular ${major}`, build: stringField(s.build) ?? 'ng build', test: stringField(s.test) ?? 'ng test', lint: stringField(s.lint) ?? 'ng lint', format: 'prettier --write .', setup: 'npm install' };
|
|
246
261
|
}
|
|
247
262
|
return {};
|
|
248
263
|
}
|
|
@@ -250,33 +265,33 @@ export async function detectAngular(pkg, workspacePkgs) {
|
|
|
250
265
|
export function detectNextjs(pkg) {
|
|
251
266
|
if (!pkg || !pkgDep(pkg, 'next')) return {};
|
|
252
267
|
const s = pkg.scripts ?? {};
|
|
253
|
-
return { stack: 'typescript', build: s.build ?? 'next build', test: s.test ?? 'jest', lint: s.lint ?? 'next lint', format: 'prettier --write .', setup: 'npm install' };
|
|
268
|
+
return { stack: 'typescript', build: stringField(s.build) ?? 'next build', test: stringField(s.test) ?? 'jest', lint: stringField(s.lint) ?? 'next lint', format: 'prettier --write .', setup: 'npm install' };
|
|
254
269
|
}
|
|
255
270
|
|
|
256
271
|
export function detectNestjs(pkg) {
|
|
257
272
|
if (!pkg || !pkgDep(pkg, '@nestjs/core')) return {};
|
|
258
273
|
const s = pkg.scripts ?? {};
|
|
259
|
-
return { stack: 'typescript', build: s.build ?? 'nest build', test: s.test ?? 'jest', lint: s.lint ?? 'eslint .', format: 'prettier --write .', setup: 'npm install' };
|
|
274
|
+
return { stack: 'typescript', build: stringField(s.build) ?? 'nest build', test: stringField(s.test) ?? 'jest', lint: stringField(s.lint) ?? 'eslint .', format: 'prettier --write .', setup: 'npm install' };
|
|
260
275
|
}
|
|
261
276
|
|
|
262
277
|
export function detectReact(pkg) {
|
|
263
278
|
if (!pkg || !pkgProdDep(pkg, 'react')) return {};
|
|
264
279
|
const s = pkg.scripts ?? {};
|
|
265
|
-
return { stack: 'typescript', build: s.build, test: s.test ?? 'jest', lint: s.lint, format: 'prettier --write .', setup: 'npm install' };
|
|
280
|
+
return { stack: 'typescript', build: stringField(s.build), test: stringField(s.test) ?? 'jest', lint: stringField(s.lint), format: 'prettier --write .', setup: 'npm install' };
|
|
266
281
|
}
|
|
267
282
|
|
|
268
283
|
export function detectVue(pkg) {
|
|
269
284
|
if (!pkg || !pkgProdDep(pkg, 'vue')) return {};
|
|
270
285
|
const s = pkg.scripts ?? {};
|
|
271
|
-
return { stack: 'typescript', build: s.build, test: s.test ?? 'vitest', lint: s.lint, format: 'prettier --write .', setup: 'npm install' };
|
|
286
|
+
return { stack: 'typescript', build: stringField(s.build), test: stringField(s.test) ?? 'vitest', lint: stringField(s.lint), format: 'prettier --write .', setup: 'npm install' };
|
|
272
287
|
}
|
|
273
288
|
|
|
274
289
|
export function detectTSNode(pkg) {
|
|
275
290
|
if (!pkg) return {};
|
|
276
291
|
const s = pkg.scripts ?? {};
|
|
277
292
|
const hasDep = pkgDep(pkg, 'typescript') || pkgDep(pkg, 'ts-node');
|
|
278
|
-
if (!hasDep && !pkg.name) return {};
|
|
279
|
-
return { stack: 'typescript', build: s.build, test: s.test, lint: s.lint, format: s.format, setup: 'npm install' };
|
|
293
|
+
if (!hasDep && !stringField(pkg.name)) return {};
|
|
294
|
+
return { stack: 'typescript', build: stringField(s.build), test: stringField(s.test), lint: stringField(s.lint), format: stringField(s.format), setup: 'npm install' };
|
|
280
295
|
}
|
|
281
296
|
|
|
282
297
|
export async function detectGo(names, root) {
|
|
@@ -500,7 +515,9 @@ async function main() {
|
|
|
500
515
|
|
|
501
516
|
const packageManager = detectPackageManager(rootNames);
|
|
502
517
|
|
|
503
|
-
const
|
|
518
|
+
const rootPkgPath = join(rootReal, 'package.json');
|
|
519
|
+
const rootPkg = rootNames.has('package.json') ? await readManifest(rootPkgPath) : null;
|
|
520
|
+
warnNonStringFields(rootPkg, rootPkgPath);
|
|
504
521
|
|
|
505
522
|
let workspaceDirs = [];
|
|
506
523
|
let monorepo = false;
|
|
@@ -546,8 +563,11 @@ async function main() {
|
|
|
546
563
|
for (const dir of workspaceDirs) {
|
|
547
564
|
const entries = await readdirSafe(dir);
|
|
548
565
|
const names = new Set(entries.map(e => e.name));
|
|
549
|
-
if (names.has('package.json')) workspacePkgs.push(
|
|
550
|
-
|
|
566
|
+
if (!names.has('package.json')) { workspacePkgs.push(null); continue; }
|
|
567
|
+
const pkgPath = join(dir, 'package.json');
|
|
568
|
+
const pkg = await readManifest(pkgPath);
|
|
569
|
+
warnNonStringFields(pkg, pkgPath);
|
|
570
|
+
workspacePkgs.push(pkg);
|
|
551
571
|
}
|
|
552
572
|
|
|
553
573
|
const allDeps = {};
|
|
@@ -594,11 +614,10 @@ async function main() {
|
|
|
594
614
|
if (langSignals.length > 1) merged.stack = langSignals.join('/');
|
|
595
615
|
|
|
596
616
|
if (rootPkg?.scripts) {
|
|
597
|
-
const
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
if (!merged.format && s.format) merged.format = s.format.trim();
|
|
617
|
+
for (const key of SCRIPT_KEYS) {
|
|
618
|
+
const command = stringField(rootPkg.scripts[key]);
|
|
619
|
+
if (!merged[key] && command) merged[key] = command.trim();
|
|
620
|
+
}
|
|
602
621
|
}
|
|
603
622
|
|
|
604
623
|
if (monorepo) {
|
|
@@ -611,7 +630,8 @@ async function main() {
|
|
|
611
630
|
}
|
|
612
631
|
|
|
613
632
|
if (!merged.name) {
|
|
614
|
-
|
|
633
|
+
const pkgName = stringField(rootPkg?.name);
|
|
634
|
+
if (pkgName) merged.name = pkgName;
|
|
615
635
|
else if (rootNames.has('go.mod')) {
|
|
616
636
|
const c = await readText(join(rootReal, 'go.mod'), 5);
|
|
617
637
|
const m = c?.match(/^module\s+(\S+)/m);
|
|
@@ -620,7 +640,8 @@ async function main() {
|
|
|
620
640
|
if (!merged.name) merged.name = basename(rootReal);
|
|
621
641
|
}
|
|
622
642
|
|
|
623
|
-
|
|
643
|
+
const description = stringField(rootPkg?.description);
|
|
644
|
+
if (description) merged.description = description.trim().replace(/\r?\n/g, ' ');
|
|
624
645
|
|
|
625
646
|
const db = await detectDb(rootNames, rootReal, rootPkg, merged.stack);
|
|
626
647
|
const { infra, ci } = await detectInfraCI(rootNames, rootReal);
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// scripts/doc-locations.mjs
|
|
3
|
+
// Spec and plan location resolver (FEAT-047). Resolves the folder pair a run writes its
|
|
4
|
+
// spec and plan into: recorded in CLAUDE.md, else discovered, else docs/specs + docs/plans,
|
|
5
|
+
// and the backlog group the item's documents sit under. Zero dependencies, node: builtins only.
|
|
6
|
+
// orchestrate.mjs imports this module, so it has no top-level side effects, installs no
|
|
7
|
+
// process handler, writes nothing, and sets an exit code only from its CLI entry.
|
|
8
|
+
import { readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
|
|
9
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
10
|
+
import { pathToFileURL } from 'node:url';
|
|
11
|
+
// Imported, not hardcoded: the spec derives DIR_MAX from this cap, and snap-contract.mjs is
|
|
12
|
+
// itself zero-dependency, so the import costs nothing and a cap change cannot drift.
|
|
13
|
+
import { V3_CAPS } from './snap-contract.mjs';
|
|
14
|
+
|
|
15
|
+
export const CANDIDATE_PAIRS = [
|
|
16
|
+
{ specs: '.claude/specs', plans: '.claude/plans' },
|
|
17
|
+
{ specs: 'docs/specs', plans: 'docs/plans' },
|
|
18
|
+
{ specs: 'docs/superpowers/specs', plans: 'docs/superpowers/plans' },
|
|
19
|
+
];
|
|
20
|
+
export const DEFAULT_PAIR = { specs: 'docs/specs', plans: 'docs/plans' };
|
|
21
|
+
export const GROUP_MAX = 47;
|
|
22
|
+
// A scope element is `<dir>/<group>/**`, so the folder leaves room for the longest group.
|
|
23
|
+
export const DIR_MAX = V3_CAPS['ops.scope'][1] - (GROUP_MAX + '/'.length + '/**'.length);
|
|
24
|
+
|
|
25
|
+
const CODE = 'ORCH_DOC_LOCATION_INVALID';
|
|
26
|
+
// A recorded folder becomes the spec and plan agents' Guard 5 write scope, so it may not cover
|
|
27
|
+
// the orchestrator write surface, git internals, or any folder that holds enforcement code
|
|
28
|
+
// (`.opencode` holds the OpenCode guard). Inside `.claude`, only specs and plans may hold
|
|
29
|
+
// documents: everything else there is agent instructions or configuration (skills, settings,
|
|
30
|
+
// rules), so the rule below it is an allowlist, not this deny list.
|
|
31
|
+
const RESERVED = ['.claude/memory', '.claude/hooks', '.claude/agents', '.claude/commands', '.claude/scripts', '.conductor', '.git', '.github', '.opencode', 'scripts'];
|
|
32
|
+
const CLAUDE_DOCS = ['.claude/specs', '.claude/plans'];
|
|
33
|
+
const GROUP_RE = /^(#{1,5})\s+(phase|epic|pillar)\b[\s:#-]*(\d+)?[\s:.-]*(.*)$/i;
|
|
34
|
+
const HEADING_RE = /^(#{1,6})\s/;
|
|
35
|
+
|
|
36
|
+
export class DocLocationError extends Error {
|
|
37
|
+
constructor(reason) {
|
|
38
|
+
super(`${CODE}: ${reason}`);
|
|
39
|
+
this.name = 'DocLocationError';
|
|
40
|
+
this.code = CODE;
|
|
41
|
+
this.reason = reason;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const stripSlash = (value) => value.replace(/\/+$/, '');
|
|
46
|
+
const underRoot = (value, base) => value === base || value.startsWith(`${base}/`);
|
|
47
|
+
const overlaps = (a, b) => a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
|
|
48
|
+
|
|
49
|
+
// Case-folded because Windows and macOS file systems treat `.Claude/Hooks` as `.claude/hooks`.
|
|
50
|
+
function reservedReason(value) {
|
|
51
|
+
const folded = value.toLowerCase();
|
|
52
|
+
const base = RESERVED.find((entry) => overlaps(folded, entry));
|
|
53
|
+
if (base) {
|
|
54
|
+
if (underRoot(folded, base)) return `sits in the reserved \`${base}\``;
|
|
55
|
+
return `covers the reserved \`${base}\``;
|
|
56
|
+
}
|
|
57
|
+
if (underRoot(folded, '.claude') && !CLAUDE_DOCS.some((ok) => underRoot(folded, ok))) {
|
|
58
|
+
return 'sits in `.claude`, where only `.claude/specs` and `.claude/plans` may hold documents';
|
|
59
|
+
}
|
|
60
|
+
return '';
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function checkDocDir(rel) {
|
|
64
|
+
const value = stripSlash(String(rel ?? ''));
|
|
65
|
+
if (value === '' || value === '<command>') return 'is empty or the template placeholder';
|
|
66
|
+
if (isAbsolute(value) || /^[A-Za-z]:/.test(value) || value.startsWith('/')) return 'is absolute; use a path relative to the repository root';
|
|
67
|
+
if (value.split('/').includes('..')) return 'climbs out with a `..` segment';
|
|
68
|
+
if (value.includes('\\')) return 'uses `\\`; separate segments with `/`';
|
|
69
|
+
if (/[*?[\]{}]/.test(value)) return 'carries a glob character';
|
|
70
|
+
if (value === '.') return 'is the repository root, which covers every reserved folder';
|
|
71
|
+
if (value.split('/').some((seg) => seg === '' || seg === '.')) return 'carries an empty or `.` segment; write the plain path from the repository root';
|
|
72
|
+
const reserved = reservedReason(value);
|
|
73
|
+
if (reserved) return reserved;
|
|
74
|
+
if (value.length > DIR_MAX) return `is ${value.length} characters; the cap is ${DIR_MAX}`;
|
|
75
|
+
return '';
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function readText(path) {
|
|
79
|
+
try { return readFileSync(path, 'utf8').replace(/\r\n/g, '\n'); } catch { return null; }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function readRecordedPair(root) {
|
|
83
|
+
const text = readText(join(root, 'CLAUDE.md'));
|
|
84
|
+
if (text === null) return null;
|
|
85
|
+
const specs = text.match(/^- Specs: (\S+)$/m)?.[1];
|
|
86
|
+
const plans = text.match(/^- Plans: (\S+)$/m)?.[1];
|
|
87
|
+
if (!specs && !plans) return null;
|
|
88
|
+
if (!specs || !plans) throw new DocLocationError('CLAUDE.md records `- Specs:` but not `- Plans:` (or the reverse); add the missing line, or remove both');
|
|
89
|
+
for (const [label, value] of [['Specs', specs], ['Plans', plans]]) {
|
|
90
|
+
const why = checkDocDir(value);
|
|
91
|
+
if (why) throw new DocLocationError(`\`- ${label}: ${value}\` ${why}; fix that line`);
|
|
92
|
+
}
|
|
93
|
+
const pair = { specs: stripSlash(specs), plans: stripSlash(plans) };
|
|
94
|
+
if (overlaps(pair.specs, pair.plans)) throw new DocLocationError('`- Specs:` and `- Plans:` overlap; use two disjoint folders');
|
|
95
|
+
return pair;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function isDir(path) {
|
|
99
|
+
try { return statSync(path).isDirectory(); } catch { return false; }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Hand-written, not readdirSync({ recursive: true }): engines is >=20 and that option arrived
|
|
103
|
+
// in 20.1. Dirent.isDirectory() is false for a symlink, so symlinked folders are not followed.
|
|
104
|
+
function countMarkdown(dir) {
|
|
105
|
+
let entries;
|
|
106
|
+
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return 0; }
|
|
107
|
+
let count = 0;
|
|
108
|
+
for (const entry of entries) {
|
|
109
|
+
if (entry.isDirectory()) count += countMarkdown(join(dir, entry.name));
|
|
110
|
+
else if (entry.isFile() && entry.name.endsWith('.md')) count += 1;
|
|
111
|
+
}
|
|
112
|
+
return count;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function discoverPair(root) {
|
|
116
|
+
let best = null;
|
|
117
|
+
let bestCount = -1;
|
|
118
|
+
for (const pair of CANDIDATE_PAIRS) {
|
|
119
|
+
if (!isDir(join(root, pair.specs)) && !isDir(join(root, pair.plans))) continue;
|
|
120
|
+
const count = countMarkdown(join(root, pair.specs)) + countMarkdown(join(root, pair.plans));
|
|
121
|
+
// Strict: on a tie the earlier pair keeps the win.
|
|
122
|
+
if (count > bestCount) { best = pair; bestCount = count; }
|
|
123
|
+
}
|
|
124
|
+
return best ? { ...best } : null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function groupName(kind, n, rest) {
|
|
128
|
+
const prefix = kind.toLowerCase();
|
|
129
|
+
if (n) return checkGroupLength(`${prefix}-${n}`);
|
|
130
|
+
const slug = rest.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40).replace(/-+$/, '');
|
|
131
|
+
if (!slug) return null;
|
|
132
|
+
return checkGroupLength(`${prefix}-${slug}`);
|
|
133
|
+
}
|
|
134
|
+
const checkGroupLength = (name) => (name.length > GROUP_MAX ? null : name);
|
|
135
|
+
|
|
136
|
+
function backlogFiles(root) {
|
|
137
|
+
try { return readdirSync(root).filter((name) => /backlog/i.test(name) && name.endsWith('.md')).sort(); } catch { return []; }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function hitsInText(text, itemRe) {
|
|
141
|
+
const hits = [];
|
|
142
|
+
let open = null;
|
|
143
|
+
for (const line of text.split('\n')) {
|
|
144
|
+
const heading = line.match(HEADING_RE);
|
|
145
|
+
if (!heading) continue;
|
|
146
|
+
const group = line.match(GROUP_RE);
|
|
147
|
+
if (group) { open = { level: group[1].length, name: groupName(group[2], group[3], group[4]) }; continue; }
|
|
148
|
+
// Close before the item check, so an item heading at the group's own level is flat.
|
|
149
|
+
if (open && heading[1].length <= open.level) open = null;
|
|
150
|
+
if (itemRe.test(line)) hits.push(open?.name ?? null);
|
|
151
|
+
}
|
|
152
|
+
return hits;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function backlogGroup(root, item) {
|
|
156
|
+
const escaped = String(item).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
157
|
+
const itemRe = new RegExp(`(?<![A-Za-z0-9_-])${escaped}(?![A-Za-z0-9_-])`);
|
|
158
|
+
const hits = [];
|
|
159
|
+
for (const name of backlogFiles(root)) {
|
|
160
|
+
const text = readText(join(root, name));
|
|
161
|
+
if (text !== null) hits.push(...hitsInText(text, itemRe));
|
|
162
|
+
}
|
|
163
|
+
// Ruling 5: group only when the item is placed exactly once.
|
|
164
|
+
return hits.length === 1 ? hits[0] : null;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export function resolveDocLocations(root, item) {
|
|
168
|
+
const group = item ? backlogGroup(root, item) : null;
|
|
169
|
+
const recorded = readRecordedPair(root);
|
|
170
|
+
if (recorded) return { ...recorded, group, source: 'claude-md' };
|
|
171
|
+
const discovered = discoverPair(root);
|
|
172
|
+
if (discovered) return { ...discovered, group, source: 'discovered' };
|
|
173
|
+
return { ...DEFAULT_PAIR, group, source: 'default' };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export function cli(argv) {
|
|
177
|
+
try {
|
|
178
|
+
const root = resolve(argv[0] ?? process.cwd());
|
|
179
|
+
if (!isDir(root)) throw new Error(`${root} is not a directory`);
|
|
180
|
+
const { specs, plans, source } = resolveDocLocations(root, null);
|
|
181
|
+
process.stdout.write(`${JSON.stringify({ specs, plans, source })}\n`);
|
|
182
|
+
return 0;
|
|
183
|
+
} catch (e) {
|
|
184
|
+
const line = e instanceof DocLocationError ? e.message : `doc-locations: ${e.message}`;
|
|
185
|
+
process.stderr.write(`${line.replace(/\s*\n\s*/g, ' ')}\n`);
|
|
186
|
+
return 1;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function invokedDirectly() {
|
|
191
|
+
try { return Boolean(process.argv[1]) && pathToFileURL(realpathSync(process.argv[1])).href === import.meta.url; } catch { return false; }
|
|
192
|
+
}
|
|
193
|
+
if (invokedDirectly()) process.exitCode = cli(process.argv.slice(2));
|