@notchlet/cli 0.0.0-stage → 0.2.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 (29) hide show
  1. package/dist/auth.js +380 -0
  2. package/dist/cli-format.js +46 -0
  3. package/dist/cli-prompt.js +73 -0
  4. package/dist/cli.js +1040 -0
  5. package/dist/guidance-install.js +111 -0
  6. package/dist/integration.js +806 -0
  7. package/dist/setup.js +92 -0
  8. package/guidance/aliases.json +27 -0
  9. package/guidance/generated/claude-code/notchlet-deliver/SKILL.md +94 -0
  10. package/guidance/generated/claude-code/notchlet-implement/SKILL.md +94 -0
  11. package/guidance/generated/claude-code/notchlet-init/SKILL.md +30 -0
  12. package/guidance/generated/claude-code/notchlet-mcp/SKILL.md +60 -0
  13. package/guidance/generated/claude-code/notchlet-plan/SKILL.md +100 -0
  14. package/guidance/generated/claude-code/notchlet-platform/SKILL.md +85 -0
  15. package/guidance/generated/claude-code/notchlet-review/SKILL.md +68 -0
  16. package/guidance/generated/claude-code/notchlet-super/SKILL.md +47 -0
  17. package/guidance/generated/compatibility.json +94 -0
  18. package/guidance/generated/manifest.json +140 -0
  19. package/guidance/generated/opencode/notchlet-deliver/SKILL.md +94 -0
  20. package/guidance/generated/opencode/notchlet-implement/SKILL.md +94 -0
  21. package/guidance/generated/opencode/notchlet-init/SKILL.md +30 -0
  22. package/guidance/generated/opencode/notchlet-mcp/SKILL.md +60 -0
  23. package/guidance/generated/opencode/notchlet-plan/SKILL.md +100 -0
  24. package/guidance/generated/opencode/notchlet-platform/SKILL.md +85 -0
  25. package/guidance/generated/opencode/notchlet-review/SKILL.md +68 -0
  26. package/guidance/generated/opencode/notchlet-super/SKILL.md +47 -0
  27. package/package.json +1 -6
  28. package/scripts/generate-guidance.mjs +115 -0
  29. package/README.md +0 -3
