create-command-center 0.0.0-stage → 0.3.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.
Files changed (67) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE.agent-skills +21 -0
  3. package/README.md +62 -2
  4. package/RELEASING.md +29 -0
  5. package/UPSTREAM.md +13 -0
  6. package/bin/create-command-center.mjs +34 -0
  7. package/installer/build-parsers.mjs +21 -0
  8. package/installer/install.mjs +103 -0
  9. package/installer/template/AGENTS.md +9 -0
  10. package/installer/template/README.md +13 -0
  11. package/installer/template/gitignore +5 -0
  12. package/installer/template/repos/index.md +5 -0
  13. package/package.json +41 -4
  14. package/references/accessibility-checklist.md +160 -0
  15. package/references/definition-of-done.md +67 -0
  16. package/references/observability-checklist.md +92 -0
  17. package/references/orchestration-patterns.md +370 -0
  18. package/references/performance-checklist.md +239 -0
  19. package/references/security-checklist.md +250 -0
  20. package/references/testing-patterns.md +236 -0
  21. package/skills/accessibility-engineering/SKILL.md +133 -0
  22. package/skills/accessibility-engineering/scripts/audit-a11y.sh +233 -0
  23. package/skills/api-and-interface-design/SKILL.md +369 -0
  24. package/skills/browser-testing-with-devtools/SKILL.md +319 -0
  25. package/skills/cc/SKILL.md +26 -0
  26. package/skills/cc/assets/config.md +28 -0
  27. package/skills/cc/assets/progress.md +23 -0
  28. package/skills/cc/references/jobs.md +30 -0
  29. package/skills/cc/references/registration.md +63 -0
  30. package/skills/cc/scripts/checks.mjs +109 -0
  31. package/skills/cc/scripts/errors.mjs +3 -0
  32. package/skills/cc/scripts/home.mjs +60 -0
  33. package/skills/cc/scripts/init.mjs +499 -0
  34. package/skills/cc/scripts/inspection.mjs +315 -0
  35. package/skills/cc/scripts/vendor/LICENSE.parsers.txt +70 -0
  36. package/skills/cc/scripts/vendor/parsers.mjs +9951 -0
  37. package/skills/ci-cd-and-automation/SKILL.md +395 -0
  38. package/skills/code-review-and-quality/SKILL.md +402 -0
  39. package/skills/code-simplification/SKILL.md +331 -0
  40. package/skills/constraint-driven-development/SKILL.md +319 -0
  41. package/skills/constraint-driven-development/references/floor-guard.md +182 -0
  42. package/skills/constraint-driven-development/scripts/quality-gate.mjs +45 -0
  43. package/skills/context-engineering/SKILL.md +353 -0
  44. package/skills/debugging-and-error-recovery/SKILL.md +300 -0
  45. package/skills/deprecation-and-migration/SKILL.md +252 -0
  46. package/skills/documentation-and-adrs/SKILL.md +320 -0
  47. package/skills/doubt-driven-development/SKILL.md +245 -0
  48. package/skills/frontend-ui-engineering/SKILL.md +346 -0
  49. package/skills/git-workflow-and-versioning/SKILL.md +355 -0
  50. package/skills/idea-refine/SKILL.md +195 -0
  51. package/skills/idea-refine/examples.md +238 -0
  52. package/skills/idea-refine/frameworks.md +99 -0
  53. package/skills/idea-refine/refinement-criteria.md +113 -0
  54. package/skills/idea-refine/scripts/idea-refine.sh +15 -0
  55. package/skills/incremental-implementation/SKILL.md +249 -0
  56. package/skills/interview-me/SKILL.md +235 -0
  57. package/skills/observability-and-instrumentation/SKILL.md +238 -0
  58. package/skills/performance-optimization/SKILL.md +267 -0
  59. package/skills/performance-optimization/references/optimization-patterns.md +250 -0
  60. package/skills/planning-and-task-breakdown/SKILL.md +259 -0
  61. package/skills/security-and-hardening/SKILL.md +216 -0
  62. package/skills/security-and-hardening/references/hardening-patterns.md +333 -0
  63. package/skills/shipping-and-launch/SKILL.md +336 -0
  64. package/skills/source-driven-development/SKILL.md +217 -0
  65. package/skills/spec-driven-development/SKILL.md +307 -0
  66. package/skills/test-driven-development/SKILL.md +400 -0
  67. package/skills/using-agent-skills/SKILL.md +194 -0
