@yeison.restrepo.r/code-conductor 1.43.0 → 1.45.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 +36 -4
- 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/audit.md +12 -3
- 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 +9 -6
- 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 +92 -12
- package/scripts/snap-build.mjs +42 -6
- package/scripts/snap-contract.mjs +3 -0
- package/scripts/snap-validate.mjs +2 -2
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// code-conductor guard for OpenCode (FEAT-048, issue #97; fails closed since the pre-1.44.0
|
|
2
|
+
// hardening). An adapter, not a copy: every mapped tool call is turned into the payload(s)
|
|
3
|
+
// Claude Code sends, handed to the project's own .claude/hooks/pre-tool-use.mjs, and a deny
|
|
4
|
+
// or ask decision is thrown back, which is how OpenCode blocks a call.
|
|
5
|
+
// Every tool is one of three kinds: mapped (sent to the guard), read-only (passes, as its
|
|
6
|
+
// Claude Code twin passes the hook matcher), or blocked. Anything not named is blocked:
|
|
7
|
+
// OpenCode's tool set is not versioned with this guard, so an unknown tool is never trusted.
|
|
8
|
+
// Zero dependencies by design; node: builtins only.
|
|
9
|
+
import { spawnSync } from 'node:child_process';
|
|
10
|
+
import { join, resolve, sep } from 'node:path';
|
|
11
|
+
|
|
12
|
+
const GUARD_REL = join('.claude', 'hooks', 'pre-tool-use.mjs');
|
|
13
|
+
// Claude Code's default hook timeout; a hung guard must not hang the session.
|
|
14
|
+
const GUARD_TIMEOUT_MS = 60000;
|
|
15
|
+
|
|
16
|
+
// None of these writes the working tree; todowrite writes OpenCode's own todo list.
|
|
17
|
+
const READ_ONLY = new Set([
|
|
18
|
+
'glob', 'grep', 'list', 'lsp', 'todoread', 'todowrite',
|
|
19
|
+
'webfetch', 'websearch', 'codesearch', 'question', 'skill', 'invalid',
|
|
20
|
+
]);
|
|
21
|
+
|
|
22
|
+
// Whether tool.execute.before fires inside a subagent is unverified, so no subagent starts.
|
|
23
|
+
const TASK_REASON = 'code-conductor guard cannot inspect OpenCode subagents; "task" is blocked';
|
|
24
|
+
const uncovered = (tool) => `code-conductor guard does not cover the OpenCode tool "${tool}"; it is blocked until the guard maps it`;
|
|
25
|
+
const blocked = (tool, why) => ({ block: `code-conductor guard blocked "${tool}": ${why}` });
|
|
26
|
+
const badArg = (tool, arg, want) => blocked(tool, `argument "${arg}" is missing or not ${want}`);
|
|
27
|
+
|
|
28
|
+
const isText = (v) => typeof v === 'string' && v.length > 0;
|
|
29
|
+
const one = (tool_name, tool_input) => ({ payloads: [{ tool_name, tool_input }] });
|
|
30
|
+
|
|
31
|
+
// A patch path must stay inside the project. No `\`, no absolute form, and the resolved
|
|
32
|
+
// path must sit strictly below the project directory (the directory itself is refused).
|
|
33
|
+
function confine(p, directory) {
|
|
34
|
+
if (p.includes('\\')) return { why: 'contains "\\"' };
|
|
35
|
+
if (p.startsWith('/') || /^[A-Za-z]:/.test(p)) return { why: 'is absolute' };
|
|
36
|
+
const root = resolve(directory);
|
|
37
|
+
const abs = resolve(root, p);
|
|
38
|
+
if (!abs.startsWith(root + sep)) return { why: 'resolves outside the project' };
|
|
39
|
+
return { path: abs };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Exact, column-0 markers only. The path group admits no leading or trailing whitespace
|
|
43
|
+
// and cannot be empty, so every malformed marker fails the match and blocks the patch.
|
|
44
|
+
const MARKER = /^\*\*\* (?:(Begin Patch|End Patch|End of File)|(Add File|Update File|Delete File|Move to): (\S(?:.*\S)?))$/;
|
|
45
|
+
|
|
46
|
+
function parsePatch(tool, text, directory) {
|
|
47
|
+
const files = [];
|
|
48
|
+
let cur = null;
|
|
49
|
+
for (const raw of text.split('\n')) {
|
|
50
|
+
const line = raw.replace(/\r$/, '');
|
|
51
|
+
if (line.trim().startsWith('***')) {
|
|
52
|
+
const m = MARKER.exec(line);
|
|
53
|
+
if (!m) return blocked(tool, `the patch has a \`***\` line that is not an exact marker: ${JSON.stringify(line)}`);
|
|
54
|
+
if (m[1]) continue;
|
|
55
|
+
const where = confine(m[3], directory);
|
|
56
|
+
if (where.why) return blocked(tool, `the patch path ${JSON.stringify(m[3])} ${where.why}`);
|
|
57
|
+
if (m[2] === 'Move to') {
|
|
58
|
+
if (!cur || cur.kind !== 'Update File' || cur.moveTo) return blocked(tool, 'a "*** Move to:" must directly follow an "*** Update File:" section');
|
|
59
|
+
cur.moveTo = where.path;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
cur = { kind: m[2], path: where.path, added: [], removed: [] };
|
|
63
|
+
files.push(cur);
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (!cur) continue;
|
|
67
|
+
if (line.startsWith('+')) cur.added.push(line.slice(1));
|
|
68
|
+
else if (line.startsWith('-')) cur.removed.push(line.slice(1));
|
|
69
|
+
}
|
|
70
|
+
if (!files.length) return blocked(tool, 'the patch names no file');
|
|
71
|
+
const payloads = [];
|
|
72
|
+
for (const f of files) {
|
|
73
|
+
const added = f.added.join('\n');
|
|
74
|
+
if (f.kind === 'Add File') payloads.push({ tool_name: 'Write', tool_input: { file_path: f.path, content: added } });
|
|
75
|
+
else if (f.kind === 'Delete File') payloads.push({ tool_name: 'Edit', tool_input: { file_path: f.path, old_string: '', new_string: '' } });
|
|
76
|
+
else payloads.push({ tool_name: 'Edit', tool_input: { file_path: f.path, old_string: f.removed.join('\n'), new_string: added } });
|
|
77
|
+
// A move writes the target, so Guard 2 sees an existing target as an overwrite.
|
|
78
|
+
if (f.moveTo) payloads.push({ tool_name: 'Write', tool_input: { file_path: f.moveTo, content: added } });
|
|
79
|
+
}
|
|
80
|
+
return { payloads };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function patchTool(a, directory, tool) {
|
|
84
|
+
if (!isText(a.patchText)) return badArg(tool, 'patchText', 'a non-empty string');
|
|
85
|
+
return parsePatch(tool, a.patchText, directory);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// OpenCode tool name -> { payloads } for the guard, or { block } before any guard runs.
|
|
89
|
+
const MAPPED = {
|
|
90
|
+
// An empty command is the guard's to judge (it allows it), so only the type is checked.
|
|
91
|
+
bash: (a, _d, t) => (typeof a.command === 'string' ? one('Bash', { command: a.command }) : badArg(t, 'command', 'a string')),
|
|
92
|
+
read: (a, _d, t) => (isText(a.filePath) ? one('Read', { file_path: a.filePath, offset: a.offset, limit: a.limit }) : badArg(t, 'filePath', 'a non-empty string')),
|
|
93
|
+
write: (a, _d, t) => (isText(a.filePath) ? one('Write', { file_path: a.filePath, content: a.content }) : badArg(t, 'filePath', 'a non-empty string')),
|
|
94
|
+
edit: (a, _d, t) => (isText(a.filePath) ? one('Edit', { file_path: a.filePath, old_string: a.oldString, new_string: a.newString }) : badArg(t, 'filePath', 'a non-empty string')),
|
|
95
|
+
multiedit: (a, _d, t) => {
|
|
96
|
+
if (!isText(a.filePath)) return badArg(t, 'filePath', 'a non-empty string');
|
|
97
|
+
if (!Array.isArray(a.edits) || a.edits.length === 0) return badArg(t, 'edits', 'a non-empty array');
|
|
98
|
+
const payloads = [];
|
|
99
|
+
for (const [i, e] of a.edits.entries()) {
|
|
100
|
+
for (const k of ['oldString', 'newString']) {
|
|
101
|
+
if (!e || typeof e[k] !== 'string') return badArg(t, `edits[${i}].${k}`, 'a string');
|
|
102
|
+
}
|
|
103
|
+
payloads.push({ tool_name: 'Edit', tool_input: { file_path: a.filePath, old_string: e.oldString, new_string: e.newString } });
|
|
104
|
+
}
|
|
105
|
+
return { payloads };
|
|
106
|
+
},
|
|
107
|
+
patch: patchTool,
|
|
108
|
+
apply_patch: patchTool,
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
// The guard emits nothing to allow and one JSON line to decide. Anything else means it
|
|
112
|
+
// did not run, and a call no guard inspected fails closed, as in the guard itself.
|
|
113
|
+
function readDecision(res, guardPath) {
|
|
114
|
+
const failed = `code-conductor guard could not run (${guardPath})`;
|
|
115
|
+
if (res.error) return `${failed}: ${res.error.message}`;
|
|
116
|
+
if (res.status !== 0) return `${failed}: exit ${res.status}. ${(res.stderr || '').trim()}`.trim();
|
|
117
|
+
const out = (res.stdout || '').trim();
|
|
118
|
+
if (!out) return null;
|
|
119
|
+
let decision;
|
|
120
|
+
try { decision = JSON.parse(out).hookSpecificOutput; } catch { return `${failed}: output was not JSON`; }
|
|
121
|
+
if (!decision) return null;
|
|
122
|
+
// A plugin cannot ask the user, so an ask blocks with the guard's own reason.
|
|
123
|
+
if (decision.permissionDecision !== 'deny' && decision.permissionDecision !== 'ask') return null;
|
|
124
|
+
return decision.permissionDecisionReason || 'denied by the code-conductor guard';
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// `node` from PATH, not process.execPath: inside OpenCode that is the OpenCode binary.
|
|
128
|
+
function runGuard(guardPath, payload, directory) {
|
|
129
|
+
return spawnSync('node', [guardPath], {
|
|
130
|
+
cwd: directory,
|
|
131
|
+
input: JSON.stringify(payload),
|
|
132
|
+
encoding: 'utf8',
|
|
133
|
+
timeout: GUARD_TIMEOUT_MS,
|
|
134
|
+
windowsHide: true,
|
|
135
|
+
env: { ...process.env, CLAUDE_PROJECT_DIR: directory },
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export const ConductorGuard = async ({ directory }) => {
|
|
140
|
+
const guardPath = join(directory, GUARD_REL);
|
|
141
|
+
return {
|
|
142
|
+
'tool.execute.before': async (input, output) => {
|
|
143
|
+
const tool = String(input && input.tool);
|
|
144
|
+
if (READ_ONLY.has(tool)) return;
|
|
145
|
+
if (tool === 'task') throw new Error(TASK_REASON);
|
|
146
|
+
if (!Object.hasOwn(MAPPED, tool)) throw new Error(uncovered(tool));
|
|
147
|
+
const mapped = MAPPED[tool]((output && output.args) || {}, directory, tool);
|
|
148
|
+
if (mapped.block) throw new Error(mapped.block);
|
|
149
|
+
// One guard run per payload; the first deny or ask blocks the whole call.
|
|
150
|
+
for (const p of mapped.payloads) {
|
|
151
|
+
const payload = { session_id: input.sessionID, cwd: directory, hook_event_name: 'PreToolUse', ...p };
|
|
152
|
+
const reason = readDecision(runGuard(guardPath, payload, directory), guardPath);
|
|
153
|
+
if (reason) throw new Error(reason);
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
};
|
|
@@ -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);
|