@notchlet/cli 0.1.0 → 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 (26) hide show
  1. package/dist/cli-format.js +46 -0
  2. package/dist/cli-prompt.js +73 -0
  3. package/dist/cli.js +895 -258
  4. package/dist/guidance-install.js +58 -35
  5. package/guidance/aliases.json +27 -27
  6. package/guidance/generated/claude-code/notchlet-deliver/SKILL.md +94 -0
  7. package/guidance/generated/claude-code/notchlet-implement/SKILL.md +94 -0
  8. package/guidance/generated/claude-code/notchlet-init/SKILL.md +30 -0
  9. package/guidance/generated/claude-code/notchlet-mcp/SKILL.md +60 -0
  10. package/guidance/generated/claude-code/notchlet-plan/SKILL.md +100 -0
  11. package/guidance/generated/claude-code/notchlet-platform/SKILL.md +85 -0
  12. package/guidance/generated/claude-code/notchlet-review/SKILL.md +68 -0
  13. package/guidance/generated/claude-code/notchlet-super/SKILL.md +47 -47
  14. package/guidance/generated/compatibility.json +7 -0
  15. package/guidance/generated/manifest.json +127 -5
  16. package/guidance/generated/opencode/notchlet-deliver/SKILL.md +94 -0
  17. package/guidance/generated/opencode/notchlet-implement/SKILL.md +94 -0
  18. package/guidance/generated/opencode/notchlet-init/SKILL.md +30 -0
  19. package/guidance/generated/opencode/notchlet-mcp/SKILL.md +60 -0
  20. package/guidance/generated/opencode/notchlet-plan/SKILL.md +100 -0
  21. package/guidance/generated/opencode/notchlet-platform/SKILL.md +85 -0
  22. package/guidance/generated/opencode/notchlet-review/SKILL.md +68 -0
  23. package/guidance/generated/opencode/notchlet-super/SKILL.md +47 -47
  24. package/package.json +1 -1
  25. package/scripts/generate-guidance.mjs +56 -20
  26. package/guidance/notchlet-super.md +0 -47
package/dist/cli.js CHANGED
@@ -2,6 +2,8 @@
2
2
  import path from 'node:path';
3
3
  import { readFile } from 'node:fs/promises';
4
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';
5
7
  const args = process.argv.slice(2);
6
8
  const profiling = process.env.NOTCHLET_PROFILE === '1';
7
9
  const profileTimings = {};
@@ -41,19 +43,75 @@ for (let i = 0; i < args.length; i++) {
41
43
  const rootOption = args.find(arg => arg.startsWith('--workspace=') || arg.startsWith('--root='));
42
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);
43
45
  const workspace = () => findWorkspace(process.cwd(), explicitRoot);
46
+ const DEFAULT_SERVER = 'https://pg-api.mbintangr.com';
44
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;
45
49
  const command = args.includes('--version') ? 'version' : positional[0] ?? 'help';
46
50
  const envelope = (ok, data = null, error = null, warnings = []) => ({ protocolVersion: 1, command, ok, data, error, warnings });
47
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
+ }
48
62
  function fail(code, message, recovery, exitCode) {
49
63
  if (json)
50
64
  console.log(JSON.stringify(envelope(false, null, { code, message, recovery }, [])));
51
65
  else
52
- console.error(`${code}: ${message}\nRecovery: ${recovery}`);
66
+ console.error(`${err(`${code}: ${message}`)}\nRecovery: ${recovery}`);
53
67
  process.exitCode = exitCode;
54
68
  throw new Error('handled');
55
69
  }
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';
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
+ `;
57
115
  function deriveStatus(state) {
58
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.`;
59
117
  }
@@ -75,10 +133,18 @@ async function syncIfAutomatic(root, changeId) {
75
133
  return autoSyncChange(root, changeId, { server: optionValue('--server'), endpoint: optionValue('--endpoint') });
76
134
  }
77
135
  function printWithSync(result, automaticSync, human) {
78
- if (!automaticSync)
79
- return print(result, 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
+ }
80
141
  const syncState = automaticSync?.state ?? 'pending';
81
- print({ result, automaticSync }, `${human ?? JSON.stringify(result, null, 2)}\nAutomatic sync: ${syncState}`);
142
+ if (json) {
143
+ console.log(JSON.stringify(envelope(true, { result, automaticSync })));
144
+ }
145
+ else {
146
+ console.log(`${base}\nAutomatic sync: ${syncState}`);
147
+ }
82
148
  }
83
149
  const EVIDENCE_INPUT_LIMIT_BYTES = 32 * 1024;
84
150
  function parseEvidenceWriteInput(value) {
@@ -120,284 +186,855 @@ async function artifactContents(root, id, change) {
120
186
  }
121
187
  return result;
122
188
  }
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));
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);
192
201
  }
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);
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}`);
229
204
  }
230
- catch {
231
- fail('invalid_input', 'Evidence input is not valid JSON.', 'Correct the JSON file and try again.', 2);
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
+ }
232
257
  }
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));
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
+ }
255
284
  }
256
- else {
257
- await initWorkspace(root);
258
- print({ root, initialized: true, mode: 'local' });
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
+ }
259
323
  }
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));
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
+ }
271
374
  }
272
- else if (action === 'list') {
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
+ }
273
387
  const root = await workspace();
274
- print({ workspace: root, changes: root ? await listChanges(root) : [] }, root ? undefined : 'No Notchlet workspace found.');
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
+ }
275
409
  }
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));
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
+ ]));
286
434
  }
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));
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
+ }
298
511
  }
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.');
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
+ }
308
540
  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}.`);
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));
313
551
  }
314
552
  }
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');
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
+ }
329
594
  }
330
- else if (action === 'update') {
331
- [, , id, taskId, status, revisionText] = positional;
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}.`);
332
624
  }
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}.`);
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}.`);
344
648
  }
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}.`);
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
+ }
352
697
  }
353
698
  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`);
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
+ }
366
751
  }
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}`);
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));
373
762
  }
374
763
  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.' }, [])));
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)'));
379
779
  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;
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
+ }
383
1019
  }
384
1020
  }
385
1021
  }
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
1022
  else
400
- console.error(`${code}: ${message}\nRecovery: ${recovery}`);
401
- process.exitCode = code === 'change_exists' ? 3 : 1;
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
+ }
402
1038
  }
403
1039
  }
1040
+ main().catch(() => { });