@notchlet/cli 0.0.0-stage → 0.1.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/dist/cli.js ADDED
@@ -0,0 +1,403 @@
1
+ #!/usr/bin/env node
2
+ import path from 'node:path';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { appendEvidence, CORE_VERSION, closeChange, evaluateState, findWorkspace, initWorkspace, instructions, listChanges, persistConversion, previewCapabilityClose, readChange, readiness, scaffold, transitionTask, WorkflowError } from '@notchlet/core';
5
+ const args = process.argv.slice(2);
6
+ const profiling = process.env.NOTCHLET_PROFILE === '1';
7
+ const profileTimings = {};
8
+ const profileNow = () => Number(process.hrtime.bigint()) / 1e6;
9
+ function profileSync(name, operation) {
10
+ if (!profiling)
11
+ return operation();
12
+ const start = profileNow();
13
+ try {
14
+ return operation();
15
+ }
16
+ finally {
17
+ profileTimings[name] = (profileTimings[name] ?? 0) + profileNow() - start;
18
+ }
19
+ }
20
+ async function profileAsync(name, operation) {
21
+ if (!profiling)
22
+ return operation();
23
+ const start = profileNow();
24
+ try {
25
+ return await operation();
26
+ }
27
+ finally {
28
+ profileTimings[name] = (profileTimings[name] ?? 0) + profileNow() - start;
29
+ }
30
+ }
31
+ const json = args.includes('--json');
32
+ const positional = [];
33
+ for (let i = 0; i < args.length; i++) {
34
+ if (['--workspace', '--root', '--schema', '--action', '--server', '--product-id', '--repository-id', '--endpoint', '--item-id', '--change', '--name', '--snapshot-revision', '--summary', '--backlog-status', '--baseline-revision', '--revision', '--file'].includes(args[i])) {
35
+ i++;
36
+ continue;
37
+ }
38
+ if (!args[i].startsWith('--'))
39
+ positional.push(args[i]);
40
+ }
41
+ const rootOption = args.find(arg => arg.startsWith('--workspace=') || arg.startsWith('--root='));
42
+ const explicitRoot = rootOption?.slice(rootOption.indexOf('=') + 1) ?? (args.includes('--workspace') ? args[args.indexOf('--workspace') + 1] : args.includes('--root') ? args[args.indexOf('--root') + 1] : undefined);
43
+ const workspace = () => findWorkspace(process.cwd(), explicitRoot);
44
+ const optionValue = (name) => { const eq = args.find(arg => arg.startsWith(`${name}=`)); return eq ? eq.slice(name.length + 1) : args.includes(name) ? args[args.indexOf(name) + 1] : undefined; };
45
+ const command = args.includes('--version') ? 'version' : positional[0] ?? 'help';
46
+ const envelope = (ok, data = null, error = null, warnings = []) => ({ protocolVersion: 1, command, ok, data, error, warnings });
47
+ function print(data, human) { console.log(json ? JSON.stringify(envelope(true, data)) : human ?? JSON.stringify(data, null, 2)); }
48
+ function fail(code, message, recovery, exitCode) {
49
+ if (json)
50
+ console.log(JSON.stringify(envelope(false, null, { code, message, recovery }, [])));
51
+ else
52
+ console.error(`${code}: ${message}\nRecovery: ${recovery}`);
53
+ process.exitCode = exitCode;
54
+ throw new Error('handled');
55
+ }
56
+ const usage = 'Usage: notchlet init [path] [--local|--interactive] | auth login|status|logout [--server https://host] [--allow-file-token-store] | profile use --server https://host | workspace bind --server <origin> --product-id <id> --repository-id <id> [--rebind] | client init|update opencode|claude [--apply] | doctor | backlog import <item-id> --product-id <id> | sync mode auto|manual | sync status|push|pull|resolve --change <id> [--yes] [--keep-local] | checkpoint --change <id> --name <name> [--summary <text>] [--backlog-status TODO|IN_PROGRESS|IN_REVIEW|DONE] | evidence record --change <id> --file <json-path> | change new <name> [--quick] | change list | change show <id> | change convert <id> --schema quick|standard | change close <id> --preview | change close <id> --baseline-revision <n> | status [change] | validate <change> | instructions <change> [--action plan|revise|implement|verify|resume] | task start <task-id> --change <id> --revision <n> | task complete <task-id> --change <id> --revision <n> | task update <change> <task> <status> <revision> | --version';
57
+ function deriveStatus(state) {
58
+ return `Tasks: ${state.execution.completed}/${state.execution.total} completed${state.execution.inProgress ? `, ${state.execution.inProgress} in progress` : ''}. Planning: ${state.planning.status}; verification: ${state.verification.status}; local closure: ${state.localClosure.status}; remote delivery: ${state.remoteDelivery.status}. Completion does not imply verification or delivery.`;
59
+ }
60
+ async function syncIfAutomatic(root, changeId) {
61
+ let mode;
62
+ try {
63
+ const workspace = JSON.parse(await readFile(path.join(root, '.notchlet', 'workspace.json'), 'utf8'));
64
+ mode = workspace.preferences?.syncMode === 'auto' ? 'auto' : 'manual';
65
+ }
66
+ catch (error) {
67
+ if (error.code === 'ENOENT')
68
+ mode = 'manual';
69
+ else
70
+ throw error;
71
+ }
72
+ if (mode !== 'auto')
73
+ return null;
74
+ const { autoSyncChange } = await import('./integration.js');
75
+ return autoSyncChange(root, changeId, { server: optionValue('--server'), endpoint: optionValue('--endpoint') });
76
+ }
77
+ function printWithSync(result, automaticSync, human) {
78
+ if (!automaticSync)
79
+ return print(result, human);
80
+ const syncState = automaticSync?.state ?? 'pending';
81
+ print({ result, automaticSync }, `${human ?? JSON.stringify(result, null, 2)}\nAutomatic sync: ${syncState}`);
82
+ }
83
+ const EVIDENCE_INPUT_LIMIT_BYTES = 32 * 1024;
84
+ function parseEvidenceWriteInput(value) {
85
+ if (!value || typeof value !== 'object' || Array.isArray(value))
86
+ throw new Error('Evidence input must be a JSON object.');
87
+ const record = value;
88
+ const allowed = new Set(['kind', 'outcome', 'summary', 'command', 'requirementIds', 'taskIds', 'checkIds', 'provenance']);
89
+ const unsupported = Object.keys(record).find(key => !allowed.has(key));
90
+ if (unsupported)
91
+ throw new Error(`Unsupported evidence field: ${unsupported}.`);
92
+ if (!['check', 'note', 'artifact'].includes(String(record.kind)))
93
+ throw new Error('Evidence kind must be check, note, or artifact.');
94
+ if (!['passed', 'failed', 'informational'].includes(String(record.outcome)))
95
+ throw new Error('Evidence outcome must be passed, failed, or informational.');
96
+ if (typeof record.summary !== 'string' || !record.summary.trim())
97
+ throw new Error('Evidence summary must be a non-empty string.');
98
+ if (!Array.isArray(record.requirementIds) || !record.requirementIds.every(item => typeof item === 'string'))
99
+ throw new Error('Evidence requirementIds must be an array of strings.');
100
+ if (!Array.isArray(record.taskIds) || !record.taskIds.every(item => typeof item === 'string'))
101
+ throw new Error('Evidence taskIds must be an array of strings.');
102
+ if (record.checkIds !== undefined && (!Array.isArray(record.checkIds) || !record.checkIds.every(item => typeof item === 'string')))
103
+ throw new Error('Evidence checkIds must be an array of strings.');
104
+ if (record.command !== undefined && typeof record.command !== 'string')
105
+ throw new Error('Evidence command must be a descriptive string.');
106
+ if (record.provenance !== 'recorded' && record.provenance !== 'imported')
107
+ throw new Error('Evidence provenance must be recorded or imported.');
108
+ return record;
109
+ }
110
+ async function artifactContents(root, id, change) {
111
+ const result = {};
112
+ for (const relative of Object.values(change.artifacts)) {
113
+ try {
114
+ result[relative] = await readFile(path.join(root, '.notchlet', 'changes', id, relative), 'utf8');
115
+ }
116
+ catch (error) {
117
+ if (error.code !== 'ENOENT')
118
+ throw error;
119
+ }
120
+ }
121
+ return result;
122
+ }
123
+ try {
124
+ if (command === 'help' || args.includes('--help') || args.includes('-h')) {
125
+ print({ usage }, usage);
126
+ }
127
+ else if (args.includes('--version') || command === 'version') {
128
+ print({ version: '0.1.0', coreVersion: CORE_VERSION }, `notchlet 0.1.0 · @notchlet/core ${CORE_VERSION}`);
129
+ }
130
+ else if (command === 'auth') {
131
+ const action = positional[1];
132
+ if (!['login', 'status', 'logout'].includes(action ?? ''))
133
+ fail('usage_error', usage, 'Run `notchlet --help` for command syntax.', 64);
134
+ const { authCommand } = await import('./auth.js');
135
+ const result = await authCommand(action, { server: optionValue('--server'), allowFileStore: args.includes('--allow-file-token-store'), json });
136
+ print(result);
137
+ }
138
+ else if (command === 'profile' && positional[1] === 'use') {
139
+ const origin = optionValue('--server');
140
+ if (!origin)
141
+ fail('usage_error', usage, 'Select a server with `--server https://host`.', 64);
142
+ const { selectProfile } = await import('./auth.js');
143
+ const profile = await selectProfile(origin);
144
+ if (!profile)
145
+ fail('profile_not_found', 'No profile exists for this server.', 'Run `notchlet auth login --server https://host` first.', 2);
146
+ print({ profile, current: true });
147
+ }
148
+ else if (command === 'workspace' && ['bind', 'rebind'].includes(positional[1] ?? '')) {
149
+ const root = await workspace();
150
+ if (!root)
151
+ fail('setup_required', 'No initialized Notchlet workspace was found.', 'Run `notchlet init` in the Git checkout root.', 2);
152
+ const server = optionValue('--server'), productId = Number(optionValue('--product-id')), repositoryId = Number(optionValue('--repository-id'));
153
+ if (!server || !Number.isSafeInteger(productId) || !Number.isSafeInteger(repositoryId))
154
+ fail('usage_error', usage, 'Provide --server, --product-id, and --repository-id.', 64);
155
+ const { bindWorkspace } = await import('./integration.js');
156
+ const result = await bindWorkspace(root, { server, productId, repositoryId, endpoint: optionValue('--endpoint'), rebind: positional[1] === 'rebind' || args.includes('--rebind') });
157
+ print(result);
158
+ }
159
+ else if (command === 'doctor') {
160
+ const root = await workspace();
161
+ const { doctor } = await import('./integration.js');
162
+ const result = await doctor(root, { server: optionValue('--server'), endpoint: optionValue('--endpoint'), allowFileStore: args.includes('--allow-file-token-store') });
163
+ print(result, `Notchlet doctor: ${result.diagnostic}\nServer: ${result.profile?.origin ?? 'not selected'}\nBackend: ${result.online ? 'reachable' : 'offline'}\nGit: ${result.git.isRepository ? result.git.repository.topLevel : result.git.reason}\nBinding: ${result.binding ? 'configured' : 'none'}`);
164
+ }
165
+ else if (command === 'sync' && positional[1] === 'mode') {
166
+ const root = await workspace();
167
+ if (!root)
168
+ fail('setup_required', 'No initialized Notchlet workspace was found.', 'Run `notchlet init` first.', 2);
169
+ const mode = positional[2];
170
+ if (mode !== 'auto' && mode !== 'manual')
171
+ fail('usage_error', usage, 'Choose `notchlet sync mode auto` or `notchlet sync mode manual`.', 64);
172
+ const { setWorkspaceSyncMode } = await import('./integration.js');
173
+ print({ ...(await setWorkspaceSyncMode(root, mode)), workspace: root });
174
+ }
175
+ else if (command === 'sync') {
176
+ const root = await workspace();
177
+ if (!root)
178
+ fail('setup_required', 'No initialized Notchlet workspace was found.', 'Run `notchlet init` and bind it with `notchlet workspace bind`.', 2);
179
+ const action = positional[1], id = optionValue('--change');
180
+ if (!['status', 'push', 'pull', 'resolve'].includes(action ?? '') || !id || (action === 'resolve' && !args.includes('--keep-local')))
181
+ fail('usage_error', usage, 'Use `notchlet sync resolve --change <id> --keep-local` after reviewing the conflict.', 64);
182
+ const { syncStatus, syncPush, syncPull, syncResolve } = await import('./integration.js');
183
+ const syncOptions = { server: optionValue('--server'), endpoint: optionValue('--endpoint'), yes: args.includes('--yes') };
184
+ if (action === 'status') {
185
+ const automaticSync = await syncIfAutomatic(root, id);
186
+ const result = await syncStatus(root, id, syncOptions);
187
+ print({ ...result, ...(automaticSync ? { automaticSync } : {}) }, JSON.stringify({ ...result, ...(automaticSync ? { automaticSync } : {}) }, null, 2));
188
+ }
189
+ else {
190
+ const result = action === 'push' ? await syncPush(root, id, syncOptions) : action === 'pull' ? await syncPull(root, id, syncOptions) : await syncResolve(root, id, 'keep-local', syncOptions);
191
+ print(result, JSON.stringify(result, null, 2));
192
+ }
193
+ }
194
+ else if (command === 'client') {
195
+ const root = await workspace();
196
+ if (!root)
197
+ fail('setup_required', 'No initialized Notchlet workspace was found.', 'Run `notchlet init` in the checkout before installing client guidance.', 2);
198
+ const action = positional[1], client = positional[2];
199
+ if (!['init', 'update'].includes(action ?? '') || !['opencode', 'claude'].includes(client ?? ''))
200
+ fail('usage_error', usage, 'Use `notchlet client init|update opencode|claude [--apply]`.', 64);
201
+ const { installClientGuidance } = await import('./guidance-install.js');
202
+ const result = await installClientGuidance(root, client, { apply: args.includes('--apply') });
203
+ print(result, `Client guidance ${result.applied ? 'installed/updated' : 'preview'}: ${result.client} ${result.action} ${result.target}`);
204
+ }
205
+ else if (command === 'checkpoint') {
206
+ const root = await workspace();
207
+ if (!root)
208
+ fail('setup_required', 'No initialized Notchlet workspace was found.', 'Run `notchlet init` and bind it with `notchlet workspace bind`.', 2);
209
+ const id = optionValue('--change'), name = optionValue('--name'), backlogStatus = optionValue('--backlog-status');
210
+ if (!id || !name || (backlogStatus !== undefined && !['TODO', 'IN_PROGRESS', 'IN_REVIEW', 'DONE'].includes(backlogStatus)))
211
+ fail('usage_error', usage, 'Provide --change, --name, and an optional supported --backlog-status.', 64);
212
+ const { syncCheckpoint } = await import('./integration.js');
213
+ const result = await syncCheckpoint(root, id, { name, ...(optionValue('--summary') === undefined ? {} : { summary: optionValue('--summary') }), ...(backlogStatus === undefined ? {} : { backlogStatus: backlogStatus }) }, { server: optionValue('--server'), endpoint: optionValue('--endpoint') });
214
+ print(result, JSON.stringify(result, null, 2));
215
+ }
216
+ else if (command === 'evidence' && positional[1] === 'record') {
217
+ const root = await workspace();
218
+ if (!root)
219
+ fail('setup_required', 'No initialized Notchlet workspace was found.', 'Run `notchlet init` in the project root.', 2);
220
+ const id = optionValue('--change'), file = optionValue('--file');
221
+ if (!id || !file)
222
+ fail('usage_error', usage, 'Provide --change and --file for evidence record.', 64);
223
+ const source = await readFile(path.resolve(process.cwd(), file), 'utf8');
224
+ if (Buffer.byteLength(source, 'utf8') > EVIDENCE_INPUT_LIMIT_BYTES)
225
+ fail('payload_too_large', 'Evidence input exceeds 32 KiB.', 'Split the evidence into smaller records and try again.', 5);
226
+ let value;
227
+ try {
228
+ value = JSON.parse(source);
229
+ }
230
+ catch {
231
+ fail('invalid_input', 'Evidence input is not valid JSON.', 'Correct the JSON file and try again.', 2);
232
+ }
233
+ const evidence = await appendEvidence(root, id, parseEvidenceWriteInput(value));
234
+ printWithSync(evidence, await syncIfAutomatic(root, id), `Recorded ${evidence.kind} evidence ${evidence.id} for ${id}.`);
235
+ }
236
+ else if (command === 'backlog' && positional[1] === 'import') {
237
+ const root = await workspace();
238
+ if (!root)
239
+ fail('setup_required', 'No initialized Notchlet workspace was found.', 'Run `notchlet init` in the project root.', 2);
240
+ const itemId = Number(positional[2]), productId = Number(optionValue('--product-id'));
241
+ if (!Number.isSafeInteger(itemId) || !Number.isSafeInteger(productId))
242
+ fail('usage_error', usage, 'Provide numeric item ID and --product-id.', 64);
243
+ const { importBacklogItem } = await import('./integration.js');
244
+ const change = await importBacklogItem(root, { itemId, productId, server: optionValue('--server'), endpoint: optionValue('--endpoint'), allowFileStore: args.includes('--allow-file-token-store') });
245
+ printWithSync({ change }, await syncIfAutomatic(root, change.id));
246
+ }
247
+ else if (command === 'init') {
248
+ const root = path.resolve(positional[1] ?? explicitRoot ?? process.cwd());
249
+ if (args.includes('--interactive') && json)
250
+ fail('usage_error', usage, 'Interactive setup cannot be combined with --json.', 64);
251
+ const interactive = args.includes('--interactive') || (!args.includes('--local') && !json && Boolean(process.stdin.isTTY && process.stderr.isTTY));
252
+ if (interactive) {
253
+ const { interactiveInit } = await import('./setup.js');
254
+ print(await interactiveInit(root));
255
+ }
256
+ else {
257
+ await initWorkspace(root);
258
+ print({ root, initialized: true, mode: 'local' });
259
+ }
260
+ }
261
+ else if (command === 'change') {
262
+ const action = positional[1];
263
+ if (action === 'new') {
264
+ if (!positional[2])
265
+ fail('usage_error', usage, 'Run `notchlet --help` for command syntax.', 64);
266
+ const root = await workspace();
267
+ if (!root)
268
+ fail('setup_required', 'No initialized Notchlet workspace was found.', 'Run `notchlet init` in the project root.', 2);
269
+ const change = await scaffold(root, positional[2], args.includes('--quick') ? 'quick' : 'standard');
270
+ printWithSync(change, await syncIfAutomatic(root, change.id));
271
+ }
272
+ else if (action === 'list') {
273
+ const root = await workspace();
274
+ print({ workspace: root, changes: root ? await listChanges(root) : [] }, root ? undefined : 'No Notchlet workspace found.');
275
+ }
276
+ else if (action === 'show') {
277
+ const root = await workspace();
278
+ if (!root)
279
+ fail('setup_required', 'No initialized Notchlet workspace was found.', 'Run `notchlet init` in the project root or select one with --workspace.', 2);
280
+ const id = positional[2];
281
+ if (!id)
282
+ fail('usage_error', usage, 'Provide a change ID from `notchlet change list`.', 64);
283
+ const change = await readChange(root, id);
284
+ const result = { change, readiness: readiness(change, await artifactContents(root, id, change)) };
285
+ printWithSync(result, await syncIfAutomatic(root, id));
286
+ }
287
+ else if (action === 'convert') {
288
+ const root = await workspace();
289
+ if (!root)
290
+ fail('setup_required', 'No initialized Notchlet workspace was found.', 'Run `notchlet init` in the project root or select one with --workspace.', 2);
291
+ const id = positional[2];
292
+ const schema = optionValue('--schema');
293
+ if (!id || (schema !== 'quick' && schema !== 'standard'))
294
+ fail('usage_error', usage, 'Use `--schema quick` or `--schema standard`.', 64);
295
+ const change = await persistConversion(root, id, schema);
296
+ const result = { change, readiness: readiness(change, await artifactContents(root, id, change)) };
297
+ printWithSync(result, await syncIfAutomatic(root, id));
298
+ }
299
+ else if (action === 'close') {
300
+ const root = await workspace();
301
+ if (!root)
302
+ fail('setup_required', 'No initialized Notchlet workspace was found.', 'Run `notchlet init` first.', 2);
303
+ const id = positional[2];
304
+ if (!id)
305
+ fail('usage_error', usage, 'Provide a change ID.', 64);
306
+ if (args.includes('--preview'))
307
+ print(await previewCapabilityClose(root, id), 'Capability closure preview. No files were changed.');
308
+ else {
309
+ const revision = Number(optionValue('--baseline-revision'));
310
+ if (!Number.isInteger(revision) || revision < 0)
311
+ fail('usage_error', usage, 'Provide --baseline-revision from the capability preview.', 64);
312
+ print(await closeChange(root, id, { expectedBaselineRevision: revision }), `Closed and archived ${id}.`);
313
+ }
314
+ }
315
+ else
316
+ fail('usage_error', usage, 'Run `notchlet --help` for command syntax.', 64);
317
+ }
318
+ else if (command === 'task') {
319
+ const root = await workspace();
320
+ if (!root)
321
+ fail('setup_required', 'No initialized Notchlet workspace was found.', 'Run `notchlet init` in the project root.', 2);
322
+ const action = positional[1];
323
+ let id, taskId, status, revisionText;
324
+ if (action === 'start' || action === 'complete') {
325
+ taskId = positional[2];
326
+ id = optionValue('--change');
327
+ status = action === 'start' ? 'in_progress' : 'completed';
328
+ revisionText = optionValue('--revision');
329
+ }
330
+ else if (action === 'update') {
331
+ [, , id, taskId, status, revisionText] = positional;
332
+ }
333
+ if (!id || !taskId || !['pending', 'in_progress', 'completed'].includes(status ?? '') || !revisionText || !Number.isInteger(Number(revisionText)))
334
+ fail('usage_error', usage, 'Use task start|complete <task-id> --change <id> --revision <n>, or task update <change> <task> <status> <revision>.', 64);
335
+ const change = await transitionTask(path.join(root, '.notchlet', 'changes', id, 'tasks.json'), taskId, status, Number(revisionText));
336
+ printWithSync(change, await syncIfAutomatic(root, id));
337
+ }
338
+ else if (['status', 'validate', 'instructions'].includes(command)) {
339
+ const root = await profileAsync('workspaceResolution', workspace);
340
+ if (!root) {
341
+ if (command === 'validate')
342
+ fail('setup_required', 'No initialized Notchlet workspace was found.', 'Run `notchlet init` in the project root.', 2);
343
+ print({ coreVersion: CORE_VERSION, workspace: null, changes: [] }, `No Notchlet workspace found. Core engine ${CORE_VERSION}.`);
344
+ }
345
+ else {
346
+ const id = positional[1];
347
+ if (!id) {
348
+ if (command !== 'status')
349
+ fail('usage_error', usage, `Provide a change ID for ${command}.`, 64);
350
+ const changes = await listChanges(root);
351
+ print({ protocolVersion: 1, coreVersion: CORE_VERSION, workspace: root, changes }, changes.length ? undefined : `No changes found. Core engine ${CORE_VERSION}.`);
352
+ }
353
+ else {
354
+ if (positional.length !== 2)
355
+ fail('usage_error', usage, 'Provide exactly one change ID.', 64);
356
+ const change = await profileAsync('changeReadAndParse', () => readChange(root, id));
357
+ const automaticSync = await profileAsync('automaticSyncModeCheck', () => syncIfAutomatic(root, id));
358
+ const contents = await profileAsync('artifactReads', () => artifactContents(root, id, change));
359
+ if (command === 'status') {
360
+ const state = profileSync('evaluateState', () => evaluateState(change, undefined, contents));
361
+ const derivedState = profileSync('deriveState', () => deriveStatus(evaluateState(change)));
362
+ const readinessState = profileSync('readinessProjection', () => ({ ready: state.planning.status === 'ready', blockers: state.planning.blockers.map(({ source: _source, ...issue }) => issue) }));
363
+ profileSync('serializeAndWrite', () => printWithSync({ protocolVersion: 1, coreVersion: CORE_VERSION, change: change.id, revision: change.revision ?? 0, state: derivedState, facets: state, readiness: readinessState }, automaticSync, `${change.name}: ${derivedState}\nCore engine: ${CORE_VERSION}\nEligible tasks: ${state.eligibleTasks.join(', ') || 'none'}\nBlockers: ${state.blockers.length}`));
364
+ if (profiling)
365
+ process.stderr.write(`NOTCHLET_PROFILE ${JSON.stringify(profileTimings)}\n`);
366
+ }
367
+ else if (command === 'instructions') {
368
+ const action = optionValue('--action') ?? 'resume';
369
+ if (!['plan', 'revise', 'implement', 'verify', 'resume'].includes(action))
370
+ fail('usage_error', usage, 'Choose a documented action: plan, revise, implement, verify, or resume.', 64);
371
+ const text = instructions(change, action);
372
+ printWithSync({ protocolVersion: 1, coreVersion: CORE_VERSION, action, instructions: text }, automaticSync, `Core engine: ${CORE_VERSION}\n${text}`);
373
+ }
374
+ else {
375
+ const result = readiness(change, contents);
376
+ const data = automaticSync ? { readiness: result, automaticSync } : result;
377
+ if (json)
378
+ console.log(JSON.stringify(envelope(result.ready, data, result.ready ? null : { code: 'validation_failed', message: 'Change is not ready.', recovery: 'Resolve the listed blockers and validate again.' }, [])));
379
+ else
380
+ printWithSync(result, automaticSync, result.ready ? 'Change is ready.' : `Change has ${result.blockers.length} readiness blocker(s).`);
381
+ if (!result.ready)
382
+ process.exitCode = 1;
383
+ }
384
+ }
385
+ }
386
+ }
387
+ else
388
+ fail('unknown_command', usage, 'Run `notchlet --help` for available commands.', 64);
389
+ }
390
+ catch (error) {
391
+ if (error instanceof Error && error.message === 'handled') { /* stable error already printed */ }
392
+ else {
393
+ const known = error instanceof WorkflowError ? error : null;
394
+ const code = known?.code ?? 'operation_failed';
395
+ const message = error instanceof Error ? error.message : String(error);
396
+ const recovery = known?.recovery ?? 'Inspect the workspace and retry; existing files were not intentionally overwritten.';
397
+ if (json)
398
+ console.log(JSON.stringify(envelope(false, null, { code, message, recovery }, [])));
399
+ else
400
+ console.error(`${code}: ${message}\nRecovery: ${recovery}`);
401
+ process.exitCode = code === 'change_exists' ? 3 : 1;
402
+ }
403
+ }
@@ -0,0 +1,88 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { lstat, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ const hash = (value) => createHash('sha256').update(value).digest('hex');
6
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
7
+ const targetFor = (client) => client === 'opencode'
8
+ ? '.opencode/skills/notchlet-super/SKILL.md'
9
+ : '.claude/skills/notchlet-super/SKILL.md';
10
+ async function lstatOrNull(file) {
11
+ try {
12
+ return await lstat(file);
13
+ }
14
+ catch (error) {
15
+ if (error.code === 'ENOENT')
16
+ return null;
17
+ throw error;
18
+ }
19
+ }
20
+ async function assertSafeParents(root, relative) {
21
+ let current = root;
22
+ for (const segment of path.dirname(relative).split(path.sep).filter(Boolean)) {
23
+ current = path.join(current, segment);
24
+ const stat = await lstatOrNull(current);
25
+ if (stat?.isSymbolicLink() || (stat && !stat.isDirectory()))
26
+ throw new Error(`Guidance target traverses a non-directory or symlink: ${relative}`);
27
+ }
28
+ const target = await lstatOrNull(path.join(root, relative));
29
+ if (target?.isSymbolicLink() || (target && !target.isFile()))
30
+ throw new Error(`Guidance target is not a regular file: ${relative}`);
31
+ return target;
32
+ }
33
+ async function readManifest(file) {
34
+ const stat = await lstatOrNull(file);
35
+ if (!stat)
36
+ return { manifestVersion: 1, clients: {} };
37
+ if (stat.isSymbolicLink() || !stat.isFile())
38
+ throw new Error('Client guidance manifest is not a regular file.');
39
+ const parsed = JSON.parse(await readFile(file, 'utf8'));
40
+ if (parsed?.manifestVersion !== 1 || !parsed.clients || typeof parsed.clients !== 'object' || Array.isArray(parsed.clients))
41
+ throw new Error('Client guidance manifest is invalid; preserve it and reconcile manually.');
42
+ return parsed;
43
+ }
44
+ async function atomicWrite(file, contents) {
45
+ await mkdir(path.dirname(file), { recursive: true });
46
+ const temporary = `${file}.${randomUUID()}.tmp`;
47
+ await writeFile(temporary, contents, { flag: 'wx' });
48
+ await rename(temporary, file).catch(async (error) => { await rm(temporary, { force: true }); throw error; });
49
+ }
50
+ /** Preview/apply one managed skill file without touching unrelated client configuration. */
51
+ export async function installClientGuidance(rootInput, client, options = {}) {
52
+ if (!['opencode', 'claude'].includes(client))
53
+ throw new Error('Client must be opencode or claude.');
54
+ const root = path.resolve(rootInput), target = targetFor(client);
55
+ const generated = path.join(packageRoot, 'guidance', 'generated', client === 'claude' ? 'claude-code' : 'opencode', 'notchlet-super', 'SKILL.md');
56
+ const source = await readFile(generated, 'utf8'), sourceHash = hash(source);
57
+ const manifestRelative = path.join('.notchlet', '.local', 'client-guidance.json');
58
+ await assertSafeParents(root, manifestRelative);
59
+ const manifestPath = path.join(root, manifestRelative);
60
+ const manifest = await readManifest(manifestPath);
61
+ const previous = manifest.clients[client];
62
+ const currentStat = await assertSafeParents(root, target);
63
+ const current = currentStat ? await readFile(path.join(root, target), 'utf8') : null;
64
+ const currentHash = current === null ? null : hash(current);
65
+ let action;
66
+ let reason;
67
+ if (current === null)
68
+ action = 'install';
69
+ else if (!previous || previous.target !== target) {
70
+ action = 'conflict';
71
+ reason = 'An unmanaged file already exists at the target path.';
72
+ }
73
+ else if (currentHash !== previous.installedHash) {
74
+ action = 'conflict';
75
+ reason = 'The managed guidance file was modified locally; local content is preserved.';
76
+ }
77
+ else if (currentHash === sourceHash)
78
+ action = 'unchanged';
79
+ else
80
+ action = 'update';
81
+ const result = { client, target, action, sourceHash, ...(reason ? { reason } : {}), applied: false };
82
+ if (!options.apply || action === 'conflict' || action === 'unchanged')
83
+ return result;
84
+ await atomicWrite(path.join(root, target), source);
85
+ manifest.clients[client] = { target, sourceHash, installedHash: sourceHash, sourceVersion: JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8')).version };
86
+ await atomicWrite(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
87
+ return { ...result, applied: true };
88
+ }