package/dist/cli.js ADDED
@@ -0,0 +1,1040 @@
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
+ import { section, kv, bullet, ok, err, warn, table, box, divider } from './cli-format.js';
6
+ import { isTty, prompt, confirm, requiredString, requiredNumber } from './cli-prompt.js';
7
+ const args = process.argv.slice(2);
8
+ const profiling = process.env.NOTCHLET_PROFILE === '1';
9
+ const profileTimings = {};
10
+ const profileNow = () => Number(process.hrtime.bigint()) / 1e6;
11
+ function profileSync(name, operation) {
12
+ if (!profiling)
13
+ return operation();
14
+ const start = profileNow();
15
+ try {
16
+ return operation();
17
+ }
18
+ finally {
19
+ profileTimings[name] = (profileTimings[name] ?? 0) + profileNow() - start;
20
+ }
21
+ }
22
+ async function profileAsync(name, operation) {
23
+ if (!profiling)
24
+ return operation();
25
+ const start = profileNow();
26
+ try {
27
+ return await operation();
28
+ }
29
+ finally {
30
+ profileTimings[name] = (profileTimings[name] ?? 0) + profileNow() - start;
31
+ }
32
+ }
33
+ const json = args.includes('--json');
34
+ const positional = [];
35
+ for (let i = 0; i < args.length; i++) {
36
+ 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])) {
37
+ i++;
38
+ continue;
39
+ }
40
+ if (!args[i].startsWith('--'))
41
+ positional.push(args[i]);
42
+ }
43
+ const rootOption = args.find(arg => arg.startsWith('--workspace=') || arg.startsWith('--root='));
44
+ const explicitRoot = rootOption?.slice(rootOption.indexOf('=') + 1) ?? (args.includes('--workspace') ? args[args.indexOf('--workspace') + 1] : args.includes('--root') ? args[args.indexOf('--root') + 1] : undefined);
45
+ const workspace = () => findWorkspace(process.cwd(), explicitRoot);
46
+ const DEFAULT_SERVER = 'https://pg-api.mbintangr.com';
47
+ 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; };
48
+ const serverOption = () => optionValue('--server') ?? DEFAULT_SERVER;
49
+ const command = args.includes('--version') ? 'version' : positional[0] ?? 'help';
50
+ const envelope = (ok, data = null, error = null, warnings = []) => ({ protocolVersion: 1, command, ok, data, error, warnings });
51
+ function print(data, human) { console.log(json ? JSON.stringify(envelope(true, data)) : human ?? JSON.stringify(data, null, 2)); }
52
+ function showCommandHelp(name, text) {
53
+ if (json) {
54
+ print({ usage: text }, text);
55
+ }
56
+ else {
57
+ console.log(text);
58
+ }
59
+ process.exitCode = 0;
60
+ throw new Error('handled');
61
+ }
62
+ function fail(code, message, recovery, exitCode) {
63
+ if (json)
64
+ console.log(JSON.stringify(envelope(false, null, { code, message, recovery }, [])));
65
+ else
66
+ console.error(`${err(`${code}: ${message}`)}\nRecovery: ${recovery}`);
67
+ process.exitCode = exitCode;
68
+ throw new Error('handled');
69
+ }
70
+ const usage = `Usage: notchlet <command> [options]
71
+
72
+ ${section('Setup')}
73
+ init [path] [--local|--interactive] Initialize a Notchlet workspace (local-only by default)
74
+
75
+ ${section('Auth')}
76
+ auth login [--server <url>] [--allow-file-token-store] Log in to a Notchlet server
77
+ auth status Show current auth profile
78
+ auth logout [--server <url>] Log out of a server
79
+ profile use --server <url> Select the current server profile
80
+
81
+ ${section('Workspace')}
82
+ workspace bind --server <url> --product-id <id> --repository-id <id> [--rebind] Bind checkout to a product/repository
83
+ workspace info Show workspace binding and config
84
+ doctor Diagnose workspace, binding, and server connectivity
85
+
86
+ ${section('Sync')}
87
+ sync mode auto|manual Set automatic sync preference
88
+ sync status|push|pull|resolve --change <id> [--yes] [--keep-local] Sync a change with the remote
89
+
90
+ ${section('Changes')}
91
+ change new <name> [--quick] Create a new change
92
+ change list List all changes
93
+ change show <id> Show change details and readiness
94
+ change convert <id> --schema quick|standard Convert a change schema
95
+ change close <id> --preview | --baseline-revision <n> [--yes] Close and archive a change
96
+
97
+ ${section('Tasks')}
98
+ task start <task-id> --change <id> --revision <n> Start a task
99
+ task complete <task-id> --change <id> --revision <n> Complete a task
100
+ task update <change> <task> <status> <revision> Update a task status
101
+
102
+ ${section('Other')}
103
+ backlog import <item-id> --product-id <id> Import a backlog item as a change
104
+ checkpoint --change <id> --name <name> [--summary <text>] [--backlog-status TODO|IN_PROGRESS|IN_REVIEW|DONE] Create a remote checkpoint
105
+ evidence record --change <id> --file <json-path> Record evidence for a change
106
+ instructions <change> [--action plan|revise|implement|verify|resume] Get workflow instructions for a change
107
+ client init|update opencode|claude [--apply] Install client guidance (skills)
108
+
109
+ ${section('Global options')}
110
+ --json Machine-readable JSON output
111
+ --workspace <root> / --root <root> Set workspace root
112
+ --server <url> Notchlet server (default: ${DEFAULT_SERVER})
113
+ --version Show version
114
+ `;
115
+ function deriveStatus(state) {
116
+ 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.`;
117
+ }
118
+ async function syncIfAutomatic(root, changeId) {
119
+ let mode;
120
+ try {
121
+ const workspace = JSON.parse(await readFile(path.join(root, '.notchlet', 'workspace.json'), 'utf8'));
122
+ mode = workspace.preferences?.syncMode === 'auto' ? 'auto' : 'manual';
123
+ }
124
+ catch (error) {
125
+ if (error.code === 'ENOENT')
126
+ mode = 'manual';
127
+ else
128
+ throw error;
129
+ }
130
+ if (mode !== 'auto')
131
+ return null;
132
+ const { autoSyncChange } = await import('./integration.js');
133
+ return autoSyncChange(root, changeId, { server: optionValue('--server'), endpoint: optionValue('--endpoint') });
134
+ }
135
+ function printWithSync(result, automaticSync, human) {
136
+ const base = json ? JSON.stringify(envelope(true, result)) : human ?? JSON.stringify(result, null, 2);
137
+ if (!automaticSync) {
138
+ console.log(base);
139
+ return;
140
+ }
141
+ const syncState = automaticSync?.state ?? 'pending';
142
+ if (json) {
143
+ console.log(JSON.stringify(envelope(true, { result, automaticSync })));
144
+ }
145
+ else {
146
+ console.log(`${base}\nAutomatic sync: ${syncState}`);
147
+ }
148
+ }
149
+ const EVIDENCE_INPUT_LIMIT_BYTES = 32 * 1024;
150
+ function parseEvidenceWriteInput(value) {
151
+ if (!value || typeof value !== 'object' || Array.isArray(value))
152
+ throw new Error('Evidence input must be a JSON object.');
153
+ const record = value;
154
+ const allowed = new Set(['kind', 'outcome', 'summary', 'command', 'requirementIds', 'taskIds', 'checkIds', 'provenance']);
155
+ const unsupported = Object.keys(record).find(key => !allowed.has(key));
156
+ if (unsupported)
157
+ throw new Error(`Unsupported evidence field: ${unsupported}.`);
158
+ if (!['check', 'note', 'artifact'].includes(String(record.kind)))
159
+ throw new Error('Evidence kind must be check, note, or artifact.');
160
+ if (!['passed', 'failed', 'informational'].includes(String(record.outcome)))
161
+ throw new Error('Evidence outcome must be passed, failed, or informational.');
162
+ if (typeof record.summary !== 'string' || !record.summary.trim())
163
+ throw new Error('Evidence summary must be a non-empty string.');
164
+ if (!Array.isArray(record.requirementIds) || !record.requirementIds.every(item => typeof item === 'string'))
165
+ throw new Error('Evidence requirementIds must be an array of strings.');
166
+ if (!Array.isArray(record.taskIds) || !record.taskIds.every(item => typeof item === 'string'))
167
+ throw new Error('Evidence taskIds must be an array of strings.');
168
+ if (record.checkIds !== undefined && (!Array.isArray(record.checkIds) || !record.checkIds.every(item => typeof item === 'string')))
169
+ throw new Error('Evidence checkIds must be an array of strings.');
170
+ if (record.command !== undefined && typeof record.command !== 'string')
171
+ throw new Error('Evidence command must be a descriptive string.');
172
+ if (record.provenance !== 'recorded' && record.provenance !== 'imported')
173
+ throw new Error('Evidence provenance must be recorded or imported.');
174
+ return record;
175
+ }
176
+ async function artifactContents(root, id, change) {
177
+ const result = {};
178
+ for (const relative of Object.values(change.artifacts)) {
179
+ try {
180
+ result[relative] = await readFile(path.join(root, '.notchlet', 'changes', id, relative), 'utf8');
181
+ }
182
+ catch (error) {
183
+ if (error.code !== 'ENOENT')
184
+ throw error;
185
+ }
186
+ }
187
+ return result;
188
+ }
189
+ async function requireWorkspace(what) {
190
+ const root = await workspace();
191
+ if (!root)
192
+ fail('setup_required', `No initialized Notchlet workspace was found.`, `Run \`notchlet init\` before \`${what}\`.`, 2);
193
+ return root;
194
+ }
195
+ async function main() {
196
+ try {
197
+ // Command-specific --help is handled inside each command block below.
198
+ // Only show general help when there's no command or command is literally 'help'.
199
+ if ((command === 'help' || positional.length === 0) && (args.includes('--help') || args.includes('-h') || command === 'help')) {
200
+ print({ usage }, usage);
201
+ }
202
+ else if (args.includes('--version') || command === 'version') {
203
+ print({ version: '0.1.0', coreVersion: CORE_VERSION }, `notchlet 0.1.0 · @notchlet/core ${CORE_VERSION}`);
204
+ }
205
+ else if (command === 'auth') {
206
+ const action = positional[1];
207
+ if (args.includes('--help') || args.includes('-h')) {
208
+ showCommandHelp('auth', `notchlet auth <action> [options]
209
+
210
+ login [--server <url>] [--allow-file-token-store] Log in to a Notchlet server
211
+ status Show current auth profile
212
+ logout [--server <url>] Log out of a server
213
+
214
+ Options:
215
+ --server <url> Notchlet server (default: ${DEFAULT_SERVER})
216
+ --allow-file-token-store Allow restricted file credential storage (Windows requires this or NOTCHLET_TOKEN)
217
+ --json Machine-readable JSON output`);
218
+ }
219
+ if (!['login', 'status', 'logout'].includes(action ?? ''))
220
+ fail('usage_error', usage, 'Run `notchlet --help` for command syntax.', 64);
221
+ const { authCommand } = await import('./auth.js');
222
+ const result = await authCommand(action, { server: action === 'login' ? serverOption() : optionValue('--server'), allowFileStore: args.includes('--allow-file-token-store'), json });
223
+ if (json) {
224
+ print(result);
225
+ }
226
+ else if (action === 'login') {
227
+ const p = result.profile;
228
+ console.log(box([
229
+ section('Logged in'),
230
+ kv('Server', p.origin),
231
+ kv('Email', p.email ?? '(not provided)'),
232
+ kv('Auth mode', p.authMode ?? '(unknown)'),
233
+ kv('Credential store', result.credential.source),
234
+ kv('Credential status', result.credential.status),
235
+ ]));
236
+ }
237
+ else if (action === 'status') {
238
+ const p = result.profile;
239
+ console.log(box([
240
+ section('Auth status'),
241
+ kv('Server', p.origin),
242
+ kv('Email', p.email ?? '(not provided)'),
243
+ kv('Current profile', result.current ? 'yes' : 'no'),
244
+ kv('Auth mode', p.authMode ?? '(unknown)'),
245
+ kv('Credential source', result.credential.source),
246
+ kv('Credential status', result.credential.status),
247
+ ]));
248
+ }
249
+ else {
250
+ console.log(box([
251
+ section('Logged out'),
252
+ kv('Server', result.profile),
253
+ kv('Server logout', result.serverLogout),
254
+ kv('Credential status', result.credential.status),
255
+ ]));
256
+ }
257
+ }
258
+ else if (command === 'profile' && positional[1] === 'use') {
259
+ if (args.includes('--help') || args.includes('-h')) {
260
+ showCommandHelp('profile use', `notchlet profile use --server <url>
261
+
262
+ Select the current server profile.
263
+
264
+ Options:
265
+ --server <url> Notchlet server (default: ${DEFAULT_SERVER})
266
+ --json Machine-readable JSON output`);
267
+ }
268
+ const origin = await requiredString(serverOption(), `Notchlet server HTTPS origin [${DEFAULT_SERVER}]: `) ?? DEFAULT_SERVER;
269
+ const { selectProfile } = await import('./auth.js');
270
+ const profile = await selectProfile(origin);
271
+ if (!profile)
272
+ fail('profile_not_found', `No profile exists for ${origin}.`, `Run \`notchlet auth login --server ${origin}\` first.`, 2);
273
+ if (json) {
274
+ print({ profile, current: true });
275
+ }
276
+ else {
277
+ console.log(box([
278
+ section('Profile selected'),
279
+ kv('Server', profile.origin),
280
+ kv('Auth mode', profile.authMode ?? '(unknown)'),
281
+ kv('Current', 'yes'),
282
+ ]));
283
+ }
284
+ }
285
+ else if (command === 'workspace' && ['bind', 'rebind'].includes(positional[1] ?? '')) {
286
+ if (args.includes('--help') || args.includes('-h')) {
287
+ showCommandHelp('workspace bind', `notchlet workspace bind --server <url> --product-id <id> --repository-id <id> [--rebind]
288
+
289
+ Bind a Git checkout to a Notchlet product and repository.
290
+
291
+ Options:
292
+ --server <url> Notchlet server (default: ${DEFAULT_SERVER})
293
+ --product-id <id> Product ID (numeric)
294
+ --repository-id <id> Repository ID (numeric)
295
+ --rebind Confirm rebinding if the workspace is already bound
296
+ --endpoint <url> Override MCP endpoint
297
+ --allow-file-token-store Allow restricted file credential storage
298
+ --json Machine-readable JSON output`);
299
+ }
300
+ const root = await requireWorkspace('workspace bind');
301
+ const server = await requiredString(serverOption(), `Notchlet server HTTPS origin [${DEFAULT_SERVER}]: `) ?? DEFAULT_SERVER;
302
+ const productId = await requiredNumber(optionValue('--product-id'), 'Product ID: ');
303
+ const repositoryId = await requiredNumber(optionValue('--repository-id'), 'Repository ID: ');
304
+ if (!Number.isSafeInteger(productId) || !Number.isSafeInteger(repositoryId))
305
+ fail('usage_error', usage, 'Provide numeric --product-id and --repository-id.', 64);
306
+ const { bindWorkspace } = await import('./integration.js');
307
+ const result = await bindWorkspace(root, { server, productId: productId, repositoryId: repositoryId, endpoint: optionValue('--endpoint'), rebind: positional[1] === 'rebind' || args.includes('--rebind') });
308
+ if (json) {
309
+ print(result);
310
+ }
311
+ else {
312
+ const b = result.binding;
313
+ console.log(box([
314
+ section(result.alreadyBound ? 'Workspace already bound' : 'Workspace bound'),
315
+ kv('Server', b.server),
316
+ kv('Product ID', String(b.productId)),
317
+ kv('Repository ID', String(b.repositoryId)),
318
+ kv('Repository remote', b.repositoryRemote),
319
+ kv('Git root', b.gitRoot),
320
+ kv('Sync mode', 'manual (run `notchlet sync mode auto` to enable automatic sync)'),
321
+ ]));
322
+ }
323
+ }
324
+ else if (command === 'workspace' && positional[1] === 'info') {
325
+ if (args.includes('--help') || args.includes('-h')) {
326
+ showCommandHelp('workspace info', `notchlet workspace info
327
+
328
+ Show the current workspace binding and configuration.
329
+
330
+ Options:
331
+ --workspace <root> / --root <root> Set workspace root
332
+ --json Machine-readable JSON output`);
333
+ }
334
+ const root = await requireWorkspace('workspace info');
335
+ const workspaceFile = path.join(root, '.notchlet', 'workspace.json');
336
+ let workspaceData = {};
337
+ try {
338
+ workspaceData = JSON.parse(await readFile(workspaceFile, 'utf8'));
339
+ }
340
+ catch {
341
+ workspaceData = {};
342
+ }
343
+ if (json) {
344
+ print(workspaceData);
345
+ }
346
+ else {
347
+ const lines = [];
348
+ lines.push(section('Workspace info'));
349
+ lines.push(kv('Root', root));
350
+ lines.push(kv('Sync mode', workspaceData.preferences?.syncMode ?? 'manual'));
351
+ const b = workspaceData.binding;
352
+ if (b) {
353
+ lines.push(divider());
354
+ lines.push(section('Binding'));
355
+ lines.push(kv('Server', b.server));
356
+ lines.push(kv('Server identity', b.serverIdentity));
357
+ lines.push(kv('Product ID', String(b.productId)));
358
+ lines.push(kv('Repository ID', String(b.repositoryId)));
359
+ lines.push(kv('Repository remote', b.repositoryRemote));
360
+ lines.push(kv('Git root', b.gitRoot));
361
+ lines.push(kv('Endpoint', b.endpoint ?? '(default)'));
362
+ lines.push(kv('Core version', b.coreVersion ?? '(unknown)'));
363
+ lines.push(kv('Schema version', b.schemaVersion ?? '(unknown)'));
364
+ if (b.protocol)
365
+ lines.push(kv('Protocol', JSON.stringify(b.protocol)));
366
+ }
367
+ else {
368
+ lines.push(divider());
369
+ lines.push(section('Binding'));
370
+ lines.push(warn('Not bound. Run `notchlet workspace bind` to connect.'));
371
+ }
372
+ console.log(box(lines));
373
+ }
374
+ }
375
+ else if (command === 'doctor') {
376
+ if (args.includes('--help') || args.includes('-h')) {
377
+ showCommandHelp('doctor', `notchlet doctor [--server <url>]
378
+
379
+ Diagnose workspace, binding, git, and server connectivity.
380
+
381
+ Options:
382
+ --server <url> Notchlet server (default: ${DEFAULT_SERVER})
383
+ --endpoint <url> Override MCP endpoint
384
+ --allow-file-token-store Allow restricted file credential storage
385
+ --json Machine-readable JSON output`);
386
+ }
387
+ const root = await workspace();
388
+ const { doctor } = await import('./integration.js');
389
+ const result = await doctor(root, { server: optionValue('--server'), endpoint: optionValue('--endpoint'), allowFileStore: args.includes('--allow-file-token-store') });
390
+ if (json) {
391
+ print(result);
392
+ }
393
+ else {
394
+ const p = result.profile;
395
+ const lines = [];
396
+ lines.push(section('Notchlet doctor'));
397
+ lines.push(kv('Server', p?.origin ?? '(none)'));
398
+ lines.push(kv('Auth mode', p?.authMode ?? '(none)'));
399
+ lines.push(kv('Backend', result.online ? ok('reachable') : err('offline')));
400
+ lines.push(kv('Diagnostic', result.diagnostic));
401
+ lines.push(kv('Git', result.git.isRepository ? ok(result.git.repository.topLevel) : err(result.git.reason ?? 'not a repository')));
402
+ lines.push(kv('Binding', result.binding ? ok('configured') : err('none')));
403
+ if (result.capabilities)
404
+ lines.push(kv('Server version', result.capabilities.server?.version ?? '(unknown)'));
405
+ if (result.authScopes?.length)
406
+ lines.push(kv('Auth scopes', result.authScopes.join(', ')));
407
+ console.log(box(lines));
408
+ }
409
+ }
410
+ else if (command === 'sync' && positional[1] === 'mode') {
411
+ if (args.includes('--help') || args.includes('-h')) {
412
+ showCommandHelp('sync mode', `notchlet sync mode auto|manual
413
+
414
+ Set automatic sync preference for the workspace.
415
+
416
+ Options:
417
+ --workspace <root> / --root <root> Set workspace root
418
+ --json Machine-readable JSON output`);
419
+ }
420
+ const root = await requireWorkspace('sync mode');
421
+ const mode = positional[2] ?? (isTty() ? await prompt('Sync mode (auto|manual): ') : undefined);
422
+ if (mode !== 'auto' && mode !== 'manual')
423
+ fail('usage_error', usage, 'Choose `notchlet sync mode auto` or `notchlet sync mode manual`.', 64);
424
+ const { setWorkspaceSyncMode } = await import('./integration.js');
425
+ const result = await setWorkspaceSyncMode(root, mode);
426
+ if (json)
427
+ print({ ...result, workspace: root });
428
+ else
429
+ console.log(box([
430
+ section('Sync mode updated'),
431
+ kv('Workspace', root),
432
+ kv('Sync mode', result.syncMode),
433
+ ]));
434
+ }
435
+ else if (command === 'sync') {
436
+ if (args.includes('--help') || args.includes('-h')) {
437
+ showCommandHelp('sync', `notchlet sync <action> --change <id> [--yes] [--keep-local]
438
+
439
+ status Show sync state of a change
440
+ push Push local change to remote
441
+ pull Pull remote change to local
442
+ resolve Resolve a conflict (requires --keep-local)
443
+
444
+ Options:
445
+ --change <id> Change ID (required)
446
+ --yes Skip confirmation prompt
447
+ --keep-local Keep local changes when resolving (required for resolve)
448
+ --server <url> Notchlet server (default: ${DEFAULT_SERVER})
449
+ --endpoint <url> Override MCP endpoint
450
+ --workspace <root> Set workspace root
451
+ --json Machine-readable JSON output`);
452
+ }
453
+ const root = await requireWorkspace('sync');
454
+ const action = positional[1];
455
+ const id = optionValue('--change') ?? (isTty() ? await prompt('Change ID: ') : undefined);
456
+ if (!['status', 'push', 'pull', 'resolve'].includes(action ?? '') || !id)
457
+ fail('usage_error', usage, 'Use `notchlet sync <status|push|pull|resolve> --change <id> [--yes] [--keep-local]`.', 64);
458
+ const { syncStatus, syncPush, syncPull, syncResolve } = await import('./integration.js');
459
+ const syncOptions = { server: optionValue('--server'), endpoint: optionValue('--endpoint'), yes: args.includes('--yes') };
460
+ if (action === 'status') {
461
+ const automaticSync = await syncIfAutomatic(root, id);
462
+ const result = await syncStatus(root, id, syncOptions);
463
+ if (json) {
464
+ print({ ...result, ...(automaticSync ? { automaticSync } : {}) });
465
+ }
466
+ else {
467
+ const lines = [];
468
+ lines.push(section(`Sync status: ${id}`));
469
+ lines.push(kv('State', result.state));
470
+ lines.push(kv('Remote ID', result.remoteId ?? '(none)'));
471
+ lines.push(kv('Local hash', result.localHash));
472
+ lines.push(kv('Remote hash', result.remoteHash ?? '(none)'));
473
+ lines.push(kv('Base hash', result.baseHash ?? '(none)'));
474
+ lines.push(kv('Remote captured at', result.remoteCapturedAt ?? '(none)'));
475
+ if (automaticSync)
476
+ lines.push(kv('Automatic sync', automaticSync.state ?? 'pending'));
477
+ console.log(box(lines));
478
+ }
479
+ }
480
+ else {
481
+ const yes = args.includes('--yes');
482
+ if (!yes && action !== 'status' && isTty()) {
483
+ const confirmed = await confirm(`Are you sure you want to \`${action}\` change ${id}?`);
484
+ if (!confirmed) {
485
+ console.log(warn('Cancelled.'));
486
+ return;
487
+ }
488
+ }
489
+ const result = action === 'push' ? await syncPush(root, id, syncOptions) : action === 'pull' ? await syncPull(root, id, syncOptions) : await syncResolve(root, id, 'keep-local', syncOptions);
490
+ if (json) {
491
+ print(result);
492
+ }
493
+ else {
494
+ const lines = [];
495
+ lines.push(section(`Sync ${action}: ${id}`));
496
+ lines.push(kv('State', result.state));
497
+ lines.push(kv('Remote ID', result.remoteId ?? '(none)'));
498
+ if (result.revision !== undefined)
499
+ lines.push(kv('Revision', String(result.revision)));
500
+ if (result.hash)
501
+ lines.push(kv('Hash', result.hash));
502
+ if (result.nextAction)
503
+ lines.push(kv('Next action', result.nextAction));
504
+ if (result.conflict)
505
+ lines.push(kv('Conflict', warn(result.conflict)));
506
+ if (result.automatic)
507
+ lines.push(kv('Automatic', 'yes'));
508
+ console.log(box(lines));
509
+ }
510
+ }
511
+ }
512
+ else if (command === 'client') {
513
+ if (args.includes('--help') || args.includes('-h')) {
514
+ showCommandHelp('client', `notchlet client init|update opencode|claude [--apply]
515
+
516
+ init Install all Notchlet client guidance skills
517
+ update Update all installed Notchlet client guidance skills
518
+
519
+ Skills installed:
520
+ notchlet-mcp, notchlet-platform, notchlet-plan, notchlet-implement, notchlet-review, notchlet-deliver, notchlet-super, notchlet-init
521
+
522
+ Targets:
523
+ opencode .opencode/skills/<skill>/SKILL.md
524
+ claude .claude/skills/<skill>/SKILL.md
525
+
526
+ Options:
527
+ --apply Actually write the guidance files (without this, only previews)
528
+ --workspace <root> Set workspace root
529
+ --json Machine-readable JSON output`);
530
+ }
531
+ const root = await requireWorkspace('client');
532
+ const action = positional[1], client = positional[2];
533
+ if (!['init', 'update'].includes(action ?? '') || !['opencode', 'claude'].includes(client ?? ''))
534
+ fail('usage_error', usage, 'Use `notchlet client init|update opencode|claude [--apply]`.', 64);
535
+ const { installClientGuidance } = await import('./guidance-install.js');
536
+ const result = await installClientGuidance(root, client, { apply: args.includes('--apply') });
537
+ if (json) {
538
+ print(result);
539
+ }
540
+ else {
541
+ const lines = [];
542
+ lines.push(section(`Client guidance: ${result.action}`));
543
+ lines.push(kv('Client', result.client));
544
+ const appliedCount = result.results.filter(r => r.applied).length;
545
+ lines.push(kv('Skills', `${appliedCount}/${result.results.length} ${result.applied ? ok('applied') : warn('preview (use --apply to install)')}`));
546
+ for (const r of result.results) {
547
+ const status = r.applied ? ok(r.action) : r.action === 'unchanged' ? warn('unchanged') : err(r.action);
548
+ lines.push(kv(r.skill, `${status}${r.reason ? ` - ${r.reason}` : ''}`));
549
+ }
550
+ console.log(box(lines));
551
+ }
552
+ }
553
+ else if (command === 'checkpoint') {
554
+ if (args.includes('--help') || args.includes('-h')) {
555
+ showCommandHelp('checkpoint', `notchlet checkpoint --change <id> --name <name> [--summary <text>] [--backlog-status TODO|IN_PROGRESS|IN_REVIEW|DONE]
556
+
557
+ Create a remote checkpoint on a synchronized change.
558
+
559
+ Options:
560
+ --change <id> Change ID (required)
561
+ --name <name> Checkpoint name (required, max 100 chars)
562
+ --summary <text> Checkpoint summary (max 4096 chars)
563
+ --backlog-status <status> Backlog status: TODO, IN_PROGRESS, IN_REVIEW, or DONE
564
+ --server <url> Notchlet server (default: ${DEFAULT_SERVER})
565
+ --endpoint <url> Override MCP endpoint
566
+ --workspace <root> Set workspace root
567
+ --json Machine-readable JSON output`);
568
+ }
569
+ const root = await requireWorkspace('checkpoint');
570
+ const id = optionValue('--change') ?? (isTty() ? await prompt('Change ID: ') : undefined);
571
+ const name = optionValue('--name') ?? (isTty() && !id ? await prompt('Checkpoint name: ') : undefined);
572
+ const backlogStatus = optionValue('--backlog-status');
573
+ if (!id || !name || (backlogStatus !== undefined && !['TODO', 'IN_PROGRESS', 'IN_REVIEW', 'DONE'].includes(backlogStatus)))
574
+ fail('usage_error', usage, 'Provide --change, --name, and an optional supported --backlog-status.', 64);
575
+ const { syncCheckpoint } = await import('./integration.js');
576
+ const result = await syncCheckpoint(root, id, { name, ...(optionValue('--summary') === undefined ? {} : { summary: optionValue('--summary') }), ...(backlogStatus === undefined ? {} : { backlogStatus: backlogStatus }) }, { server: optionValue('--server'), endpoint: optionValue('--endpoint') });
577
+ if (json) {
578
+ print(result);
579
+ }
580
+ else {
581
+ const c = result.checkpoint;
582
+ const lines = [];
583
+ lines.push(section('Checkpoint created'));
584
+ lines.push(kv('Change', id));
585
+ lines.push(kv('Remote ID', result.remoteId));
586
+ lines.push(kv('Name', c?.name ?? name));
587
+ lines.push(kv('Snapshot revision', String(c?.snapshotRevision ?? '(unknown)')));
588
+ if (c?.summary)
589
+ lines.push(kv('Summary', c.summary));
590
+ if (c?.backlogStatus)
591
+ lines.push(kv('Backlog status', c.backlogStatus));
592
+ console.log(box(lines));
593
+ }
594
+ }
595
+ else if (command === 'evidence' && positional[1] === 'record') {
596
+ if (args.includes('--help') || args.includes('-h')) {
597
+ showCommandHelp('evidence record', `notchlet evidence record --change <id> --file <json-path>
598
+
599
+ Record evidence for a change.
600
+
601
+ Options:
602
+ --change <id> Change ID (required)
603
+ --file <path> Path to evidence JSON file (required, max 32 KiB)
604
+ --workspace <root> Set workspace root
605
+ --json Machine-readable JSON output`);
606
+ }
607
+ const root = await requireWorkspace('evidence record');
608
+ const id = optionValue('--change') ?? (isTty() ? await prompt('Change ID: ') : undefined);
609
+ const file = optionValue('--file') ?? (isTty() && !id ? await prompt('Evidence JSON file path: ') : undefined);
610
+ if (!id || !file)
611
+ fail('usage_error', usage, 'Provide --change and --file for evidence record.', 64);
612
+ const source = await readFile(path.resolve(process.cwd(), file), 'utf8');
613
+ if (Buffer.byteLength(source, 'utf8') > EVIDENCE_INPUT_LIMIT_BYTES)
614
+ fail('payload_too_large', 'Evidence input exceeds 32 KiB.', 'Split the evidence into smaller records and try again.', 5);
615
+ let value;
616
+ try {
617
+ value = JSON.parse(source);
618
+ }
619
+ catch {
620
+ fail('invalid_input', 'Evidence input is not valid JSON.', 'Correct the JSON file and try again.', 2);
621
+ }
622
+ const evidence = await appendEvidence(root, id, parseEvidenceWriteInput(value));
623
+ printWithSync(evidence, await syncIfAutomatic(root, id), `Recorded ${evidence.kind} evidence ${evidence.id} for ${id}.`);
624
+ }
625
+ else if (command === 'backlog' && positional[1] === 'import') {
626
+ if (args.includes('--help') || args.includes('-h')) {
627
+ showCommandHelp('backlog import', `notchlet backlog import <item-id> --product-id <id>
628
+
629
+ Import a backlog item as a change.
630
+
631
+ Options:
632
+ <item-id> Backlog item ID (numeric, required)
633
+ --product-id <id> Product ID (numeric, required)
634
+ --server <url> Notchlet server (default: ${DEFAULT_SERVER})
635
+ --endpoint <url> Override MCP endpoint
636
+ --allow-file-token-store Allow restricted file credential storage
637
+ --workspace <root> Set workspace root
638
+ --json Machine-readable JSON output`);
639
+ }
640
+ const root = await requireWorkspace('backlog import');
641
+ const itemId = await requiredNumber(positional[2], 'Backlog item ID: ');
642
+ const productId = await requiredNumber(optionValue('--product-id'), 'Product ID: ');
643
+ if (!Number.isSafeInteger(itemId) || !Number.isSafeInteger(productId))
644
+ fail('usage_error', usage, 'Provide numeric item ID and --product-id.', 64);
645
+ const { importBacklogItem } = await import('./integration.js');
646
+ const change = await importBacklogItem(root, { itemId: itemId, productId: productId, server: optionValue('--server'), endpoint: optionValue('--endpoint'), allowFileStore: args.includes('--allow-file-token-store') });
647
+ printWithSync({ change }, await syncIfAutomatic(root, change.id), `Imported backlog item ${itemId} as change ${change.id}.`);
648
+ }
649
+ else if (command === 'init') {
650
+ if (args.includes('--help') || args.includes('-h')) {
651
+ showCommandHelp('init', `notchlet init [path] [--local|--interactive]
652
+
653
+ Initialize a Notchlet workspace in the given path (or current directory).
654
+
655
+ Options:
656
+ --local Initialize local-only mode (no account login)
657
+ --interactive Force interactive setup (prompts for server, org, product, repository)
658
+ --workspace <root> / --root <root> Set workspace root
659
+ --json Machine-readable JSON output`);
660
+ }
661
+ const root = path.resolve(positional[1] ?? explicitRoot ?? process.cwd());
662
+ if (args.includes('--interactive') && json)
663
+ fail('usage_error', usage, 'Interactive setup cannot be combined with --json.', 64);
664
+ const interactive = args.includes('--interactive') || (!args.includes('--local') && !json && Boolean(process.stdin.isTTY && process.stderr.isTTY));
665
+ if (interactive) {
666
+ const { interactiveInit } = await import('./setup.js');
667
+ const result = await interactiveInit(root);
668
+ if (json) {
669
+ print(result);
670
+ }
671
+ else {
672
+ const lines = [];
673
+ lines.push(section('Workspace initialized'));
674
+ lines.push(kv('Root', result.root));
675
+ lines.push(kv('Mode', result.mode));
676
+ if (result.accountConnected)
677
+ lines.push(kv('Account connected', 'yes'));
678
+ if (result.organizationId)
679
+ lines.push(kv('Organization ID', String(result.organizationId)));
680
+ if (result.productId)
681
+ lines.push(kv('Product ID', String(result.productId)));
682
+ if (result.syncMode)
683
+ lines.push(kv('Sync mode', result.syncMode));
684
+ if (result.message)
685
+ lines.push(kv('Message', result.message));
686
+ if (result.binding) {
687
+ lines.push(divider());
688
+ lines.push(section('Binding'));
689
+ const b = result.binding;
690
+ lines.push(kv('Server', b.server));
691
+ lines.push(kv('Product ID', String(b.productId)));
692
+ lines.push(kv('Repository ID', String(b.repositoryId)));
693
+ lines.push(kv('Repository remote', b.repositoryRemote));
694
+ }
695
+ console.log(box(lines));
696
+ }
697
+ }
698
+ else {
699
+ await initWorkspace(root);
700
+ print({ root, initialized: true, mode: 'local' }, `Initialized Notchlet workspace at ${root} (local mode).`);
701
+ }
702
+ }
703
+ else if (command === 'change') {
704
+ const action = positional[1];
705
+ if (args.includes('--help') || args.includes('-h')) {
706
+ showCommandHelp('change', `notchlet change <action> [options]
707
+
708
+ new <name> [--quick] Create a new change
709
+ list List all changes
710
+ show <id> Show change details and readiness
711
+ convert <id> --schema <q|s> Convert a change schema
712
+ close <id> --preview | --baseline-revision <n> Close and archive a change
713
+
714
+ Options:
715
+ --quick Create a quick (minimal) change
716
+ --schema quick|standard Schema for conversion (required for convert)
717
+ --preview Preview closure without changing files (for close)
718
+ --baseline-revision <n> Baseline revision for closing (required for close)
719
+ --yes Skip confirmation prompt (for close)
720
+ --workspace <root> Set workspace root
721
+ --json Machine-readable JSON output`);
722
+ }
723
+ if (action === 'new') {
724
+ const name = positional[2] ?? (isTty() ? await prompt('Change name: ') : undefined);
725
+ if (!name)
726
+ fail('usage_error', usage, 'Run `notchlet --help` for command syntax.', 64);
727
+ const root = await requireWorkspace('change new');
728
+ const change = await scaffold(root, name, args.includes('--quick') ? 'quick' : 'standard');
729
+ printWithSync(change, await syncIfAutomatic(root, change.id), `Created change ${change.id}: ${change.name}.`);
730
+ }
731
+ else if (action === 'list') {
732
+ const root = await workspace();
733
+ if (!root) {
734
+ print({ changes: [] }, 'No Notchlet workspace found.');
735
+ }
736
+ else {
737
+ const changes = await listChanges(root);
738
+ if (json) {
739
+ print({ workspace: root, changes });
740
+ }
741
+ else {
742
+ console.log(section(`Changes in ${root}`));
743
+ if (changes.length === 0) {
744
+ console.log(warn('(none)'));
745
+ }
746
+ else {
747
+ const rows = changes.map((c) => [c.id, c.name, String(c.taskCount ?? 0), c.ready ? ok('ready') : err('not ready')]);
748
+ console.log(table(['ID', 'Name', 'Tasks', 'Ready'], rows));
749
+ }
750
+ }
751
+ }
752
+ }
753
+ else if (action === 'show') {
754
+ const root = await requireWorkspace('change show');
755
+ const id = positional[2] ?? (isTty() ? await prompt('Change ID: ') : undefined);
756
+ if (!id)
757
+ fail('usage_error', usage, 'Provide a change ID from `notchlet change list`.', 64);
758
+ const change = await readChange(root, id);
759
+ const result = { change, readiness: readiness(change, await artifactContents(root, id, change)) };
760
+ if (json) {
761
+ printWithSync(result, await syncIfAutomatic(root, id));
762
+ }
763
+ else {
764
+ const lines = [];
765
+ lines.push(section(`Change: ${id}`));
766
+ lines.push(kv('Name', change.name));
767
+ lines.push(kv('Mode', change.mode));
768
+ lines.push(kv('Revision', String(change.revision ?? 0)));
769
+ lines.push(kv('Intent', change.intent));
770
+ lines.push(kv('Outcome', change.outcome));
771
+ lines.push(kv('Requirements', String(change.requirements.length)));
772
+ lines.push(kv('Checks', String(change.checks.length)));
773
+ lines.push(kv('Tasks', String(change.tasks.length)));
774
+ lines.push(divider());
775
+ lines.push(section('Artifacts'));
776
+ const artifactNames = Object.keys(change.artifacts);
777
+ if (artifactNames.length === 0)
778
+ lines.push(warn('(none)'));
779
+ else
780
+ for (const name of artifactNames)
781
+ lines.push(bullet(`${name}: ${change.artifacts[name]}`));
782
+ lines.push(divider());
783
+ lines.push(section('Readiness'));
784
+ lines.push(kv('Ready', result.readiness.ready ? ok('yes') : err('no')));
785
+ if (result.readiness.blockers?.length) {
786
+ lines.push(section('Blockers'));
787
+ for (const b of result.readiness.blockers)
788
+ lines.push(bullet(String(b.message ?? b)));
789
+ }
790
+ else {
791
+ lines.push(bullet('No blockers.'));
792
+ }
793
+ console.log(box(lines));
794
+ }
795
+ }
796
+ else if (action === 'convert') {
797
+ const root = await requireWorkspace('change convert');
798
+ const id = positional[2] ?? (isTty() ? await prompt('Change ID: ') : undefined);
799
+ const schema = optionValue('--schema') ?? (isTty() && !id ? await prompt('Schema (quick|standard): ') : undefined);
800
+ if (!id || (schema !== 'quick' && schema !== 'standard'))
801
+ fail('usage_error', usage, 'Use `--schema quick` or `--schema standard`.', 64);
802
+ const change = await persistConversion(root, id, schema);
803
+ const result = { change, readiness: readiness(change, await artifactContents(root, id, change)) };
804
+ printWithSync(result, await syncIfAutomatic(root, id), `Converted change ${id} to ${schema} schema.`);
805
+ }
806
+ else if (action === 'close') {
807
+ const root = await requireWorkspace('change close');
808
+ const id = positional[2] ?? (isTty() ? await prompt('Change ID: ') : undefined);
809
+ if (!id)
810
+ fail('usage_error', usage, 'Provide a change ID.', 64);
811
+ if (args.includes('--preview')) {
812
+ const preview = await previewCapabilityClose(root, id);
813
+ if (json) {
814
+ print(preview);
815
+ }
816
+ else {
817
+ const lines = [];
818
+ lines.push(section(`Closure preview: ${id}`));
819
+ if (preview.baselineName)
820
+ lines.push(kv('Baseline name', preview.baselineName));
821
+ if (preview.baselineRevision !== undefined)
822
+ lines.push(kv('Baseline revision', String(preview.baselineRevision)));
823
+ if (preview.additions?.length)
824
+ lines.push(kv('Additions', String(preview.additions.length)));
825
+ if (preview.updates?.length)
826
+ lines.push(kv('Updates', String(preview.updates.length)));
827
+ if (preview.removals?.length)
828
+ lines.push(kv('Removals', String(preview.removals.length)));
829
+ if (preview.blockers?.length) {
830
+ lines.push(section('Blockers'));
831
+ for (const b of preview.blockers)
832
+ lines.push(bullet(`${b.code}: ${b.message}`));
833
+ }
834
+ console.log(box(lines));
835
+ console.log(warn('No files were changed.'));
836
+ }
837
+ }
838
+ else {
839
+ const yes = args.includes('--yes');
840
+ if (!yes && isTty()) {
841
+ const confirmed = await confirm(`Are you sure you want to close and archive change ${id}?`);
842
+ if (!confirmed) {
843
+ console.log(warn('Cancelled.'));
844
+ return;
845
+ }
846
+ }
847
+ const revision = Number(optionValue('--baseline-revision'));
848
+ if (!Number.isInteger(revision) || revision < 0)
849
+ fail('usage_error', usage, 'Provide --baseline-revision from the capability preview.', 64);
850
+ print(await closeChange(root, id, { expectedBaselineRevision: revision }), `Closed and archived ${id}.`);
851
+ }
852
+ }
853
+ else
854
+ fail('usage_error', usage, 'Run `notchlet --help` for command syntax.', 64);
855
+ }
856
+ else if (command === 'task') {
857
+ if (args.includes('--help') || args.includes('-h')) {
858
+ showCommandHelp('task', `notchlet task <action> [options]
859
+
860
+ start <task-id> --change <id> --revision <n> Start a task
861
+ complete <task-id> --change <id> --revision <n> Complete a task
862
+ update <change> <task> <status> <revision> Update a task status
863
+
864
+ Options:
865
+ --change <id> Change ID (required for start/complete)
866
+ --revision <n> Revision number (required)
867
+ --workspace <root> Set workspace root
868
+ --json Machine-readable JSON output`);
869
+ }
870
+ const root = await requireWorkspace('task');
871
+ const action = positional[1];
872
+ let id, taskId, status, revisionText;
873
+ if (action === 'start' || action === 'complete') {
874
+ taskId = positional[2] ?? (isTty() ? await prompt('Task ID: ') : undefined);
875
+ id = optionValue('--change') ?? (isTty() && !taskId ? await prompt('Change ID: ') : undefined);
876
+ status = action === 'start' ? 'in_progress' : 'completed';
877
+ revisionText = optionValue('--revision') ?? (isTty() ? await prompt('Revision: ') : undefined);
878
+ }
879
+ else if (action === 'update') {
880
+ [, , id, taskId, status, revisionText] = positional;
881
+ id = id ?? (isTty() ? await prompt('Change ID: ') : undefined);
882
+ taskId = taskId ?? (isTty() ? await prompt('Task ID: ') : undefined);
883
+ status = status ?? (isTty() ? await prompt('Status (pending|in_progress|completed): ') : undefined);
884
+ revisionText = revisionText ?? (isTty() ? await prompt('Revision: ') : undefined);
885
+ }
886
+ if (!id || !taskId || !['pending', 'in_progress', 'completed'].includes(status ?? '') || !revisionText || !Number.isInteger(Number(revisionText)))
887
+ fail('usage_error', usage, 'Use task start|complete <task-id> --change <id> --revision <n>, or task update <change> <task> <status> <revision>.', 64);
888
+ const change = await transitionTask(path.join(root, '.notchlet', 'changes', id, 'tasks.json'), taskId, status, Number(revisionText));
889
+ printWithSync(change, await syncIfAutomatic(root, id), `Task ${taskId} marked ${status} in change ${id}.`);
890
+ }
891
+ else if (['status', 'validate', 'instructions'].includes(command)) {
892
+ if (args.includes('--help') || args.includes('-h')) {
893
+ const helpText = command === 'status'
894
+ ? `notchlet status [change]
895
+
896
+ Show workspace status, or status of a specific change.
897
+
898
+ Options:
899
+ [change] Change ID (optional; lists all changes if omitted)
900
+ --workspace <root> Set workspace root
901
+ --json Machine-readable JSON output`
902
+ : command === 'validate'
903
+ ? `notchlet validate <change>
904
+
905
+ Validate that a change is ready.
906
+
907
+ Options:
908
+ <change> Change ID (required)
909
+ --workspace <root> Set workspace root
910
+ --json Machine-readable JSON output`
911
+ : `notchlet instructions <change> [--action <action>]
912
+
913
+ Get workflow instructions for a change.
914
+
915
+ Options:
916
+ <change> Change ID (required)
917
+ --action plan|revise|implement|verify|resume Action to get instructions for (default: resume)
918
+ --workspace <root> Set workspace root
919
+ --json Machine-readable JSON output`;
920
+ showCommandHelp(command, helpText);
921
+ }
922
+ const root = await profileAsync('workspaceResolution', workspace);
923
+ if (!root) {
924
+ if (command === 'validate')
925
+ fail('setup_required', 'No initialized Notchlet workspace was found.', 'Run `notchlet init` in the project root.', 2);
926
+ print({ coreVersion: CORE_VERSION, workspace: null, changes: [] }, `No Notchlet workspace found. Core engine ${CORE_VERSION}.`);
927
+ }
928
+ else {
929
+ const id = positional[1] ?? (isTty() ? await prompt('Change ID: ') : undefined);
930
+ if (!id) {
931
+ if (command !== 'status')
932
+ fail('usage_error', usage, `Provide a change ID for ${command}.`, 64);
933
+ const changes = await listChanges(root);
934
+ if (json) {
935
+ print({ protocolVersion: 1, coreVersion: CORE_VERSION, workspace: root, changes });
936
+ }
937
+ else {
938
+ console.log(section(`Changes in ${root}`));
939
+ if (changes.length === 0) {
940
+ console.log(warn('No changes found.'));
941
+ }
942
+ else {
943
+ const rows = changes.map((c) => [c.id, c.name, String(c.taskCount ?? 0), c.ready ? ok('ready') : err('not ready')]);
944
+ console.log(table(['ID', 'Name', 'Tasks', 'Ready'], rows));
945
+ }
946
+ }
947
+ }
948
+ else {
949
+ if (positional.length !== 2 && !(isTty() && positional.length === 1))
950
+ fail('usage_error', usage, 'Provide exactly one change ID.', 64);
951
+ const change = await profileAsync('changeReadAndParse', () => readChange(root, id));
952
+ const automaticSync = await profileAsync('automaticSyncModeCheck', () => syncIfAutomatic(root, id));
953
+ const contents = await profileAsync('artifactReads', () => artifactContents(root, id, change));
954
+ if (command === 'status') {
955
+ const state = profileSync('evaluateState', () => evaluateState(change, undefined, contents));
956
+ const derivedState = profileSync('deriveState', () => deriveStatus(evaluateState(change)));
957
+ const readinessState = profileSync('readinessProjection', () => ({ ready: state.planning.status === 'ready', blockers: state.planning.blockers.map(({ source: _source, ...issue }) => issue) }));
958
+ if (json) {
959
+ 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}`);
960
+ }
961
+ else {
962
+ const lines = [];
963
+ lines.push(section(`Status: ${change.name} (${id})`));
964
+ lines.push(kv('Revision', String(change.revision ?? 0)));
965
+ lines.push(kv('Core engine', CORE_VERSION));
966
+ lines.push(divider());
967
+ lines.push(section('Progress'));
968
+ lines.push(kv('Tasks', `${state.execution.completed}/${state.execution.total} completed${state.execution.inProgress ? `, ${state.execution.inProgress} in progress` : ''}`));
969
+ lines.push(kv('Planning', state.planning.status));
970
+ lines.push(kv('Verification', state.verification.status));
971
+ lines.push(kv('Local closure', state.localClosure.status));
972
+ lines.push(kv('Remote delivery', state.remoteDelivery.status));
973
+ lines.push(divider());
974
+ lines.push(section('Eligible tasks'));
975
+ lines.push(state.eligibleTasks.length ? state.eligibleTasks.join(', ') : warn('none'));
976
+ lines.push(divider());
977
+ lines.push(section('Blockers'));
978
+ if (state.blockers.length)
979
+ for (const b of state.blockers)
980
+ lines.push(bullet(String(b.message ?? b)));
981
+ else
982
+ lines.push(bullet('None.'));
983
+ lines.push(divider());
984
+ lines.push(kv('Readiness', readinessState.ready ? ok('ready') : err(`not ready (${readinessState.blockers.length} blocker(s))`)));
985
+ console.log(box(lines));
986
+ }
987
+ if (profiling)
988
+ process.stderr.write(`NOTCHLET_PROFILE ${JSON.stringify(profileTimings)}\n`);
989
+ }
990
+ else if (command === 'instructions') {
991
+ const action = optionValue('--action') ?? 'resume';
992
+ if (!['plan', 'revise', 'implement', 'verify', 'resume'].includes(action))
993
+ fail('usage_error', usage, 'Choose a documented action: plan, revise, implement, verify, or resume.', 64);
994
+ const text = instructions(change, action);
995
+ printWithSync({ protocolVersion: 1, coreVersion: CORE_VERSION, action, instructions: text }, automaticSync, `Core engine: ${CORE_VERSION}\n${text}`);
996
+ }
997
+ else {
998
+ const result = readiness(change, contents);
999
+ const data = automaticSync ? { readiness: result, automaticSync } : result;
1000
+ if (json)
1001
+ 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.' }, [])));
1002
+ else {
1003
+ const lines = [];
1004
+ lines.push(section(`Validate: ${change.name} (${id})`));
1005
+ lines.push(kv('Ready', result.ready ? ok('yes') : err('no')));
1006
+ if (result.blockers?.length) {
1007
+ lines.push(section('Blockers'));
1008
+ for (const b of result.blockers)
1009
+ lines.push(bullet(String(b.message ?? b)));
1010
+ }
1011
+ else {
1012
+ lines.push(bullet('No blockers.'));
1013
+ }
1014
+ console.log(box(lines));
1015
+ }
1016
+ if (!result.ready)
1017
+ process.exitCode = 1;
1018
+ }
1019
+ }
1020
+ }
1021
+ }
1022
+ else
1023
+ fail('unknown_command', usage, 'Run `notchlet --help` for available commands.', 64);
1024
+ }
1025
+ catch (error) {
1026
+ if (error instanceof Error && error.message === 'handled') { /* stable error already printed */ }
1027
+ else {
1028
+ const known = error instanceof WorkflowError ? error : null;
1029
+ const code = known?.code ?? 'operation_failed';
1030
+ const message = error instanceof Error ? error.message : String(error);
1031
+ const recovery = known?.recovery ?? 'Inspect the workspace and retry; existing files were not intentionally overwritten.';
1032
+ if (json)
1033
+ console.log(JSON.stringify(envelope(false, null, { code, message, recovery }, [])));
1034
+ else
1035
+ console.error(`${err(`${code}: ${message}`)}\nRecovery: ${recovery}`);
1036
+ process.exitCode = code === 'change_exists' ? 3 : 1;
1037
+ }
1038
+ }
1039
+ }
1040
+ main().catch(() => { });