@@ -0,0 +1,499 @@
1
+ #!/usr/bin/env node
2
+ import { readFile, writeFile, mkdir, readdir, lstat, realpath, rename, unlink, open } from 'node:fs/promises';
3
+ import { join, resolve, relative, dirname, basename, isAbsolute, sep } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { execFile } from 'node:child_process';
6
+ import { promisify, parseArgs } from 'node:util';
7
+ import { randomUUID } from 'node:crypto';
8
+ import { discoverHome } from './home.mjs';
9
+ import { buildCatalog, snapshot, compareSnapshots, collectFacts, instructionScopes } from './inspection.mjs';
10
+ import { validateSkills, validateChecks, checkGaps } from './checks.mjs';
11
+ import { failure } from './errors.mjs';
12
+
13
+ const exec = promisify(execFile);
14
+ const fields = ['Purpose', 'Checkout', 'Remote', 'Repository identity', 'Base branch', 'Instructions'];
15
+ const instructionNames = new Set(['AGENTS.md', 'CLAUDE.md']);
16
+ const manifestNames = new Set(['package.json', 'pnpm-workspace.yaml', 'pyproject.toml', 'Pipfile', 'setup.cfg', 'setup.py', 'requirements.txt', 'go.mod', 'go.work', 'Cargo.toml', 'pom.xml', 'build.gradle', 'build.gradle.kts', 'Gemfile', 'composer.json', 'Makefile', 'CMakeLists.txt', 'mix.exs']);
17
+ const lockNames = new Set(['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lock', 'bun.lockb', 'uv.lock', 'poetry.lock', 'Pipfile.lock', 'Cargo.lock', 'go.sum', 'Gemfile.lock', 'composer.lock']);
18
+ const skippedDirectories = new Set(['.git', 'node_modules', 'vendor', '.venv', 'venv', '.cache', 'dist', 'build', '.worktrees']);
19
+
20
+ async function stat(path) {
21
+ try { return await lstat(path); }
22
+ catch (error) { if (error.code === 'ENOENT') return null; throw error; }
23
+ }
24
+
25
+ function pathKey(path) {
26
+ const normalized = resolve(path);
27
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
28
+ }
29
+
30
+ function contained(root, path) {
31
+ const rel = relative(root, path);
32
+ return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);
33
+ }
34
+
35
+ async function safePath(root, path) {
36
+ if (!contained(root, path)) throw new Error('Path escapes the home directory.');
37
+ let current = root;
38
+ for (const component of relative(root, path).split(sep).filter(Boolean)) {
39
+ current = join(current, component);
40
+ const info = await stat(current);
41
+ if (info?.isSymbolicLink()) throw new Error('Linked paths inside the home require a path decision.');
42
+ }
43
+ }
44
+
45
+ function githubParts(owner, repo) {
46
+ if (!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(owner) ||
47
+ !/^[a-z0-9._-]+$/i.test(repo) || ['.', '..'].includes(repo)) {
48
+ throw new Error('Invalid GitHub owner or repository component.');
49
+ }
50
+ return { owner: owner.toLowerCase(), repo: repo.toLowerCase() };
51
+ }
52
+
53
+ function remoteSource(input) {
54
+ let owner;
55
+ let repo;
56
+ let ssh = false;
57
+ if (/^https:\/\//i.test(input) || /^ssh:\/\//i.test(input)) {
58
+ // Match the raw path so URL normalization cannot hide traversal or encoded segments.
59
+ const match = /^(https|ssh):\/\/([^/]+)\/([^?#]*)$/i.exec(input);
60
+ if (!match) throw new Error('Use a repository root URL without queries or fragments.');
61
+ const protocol = match[1].toLowerCase();
62
+ const authority = match[2];
63
+ if ((protocol === 'https' && authority.includes('@')) || (protocol === 'ssh' && authority.toLowerCase() !== 'git@github.com')) {
64
+ throw new Error('Credential-bearing URLs are rejected; use a clean GitHub URL or git SSH user.');
65
+ }
66
+ if (protocol === 'https' && authority.toLowerCase() !== 'github.com') throw new Error('Only GitHub repository URLs are supported.');
67
+ ssh = protocol === 'ssh';
68
+ [owner, repo] = match[3].replace(/\/+$/, '').split('/');
69
+ if (match[3].replace(/\/+$/, '').split('/').length !== 2) throw new Error('Use a repository root URL.');
70
+ } else {
71
+ const match = /^(git@github\.com:)?([^/]+)\/([^/]+)\/*$/i.exec(input);
72
+ if (!match) throw new Error('Use a documented GitHub URL, owner/repo, or an existing local path.');
73
+ ssh = Boolean(match[1]);
74
+ [, , owner, repo] = match;
75
+ }
76
+ repo = repo.replace(/\.git$/i, '');
77
+ ({ owner, repo } = githubParts(owner, repo));
78
+ return {
79
+ kind: 'remote', identity: `github.com/${owner}/${repo}`, id: `${owner}--${repo}`,
80
+ checkout: `projects/${owner}/${repo}`,
81
+ url: ssh ? `git@github.com:${owner}/${repo}.git` : `https://github.com/${owner}/${repo}.git`,
82
+ };
83
+ }
84
+
85
+ export async function parseSource(input, cwd = process.cwd()) {
86
+ if (typeof input !== 'string' || !input.trim() || /[\r\n\0]/.test(input)) throw new Error('A project source is required.');
87
+ const local = resolve(cwd, input);
88
+ if (await stat(local)) return { kind: 'local', checkout: await realpath(local) };
89
+ return remoteSource(input);
90
+ }
91
+
92
+ async function gitRunner(args, cwd) {
93
+ try { return { code: 0, ...await exec('git', args, { cwd, maxBuffer: 16 * 1024 * 1024 }) }; }
94
+ catch (error) {
95
+ if (error.code === 'ENOENT') throw new Error('Git must be installed and available on PATH.');
96
+ return { code: error.code, stdout: error.stdout || '', stderr: error.stderr || '' };
97
+ }
98
+ }
99
+
100
+ async function gitText(run, args, cwd, optional = false) {
101
+ const result = await run(args, cwd);
102
+ if (result.code !== 0 && !optional) throw new Error(`Git checkout inspection failed (${args[0]}).`);
103
+ if (result.code !== 0) return null;
104
+ return args.includes('-z') ? result.stdout : result.stdout.trim();
105
+ }
106
+
107
+ function checkCredentials(remote) {
108
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(remote)) {
109
+ let url;
110
+ try { url = new URL(remote); } catch { throw new Error('Invalid checkout remote.'); }
111
+ if (url.password || (url.username && !(url.protocol === 'ssh:' && url.username === 'git')) || url.search || url.hash) {
112
+ throw new Error('Credential-bearing or ambiguous checkout remote; supply a clean origin before registration.');
113
+ }
114
+ } else if (remote.includes('@') && !/^git@[^:]+:[^\r\n]+$/.test(remote)) {
115
+ throw new Error('Credential-bearing checkout remote is rejected.');
116
+ }
117
+ }
118
+
119
+ function identityForRemote(remote) {
120
+ if (!remote) return null;
121
+ checkCredentials(remote);
122
+ if (/^(?:https:\/\/github\.com\/|ssh:\/\/git@github\.com\/|git@github\.com:)/i.test(remote)) return remoteSource(remote).identity;
123
+ return null;
124
+ }
125
+
126
+ async function inspectCheckout(path, run, exactRoot = false) {
127
+ if (!(await stat(path))) throw new Error('Recorded checkout is missing or unavailable.');
128
+ const top = await gitText(run, ['rev-parse', '--show-toplevel'], path);
129
+ const canonicalTop = await realpath(top);
130
+ if (exactRoot && pathKey(canonicalTop) !== pathKey(await realpath(path))) throw new Error('Destination is not the exact Git checkout root.');
131
+ const common = await gitText(run, ['rev-parse', '--path-format=absolute', '--git-common-dir'], canonicalTop);
132
+ const worktrees = await gitText(run, ['worktree', 'list', '--porcelain', '-z'], canonicalTop);
133
+ const primary = /^worktree ([^\0]+)/.exec(worktrees)?.[1];
134
+ if (!primary) throw new Error('Cannot resolve the primary checkout.');
135
+ const checkout = await realpath(primary);
136
+ const remote = await gitText(run, ['remote', 'get-url', 'origin'], checkout, true);
137
+ const identity = identityForRemote(remote) || `local:${pathKey(checkout)}`;
138
+ const currentBranch = await gitText(run, ['symbolic-ref', '--short', 'HEAD'], checkout, true);
139
+ const originHead = await gitText(run, ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], checkout, true);
140
+ const resolvedOriginHead = originHead && await gitText(run, ['rev-parse', '--verify', 'refs/remotes/origin/HEAD^{commit}'], checkout, true);
141
+ const defaultBranch = resolvedOriginHead ? originHead.replace(/^origin\//, '') : null;
142
+ const tracked = await gitText(run, ['ls-files', '-co', '--exclude-standard', '-z'], checkout);
143
+ const paths = new Set(tracked.split('\0').filter(Boolean));
144
+ for (const name of [...instructionNames, ...manifestNames, ...lockNames, 'README.md', '.gitlab-ci.yml', 'azure-pipelines.yml', 'Jenkinsfile']) {
145
+ if ((await stat(join(checkout, name)))?.isFile()) paths.add(name);
146
+ }
147
+ const inspection = { instructions: [], manifests: [], lockfiles: [], ci: [], documentation: [], currentBranch, defaultBranch, defaultBranchSource: defaultBranch ? 'refs/remotes/origin/HEAD' : null };
148
+ for (const name of [...paths].sort()) {
149
+ const components = name.split('/');
150
+ if (components.some(part => skippedDirectories.has(part))) continue;
151
+ const leaf = components.at(-1);
152
+ if (instructionNames.has(leaf)) inspection.instructions.push(name);
153
+ if (manifestNames.has(leaf) || /\.(?:sln|csproj|fsproj)$/.test(leaf)) inspection.manifests.push(name);
154
+ if (lockNames.has(leaf)) inspection.lockfiles.push(name);
155
+ if (/^(?:\.github\/workflows\/.*\.ya?ml|\.circleci\/config\.yml|\.gitlab-ci\.yml|azure-pipelines\.yml|Jenkinsfile)$/.test(name)) inspection.ci.push(name);
156
+ if (/^(?:README(?:\.md)?|docs\/.*\.md)$/i.test(name)) inspection.documentation.push(name);
157
+ }
158
+ return { checkout, commonDirectory: await realpath(common), remote, identity, inspection };
159
+ }
160
+
161
+ function parseFields(text) {
162
+ const values = {};
163
+ for (const name of fields) {
164
+ const matches = [...text.matchAll(new RegExp(`^- ${name} — (.*)$`, 'gm'))];
165
+ if (matches.length > 1) throw new Error(`Ambiguous config field: ${name}.`);
166
+ const value = matches[0]?.[1].trim();
167
+ if (value && value !== 'unknown' && !/^<[^>]+>$/.test(value)) values[name] = value;
168
+ }
169
+ return values;
170
+ }
171
+
172
+ async function scanRecords(home) {
173
+ const root = join(home, 'repos');
174
+ if (!(await stat(root))) return [];
175
+ await safePath(home, root);
176
+ const records = [];
177
+ for (const entry of (await readdir(root, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name, 'en'))) {
178
+ if (entry.isSymbolicLink()) throw new Error('Linked registry directories require a path decision.');
179
+ if (!entry.isDirectory()) continue;
180
+ if (!/^[a-z0-9][a-z0-9._-]*$/i.test(entry.name)) throw new Error('Invalid record ID.');
181
+ const path = join(root, entry.name, 'config.md');
182
+ await safePath(home, path);
183
+ if (!(await stat(path))) throw new Error(`Incomplete config record: ${entry.name}. Inspect it before recovery.`);
184
+ const text = await readFile(path, 'utf8');
185
+ const values = parseFields(text);
186
+ if (!values.Checkout) throw new Error(`Malformed config record ${entry.name}: Checkout is required.`);
187
+ const checkout = resolve(home, values.Checkout);
188
+ const remoteIdentity = identityForRemote(values.Remote);
189
+ let identity = values['Repository identity'];
190
+ const github = identity && /^github\.com\/([^/]+)\/([^/]+)$/i.exec(identity);
191
+ if (github) {
192
+ const parts = githubParts(github[1], github[2]);
193
+ identity = `github.com/${parts.owner}/${parts.repo}`;
194
+ } else if (identity && identity !== 'local-only' && !identity.startsWith('local:')) throw new Error(`Malformed identity in config ${entry.name}.`);
195
+ if (identity?.startsWith('local:')) identity = null;
196
+ if (identity === 'local-only') identity = null;
197
+ if (identity && remoteIdentity && identity !== remoteIdentity) throw new Error(`Conflicting identity in config ${entry.name}.`);
198
+ identity ||= remoteIdentity || `local:${pathKey(await stat(checkout) ? await realpath(checkout) : checkout)}`;
199
+ if (records.some(record => record.identity === identity)) throw new Error('Duplicate repository identities in configs; resolve the ambiguous records.');
200
+ records.push({ id: entry.name, text, checkout, identity });
201
+ }
202
+ return records;
203
+ }
204
+
205
+ async function withLock(homePath, action) {
206
+ const home = await realpath(resolve(homePath));
207
+ const control = join(home, '.cc');
208
+ await safePath(home, control);
209
+ await mkdir(control, { recursive: true });
210
+ const lock = join(control, 'init.lock');
211
+ let handle;
212
+ try { handle = await open(lock, 'wx'); }
213
+ catch (error) {
214
+ if (error.code === 'EEXIST') throw new Error('Another init operation owns the lock. Inspect .cc/init.lock and its owner before recovery.');
215
+ throw error;
216
+ }
217
+ try {
218
+ await handle.writeFile(JSON.stringify({ pid: process.pid, started: new Date().toISOString() }));
219
+ return await action(home);
220
+ } finally { await handle.close(); await unlink(lock); }
221
+ }
222
+
223
+ async function atomicWrite(home, path, text) {
224
+ await safePath(home, path);
225
+ await mkdir(dirname(path), { recursive: true });
226
+ const temporary = `${path}.${randomUUID()}.tmp`;
227
+ try {
228
+ await writeFile(temporary, text, { flag: 'wx' });
229
+ await rename(temporary, path);
230
+ } finally { if (await stat(temporary)) await unlink(temporary); }
231
+ }
232
+
233
+ async function ensureIgnored(home) {
234
+ const path = join(home, '.gitignore');
235
+ await safePath(home, path);
236
+ const existed = Boolean(await stat(path));
237
+ let text = existed ? await readFile(path, 'utf8') : '';
238
+ const rules = '/projects/\n/.cc/\n';
239
+ if (!text.replaceAll('\r\n', '\n').endsWith(rules)) {
240
+ text += `${text && !text.endsWith('\n') ? '\n' : ''}${rules}`;
241
+ await atomicWrite(home, path, text);
242
+ return existed ? 'updated' : 'created';
243
+ }
244
+ return false;
245
+ }
246
+
247
+ async function chooseTarget(home, source, records, run) {
248
+ const local = source.kind === 'local' ? await inspectCheckout(source.checkout, run) : null;
249
+ const identity = local?.identity || source.identity;
250
+ const existing = records.find(record => record.identity === identity || local && pathKey(record.checkout) === pathKey(local.checkout));
251
+ if (existing) {
252
+ if (existing.identity !== identity) throw new Error('Recorded checkout identity has changed.');
253
+ return { id: existing.id, checkout: existing.checkout, identity, existing };
254
+ }
255
+ const id = source.kind === 'remote' ? source.id : basename(local.checkout).toLowerCase().replaceAll(' ', '-');
256
+ if (!/^[a-z0-9][a-z0-9._-]*$/i.test(id)) throw new Error('Checkout basename cannot form a stable repo ID; choose a supported checkout name.');
257
+ if (records.some(record => record.id.toLowerCase() === id.toLowerCase())) throw new Error('Repository ID collision; resolve existing records before proceeding.');
258
+ const checkout = local?.checkout || join(home, source.checkout);
259
+ return { id, checkout, identity, existing: null };
260
+ }
261
+
262
+ export async function prepare({ home, cwd = process.cwd(), source, gitRunner: run = gitRunner }) {
263
+ const homeResolution = await discoverHome({ home, cwd });
264
+ home = homeResolution.home;
265
+ if (!source && pathKey(await realpath(cwd)) === pathKey(home)) throw failure('SOURCE_REQUIRED', 'Supply a project link or local path when invoking init in the home root.');
266
+ const parsed = await parseSource(source || '.', cwd);
267
+ return withLock(home, async homeRoot => {
268
+ const changes = [];
269
+ const records = await scanRecords(homeRoot);
270
+ const target = await chooseTarget(homeRoot, parsed, records, run);
271
+ if (parsed.kind === 'remote' && !target.existing) {
272
+ await safePath(homeRoot, target.checkout);
273
+ if (!(await stat(target.checkout))) {
274
+ const ignored = await ensureIgnored(homeRoot);
275
+ if (ignored) changes.push({ path: '.gitignore', action: ignored, fields: ['ignore rules'] });
276
+ await mkdir(dirname(target.checkout), { recursive: true });
277
+ const result = await run(['clone', '--', parsed.url, target.checkout], homeRoot);
278
+ if (result.code !== 0) throw new Error('Git clone failed. The repo remains unregistered. Inspect the destination for a partial clone before retrying.');
279
+ changes.push({ path: relative(homeRoot, target.checkout).split(sep).join('/'), action: 'created', fields: ['checkout'] });
280
+ }
281
+ }
282
+ const inspected = await inspectCheckout(target.checkout, run, parsed.kind === 'remote');
283
+ if (inspected.identity !== target.identity) throw new Error('Checkout origin identity does not match the requested repository.');
284
+ const ignored = await ensureIgnored(homeRoot);
285
+ if (ignored) changes.push({ path: '.gitignore', action: ignored, fields: ['ignore rules'] });
286
+ const catalog = await buildCatalog(homeRoot);
287
+ const beforeFacts = await snapshot(inspected.checkout, inspected.inspection, homeRoot, catalog);
288
+ const facts = await collectFacts(inspected.checkout, inspected.inspection);
289
+ const preparedSnapshot = await snapshot(inspected.checkout, inspected.inspection, homeRoot, catalog);
290
+ const changedDuringInspection = compareSnapshots(beforeFacts, preparedSnapshot);
291
+ if (changedDuringInspection.length) throw failure('INSPECTION_STALE', 'Inputs changed during inspection; prepare again.', { paths: changedDuringInspection });
292
+ const reportPath = join(homeRoot, '.cc/init', `${randomUUID()}.json`);
293
+ changes.push({ path: relative(homeRoot, reportPath).split(sep).join('/'), action: 'created', fields: ['inspection report'] });
294
+ const report = { version: 2, home: homeRoot, homeResolution: { selectedBy: homeResolution.selectedBy }, id: target.id, ...inspected,
295
+ facts, instructionScopes: instructionScopes(inspected.inspection.instructions), catalog,
296
+ snapshot: preparedSnapshot, changes };
297
+ await atomicWrite(homeRoot, reportPath, JSON.stringify(report, null, 2) + '\n');
298
+ return { ...report, reportPath };
299
+ });
300
+ }
301
+
302
+ function singleLine(value, name) {
303
+ if (typeof value !== 'string' || !value.trim() || /[\r\n\0]/.test(value)) throw new Error(`${name} must be a nonempty single-line string.`);
304
+ return value.trim();
305
+ }
306
+
307
+ async function validateDetails(details, inspection, checkout) {
308
+ if (!details || !Array.isArray(details.checks) || !Array.isArray(details.skills) || !Array.isArray(details.setupGaps)) throw failure('CHECK_INVALID', 'Details require checks, skills, and setupGaps arrays.');
309
+ if (details.purpose !== undefined) singleLine(details.purpose, 'purpose');
310
+ for (const skill of details.skills) {
311
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(skill)) throw failure('SKILL_INVALID', 'Invalid skill name.');
312
+ }
313
+ const sources = [...inspection.instructions, ...inspection.ci, ...inspection.manifests, ...inspection.documentation];
314
+ for (const check of details.checks) {
315
+ singleLine(check.command, 'command'); singleLine(check.workingDirectory, 'workingDirectory'); singleLine(check.source, 'source');
316
+ if (!sources.includes(check.source)) throw failure('CHECK_INVALID', 'Each check source must appear in the inspection checklist.');
317
+ const path = resolve(checkout, check.workingDirectory);
318
+ if (!contained(checkout, path) || !contained(await realpath(checkout), await realpath(path))) throw new Error('Check workingDirectory escapes the checkout.');
319
+ if (!(await stat(path))?.isDirectory()) throw new Error('Check workingDirectory must be a directory.');
320
+ }
321
+ for (const gap of details.setupGaps) singleLine(gap, 'setup gap');
322
+ }
323
+
324
+ function factualFields(report) {
325
+ return {
326
+ Checkout: relative(report.home, report.checkout).split(sep).join('/'),
327
+ Remote: report.remote || 'none',
328
+ 'Repository identity': report.identity,
329
+ 'Base branch': report.inspection.defaultBranch || 'unknown',
330
+ Instructions: report.instructionScopes.filter(item => item.kind === 'root').map(item => item.path).join(', ') || 'none found',
331
+ };
332
+ }
333
+
334
+ async function renderConfig(report, details) {
335
+ let text = await readFile(new URL('../assets/config.md', import.meta.url), 'utf8');
336
+ text = text.replace('<repo-id>', report.id);
337
+ const facts = { Purpose: details.purpose || 'unknown', ...factualFields(report) };
338
+ for (const [name, value] of Object.entries(facts)) {
339
+ singleLine(value, name);
340
+ text = text.replace(new RegExp(`^- ${name} — .*$`, 'm'), () => `- ${name} — ${value}`);
341
+ }
342
+ const checks = details.checks.map(check => `- Command — ${check.command}\n Working directory — ${check.workingDirectory}\n Source — ${check.source}`).join('\n');
343
+ const gaps = [...details.setupGaps];
344
+ if (!details.checks.length) gaps.push('Validation commands need setup.');
345
+ if (!report.inspection.defaultBranch) gaps.push('Default branch needs confirmation.');
346
+ if (!details.purpose) gaps.push('Project purpose needs setup.');
347
+ const setup = [...new Set(gaps)].map(gap => `- ${gap}`).join('\n') || 'None.';
348
+ text = text.replace(/(## Validation\r?\n)[\s\S]*?(?=\r?\n## Engineering skills)/, (_, heading) => `${heading}\n${checks || 'No validation commands confirmed.'}\n\n## Setup gaps\n\n${setup}\n`);
349
+ text = text.replace(/(## Engineering skills\r?\n)[\s\S]*?(?=\r?\n## Delivery)/, (_, heading) => `${heading}\n${details.skills.join(', ') || 'Use relevant shared lifecycle skills and warranted specialists.'}\n`);
350
+ return text;
351
+ }
352
+
353
+ function repairMetadata(text, report) {
354
+ const saved = parseFields(text);
355
+ const missing = [];
356
+ for (const [name, value] of Object.entries(factualFields(report))) {
357
+ if (!saved[name]) {
358
+ singleLine(value, name);
359
+ const line = new RegExp(`^- ${name} — .*$`, 'm');
360
+ if (line.test(text)) text = text.replace(line, () => `- ${name} — ${value}`);
361
+ else missing.push(`- ${name} — ${value}`);
362
+ }
363
+ }
364
+ if (missing.length) {
365
+ if (!/^## Repository\s*$/m.test(text)) throw new Error('Config requires a Repository section before metadata can be repaired.');
366
+ text = text.replace(/^(## Repository\s*)$/m, match => `${match}\n${missing.join('\n')}\n`);
367
+ }
368
+ return text;
369
+ }
370
+
371
+ function section(text, heading) {
372
+ const start = new RegExp(`^## ${heading}[ \\t]*\\r?$`, 'm').exec(text);
373
+ if (!start) return '';
374
+ const rest = text.slice(start.index + start[0].length);
375
+ const end = /^## /m.exec(rest);
376
+ return rest.slice(0, end?.index).trim();
377
+ }
378
+
379
+ function savedSettings(text) {
380
+ const values = parseFields(text);
381
+ const validation = section(text, 'Validation');
382
+ const checkPattern = /^- Command — (.+)\r?\n Working directory — (.+)\r?\n Source — (.+)/gm;
383
+ const checks = [...validation.matchAll(checkPattern)]
384
+ .map(match => ({ command: match[1].trim(), workingDirectory: match[2].trim(), source: match[3].trim() }));
385
+ const skillsText = section(text, 'Engineering skills');
386
+ const skills = /^[a-z0-9,\s-]+$/.test(skillsText) ? skillsText.split(/[\s,]+/).filter(Boolean) : [];
387
+ const gapsText = section(text, 'Setup gaps');
388
+ const setupGaps = gapsText && gapsText !== 'None.' ? gapsText.split(/\r?\n/).filter(line => line.trim()).map(line => line.replace(/^- /, '').trim()) : [];
389
+ const remaining = validation.replace(checkPattern, '').replace('No validation commands confirmed.', '').trim();
390
+ if (remaining) setupGaps.push('Saved validation prose requires structured check details through cc config.');
391
+ return { purpose: values.Purpose, checks, skills, setupGaps };
392
+ }
393
+
394
+ function generatedSection(text, name, heading, value) {
395
+ const start = `<!-- cc-init:${name}:start -->`;
396
+ const end = `<!-- cc-init:${name}:end -->`;
397
+ const block = `${start}\n## ${heading}\n\n\`\`\`json\n${JSON.stringify(value, null, 2)}\n\`\`\`\n${end}`;
398
+ const starts = [...text.matchAll(new RegExp(`^${start}\\r?$`, 'gm'))];
399
+ const ends = [...text.matchAll(new RegExp(`^${end}\\r?$`, 'gm'))];
400
+ if (!starts.length && !ends.length) return `${text.trimEnd()}\n\n${block}\n`;
401
+ if (starts.length !== 1 || ends.length !== 1 || ends[0].index < starts[0].index) throw failure('RECORD_INVALID', 'Malformed generated config section.');
402
+ return text.slice(0, starts[0].index) + block + text.slice(ends[0].index + ends[0][0].length);
403
+ }
404
+
405
+ function settingsGaps(settings, inspection, facts, checks) {
406
+ const gaps = [...settings.setupGaps, ...checkGaps(checks), ...facts.diagnostics.map(item => `${item.code} affects ${item.path}. ${item.message}`)];
407
+ if (!settings.purpose) gaps.push('Project purpose needs setup.');
408
+ if (!settings.checks.length) gaps.push('Validation commands need setup.');
409
+ if (!inspection.defaultBranch) gaps.push('Default branch needs confirmation.');
410
+ return [...new Set(gaps)];
411
+ }
412
+
413
+ export async function register({ home, cwd = process.cwd(), report: reportPath, details, gitRunner: run = gitRunner }) {
414
+ const { home: homeRoot } = await discoverHome({ home, cwd });
415
+ const absoluteReport = resolve(reportPath);
416
+ if (!contained(join(homeRoot, '.cc/init'), absoluteReport)) throw new Error('Use a preparation report from this home.');
417
+ await safePath(homeRoot, absoluteReport);
418
+ const report = JSON.parse(await readFile(absoluteReport, 'utf8'));
419
+ if (report.version !== 2 || !report.snapshot?.files || pathKey(report.home) !== pathKey(homeRoot) || !/^[a-z0-9][a-z0-9._-]*$/i.test(report.id)) throw failure('INSPECTION_STALE', 'Preparation report is unsupported or stale; prepare again.', { paths: [absoluteReport] });
420
+ return withLock(homeRoot, async () => {
421
+ const records = await scanRecords(homeRoot);
422
+ const inspected = await inspectCheckout(report.checkout, run, true);
423
+ if (inspected.identity !== report.identity || pathKey(inspected.commonDirectory) !== pathKey(report.commonDirectory)) throw new Error('Prepared checkout identity changed; prepare again.');
424
+ const catalog = await buildCatalog(homeRoot);
425
+ const currentSnapshot = await snapshot(inspected.checkout, inspected.inspection, homeRoot, catalog);
426
+ const changedPaths = compareSnapshots(report.snapshot, currentSnapshot);
427
+ if (changedPaths.length) throw failure('INSPECTION_STALE', 'Inspection inputs changed; prepare and inspect again.', { paths: changedPaths });
428
+ const existing = records.find(record => record.identity === report.identity || pathKey(record.checkout) === pathKey(inspected.checkout));
429
+ if (existing && (existing.identity !== report.identity || pathKey(existing.checkout) !== pathKey(inspected.checkout))) throw new Error('Prepared record changed; prepare again.');
430
+ if (!existing && records.some(record => record.id.toLowerCase() === report.id.toLowerCase())) throw new Error('Repository ID collision.');
431
+ const id = existing?.id || report.id;
432
+ const current = { ...report, ...inspected, id, home: homeRoot,
433
+ facts: await collectFacts(inspected.checkout, inspected.inspection), instructionScopes: instructionScopes(inspected.inspection.instructions) };
434
+ const settings = existing ? savedSettings(existing.text) : details;
435
+ try { await validateDetails(settings, current.inspection, current.checkout); }
436
+ catch (error) { error.code ||= 'CHECK_INVALID'; throw error; }
437
+ const resolvedSkills = validateSkills(settings.skills, catalog).map(({ name, path, digest }) => ({ name, path, digest }));
438
+ const checks = validateChecks(settings.checks, current.facts, current.instructionScopes);
439
+ const setupGaps = settingsGaps(settings, current.inspection, current.facts, checks);
440
+ const configPath = join(homeRoot, 'repos', id, 'config.md');
441
+ const indexPath = join(homeRoot, 'repos/index.md');
442
+ await safePath(homeRoot, indexPath);
443
+ const indexExisted = Boolean(await stat(indexPath));
444
+ let index = indexExisted ? await readFile(indexPath, 'utf8') : '# Registered repositories\n';
445
+ const link = `${id}/config.md`;
446
+ const links = [...index.matchAll(/\]\(([^)]+)\)/g)].filter(match => match[1] === link || match[1] === `./${link}`);
447
+ if (links.length > 1) throw new Error('Duplicate index links require inspection.');
448
+ let text = existing ? repairMetadata(existing.text, current) : await renderConfig(current, { ...settings, setupGaps });
449
+ const changedFields = existing ? Object.keys(factualFields(current)).filter(name => new RegExp(`^- ${name} — .*$`, 'm').exec(existing.text)?.[0] !== new RegExp(`^- ${name} — .*$`, 'm').exec(text)?.[0]) : ['Repository', 'Validation', 'Setup gaps', 'Engineering skills', 'Delivery'];
450
+ for (const [name, heading, value] of [
451
+ ['project-facts', 'Project facts', current.facts],
452
+ ['instruction-scope', 'Instruction scope', current.instructionScopes],
453
+ ['check-validation', 'Check validation', { checks, setupGaps, resolvedSkills, catalogDiagnostics: catalog.diagnostics }],
454
+ ]) {
455
+ const next = generatedSection(text, name, heading, value);
456
+ if (next !== text) changedFields.push(heading);
457
+ text = next;
458
+ }
459
+ const changes = [];
460
+ const finalInspection = await inspectCheckout(current.checkout, run, true);
461
+ const finalCatalog = await buildCatalog(homeRoot);
462
+ const finalSnapshot = await snapshot(current.checkout, finalInspection.inspection, homeRoot, finalCatalog);
463
+ const changedBeforeWrite = compareSnapshots(report.snapshot, finalSnapshot);
464
+ if (changedBeforeWrite.length || finalInspection.identity !== report.identity) throw failure('INSPECTION_STALE', 'Inspection changed before saving; prepare again.', { paths: changedBeforeWrite.length ? changedBeforeWrite : ['git:identity'] });
465
+ if (text !== existing?.text) {
466
+ await atomicWrite(homeRoot, configPath, text);
467
+ changes.push({ path: relative(homeRoot, configPath).split(sep).join('/'), action: existing ? 'updated' : 'created', fields: changedFields });
468
+ }
469
+ if (!links.length) {
470
+ index = index.replace(/^No projects registered yet\..*\r?\n/gm, '');
471
+ index += `${index.endsWith('\n') ? '' : '\n'}\n- [${id}](${link})\n`;
472
+ await atomicWrite(homeRoot, indexPath, index);
473
+ changes.push({ path: 'repos/index.md', action: indexExisted ? 'updated' : 'created', fields: [link] });
474
+ }
475
+ return { id, identity: current.identity, checkout: current.checkout, configPath, indexPath, reused: Boolean(existing),
476
+ status: !existing ? 'created' : changes.length ? 'repaired' : 'reused', changes, settings: savedSettings(text), checks, setupGaps,
477
+ validationLimits: checks.flatMap(check => check.limits), resolvedSkills, catalogDiagnostics: catalog.diagnostics };
478
+ });
479
+ }
480
+
481
+ async function main() {
482
+ const { values, positionals } = parseArgs({ allowPositionals: true, options: {
483
+ home: { type: 'string' }, cwd: { type: 'string' }, source: { type: 'string' }, report: { type: 'string' }, details: { type: 'string' },
484
+ } });
485
+ if (positionals.length !== 1) throw new Error('Use prepare [--home <home>] [--cwd <invocation-directory>] [--source <source>] or register [--home <home>] --report <file> --details <file>.');
486
+ let result;
487
+ if (positionals[0] === 'prepare') result = await prepare(values);
488
+ else if (positionals[0] === 'register' && values.report && values.details) result = await register({ ...values, details: JSON.parse(await readFile(values.details, 'utf8')) });
489
+ else throw new Error('Unknown operation or missing register inputs.');
490
+ console.log(JSON.stringify({ ok: true, ...result }, null, 2));
491
+ }
492
+
493
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
494
+ main().catch(error => {
495
+ const message = String(error.message).replace(/([a-z]+:\/\/)[^\s/]*@/gi, '$1[redacted]@').replace(/\b(token|password|secret)=[^\s&]+/gi, '$1=[redacted]');
496
+ console.error(JSON.stringify({ ok: false, code: error.code || 'INIT_FAILED', error: message, paths: error.paths, candidates: error.candidates }));
497
+ process.exitCode = 1;
498
+ });
499
+ }