geloforge 0.0.0-stage → 0.6.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 (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +140 -2
  3. package/THIRD_PARTY_NOTICES.md +33 -0
  4. package/VERSION +1 -0
  5. package/core/adopt-project.mjs +458 -0
  6. package/core/checkpoint.mjs +438 -0
  7. package/core/codebase-map.mjs +886 -0
  8. package/core/compatibility.json +16 -0
  9. package/core/compatibility.mjs +123 -0
  10. package/core/context-compiler.mjs +1315 -0
  11. package/core/evidence-capture.mjs +326 -0
  12. package/core/git-utils.mjs +167 -0
  13. package/core/handoff.mjs +815 -0
  14. package/core/json-schema-lite.mjs +119 -0
  15. package/core/mcp-init.mjs +248 -0
  16. package/core/mcp-server.mjs +915 -0
  17. package/core/path-safety.mjs +508 -0
  18. package/core/project-locator.mjs +231 -0
  19. package/core/project-lock.mjs +438 -0
  20. package/core/project-status.mjs +609 -0
  21. package/core/project-validator.mjs +544 -0
  22. package/core/skills-history.mjs +572 -0
  23. package/core/skills-lifecycle.mjs +2225 -0
  24. package/core/skills-lint.mjs +365 -0
  25. package/core/skills.mjs +1449 -0
  26. package/core/task-manager.mjs +1042 -0
  27. package/core/template-utils.mjs +190 -0
  28. package/core/text-utils.mjs +48 -0
  29. package/core/verify-task.mjs +48 -0
  30. package/core/yaml-subset.mjs +572 -0
  31. package/package.json +47 -4
  32. package/policies/approval-boundaries.md +42 -0
  33. package/policies/memory-policy.md +53 -0
  34. package/policies/token-efficiency.md +30 -0
  35. package/schemas/README.md +43 -0
  36. package/schemas/adr.schema.json +64 -0
  37. package/schemas/agent-handoff.schema.json +139 -0
  38. package/schemas/approval-record.schema.json +101 -0
  39. package/schemas/conflict-record.schema.json +60 -0
  40. package/schemas/context-pack-manifest.schema.json +194 -0
  41. package/schemas/evidence-manifest.schema.json +83 -0
  42. package/schemas/incident-record.schema.json +53 -0
  43. package/schemas/project-manifest.schema.json +90 -0
  44. package/schemas/project-state.schema.json +64 -0
  45. package/schemas/recovery-checkpoint.schema.json +49 -0
  46. package/schemas/research-record.schema.json +76 -0
  47. package/schemas/task-contract.schema.json +95 -0
  48. package/scripts/bootstrap-project.mjs +357 -0
  49. package/scripts/geloforge.mjs +2291 -0
  50. package/templates/profiles/README.md +19 -0
  51. package/templates/profiles/ai-system/brain/profile.md +21 -0
  52. package/templates/profiles/ai-system/gitignore.append +5 -0
  53. package/templates/profiles/ai-system/profile.json +6 -0
  54. package/templates/profiles/automation/brain/profile.md +19 -0
  55. package/templates/profiles/automation/gitignore.append +5 -0
  56. package/templates/profiles/automation/profile.json +6 -0
  57. package/templates/profiles/desktop/brain/profile.md +21 -0
  58. package/templates/profiles/desktop/gitignore.append +7 -0
  59. package/templates/profiles/desktop/profile.json +6 -0
  60. package/templates/profiles/mobile/brain/profile.md +20 -0
  61. package/templates/profiles/mobile/gitignore.append +8 -0
  62. package/templates/profiles/mobile/profile.json +6 -0
  63. package/templates/profiles/web/brain/profile.md +21 -0
  64. package/templates/profiles/web/gitignore.append +6 -0
  65. package/templates/profiles/web/profile.json +6 -0
  66. package/templates/project-starter/AGENTS.md +26 -0
  67. package/templates/project-starter/GEMINI.md +16 -0
  68. package/templates/project-starter/README.md +26 -0
  69. package/templates/project-starter/brain/INDEX.md +40 -0
  70. package/templates/project-starter/brain/architecture/overview.md +30 -0
  71. package/templates/project-starter/brain/decisions/.gitkeep +0 -0
  72. package/templates/project-starter/brain/manifest.yaml +36 -0
  73. package/templates/project-starter/brain/requirements/constraints.md +29 -0
  74. package/templates/project-starter/brain/requirements/prd.md +37 -0
  75. package/templates/project-starter/brain/state/current.yaml +19 -0
  76. package/templates/project-starter/gitignore.template +25 -0
  77. package/templates/project-starter/src/.gitkeep +0 -0
  78. package/templates/project-starter/tasks/.gitkeep +0 -0
  79. package/templates/project-starter/tests/.gitkeep +0 -0
@@ -0,0 +1,2291 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Unified non-interactive CLI entrypoint for GeloForge.
4
+ * Commands: init, validate, context, handoff, status.
5
+ */
6
+
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import readline from "node:readline/promises";
10
+ import { parseArgs } from "node:util";
11
+ import { fileURLToPath } from "node:url";
12
+ import { bootstrapProject, DEFAULT_INIT_LOCATION } from "./bootstrap-project.mjs";
13
+ import { adoptProject } from "../core/adopt-project.mjs";
14
+ import { validateProject } from "../core/project-validator.mjs";
15
+ import { compileContext } from "../core/context-compiler.mjs";
16
+ import { getProjectStatus, getProjectRecommendations } from "../core/project-status.mjs";
17
+ import { createHandoff, inspectHandoff } from "../core/handoff.mjs";
18
+ import {
19
+ claimTaskLease,
20
+ completeTask,
21
+ createTask,
22
+ getTask,
23
+ listTaskLeases,
24
+ listTasks,
25
+ releaseTaskLease,
26
+ updateTask,
27
+ } from "../core/task-manager.mjs";
28
+ import { captureEvidence } from "../core/evidence-capture.mjs";
29
+ import { verifyTask } from "../core/verify-task.mjs";
30
+ import { createCheckpoint, getCheckpoint, listCheckpoints } from "../core/checkpoint.mjs";
31
+ import { startMcpStdioServer } from "../core/mcp-server.mjs";
32
+ import { initMcpClients } from "../core/mcp-init.mjs";
33
+ import {
34
+ discoverSkills,
35
+ resolveProjectForSkills,
36
+ } from "../core/skills.mjs";
37
+ import { STATIC_LINT_DISCLAIMER, lintDiscoveredSkills, lintSkill } from "../core/skills-lint.mjs";
38
+ import {
39
+ draftSkillFromExperience,
40
+ generateApproverKeypair,
41
+ getSkillHistory,
42
+ promoteSkillProposal,
43
+ proposeSkillUpdate,
44
+ rollbackSkill,
45
+ signSkillApproval,
46
+ } from "../core/skills-lifecycle.mjs";
47
+ import { atomicWriteFile, redactSecretContent, validateOutputFilePath } from "../core/path-safety.mjs";
48
+ import { resolveProjectDir } from "../core/project-locator.mjs";
49
+
50
+ const __filename = fileURLToPath(import.meta.url);
51
+ const __dirname = path.dirname(__filename);
52
+ const HARNESS_DIR = path.resolve(__dirname, "..");
53
+ const WORKSPACE_ROOT = path.resolve(HARNESS_DIR, "..");
54
+
55
+ function getVersion() {
56
+ return fs.readFileSync(path.join(HARNESS_DIR, "VERSION"), "utf8").trim();
57
+ }
58
+
59
+ function printMainHelp() {
60
+ console.log(`GeloForge CLI v${getVersion()}
61
+
62
+ Usage:
63
+ geloforge <command> [options]
64
+
65
+ Commands:
66
+ init Initialize a new project Second Brain (supports profiles & --dry-run)
67
+ adopt Add GeloForge Second Brain to an existing project without overwriting files
68
+ task Create, update, lease, complete, list, or inspect scoped task contracts (TASK-NNNN)
69
+ evidence Run an explicit command (shell: false) and record EVID-NNNN manifest
70
+ verify Run a check, save a checkpoint, and complete the task on verified evidence
71
+ validate Validate a project's schemas, compatibility, IDs, references, and links
72
+ context Compile a deterministic, trust-tiered context packet for a task or query
73
+ skills Discover, inspect, validate, and security-lint portable SKILL.md packages
74
+ handoff Create or inspect a cross-agent file-based handoff record (HANDOFF-NNNN)
75
+ checkpoint Create, list, or inspect session recovery checkpoints (CHKPT-NNNN)
76
+ recommend Show ranked Human-in-the-Loop Co-Pilot recommendations & approval inbox
77
+ status Inspect project health, operational task state, leases, and Git status
78
+ mcp Start the stdio MCP server or configure MCP clients with mcp init
79
+
80
+ Global Options:
81
+ -h, --help Show help (use "geloforge <command> --help" for command options)
82
+ -v, --version Show GeloForge version
83
+ `);
84
+ }
85
+
86
+ function printSubHelp(cmd) {
87
+ switch (cmd) {
88
+ case "init":
89
+ console.log(`Usage: geloforge init --name "<Project Name>" [options]
90
+
91
+ Options:
92
+ --name <string> Project display name (required, 3-80 chars)
93
+ --slug <string> Lowercase ASCII slug (optional)
94
+ --dest <path> Target directory (default: ${DEFAULT_INIT_LOCATION})
95
+ --owner <string> Project owner name
96
+ --description <string> Short project description
97
+ --profile <name> Optional overlay: web, desktop, mobile, automation, ai-system
98
+ --created-at <iso> ISO-8601 timestamp for deterministic output
99
+ --git Initialize local Git repo (git init -b main)
100
+ --dry-run Preview planned files without writing
101
+ --json Emit structured JSON output
102
+ -h, --help Show help
103
+ `);
104
+ break;
105
+ case "adopt":
106
+ console.log(`Usage: geloforge adopt [--dest <path>] [options]
107
+
108
+ Options:
109
+ -d, --dest <path> Existing project directory (default: current working directory)
110
+ -p, --project <path> Alias for --dest
111
+ --name <string> Display name (default: inferred from manifest or directory name)
112
+ --slug <string> Lowercase ASCII slug (optional)
113
+ --owner <string> Project owner name (default: "Project Owner")
114
+ --description <string> Short project description
115
+ --profile <name> Optional overlay: web, desktop, mobile, automation, ai-system
116
+ --tasks-dir <relpath> Relative task contracts folder (default: "tasks")
117
+ --evidence-dir <rel> Relative evidence manifests folder (default: "evidence")
118
+ --with-agent-guides Also create AGENTS.md & GEMINI.md (refuses overwrite if present)
119
+ --created-at <iso> ISO-8601 timestamp for deterministic output
120
+ --dry-run Preview planned files without modifying disk
121
+ --json Emit structured JSON output
122
+ -h, --help Show help
123
+ `);
124
+ break;
125
+ case "validate":
126
+ console.log(`Usage: geloforge validate [--project <path>] [--json]
127
+
128
+ Options:
129
+ -p, --project <path> Target project directory (auto-detected from CWD if omitted)
130
+ --json Emit structured JSON output
131
+ -h, --help Show help
132
+ `);
133
+ break;
134
+ case "context":
135
+ console.log(`Usage: geloforge context [--project <path>] (--task TASK-NNNN | --query <text> | --from-diff) [options]
136
+
137
+ Options:
138
+ -p, --project <path> Target project directory (auto-detected from CWD if omitted)
139
+ -t, --task <id> Task contract ID (e.g. TASK-0001)
140
+ -q, --query <text> Task description or search query
141
+ --from-diff Focus context packet on current scoped Git working-tree changes
142
+ --include-completed Include completed/cancelled/superseded tasks (pruned by default)
143
+ --profile <name> Budget profile: quick (~4000), working (~8000), deep (~16000)
144
+ --budget <int> Override estimated-token budget target (>= 100)
145
+ --map Include selective deterministic codebase symbol outline map
146
+ --map-budget <int> Override codebase map token budget (>= 100)
147
+ --skills Include portable Agent Skills with Tier 0/1/2 progressive disclosure
148
+ --skill <name> Explicitly pin a trusted skill into Tier 1 (repeatable; implies --skills)
149
+ --skills-budget <int> Override portable skills estimated-token budget (>= 100)
150
+ --exclude-unverified Omit A5-A6, draft, and unverified records/skills completely
151
+ --format <type> Output format: markdown (default) or json
152
+ -o, --out <file> Write output atomically to a safe file path
153
+ --compiled-at <iso> ISO-8601 timestamp for deterministic manifest
154
+ --json Alias for --format json
155
+ -h, --help Show help
156
+ `);
157
+ break;
158
+ case "status":
159
+ console.log(`Usage: geloforge status [--project <path>] [--json]
160
+
161
+ Options:
162
+ -p, --project <path> Target project directory (auto-detected from CWD if omitted)
163
+ --json Emit structured JSON output
164
+ -h, --help Show help
165
+ `);
166
+ break;
167
+ case "recommend":
168
+ console.log(`Usage: geloforge recommend [--project <path>] [--json]
169
+
170
+ Options:
171
+ -p, --project <path> Target project directory (auto-detected from CWD if omitted)
172
+ --json Emit structured JSON output
173
+ -h, --help Show help
174
+ `);
175
+ break;
176
+ case "checkpoint":
177
+ console.log(`Usage: geloforge checkpoint <create|list|show> [options]
178
+
179
+ Subcommands:
180
+ create Capture a CHKPT-NNNN session recovery checkpoint
181
+ list List recovery checkpoints ordered newest first
182
+ show Inspect a specific checkpoint (or latest if ID omitted)
183
+
184
+ Options:
185
+ -p, --project <path> Target project directory (auto-detected from CWD if omitted)
186
+ --summary <text> Progress summary for resume instructions ('create')
187
+ --resume <text> Explicit resume instructions override ('create')
188
+ --evidence <EVID-NNNN> Link verified evidence ID ('create')
189
+ --created-by <name> Creator label ('create')
190
+ --role <role> Agent role fallback creator ('create')
191
+ --status <status> Checkpoint status (filter for 'list', override for 'create')
192
+ --id <CHKPT-NNNN> Explicit checkpoint ID ('create' or 'show')
193
+ --created-at <iso> ISO-8601 timestamp override ('create')
194
+ --dry-run Preview checkpoint without writing disk ('create')
195
+ --json Emit structured JSON output
196
+ -h, --help Show help
197
+ `);
198
+ break;
199
+ case "mcp":
200
+ console.log(`Usage: geloforge mcp [serve] [--project <path>] [--read-only]
201
+ geloforge mcp init [--project <path>] [--client <name>] [--read-only] [--dry-run] [--json]
202
+
203
+ Runs GeloForge's zero-dependency JSON-RPC 2.0 MCP server on stdin/stdout.
204
+ Pins operations to the configured/current project root (when present).
205
+ Read-only tools: geloforge_status, geloforge_recommend, geloforge_context.
206
+ State-mutating tools (disabled by --read-only): geloforge_task (new/update/done/claim/release),
207
+ geloforge_checkpoint (create), geloforge_skills (draft/propose in quarantine only).
208
+ Privileged skill promote/rollback/keygen/sign actions remain strictly refused over MCP.
209
+
210
+ Options:
211
+ -p, --project <path> Trusted project root directory
212
+ --read-only Refuse all state-mutating MCP actions
213
+ -h, --help Show help
214
+
215
+ Init options:
216
+ --client <name> cursor, vscode, claude, or gemini (repeatable, defaults to all four)
217
+ --dry-run Preview project configuration and rule updates
218
+ --json Emit the list of planned or written files
219
+ `);
220
+ break;
221
+ case "handoff":
222
+ console.log(`Usage: geloforge handoff [--project <path>] [options]
223
+
224
+ Create Options:
225
+ -p, --project <path> Target project directory (auto-detected from CWD if omitted)
226
+ -t, --task <id> Target task ID (defaults to first active task if any)
227
+ --id <HANDOFF-NNNN> Explicit handoff ID (auto-assigned if omitted)
228
+ --from-role <role> Source agent role (default: developer)
229
+ --to-role <role> Receiving agent role (default: qa-security-reviewer)
230
+ --from-tool <name> Source AI tool label (e.g. "codex", "antigravity")
231
+ --to-tool <name> Target AI tool label (e.g. "gemini-cli", "claude-code")
232
+ --summary <text> Concise transfer summary
233
+ --next-action <text> Recommended next action
234
+ --completed <text> Completed item (repeatable)
235
+ --open <text> Remaining open item (repeatable)
236
+ --claim <text> Unverified agent claim (repeatable)
237
+ --blocker <text> Blocker description (repeatable)
238
+ --question <text> Open question (repeatable)
239
+ --risk <text> Unresolved risk (repeatable)
240
+ --evidence <EVID-NNNN> Evidence ID reference (repeatable)
241
+ --context-pack-ref <id> Associated CPACK-NNNN ID
242
+ --created-at <iso> ISO-8601 timestamp override
243
+ --dry-run Validate and preview without writing file
244
+ -o, --out <file> Custom safe output YAML path (default: handoffs/HANDOFF-NNNN-*.yaml)
245
+ --format <type> Stdout format: markdown (default), yaml, or json
246
+ --json Alias for --format json
247
+
248
+ Inspect Options:
249
+ --inspect <file> Validate and render an existing handoff YAML file
250
+ -h, --help Show help
251
+ `);
252
+ break;
253
+ case "task":
254
+ console.log(`Usage: geloforge task <new|update|done|claim|release|leases|list|show> [options]
255
+
256
+ Subcommands:
257
+ new Create a new schema-valid TASK-NNNN contract
258
+ update Update task status/priority/role cleanly in state
259
+ done Mark task completed, update state, and release active lease
260
+ claim Claim a cooperative multi-IDE task/file-scope lease
261
+ release Release an active task lease
262
+ leases List active (and optionally expired) multi-IDE leases
263
+ list List tasks under configured tasks_dir
264
+ show Show details for a specific TASK-NNNN contract
265
+
266
+ Common Options:
267
+ -p, --project <path> Target project directory (auto-detected from CWD if omitted)
268
+ --json Emit structured JSON output
269
+ -h, --help Show help
270
+
271
+ 'task new' / 'task update' / 'task done' Options:
272
+ --title <string> Task title (required for 'new', >= 3 chars)
273
+ --objective <string> Detailed task objective ('new')
274
+ --id <TASK-NNNN> Explicit task ID ('new')
275
+ -t, --task <TASK-NNNN> Target task ID ('update'/'done'/'show'/'claim'/'release')
276
+ --priority <level> low, medium (default), high, or critical
277
+ --role <role> orchestrator, researcher, software-architect, developer, qa-security-reviewer
278
+ --budget <profile> quick, working (default), or deep
279
+ --status <status> inbox, ready, active, blocked, in_review, completed, cancelled
280
+ --activate Add task to active_tasks in operational state
281
+ --criteria <text> Acceptance criterion ('new', repeatable)
282
+ --scope-in <text> In-scope item ('new', repeatable)
283
+ --scope-out <text> Out-of-scope item ('new', repeatable)
284
+ --input <relpath> Required project input file path ('new', repeatable)
285
+ --dep <TASK-NNNN> Dependency task ID ('new', repeatable)
286
+ --evidence <EVID-NNNN> Link verified evidence ID ('update'/'done', repeatable)
287
+ --require-evidence Refuse 'done' unless task has verified EVID-* check(s)
288
+ --created-by <name> Author label ('new')
289
+ --created-at <iso> ISO-8601 timestamp override
290
+ --dry-run Preview changes without writing disk
291
+
292
+ 'task claim' / 'task release' / 'task leases' Options:
293
+ --tool <name> Advisory IDE / agent tool label (e.g. "codex", "antigravity")
294
+ --session <id> Advisory session identifier label
295
+ --scope <path-prefix> Owned file/dir scope (repeatable; defaults to task scope_in)
296
+ --ttl <minutes> Lease TTL in minutes (1-1440, default: 120)
297
+ --force Override colliding active lease or ownership mismatch
298
+ --include-expired Include expired leases in 'leases' output
299
+ `);
300
+ break;
301
+ case "verify":
302
+ console.log(`Usage: geloforge verify [options] -- <command> [args...]
303
+
304
+ Run the explicit command from the project root. A successful check records verified
305
+ evidence, saves a checkpoint, and completes the task with --require-evidence.
306
+ A failed check saves draft evidence and leaves the task open for a retry.
307
+
308
+ Options:
309
+ -p, --project <path> Target project (auto-detected from CWD if omitted)
310
+ -t, --task <id> Task to finish (defaults to the sole active task)
311
+ --name <text> Evidence check name
312
+ --timeout <ms> Command timeout (50-600000, default 60000)
313
+ --tool <name> Cooperative lease tool label
314
+ --session <id> Cooperative lease session label
315
+ --dry-run Preview verification without running the command
316
+ --json Emit verification results
317
+ -h, --help Show help
318
+ `);
319
+ break;
320
+ case "evidence":
321
+ console.log(`Usage: geloforge evidence capture --task TASK-NNNN [options] -- <command> [args...]
322
+
323
+ Options:
324
+ -p, --project <path> Target project directory (auto-detected from CWD if omitted)
325
+ -t, --task <TASK-NNNN> Target task contract ID (required)
326
+ --name <string> Short check name (defaults to command executable)
327
+ --title <string> Manifest title override
328
+ --id <EVID-NNNN> Explicit evidence ID (auto-assigned if omitted)
329
+ --role <role> Producer role (default: developer)
330
+ --verified-by <label> Verifier label used ONLY when exit code === 0
331
+ --timeout <ms> Command timeout in ms (50-600000, default: 60000)
332
+ --no-link Do not attach EVID-NNNN to TASK-NNNN or project state
333
+ --created-at <iso> ISO-8601 timestamp override
334
+ --dry-run Preview manifest without executing command or writing files
335
+ --json Emit structured JSON output
336
+ -h, --help Show help
337
+
338
+ Safety & Accuracy Notes:
339
+ - Executes ONLY the explicit command after "--" with shell: false (no shell interpolation).
340
+ - Secret tokens/keys are redacted before persisting output or printing diagnostics.
341
+ - Exits 0 only when command exit code === 0 (writes draft EVID-NNNN and exits 1 on failures/timeouts).
342
+ `);
343
+ break;
344
+ case "skills":
345
+ console.log(`Usage: geloforge skills <subcommand> [options]
346
+
347
+ Discovery & Static Checks:
348
+ list List discovered portable skills across project (.agents/skills) and global dirs
349
+ show Inspect one skill's metadata, supporting resources, and instructions
350
+ validate Validate SKILL.md frontmatter, path/symlink/secret safety, and local links
351
+ lint Run static security and quality lint checks across discovered skills
352
+
353
+ Adaptive Skills Lifecycle (Evidence-Backed & Human-Authorized):
354
+ draft Draft a quarantined skill in proposals/skills/ from verified EVID/HANDOFF records
355
+ propose-update Propose an isolated update to an existing trusted skill with diff preview
356
+ keygen Generate an Ed25519 approver keypair (public key in repo, optional --pub-out external pin, private key external)
357
+ sign Sign an APPR-NNNN approval bound to content SHA-256, base SHA-256, & evidence
358
+ promote Promote a validated quarantined proposal after genuine authorization
359
+ history Inspect append-only revision ledger and snapshot integrity for a skill
360
+ rollback Restore an authorized verified snapshot revision (never bypasses approval)
361
+
362
+ Authorization Options for 'promote' & 'rollback':
363
+ --approval <APPR-NNNN> Verify cryptographic Ed25519 signature (recommended)
364
+ --public-key <file> Verify signature against an external pinned SPKI public key PEM
365
+ --mode pr-branch Commit isolated branch for protected-branch human PR review (not pushed)
366
+ --interactive Explicit TTY confirmation (convenience safeguard; weaker than Ed25519/PR)
367
+ (--approved-by is REFUSED: self-reported flags do not authorize promotion or rollback)
368
+
369
+ Common Options:
370
+ -p, --project <path> Target project directory (auto-detected from CWD if omitted)
371
+ --global-dir <path> Override global skills directory (default: GELOFORGE_SKILLS_DIR or ~/.geloforge/skills)
372
+ --include-drafts Include quarantined drafts under proposals/skills/ (never auto-trusted)
373
+ --strict In 'lint': fail on high/warning findings in addition to critical/error
374
+ --dry-run Preview lifecycle operation without mutating disk
375
+ --json Emit structured JSON output
376
+ -h, --help Show help
377
+ `);
378
+ break;
379
+ }
380
+ }
381
+
382
+ function handleInit(args) {
383
+ const parsed = parseArgs({
384
+ args,
385
+ options: {
386
+ name: { type: "string" },
387
+ slug: { type: "string" },
388
+ dest: { type: "string" },
389
+ owner: { type: "string" },
390
+ description: { type: "string" },
391
+ profile: { type: "string" },
392
+ "created-at": { type: "string" },
393
+ git: { type: "boolean", default: false },
394
+ "dry-run": { type: "boolean", default: false },
395
+ json: { type: "boolean", default: false },
396
+ help: { type: "boolean", short: "h", default: false },
397
+ },
398
+ strict: true,
399
+ allowPositionals: false,
400
+ });
401
+ if (parsed.values.help) {
402
+ printSubHelp("init");
403
+ return 0;
404
+ }
405
+ const res = bootstrapProject({
406
+ name: parsed.values.name,
407
+ slug: parsed.values.slug,
408
+ dest: parsed.values.dest,
409
+ owner: parsed.values.owner,
410
+ description: parsed.values.description,
411
+ profile: parsed.values.profile,
412
+ createdAt: parsed.values["created-at"],
413
+ git: parsed.values.git,
414
+ dryRun: parsed.values["dry-run"],
415
+ });
416
+ if (parsed.values.json) {
417
+ console.log(JSON.stringify(res, null, 2));
418
+ return 0;
419
+ }
420
+ console.log(res.dryRun ? "DRY RUN — No files created." : "Project Second Brain initialized successfully.");
421
+ console.log(`Project ID : ${res.projectId}`);
422
+ console.log(`Profile : ${res.profile ? `${res.profile} (${res.profileVersion})` : "none"}`);
423
+ console.log(`Destination : ${res.destDir}`);
424
+ console.log(`Files : ${res.files.length}`);
425
+ return 0;
426
+ }
427
+
428
+ function handleAdopt(args) {
429
+ const parsed = parseArgs({
430
+ args,
431
+ options: {
432
+ dest: { type: "string", short: "d" },
433
+ project: { type: "string", short: "p" },
434
+ name: { type: "string" },
435
+ slug: { type: "string" },
436
+ owner: { type: "string" },
437
+ description: { type: "string" },
438
+ profile: { type: "string" },
439
+ "tasks-dir": { type: "string" },
440
+ "evidence-dir": { type: "string" },
441
+ "with-agent-guides": { type: "boolean", default: false },
442
+ "created-at": { type: "string" },
443
+ "dry-run": { type: "boolean", default: false },
444
+ json: { type: "boolean", default: false },
445
+ help: { type: "boolean", short: "h", default: false },
446
+ },
447
+ strict: true,
448
+ allowPositionals: false,
449
+ });
450
+ if (parsed.values.help) {
451
+ printSubHelp("adopt");
452
+ return 0;
453
+ }
454
+ const dest = parsed.values.dest || parsed.values.project || process.cwd();
455
+ const res = adoptProject({
456
+ dest,
457
+ name: parsed.values.name,
458
+ slug: parsed.values.slug,
459
+ owner: parsed.values.owner,
460
+ description: parsed.values.description,
461
+ profile: parsed.values.profile,
462
+ tasksDir: parsed.values["tasks-dir"],
463
+ evidenceDir: parsed.values["evidence-dir"],
464
+ withAgentGuides: parsed.values["with-agent-guides"],
465
+ createdAt: parsed.values["created-at"],
466
+ dryRun: parsed.values["dry-run"],
467
+ harnessDir: HARNESS_DIR,
468
+ workspaceRoot: WORKSPACE_ROOT,
469
+ });
470
+ if (parsed.values.json) {
471
+ console.log(JSON.stringify(res, null, 2));
472
+ return 0;
473
+ }
474
+ console.log(res.dryRun ? "DRY RUN — No files written." : "Existing project adopted into GeloForge.");
475
+ console.log(`Project : ${res.projectName} (${res.projectId})`);
476
+ console.log(`Directory : ${res.destDir}`);
477
+ console.log(`Git Repo : ${res.gitDetected ? `yes (branch=${res.defaultBranch})` : "no"}`);
478
+ console.log(`Added Files : ${res.files.length}`);
479
+ for (const w of res.warnings) console.log(` - [WARN] ${w}`);
480
+ return 0;
481
+ }
482
+
483
+ function handleValidate(args) {
484
+ const parsed = parseArgs({
485
+ args,
486
+ options: {
487
+ project: { type: "string", short: "p" },
488
+ json: { type: "boolean", default: false },
489
+ help: { type: "boolean", short: "h", default: false },
490
+ },
491
+ strict: true,
492
+ allowPositionals: true,
493
+ });
494
+ if (parsed.values.help) {
495
+ printSubHelp("validate");
496
+ return 0;
497
+ }
498
+ const explicitTarget = parsed.values.project || parsed.positionals[0] || null;
499
+ const { projectDir } = resolveProjectDir({ project: explicitTarget, harnessDir: HARNESS_DIR });
500
+ const result = validateProject(projectDir);
501
+ if (parsed.values.json) {
502
+ console.log(JSON.stringify(result, null, 2));
503
+ return result.valid ? 0 : 1;
504
+ }
505
+ console.log(`Project Validation: ${result.valid ? "PASS" : "FAIL"}`);
506
+ console.log(`Compatibility : ${result.compatibilityStatus}`);
507
+ console.log(`Records Checked : ${result.recordCount}`);
508
+ console.log(`Markdown Checked : ${result.checkedMarkdownFiles}`);
509
+ for (const w of result.warnings) console.log(` - [WARN] ${w}`);
510
+ for (const e of result.errors) console.error(` - [ERR] ${e}`);
511
+ return result.valid ? 0 : 1;
512
+ }
513
+
514
+ function handleContext(args) {
515
+ const parsed = parseArgs({
516
+ args,
517
+ options: {
518
+ project: { type: "string", short: "p" },
519
+ task: { type: "string", short: "t" },
520
+ query: { type: "string", short: "q" },
521
+ profile: { type: "string" },
522
+ budget: { type: "string" },
523
+ map: { type: "boolean", default: false },
524
+ "map-budget": { type: "string" },
525
+ skills: { type: "boolean", default: false },
526
+ skill: { type: "string", multiple: true },
527
+ "skills-budget": { type: "string" },
528
+ "exclude-unverified": { type: "boolean", default: false },
529
+ "from-diff": { type: "boolean", default: false },
530
+ "include-completed": { type: "boolean", default: false },
531
+ format: { type: "string", default: "markdown" },
532
+ out: { type: "string", short: "o" },
533
+ "compiled-at": { type: "string" },
534
+ json: { type: "boolean", default: false },
535
+ help: { type: "boolean", short: "h", default: false },
536
+ },
537
+ strict: true,
538
+ allowPositionals: false,
539
+ });
540
+ if (parsed.values.help) {
541
+ printSubHelp("context");
542
+ return 0;
543
+ }
544
+ const format = parsed.values.json ? "json" : parsed.values.format;
545
+ if (format !== "markdown" && format !== "json") {
546
+ throw new Error(`Invalid --format "${format}". Expected "markdown" or "json".`);
547
+ }
548
+
549
+ let budgetNum;
550
+ if (parsed.values.budget !== undefined) {
551
+ if (!/^\d+$/.test(parsed.values.budget.trim())) {
552
+ throw new Error(`Invalid --budget "${parsed.values.budget}". Must be a positive integer.`);
553
+ }
554
+ budgetNum = Number.parseInt(parsed.values.budget.trim(), 10);
555
+ }
556
+
557
+ let mapBudgetNum;
558
+ if (parsed.values["map-budget"] !== undefined) {
559
+ if (!parsed.values.map) {
560
+ throw new Error("--map-budget requires --map.");
561
+ }
562
+ if (!/^\d+$/.test(parsed.values["map-budget"].trim())) {
563
+ throw new Error(`Invalid --map-budget "${parsed.values["map-budget"]}". Must be a positive integer.`);
564
+ }
565
+ mapBudgetNum = Number.parseInt(parsed.values["map-budget"].trim(), 10);
566
+ }
567
+
568
+ const pinnedSkills = parsed.values.skill || [];
569
+ const includeSkills = parsed.values.skills || pinnedSkills.length > 0;
570
+ let skillsBudgetNum;
571
+ if (parsed.values["skills-budget"] !== undefined) {
572
+ if (!includeSkills) {
573
+ throw new Error("--skills-budget requires --skills or --skill.");
574
+ }
575
+ if (!/^\d+$/.test(parsed.values["skills-budget"].trim())) {
576
+ throw new Error(`Invalid --skills-budget "${parsed.values["skills-budget"]}". Must be a positive integer.`);
577
+ }
578
+ skillsBudgetNum = Number.parseInt(parsed.values["skills-budget"].trim(), 10);
579
+ }
580
+
581
+ let resolvedOut = null;
582
+ if (parsed.values.out !== undefined) {
583
+ resolvedOut = validateOutputFilePath(parsed.values.out, {
584
+ harnessDir: HARNESS_DIR,
585
+ workspaceRoot: WORKSPACE_ROOT,
586
+ });
587
+ }
588
+
589
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
590
+ const result = compileContext({
591
+ projectDir,
592
+ taskId: parsed.values.task,
593
+ query: parsed.values.query,
594
+ profile: parsed.values.profile || "working",
595
+ budget: budgetNum,
596
+ includeMap: parsed.values.map,
597
+ mapBudget: mapBudgetNum,
598
+ includeSkills,
599
+ pinnedSkills,
600
+ skillsBudget: skillsBudgetNum,
601
+ excludeUnverified: parsed.values["exclude-unverified"],
602
+ fromDiff: parsed.values["from-diff"],
603
+ includeCompleted: parsed.values["include-completed"],
604
+ compiledAt: parsed.values["compiled-at"],
605
+ harnessDir: HARNESS_DIR,
606
+ });
607
+
608
+ const payload = format === "json" ? `${JSON.stringify(result, null, 2)}\n` : result.markdown;
609
+
610
+ if (resolvedOut) {
611
+ atomicWriteFile(resolvedOut, payload);
612
+ if (parsed.values.json) {
613
+ console.log(
614
+ JSON.stringify(
615
+ {
616
+ writtenTo: resolvedOut,
617
+ format,
618
+ manifest: result.manifest,
619
+ warnings: result.warnings,
620
+ },
621
+ null,
622
+ 2
623
+ )
624
+ );
625
+ } else {
626
+ console.log(`Context packet written to: ${resolvedOut}`);
627
+ console.log(
628
+ `Profile: ${result.manifest.profile} (effective: ${result.manifest.effective_profile}) | ~${result.estimatedTokens} est. tokens (${result.tokenEstimateMethod}) | Budget Overrun: ${result.budgetOverrun}`
629
+ );
630
+ for (const w of result.warnings) console.log(` - [WARN] ${w}`);
631
+ }
632
+ return 0;
633
+ }
634
+
635
+ process.stdout.write(payload);
636
+ return 0;
637
+ }
638
+
639
+ function handleStatus(args) {
640
+ const parsed = parseArgs({
641
+ args,
642
+ options: {
643
+ project: { type: "string", short: "p" },
644
+ json: { type: "boolean", default: false },
645
+ help: { type: "boolean", short: "h", default: false },
646
+ },
647
+ strict: true,
648
+ allowPositionals: true,
649
+ });
650
+ if (parsed.values.help) {
651
+ printSubHelp("status");
652
+ return 0;
653
+ }
654
+ const explicitTarget = parsed.values.project || parsed.positionals[0] || null;
655
+ const { projectDir } = resolveProjectDir({ project: explicitTarget, harnessDir: HARNESS_DIR });
656
+ const status = getProjectStatus(projectDir);
657
+ if (parsed.values.json) {
658
+ console.log(JSON.stringify(status, null, 2));
659
+ return 0;
660
+ }
661
+ console.log(`Project Status : ${status.valid ? "VALID" : "INVALID"} (${status.compatibilityStatus})`);
662
+ if (status.project) {
663
+ console.log(
664
+ `Project : ${status.project.name} (${status.project.id}) | profile=${status.project.profile || "none"} | schema=${status.project.schemaVersion}`
665
+ );
666
+ }
667
+ if (status.operationalState) {
668
+ const s = status.operationalState;
669
+ console.log(
670
+ `Operational : phase=${s.currentPhase} | active=${s.activeTasks.length} | blocked=${s.blockedTasks.length} | approvals=${s.pendingApprovals.length} | conflicts=${s.openConflicts.length}`
671
+ );
672
+ }
673
+ console.log(
674
+ `Git : ${
675
+ status.vcs.available
676
+ ? `branch=${status.vcs.branch || "detached"} | head=${status.vcs.head} | dirty=${status.vcs.dirtyCount}`
677
+ : "not a Git repository"
678
+ }`
679
+ );
680
+ console.log(`Counts : records=${status.counts.records} | markdown=${status.counts.markdownFiles} | errors=${status.counts.errors} | warnings=${status.counts.warnings}`);
681
+ if ((status.activeLeases || []).length > 0) {
682
+ console.log(
683
+ `Leases : ${status.activeLeases.map((l) => `${l.task_id} (${l.tool || "unknown"}/${l.role || "unassigned"})`).join(", ")}`
684
+ );
685
+ }
686
+ if ((status.pendingApprovalsInbox || []).length > 0) {
687
+ console.log(
688
+ `Approval Inbox : ${status.pendingApprovalsInbox.length} item(s) — ${status.pendingApprovalsInbox.map((i) => `${i.kind}:${i.id}`).join(", ")}`
689
+ );
690
+ }
691
+ if (Array.isArray(status.recommendations) && status.recommendations.length > 0) {
692
+ const topRec = status.recommendations[0];
693
+ console.log(`Recommendation : [${topRec.priority}] ${topRec.title} -> ${topRec.command}`);
694
+ }
695
+ if (Array.isArray(status.nextSteps) && status.nextSteps.length > 0) {
696
+ console.log(`Next Step : ${status.nextSteps[0]}`);
697
+ }
698
+ for (const w of status.warnings) console.log(` - [WARN] ${w}`);
699
+ for (const e of status.errors) console.error(` - [ERR] ${e}`);
700
+ return 0;
701
+ }
702
+
703
+ function handleRecommend(args) {
704
+ const parsed = parseArgs({
705
+ args,
706
+ options: {
707
+ project: { type: "string", short: "p" },
708
+ json: { type: "boolean", default: false },
709
+ help: { type: "boolean", short: "h", default: false },
710
+ },
711
+ strict: true,
712
+ allowPositionals: true,
713
+ });
714
+ if (parsed.values.help) {
715
+ printSubHelp("recommend");
716
+ return 0;
717
+ }
718
+ const explicitTarget = parsed.values.project || parsed.positionals[0] || null;
719
+ const { projectDir } = resolveProjectDir({ project: explicitTarget, harnessDir: HARNESS_DIR });
720
+ const rec = getProjectRecommendations(projectDir);
721
+ if (parsed.values.json) {
722
+ console.log(JSON.stringify(rec, null, 2));
723
+ return 0;
724
+ }
725
+ console.log(`Co-Pilot Recommend : ${rec.project ? `${rec.project.name} (${rec.project.id})` : rec.projectDir}`);
726
+ console.log(
727
+ `Approval Inbox : ${rec.pendingApprovalsInbox.length} pending item(s) | Active Leases: ${rec.activeLeases.length}`
728
+ );
729
+ if (rec.pendingApprovalsInbox.length > 0) {
730
+ console.log("\nPending Human Approvals:");
731
+ for (const item of rec.pendingApprovalsInbox) {
732
+ console.log(` - [${item.kind}] ${item.id} (${item.status}) — ${item.title}`);
733
+ console.log(` Action: ${item.approveHint}`);
734
+ }
735
+ }
736
+ if (rec.recommendations.length > 0) {
737
+ console.log("\nRanked Next Actions:");
738
+ for (const r of rec.recommendations) {
739
+ const gate = r.requiresHumanApproval ? " [HUMAN-APPROVAL]" : "";
740
+ console.log(` - [${r.priority.toUpperCase()}${gate}] ${r.title}`);
741
+ console.log(` Why : ${r.reason}`);
742
+ if (Array.isArray(r.options) && r.options.length > 0) {
743
+ console.log(` Options: ${r.options.join(" | ")}`);
744
+ }
745
+ console.log(` Run : ${r.command}`);
746
+ }
747
+ } else {
748
+ console.log(" (no pending actions)");
749
+ }
750
+ return 0;
751
+ }
752
+
753
+ function handleCheckpoint(args) {
754
+ if (args.length === 0 || args[0] === "-h" || args[0] === "--help") {
755
+ printSubHelp("checkpoint");
756
+ return 0;
757
+ }
758
+ const [subcmd, ...rest] = args;
759
+ if (subcmd === "create") {
760
+ const parsed = parseArgs({
761
+ args: rest,
762
+ options: {
763
+ project: { type: "string", short: "p" },
764
+ summary: { type: "string" },
765
+ resume: { type: "string" },
766
+ evidence: { type: "string" },
767
+ "created-by": { type: "string" },
768
+ role: { type: "string" },
769
+ status: { type: "string" },
770
+ id: { type: "string" },
771
+ "created-at": { type: "string" },
772
+ "dry-run": { type: "boolean", default: false },
773
+ json: { type: "boolean", default: false },
774
+ help: { type: "boolean", short: "h", default: false },
775
+ },
776
+ strict: true,
777
+ allowPositionals: false,
778
+ });
779
+ if (parsed.values.help) {
780
+ printSubHelp("checkpoint");
781
+ return 0;
782
+ }
783
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
784
+ const res = createCheckpoint({
785
+ projectDir,
786
+ harnessDir: HARNESS_DIR,
787
+ summary: parsed.values.summary,
788
+ resumeInstructions: parsed.values.resume,
789
+ evidenceRef: parsed.values.evidence,
790
+ createdBy: parsed.values["created-by"],
791
+ role: parsed.values.role,
792
+ status: parsed.values.status,
793
+ id: parsed.values.id,
794
+ createdAt: parsed.values["created-at"],
795
+ dryRun: parsed.values["dry-run"],
796
+ });
797
+ if (parsed.values.json) {
798
+ console.log(JSON.stringify(res, null, 2));
799
+ return 0;
800
+ }
801
+ console.log(res.dryRun ? `DRY RUN — Checkpoint ${res.checkpointId} not written.` : `Checkpoint created: ${res.recordPath}`);
802
+ console.log(`ID / State Rev : ${res.checkpointId} | state_revision=${res.stateRevision} | branch=${res.record.git_branch}`);
803
+ console.log(`Resume : ${res.record.resume_instructions}`);
804
+ return 0;
805
+ }
806
+
807
+ if (subcmd === "list") {
808
+ const parsed = parseArgs({
809
+ args: rest,
810
+ options: {
811
+ project: { type: "string", short: "p" },
812
+ status: { type: "string" },
813
+ json: { type: "boolean", default: false },
814
+ help: { type: "boolean", short: "h", default: false },
815
+ },
816
+ strict: true,
817
+ allowPositionals: false,
818
+ });
819
+ if (parsed.values.help) {
820
+ printSubHelp("checkpoint");
821
+ return 0;
822
+ }
823
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
824
+ const res = listCheckpoints({ projectDir, status: parsed.values.status, harnessDir: HARNESS_DIR });
825
+ if (parsed.values.json) {
826
+ console.log(JSON.stringify(res, null, 2));
827
+ return 0;
828
+ }
829
+ console.log(`Checkpoints (${res.count}) | latest=${res.lastCheckpointId || "none"}:`);
830
+ for (const c of res.checkpoints) {
831
+ console.log(` - ${c.id} [${c.status}] branch=${c.git_branch} rev=${c.state_revision} — ${c.resume_instructions}`);
832
+ }
833
+ return 0;
834
+ }
835
+
836
+ if (subcmd === "show") {
837
+ const parsed = parseArgs({
838
+ args: rest,
839
+ options: {
840
+ project: { type: "string", short: "p" },
841
+ id: { type: "string" },
842
+ json: { type: "boolean", default: false },
843
+ help: { type: "boolean", short: "h", default: false },
844
+ },
845
+ strict: true,
846
+ allowPositionals: true,
847
+ });
848
+ if (parsed.values.help) {
849
+ printSubHelp("checkpoint");
850
+ return 0;
851
+ }
852
+ const targetId = parsed.values.id || parsed.positionals[0] || null;
853
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
854
+ const res = getCheckpoint({ projectDir, checkpointId: targetId, harnessDir: HARNESS_DIR });
855
+ if (parsed.values.json) {
856
+ console.log(JSON.stringify(res, null, 2));
857
+ return 0;
858
+ }
859
+ console.log(`Checkpoint : ${res.checkpointId} (${res.record.status})${res.isLastCheckpoint ? " [LATEST]" : ""}`);
860
+ console.log(`File : ${res.recordPath}`);
861
+ console.log(`Git : ${res.record.git_branch} @ ${res.record.git_commit} (clean=${res.record.working_tree_clean})`);
862
+ console.log(`Active : ${(res.record.active_tasks || []).join(", ") || "(none)"}`);
863
+ console.log(`Resume : ${res.record.resume_instructions}`);
864
+ return 0;
865
+ }
866
+
867
+ throw new Error(`Unknown checkpoint subcommand "${subcmd}". Expected: create, list, or show.`);
868
+ }
869
+
870
+ function handleMcpInit(args) {
871
+ const { values } = parseArgs({
872
+ args,
873
+ options: {
874
+ project: { type: "string", short: "p" },
875
+ client: { type: "string", multiple: true },
876
+ "read-only": { type: "boolean" },
877
+ "dry-run": { type: "boolean" },
878
+ json: { type: "boolean" },
879
+ help: { type: "boolean", short: "h" },
880
+ },
881
+ });
882
+ if (values.help) {
883
+ printSubHelp("mcp");
884
+ return 0;
885
+ }
886
+ const { projectDir } = resolveProjectDir({ project: values.project, harnessDir: HARNESS_DIR });
887
+ const result = initMcpClients({
888
+ projectDir, harnessDir: HARNESS_DIR, clients: values.client,
889
+ readOnly: values["read-only"], dryRun: values["dry-run"],
890
+ });
891
+ if (values.json) {
892
+ console.log(JSON.stringify(result, null, 2));
893
+ } else {
894
+ console.log(result.dryRun ? `MCP setup preview for ${projectDir}` : `MCP setup for ${projectDir}`);
895
+ for (const file of result.files) console.log(` ${file.action.padEnd(10)} ${file.path}`);
896
+ }
897
+ return 0;
898
+ }
899
+
900
+ async function handleMcp(args) {
901
+ if (args[0] === "init") return handleMcpInit(args.slice(1));
902
+ let effectiveArgs = args;
903
+ if (args.length > 0 && (args[0] === "-h" || args[0] === "--help")) {
904
+ printSubHelp("mcp");
905
+ return 0;
906
+ }
907
+ if (args.length > 0 && args[0] === "serve") {
908
+ effectiveArgs = args.slice(1);
909
+ }
910
+ const parsed = parseArgs({
911
+ args: effectiveArgs,
912
+ options: {
913
+ project: { type: "string", short: "p" },
914
+ "read-only": { type: "boolean", default: false },
915
+ help: { type: "boolean", short: "h", default: false },
916
+ },
917
+ strict: true,
918
+ allowPositionals: false,
919
+ });
920
+ if (parsed.values.help) {
921
+ printSubHelp("mcp");
922
+ return 0;
923
+ }
924
+ let defaultProjectDir = null;
925
+ if (parsed.values.project) {
926
+ defaultProjectDir = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR }).projectDir;
927
+ }
928
+ await startMcpStdioServer({
929
+ defaultProjectDir,
930
+ harnessDir: HARNESS_DIR,
931
+ readOnly: parsed.values["read-only"],
932
+ });
933
+ return 0;
934
+ }
935
+
936
+ function handleHandoff(args) {
937
+ const parsed = parseArgs({
938
+ args,
939
+ options: {
940
+ project: { type: "string", short: "p" },
941
+ inspect: { type: "string" },
942
+ task: { type: "string", short: "t" },
943
+ id: { type: "string" },
944
+ "from-role": { type: "string" },
945
+ "to-role": { type: "string" },
946
+ "from-tool": { type: "string" },
947
+ "to-tool": { type: "string" },
948
+ status: { type: "string" },
949
+ summary: { type: "string" },
950
+ "next-action": { type: "string" },
951
+ completed: { type: "string", multiple: true },
952
+ open: { type: "string", multiple: true },
953
+ claim: { type: "string", multiple: true },
954
+ blocker: { type: "string", multiple: true },
955
+ question: { type: "string", multiple: true },
956
+ risk: { type: "string", multiple: true },
957
+ evidence: { type: "string", multiple: true },
958
+ "context-pack-ref": { type: "string" },
959
+ "created-at": { type: "string" },
960
+ "dry-run": { type: "boolean", default: false },
961
+ out: { type: "string", short: "o" },
962
+ format: { type: "string", default: "markdown" },
963
+ json: { type: "boolean", default: false },
964
+ help: { type: "boolean", short: "h", default: false },
965
+ },
966
+ strict: true,
967
+ allowPositionals: false,
968
+ });
969
+
970
+ if (parsed.values.help) {
971
+ printSubHelp("handoff");
972
+ return 0;
973
+ }
974
+
975
+ const format = parsed.values.json ? "json" : parsed.values.format;
976
+ if (format !== "markdown" && format !== "yaml" && format !== "json") {
977
+ throw new Error(`Invalid --format "${format}". Expected "markdown", "yaml", or "json".`);
978
+ }
979
+
980
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
981
+
982
+ if (parsed.values.inspect) {
983
+ const res = inspectHandoff({
984
+ projectDir,
985
+ handoffPath: parsed.values.inspect,
986
+ harnessDir: HARNESS_DIR,
987
+ });
988
+ if (format === "json") {
989
+ console.log(JSON.stringify(res, null, 2));
990
+ return res.valid ? 0 : 1;
991
+ }
992
+ if (format === "yaml") {
993
+ console.log(fs.readFileSync(res.filePath, "utf8"));
994
+ return res.valid ? 0 : 1;
995
+ }
996
+ console.log(`Handoff Inspection : ${res.valid ? "PASS" : "FAIL"} (${res.compatibilityStatus})`);
997
+ console.log(`File / ID / Schema : ${res.relPath} | ${res.id} | ${res.schemaVersion}`);
998
+ for (const w of res.warnings) console.log(` - [WARN] ${w}`);
999
+ for (const e of res.errors) console.error(` - [ERR] ${e}`);
1000
+ if (res.markdown) {
1001
+ console.log("");
1002
+ process.stdout.write(res.markdown);
1003
+ }
1004
+ return res.valid ? 0 : 1;
1005
+ }
1006
+
1007
+ const res = createHandoff({
1008
+ projectDir,
1009
+ taskId: parsed.values.task,
1010
+ id: parsed.values.id,
1011
+ fromRole: parsed.values["from-role"],
1012
+ toRole: parsed.values["to-role"],
1013
+ fromTool: parsed.values["from-tool"],
1014
+ toTool: parsed.values["to-tool"],
1015
+ status: parsed.values.status,
1016
+ summary: parsed.values.summary,
1017
+ nextAction: parsed.values["next-action"],
1018
+ completedItems: parsed.values.completed,
1019
+ openItems: parsed.values.open,
1020
+ unverifiedClaims: parsed.values.claim,
1021
+ blockers: parsed.values.blocker,
1022
+ openQuestions: parsed.values.question,
1023
+ unresolvedRisks: parsed.values.risk,
1024
+ evidenceRefs: parsed.values.evidence,
1025
+ contextPackRef: parsed.values["context-pack-ref"],
1026
+ createdAt: parsed.values["created-at"],
1027
+ dryRun: parsed.values["dry-run"],
1028
+ out: parsed.values.out,
1029
+ harnessDir: HARNESS_DIR,
1030
+ workspaceRoot: WORKSPACE_ROOT,
1031
+ });
1032
+
1033
+ if (format === "json") {
1034
+ console.log(JSON.stringify(res, null, 2));
1035
+ return 0;
1036
+ }
1037
+ if (format === "yaml") {
1038
+ process.stdout.write(res.yaml);
1039
+ return 0;
1040
+ }
1041
+ console.log(res.dryRun ? `DRY RUN — Handoff ${res.id} not written.` : `Handoff created: ${res.filePath}`);
1042
+ for (const w of res.warnings) console.log(` - [WARN] ${w}`);
1043
+ console.log("");
1044
+ process.stdout.write(res.markdown);
1045
+ return 0;
1046
+ }
1047
+
1048
+ function handleTask(args) {
1049
+ if (args.length === 0 || args[0] === "-h" || args[0] === "--help") {
1050
+ printSubHelp("task");
1051
+ return 0;
1052
+ }
1053
+ const [subcmd, ...rest] = args;
1054
+ if (subcmd === "new") {
1055
+ const parsed = parseArgs({
1056
+ args: rest,
1057
+ options: {
1058
+ project: { type: "string", short: "p" },
1059
+ title: { type: "string" },
1060
+ objective: { type: "string" },
1061
+ id: { type: "string" },
1062
+ priority: { type: "string" },
1063
+ role: { type: "string" },
1064
+ budget: { type: "string" },
1065
+ status: { type: "string" },
1066
+ activate: { type: "boolean", default: false },
1067
+ criteria: { type: "string", multiple: true },
1068
+ "scope-in": { type: "string", multiple: true },
1069
+ "scope-out": { type: "string", multiple: true },
1070
+ output: { type: "string", multiple: true },
1071
+ input: { type: "string", multiple: true },
1072
+ dep: { type: "string", multiple: true },
1073
+ "created-by": { type: "string" },
1074
+ "created-at": { type: "string" },
1075
+ "dry-run": { type: "boolean", default: false },
1076
+ json: { type: "boolean", default: false },
1077
+ help: { type: "boolean", short: "h", default: false },
1078
+ },
1079
+ strict: true,
1080
+ allowPositionals: false,
1081
+ });
1082
+ if (parsed.values.help) {
1083
+ printSubHelp("task");
1084
+ return 0;
1085
+ }
1086
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
1087
+ const res = createTask({
1088
+ projectDir,
1089
+ harnessDir: HARNESS_DIR,
1090
+ title: parsed.values.title,
1091
+ objective: parsed.values.objective,
1092
+ id: parsed.values.id,
1093
+ priority: parsed.values.priority,
1094
+ assignedRole: parsed.values.role,
1095
+ contextBudget: parsed.values.budget,
1096
+ status: parsed.values.status,
1097
+ activate: parsed.values.activate,
1098
+ acceptanceCriteria: parsed.values.criteria,
1099
+ scopeIn: parsed.values["scope-in"],
1100
+ scopeOut: parsed.values["scope-out"],
1101
+ expectedOutputs: parsed.values.output,
1102
+ requiredInputs: parsed.values.input,
1103
+ dependencies: parsed.values.dep,
1104
+ createdBy: parsed.values["created-by"],
1105
+ createdAt: parsed.values["created-at"],
1106
+ dryRun: parsed.values["dry-run"],
1107
+ });
1108
+ if (parsed.values.json) {
1109
+ console.log(JSON.stringify(res, null, 2));
1110
+ return 0;
1111
+ }
1112
+ console.log(res.dryRun ? `DRY RUN — Task ${res.id} not written.` : `Task created: ${res.relPath}`);
1113
+ console.log(`ID / Status : ${res.id} (${res.record.status}) | activated=${res.activated}`);
1114
+ console.log(`Title : ${res.record.title}`);
1115
+ return 0;
1116
+ }
1117
+
1118
+ if (subcmd === "list") {
1119
+ const parsed = parseArgs({
1120
+ args: rest,
1121
+ options: {
1122
+ project: { type: "string", short: "p" },
1123
+ status: { type: "string" },
1124
+ json: { type: "boolean", default: false },
1125
+ help: { type: "boolean", short: "h", default: false },
1126
+ },
1127
+ strict: true,
1128
+ allowPositionals: false,
1129
+ });
1130
+ if (parsed.values.help) {
1131
+ printSubHelp("task");
1132
+ return 0;
1133
+ }
1134
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
1135
+ const res = listTasks({ projectDir, status: parsed.values.status, harnessDir: HARNESS_DIR });
1136
+ if (parsed.values.json) {
1137
+ console.log(JSON.stringify(res, null, 2));
1138
+ return 0;
1139
+ }
1140
+ console.log(`Tasks in ${res.tasksDir}/ (${res.tasks.length}):`);
1141
+ if (res.tasks.length === 0) {
1142
+ console.log(" (none yet — run: geloforge task new --title \"...\")");
1143
+ } else {
1144
+ for (const t of res.tasks) {
1145
+ console.log(
1146
+ ` - ${t.id} [${t.status}${t.activeInState ? ", active-in-state" : ""}] (${t.priority}, evid=${t.evidenceCount}) — ${t.title}`
1147
+ );
1148
+ }
1149
+ }
1150
+ return 0;
1151
+ }
1152
+
1153
+ if (subcmd === "show") {
1154
+ const parsed = parseArgs({
1155
+ args: rest,
1156
+ options: {
1157
+ project: { type: "string", short: "p" },
1158
+ task: { type: "string", short: "t" },
1159
+ json: { type: "boolean", default: false },
1160
+ help: { type: "boolean", short: "h", default: false },
1161
+ },
1162
+ strict: true,
1163
+ allowPositionals: true,
1164
+ });
1165
+ if (parsed.values.help) {
1166
+ printSubHelp("task");
1167
+ return 0;
1168
+ }
1169
+ const targetId = parsed.values.task || parsed.positionals[0];
1170
+ if (!targetId) {
1171
+ throw new Error("Missing task ID for 'geloforge task show <TASK-NNNN>'.");
1172
+ }
1173
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
1174
+ const res = getTask({ projectDir, taskId: targetId, harnessDir: HARNESS_DIR });
1175
+ if (parsed.values.json) {
1176
+ console.log(JSON.stringify(res, null, 2));
1177
+ return 0;
1178
+ }
1179
+ console.log(`Task : ${res.id} (${res.record.status})`);
1180
+ console.log(`File : ${res.relPath}`);
1181
+ console.log(`Title : ${res.record.title}`);
1182
+ console.log(`Objective : ${res.record.objective}`);
1183
+ console.log(`Evidence : ${(res.record.evidence_refs || []).join(", ") || "(none)"}`);
1184
+ return 0;
1185
+ }
1186
+
1187
+ if (subcmd === "update" || subcmd === "done") {
1188
+ const parsed = parseArgs({
1189
+ args: rest,
1190
+ options: {
1191
+ project: { type: "string", short: "p" },
1192
+ task: { type: "string", short: "t" },
1193
+ id: { type: "string" },
1194
+ status: { type: "string" },
1195
+ priority: { type: "string" },
1196
+ role: { type: "string" },
1197
+ activate: { type: "boolean", default: false },
1198
+ evidence: { type: "string", multiple: true },
1199
+ "require-evidence": { type: "boolean", default: false },
1200
+ tool: { type: "string" },
1201
+ session: { type: "string" },
1202
+ force: { type: "boolean", default: false },
1203
+ "created-at": { type: "string" },
1204
+ "dry-run": { type: "boolean", default: false },
1205
+ json: { type: "boolean", default: false },
1206
+ help: { type: "boolean", short: "h", default: false },
1207
+ },
1208
+ strict: true,
1209
+ allowPositionals: true,
1210
+ });
1211
+ if (parsed.values.help) {
1212
+ printSubHelp("task");
1213
+ return 0;
1214
+ }
1215
+ const targetId = parsed.values.task || parsed.values.id || parsed.positionals[0];
1216
+ if (!targetId) {
1217
+ throw new Error(`Missing task ID for 'geloforge task ${subcmd} <TASK-NNNN>'.`);
1218
+ }
1219
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
1220
+ const res =
1221
+ subcmd === "done"
1222
+ ? completeTask({
1223
+ projectDir,
1224
+ harnessDir: HARNESS_DIR,
1225
+ taskId: targetId,
1226
+ evidenceRefs: parsed.values.evidence,
1227
+ requireEvidence: parsed.values["require-evidence"],
1228
+ tool: parsed.values.tool,
1229
+ sessionId: parsed.values.session,
1230
+ force: parsed.values.force,
1231
+ updatedAt: parsed.values["created-at"],
1232
+ dryRun: parsed.values["dry-run"],
1233
+ })
1234
+ : updateTask({
1235
+ projectDir,
1236
+ harnessDir: HARNESS_DIR,
1237
+ taskId: targetId,
1238
+ status: parsed.values.status,
1239
+ priority: parsed.values.priority,
1240
+ assignedRole: parsed.values.role,
1241
+ activate: parsed.values.activate,
1242
+ evidenceRefs: parsed.values.evidence,
1243
+ requireEvidence: parsed.values["require-evidence"],
1244
+ tool: parsed.values.tool,
1245
+ sessionId: parsed.values.session,
1246
+ force: parsed.values.force,
1247
+ updatedAt: parsed.values["created-at"],
1248
+ dryRun: parsed.values["dry-run"],
1249
+ });
1250
+ if (parsed.values.json) {
1251
+ console.log(JSON.stringify(res, null, 2));
1252
+ return 0;
1253
+ }
1254
+ console.log(
1255
+ res.dryRun
1256
+ ? `DRY RUN — Task ${res.id} not updated.`
1257
+ : `Task updated: ${res.id} (${res.previousStatus} -> ${res.status}) | state_revision=${res.stateRevision}`
1258
+ );
1259
+ if (res.status === "completed") {
1260
+ const evLabel =
1261
+ (res.verifiedEvidenceRefs || []).length > 0 ? res.verifiedEvidenceRefs.join(", ") : "no verified EVID-* check";
1262
+ console.log(`Verification : ${res.verificationStatus} (${evLabel})`);
1263
+ }
1264
+ for (const w of res.warnings || []) console.log(` - [WARN] ${w}`);
1265
+ return 0;
1266
+ }
1267
+
1268
+ if (subcmd === "claim") {
1269
+ const parsed = parseArgs({
1270
+ args: rest,
1271
+ options: {
1272
+ project: { type: "string", short: "p" },
1273
+ task: { type: "string", short: "t" },
1274
+ id: { type: "string" },
1275
+ role: { type: "string" },
1276
+ tool: { type: "string" },
1277
+ session: { type: "string" },
1278
+ scope: { type: "string", multiple: true },
1279
+ ttl: { type: "string" },
1280
+ force: { type: "boolean", default: false },
1281
+ "created-at": { type: "string" },
1282
+ "dry-run": { type: "boolean", default: false },
1283
+ json: { type: "boolean", default: false },
1284
+ help: { type: "boolean", short: "h", default: false },
1285
+ },
1286
+ strict: true,
1287
+ allowPositionals: true,
1288
+ });
1289
+ if (parsed.values.help) {
1290
+ printSubHelp("task");
1291
+ return 0;
1292
+ }
1293
+ const targetId = parsed.values.task || parsed.values.id || parsed.positionals[0];
1294
+ if (!targetId) {
1295
+ throw new Error("Missing task ID for 'geloforge task claim <TASK-NNNN>'.");
1296
+ }
1297
+ let ttlMinutes;
1298
+ if (parsed.values.ttl !== undefined) {
1299
+ if (!/^\d+$/.test(parsed.values.ttl.trim())) {
1300
+ throw new Error(`Invalid --ttl "${parsed.values.ttl}". Must be a positive integer.`);
1301
+ }
1302
+ ttlMinutes = Number.parseInt(parsed.values.ttl.trim(), 10);
1303
+ }
1304
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
1305
+ const res = claimTaskLease({
1306
+ projectDir,
1307
+ harnessDir: HARNESS_DIR,
1308
+ taskId: targetId,
1309
+ role: parsed.values.role,
1310
+ tool: parsed.values.tool,
1311
+ sessionId: parsed.values.session,
1312
+ scopes: parsed.values.scope,
1313
+ ttlMinutes,
1314
+ force: parsed.values.force,
1315
+ createdAt: parsed.values["created-at"],
1316
+ dryRun: parsed.values["dry-run"],
1317
+ });
1318
+ if (parsed.values.json) {
1319
+ console.log(JSON.stringify(res, null, 2));
1320
+ return 0;
1321
+ }
1322
+ console.log(res.dryRun ? `DRY RUN — Lease for ${res.lease.task_id} not written.` : `Lease claimed: ${res.lease.task_id} (${res.leasesRelPath})`);
1323
+ console.log(`Tool / Role : ${res.lease.tool} / ${res.lease.role} | expires=${res.lease.expires_at}`);
1324
+ console.log(`Scopes : ${(res.lease.claimed_scope || []).join(", ") || "(none)"}`);
1325
+ return 0;
1326
+ }
1327
+
1328
+ if (subcmd === "release") {
1329
+ const parsed = parseArgs({
1330
+ args: rest,
1331
+ options: {
1332
+ project: { type: "string", short: "p" },
1333
+ task: { type: "string", short: "t" },
1334
+ id: { type: "string" },
1335
+ tool: { type: "string" },
1336
+ session: { type: "string" },
1337
+ role: { type: "string" },
1338
+ force: { type: "boolean", default: false },
1339
+ "created-at": { type: "string" },
1340
+ "dry-run": { type: "boolean", default: false },
1341
+ json: { type: "boolean", default: false },
1342
+ help: { type: "boolean", short: "h", default: false },
1343
+ },
1344
+ strict: true,
1345
+ allowPositionals: true,
1346
+ });
1347
+ if (parsed.values.help) {
1348
+ printSubHelp("task");
1349
+ return 0;
1350
+ }
1351
+ const targetId = parsed.values.task || parsed.values.id || parsed.positionals[0];
1352
+ if (!targetId) {
1353
+ throw new Error("Missing task ID for 'geloforge task release <TASK-NNNN>'.");
1354
+ }
1355
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
1356
+ const res = releaseTaskLease({
1357
+ projectDir,
1358
+ harnessDir: HARNESS_DIR,
1359
+ taskId: targetId,
1360
+ tool: parsed.values.tool,
1361
+ sessionId: parsed.values.session,
1362
+ role: parsed.values.role,
1363
+ force: parsed.values.force,
1364
+ nowIso: parsed.values["created-at"],
1365
+ dryRun: parsed.values["dry-run"],
1366
+ });
1367
+ if (parsed.values.json) {
1368
+ console.log(JSON.stringify(res, null, 2));
1369
+ return 0;
1370
+ }
1371
+ console.log(
1372
+ res.dryRun
1373
+ ? `DRY RUN — Release check for ${res.taskId}.`
1374
+ : res.released
1375
+ ? `Lease released: ${res.taskId}`
1376
+ : `No active lease found for ${res.taskId}`
1377
+ );
1378
+ return 0;
1379
+ }
1380
+
1381
+ if (subcmd === "leases") {
1382
+ const parsed = parseArgs({
1383
+ args: rest,
1384
+ options: {
1385
+ project: { type: "string", short: "p" },
1386
+ "include-expired": { type: "boolean", default: false },
1387
+ "created-at": { type: "string" },
1388
+ json: { type: "boolean", default: false },
1389
+ help: { type: "boolean", short: "h", default: false },
1390
+ },
1391
+ strict: true,
1392
+ allowPositionals: false,
1393
+ });
1394
+ if (parsed.values.help) {
1395
+ printSubHelp("task");
1396
+ return 0;
1397
+ }
1398
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
1399
+ const res = listTaskLeases({
1400
+ projectDir,
1401
+ includeExpired: parsed.values["include-expired"],
1402
+ nowIso: parsed.values["created-at"],
1403
+ harnessDir: HARNESS_DIR,
1404
+ });
1405
+ if (parsed.values.json) {
1406
+ console.log(JSON.stringify(res, null, 2));
1407
+ return 0;
1408
+ }
1409
+ console.log(`Task Leases (${res.activeLeases.length} active, ${res.expiredLeases.length} expired):`);
1410
+ for (const l of res.leases) {
1411
+ console.log(
1412
+ ` - ${l.task_id} [${l.tool}/${l.role}] expires=${l.expires_at} scopes=[${(l.claimed_scope || []).join(", ")}]`
1413
+ );
1414
+ }
1415
+ return 0;
1416
+ }
1417
+
1418
+ throw new Error(`Unknown task subcommand "${subcmd}". Expected: new, update, done, claim, release, leases, list, or show.`);
1419
+ }
1420
+
1421
+ function splitCheckArguments(args) {
1422
+ const dash = args.indexOf("--");
1423
+ return dash === -1 ? { options: args, command: [] } : { options: args.slice(0, dash), command: args.slice(dash + 1) };
1424
+ }
1425
+
1426
+ function parseCheckTimeout(value) {
1427
+ if (value === undefined) return undefined;
1428
+ if (!/^\d+$/.test(value.trim())) throw new Error(`Invalid --timeout "${value}". Must be a positive integer.`);
1429
+ return Number.parseInt(value.trim(), 10);
1430
+ }
1431
+
1432
+ function handleVerify(args) {
1433
+ const { options, command } = splitCheckArguments(args);
1434
+ const { values } = parseArgs({
1435
+ args: options,
1436
+ options: {
1437
+ project: { type: "string", short: "p" },
1438
+ task: { type: "string", short: "t" },
1439
+ name: { type: "string" },
1440
+ timeout: { type: "string" },
1441
+ tool: { type: "string" },
1442
+ session: { type: "string" },
1443
+ "dry-run": { type: "boolean" },
1444
+ json: { type: "boolean" },
1445
+ help: { type: "boolean", short: "h" },
1446
+ },
1447
+ });
1448
+ if (!args.length || values.help) {
1449
+ printSubHelp("verify");
1450
+ return 0;
1451
+ }
1452
+ if (!command.length) throw new Error('Pass a command after "--". Example: geloforge verify -- node --test');
1453
+ const { projectDir } = resolveProjectDir({ project: values.project, harnessDir: HARNESS_DIR });
1454
+ const result = verifyTask({
1455
+ projectDir, harnessDir: HARNESS_DIR, taskId: values.task, commandArgv: command,
1456
+ name: values.name, timeoutMs: parseCheckTimeout(values.timeout),
1457
+ tool: values.tool, sessionId: values.session, dryRun: values["dry-run"],
1458
+ });
1459
+ if (values.json) {
1460
+ console.log(JSON.stringify(result, null, 2));
1461
+ } else if (result.status === "dry_run") {
1462
+ console.log(`Would check ${result.taskId} with ${result.evidence.command}`);
1463
+ } else {
1464
+ console.log(`${result.evidence.id} ${result.evidence.status} for ${result.taskId}`);
1465
+ if (result.checkpoint) console.log(`${result.checkpoint.checkpointId} saved`);
1466
+ if (result.completion) {
1467
+ console.log(`${result.taskId} completed with verified evidence`);
1468
+ for (const warning of result.completion.warnings) console.log(` [WARN] ${warning}`);
1469
+ } else {
1470
+ console.error(result.error || result.evidence.record.checks[0].summary);
1471
+ }
1472
+ }
1473
+ return ["completed", "dry_run"].includes(result.status) ? 0 : 1;
1474
+ }
1475
+
1476
+ function handleEvidence(args) {
1477
+ if (args.length === 0 || args[0] === "-h" || args[0] === "--help") {
1478
+ printSubHelp("evidence");
1479
+ return 0;
1480
+ }
1481
+ const [subcmd, ...rest] = args;
1482
+ if (subcmd !== "capture") {
1483
+ throw new Error(`Unknown evidence subcommand "${subcmd}". Expected: capture.`);
1484
+ }
1485
+
1486
+ const { options, command } = splitCheckArguments(rest);
1487
+
1488
+ const parsed = parseArgs({
1489
+ args: options,
1490
+ options: {
1491
+ project: { type: "string", short: "p" },
1492
+ task: { type: "string", short: "t" },
1493
+ name: { type: "string" },
1494
+ title: { type: "string" },
1495
+ id: { type: "string" },
1496
+ role: { type: "string" },
1497
+ "verified-by": { type: "string" },
1498
+ timeout: { type: "string" },
1499
+ "no-link": { type: "boolean", default: false },
1500
+ "created-at": { type: "string" },
1501
+ "dry-run": { type: "boolean", default: false },
1502
+ json: { type: "boolean", default: false },
1503
+ help: { type: "boolean", short: "h", default: false },
1504
+ },
1505
+ strict: true,
1506
+ allowPositionals: false,
1507
+ });
1508
+ if (parsed.values.help) {
1509
+ printSubHelp("evidence");
1510
+ return 0;
1511
+ }
1512
+
1513
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
1514
+ const res = captureEvidence({
1515
+ projectDir,
1516
+ harnessDir: HARNESS_DIR,
1517
+ taskId: parsed.values.task,
1518
+ name: parsed.values.name,
1519
+ title: parsed.values.title,
1520
+ id: parsed.values.id,
1521
+ producedByRole: parsed.values.role,
1522
+ verifiedBy: parsed.values["verified-by"],
1523
+ timeoutMs: parseCheckTimeout(parsed.values.timeout),
1524
+ linkTask: !parsed.values["no-link"],
1525
+ createdAt: parsed.values["created-at"],
1526
+ dryRun: parsed.values["dry-run"],
1527
+ commandArgv: command,
1528
+ });
1529
+
1530
+ if (parsed.values.json) {
1531
+ console.log(JSON.stringify(res, null, 2));
1532
+ return res.dryRun || res.verified ? 0 : 1;
1533
+ }
1534
+
1535
+ console.log(
1536
+ res.dryRun
1537
+ ? `DRY RUN — Evidence ${res.id} not written.`
1538
+ : `Evidence recorded: ${res.relPath} (status=${res.status}, check=${res.checkResult})`
1539
+ );
1540
+ console.log(`Task / Cmd : ${res.taskId} | ${res.command}`);
1541
+ console.log(`Duration : ${res.durationMs}ms | exit=${res.exitCode ?? "n/a"} | linked=${res.linkedToTask}`);
1542
+ return res.dryRun || res.verified ? 0 : 1;
1543
+ }
1544
+
1545
+ function summarizeSkillForJson(skill) {
1546
+ return {
1547
+ name: skill.name,
1548
+ folderName: skill.folderName,
1549
+ source: skill.source,
1550
+ trustTier: skill.trustTier,
1551
+ trusted: skill.trusted,
1552
+ valid: skill.valid,
1553
+ blocked: skill.blocked,
1554
+ hasSecrets: skill.hasSecrets,
1555
+ displayPath: skill.displayPath,
1556
+ contentDigest: skill.contentDigest,
1557
+ estimatedTokens: skill.estimatedTokens,
1558
+ description: skill.hasSecrets
1559
+ ? "[REDACTED]"
1560
+ : typeof skill.frontmatter?.description === "string"
1561
+ ? skill.frontmatter.description
1562
+ : null,
1563
+ tags: skill.tags,
1564
+ triggers: skill.triggers,
1565
+ resources: skill.resources,
1566
+ errors: skill.errors,
1567
+ warnings: skill.warnings,
1568
+ };
1569
+ }
1570
+
1571
+ async function promptTtyAuthorization({ action, skillName, targetRevision, contentSha256, expectedInput }) {
1572
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
1573
+ throw new Error(
1574
+ "--interactive requires a real interactive terminal (TTY). Use --approval <APPR-NNNN> or --mode pr-branch in non-interactive sessions."
1575
+ );
1576
+ }
1577
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1578
+ try {
1579
+ console.log("");
1580
+ console.log(
1581
+ "Local Interactive Authorization (CONVENIENCE SAFEGUARD ONLY — weaker than Ed25519 signatures or protected-branch PR reviews):"
1582
+ );
1583
+ console.log(` Action : ${action}${targetRevision ? ` (${targetRevision})` : ""}`);
1584
+ console.log(` Skill : ${skillName}`);
1585
+ console.log(` Digest : ${contentSha256}`);
1586
+ const answer = await rl.question(`Type exact phrase "${expectedInput}" to authorize: `);
1587
+ return answer.trim() === expectedInput;
1588
+ } finally {
1589
+ rl.close();
1590
+ }
1591
+ }
1592
+
1593
+ async function handleSkillsLifecycle(subcmd, rest) {
1594
+ if (subcmd === "draft") {
1595
+ const parsed = parseArgs({
1596
+ args: rest,
1597
+ options: {
1598
+ project: { type: "string", short: "p" },
1599
+ "from-evidence": { type: "string", multiple: true },
1600
+ evidence: { type: "string", multiple: true },
1601
+ "from-handoff": { type: "string", multiple: true },
1602
+ handoff: { type: "string", multiple: true },
1603
+ name: { type: "string" },
1604
+ title: { type: "string" },
1605
+ description: { type: "string" },
1606
+ step: { type: "string", multiple: true },
1607
+ tag: { type: "string", multiple: true },
1608
+ trigger: { type: "string", multiple: true },
1609
+ "created-at": { type: "string" },
1610
+ "dry-run": { type: "boolean", default: false },
1611
+ json: { type: "boolean", default: false },
1612
+ help: { type: "boolean", short: "h", default: false },
1613
+ },
1614
+ strict: true,
1615
+ allowPositionals: false,
1616
+ });
1617
+ if (parsed.values.help) {
1618
+ printSubHelp("skills");
1619
+ return 0;
1620
+ }
1621
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
1622
+ const res = draftSkillFromExperience({
1623
+ projectDir,
1624
+ harnessDir: HARNESS_DIR,
1625
+ evidenceIds: [...(parsed.values["from-evidence"] || []), ...(parsed.values.evidence || [])],
1626
+ handoffIds: [...(parsed.values["from-handoff"] || []), ...(parsed.values.handoff || [])],
1627
+ skillName: parsed.values.name,
1628
+ title: parsed.values.title,
1629
+ description: parsed.values.description,
1630
+ steps: parsed.values.step,
1631
+ tags: parsed.values.tag,
1632
+ triggers: parsed.values.trigger,
1633
+ createdAt: parsed.values["created-at"],
1634
+ dryRun: parsed.values["dry-run"],
1635
+ });
1636
+ if (parsed.values.json) {
1637
+ console.log(JSON.stringify(res, null, 2));
1638
+ return 0;
1639
+ }
1640
+ console.log(res.dryRun ? `DRY RUN — Quarantined draft "${res.skillName}" not written.` : `Skill draft created (QUARANTINED): ${res.proposalDir}/SKILL.md`);
1641
+ console.log(`Candidate SHA : ${res.candidateDigest}`);
1642
+ console.log(`Provenance : ${res.evidenceDigests.join(", ")}`);
1643
+ for (const w of res.stalenessWarnings) console.log(` - [WARN] ${w}`);
1644
+ return 0;
1645
+ }
1646
+
1647
+ if (subcmd === "propose-update") {
1648
+ const parsed = parseArgs({
1649
+ args: rest,
1650
+ options: {
1651
+ project: { type: "string", short: "p" },
1652
+ name: { type: "string" },
1653
+ "from-evidence": { type: "string", multiple: true },
1654
+ evidence: { type: "string", multiple: true },
1655
+ "from-handoff": { type: "string", multiple: true },
1656
+ handoff: { type: "string", multiple: true },
1657
+ reason: { type: "string" },
1658
+ "patch-file": { type: "string" },
1659
+ "append-note": { type: "string" },
1660
+ "created-at": { type: "string" },
1661
+ "dry-run": { type: "boolean", default: false },
1662
+ json: { type: "boolean", default: false },
1663
+ help: { type: "boolean", short: "h", default: false },
1664
+ },
1665
+ strict: true,
1666
+ allowPositionals: true,
1667
+ });
1668
+ if (parsed.values.help) {
1669
+ printSubHelp("skills");
1670
+ return 0;
1671
+ }
1672
+ const targetName = parsed.values.name || parsed.positionals[0];
1673
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
1674
+ const res = proposeSkillUpdate({
1675
+ projectDir,
1676
+ harnessDir: HARNESS_DIR,
1677
+ skillName: targetName,
1678
+ evidenceIds: [...(parsed.values["from-evidence"] || []), ...(parsed.values.evidence || [])],
1679
+ handoffIds: [...(parsed.values["from-handoff"] || []), ...(parsed.values.handoff || [])],
1680
+ reason: parsed.values.reason,
1681
+ patchFile: parsed.values["patch-file"],
1682
+ appendNote: parsed.values["append-note"],
1683
+ createdAt: parsed.values["created-at"],
1684
+ dryRun: parsed.values["dry-run"],
1685
+ });
1686
+ if (parsed.values.json) {
1687
+ console.log(JSON.stringify(res, null, 2));
1688
+ return 0;
1689
+ }
1690
+ console.log(res.dryRun ? `DRY RUN — Update proposal for "${res.skillName}" not written.` : `Update proposal staged (QUARANTINED): ${res.proposalDir}/SKILL.md`);
1691
+ console.log(`Base / Cand : ${res.baseSkillDigest.slice(0, 19)} -> ${res.candidateDigest.slice(0, 19)} (${res.diffSummary})`);
1692
+ console.log(`Provenance : ${res.evidenceDigests.join(", ")}`);
1693
+ for (const w of res.stalenessWarnings) console.log(` - [WARN] ${w}`);
1694
+ return 0;
1695
+ }
1696
+
1697
+ if (subcmd === "keygen") {
1698
+ const parsed = parseArgs({
1699
+ args: rest,
1700
+ options: {
1701
+ project: { type: "string", short: "p" },
1702
+ approver: { type: "string" },
1703
+ out: { type: "string", short: "o" },
1704
+ "pub-out": { type: "string" },
1705
+ "created-at": { type: "string" },
1706
+ json: { type: "boolean", default: false },
1707
+ help: { type: "boolean", short: "h", default: false },
1708
+ },
1709
+ strict: true,
1710
+ allowPositionals: false,
1711
+ });
1712
+ if (parsed.values.help) {
1713
+ printSubHelp("skills");
1714
+ return 0;
1715
+ }
1716
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
1717
+ const res = generateApproverKeypair({
1718
+ projectDir,
1719
+ harnessDir: HARNESS_DIR,
1720
+ workspaceRoot: WORKSPACE_ROOT,
1721
+ approverId: parsed.values.approver,
1722
+ privateKeyOut: parsed.values.out,
1723
+ publicKeyOut: parsed.values["pub-out"],
1724
+ createdAt: parsed.values["created-at"],
1725
+ });
1726
+ if (parsed.values.json) {
1727
+ console.log(JSON.stringify(res, null, 2));
1728
+ return 0;
1729
+ }
1730
+ console.log(`Ed25519 Approver Registered : ${res.approverId} (${res.keyFingerprint})`);
1731
+ console.log(`Public Registry (repo) : ${res.registryPath}`);
1732
+ console.log(`Private Key (external 0600) : ${res.privateKeyPath}`);
1733
+ if (res.publicKeyPath) console.log(`Public Key (external pin) : ${res.publicKeyPath}`);
1734
+ return 0;
1735
+ }
1736
+
1737
+ if (subcmd === "sign") {
1738
+ const parsed = parseArgs({
1739
+ args: rest,
1740
+ options: {
1741
+ project: { type: "string", short: "p" },
1742
+ action: { type: "string", default: "promote" },
1743
+ skill: { type: "string" },
1744
+ name: { type: "string" },
1745
+ proposal: { type: "string" },
1746
+ revision: { type: "string" },
1747
+ approver: { type: "string" },
1748
+ key: { type: "string" },
1749
+ rationale: { type: "string" },
1750
+ "risk-assessment": { type: "string" },
1751
+ "expires-at": { type: "string" },
1752
+ "decided-at": { type: "string" },
1753
+ json: { type: "boolean", default: false },
1754
+ help: { type: "boolean", short: "h", default: false },
1755
+ },
1756
+ strict: true,
1757
+ allowPositionals: true,
1758
+ });
1759
+ if (parsed.values.help) {
1760
+ printSubHelp("skills");
1761
+ return 0;
1762
+ }
1763
+ const skillName = parsed.values.skill || parsed.values.name || parsed.values.proposal || parsed.positionals[0];
1764
+ const targetRev = parsed.values.revision || parsed.positionals[1];
1765
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
1766
+ const res = signSkillApproval({
1767
+ projectDir,
1768
+ harnessDir: HARNESS_DIR,
1769
+ action: parsed.values.action,
1770
+ skillName,
1771
+ targetRevision: targetRev,
1772
+ approverId: parsed.values.approver,
1773
+ privateKeyPath: parsed.values.key,
1774
+ rationale: parsed.values.rationale,
1775
+ riskAssessment: parsed.values["risk-assessment"],
1776
+ expiresAt: parsed.values["expires-at"],
1777
+ decidedAt: parsed.values["decided-at"],
1778
+ });
1779
+ if (parsed.values.json) {
1780
+ console.log(JSON.stringify(res, null, 2));
1781
+ return 0;
1782
+ }
1783
+ console.log(`Signed Approval Created : ${res.approvalId} -> ${res.relPath}`);
1784
+ console.log(`Bound Operation : ${res.action} ${res.skillName}${res.targetRevision ? ` (${res.targetRevision})` : ""}`);
1785
+ console.log(`Bound Content SHA-256 : ${res.contentSha256}`);
1786
+ console.log(`Approver / Key : ${res.approverId} (${res.keyFingerprint})`);
1787
+ return 0;
1788
+ }
1789
+
1790
+ if (subcmd === "promote") {
1791
+ const parsed = parseArgs({
1792
+ args: rest,
1793
+ options: {
1794
+ project: { type: "string", short: "p" },
1795
+ name: { type: "string" },
1796
+ approval: { type: "string" },
1797
+ "public-key": { type: "string" },
1798
+ mode: { type: "string" },
1799
+ branch: { type: "string" },
1800
+ interactive: { type: "boolean", default: false },
1801
+ "approved-by": { type: "string" },
1802
+ "created-at": { type: "string" },
1803
+ "dry-run": { type: "boolean", default: false },
1804
+ json: { type: "boolean", default: false },
1805
+ help: { type: "boolean", short: "h", default: false },
1806
+ },
1807
+ strict: true,
1808
+ allowPositionals: true,
1809
+ });
1810
+ if (parsed.values.help) {
1811
+ printSubHelp("skills");
1812
+ return 0;
1813
+ }
1814
+ const proposalName = parsed.values.name || parsed.positionals[0];
1815
+ if (parsed.values.interactive && parsed.values.mode) {
1816
+ throw new Error("Cannot combine --interactive with --mode; choose one authorization mode.");
1817
+ }
1818
+ if (parsed.values.approval && (parsed.values.mode || parsed.values.interactive)) {
1819
+ throw new Error("Cannot combine --approval with --mode or --interactive; choose one authorization mode.");
1820
+ }
1821
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
1822
+ const authMode = parsed.values.interactive ? "interactive" : parsed.values.mode;
1823
+
1824
+ let interactiveConfirm = null;
1825
+ if (authMode === "interactive" && !parsed.values["dry-run"] && !parsed.values["approved-by"] && !parsed.values.approval) {
1826
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
1827
+ throw new Error(
1828
+ "--interactive requires a real interactive terminal (TTY). Use --approval <APPR-NNNN> or --mode pr-branch in non-interactive sessions."
1829
+ );
1830
+ }
1831
+ const preview = promoteSkillProposal({
1832
+ projectDir,
1833
+ harnessDir: HARNESS_DIR,
1834
+ proposalName,
1835
+ dryRun: true,
1836
+ });
1837
+ const expectedInput = `promote ${preview.skillName} ${preview.candidateDigest.slice(7, 15)}`;
1838
+ const ok = await promptTtyAuthorization({
1839
+ action: preview.action,
1840
+ skillName: preview.skillName,
1841
+ targetRevision: null,
1842
+ contentSha256: preview.candidateDigest,
1843
+ expectedInput,
1844
+ });
1845
+ interactiveConfirm = () => ok;
1846
+ }
1847
+
1848
+ const res = promoteSkillProposal({
1849
+ projectDir,
1850
+ harnessDir: HARNESS_DIR,
1851
+ proposalName,
1852
+ approvalId: parsed.values.approval,
1853
+ publicKeyPath: parsed.values["public-key"],
1854
+ mode: authMode,
1855
+ branch: parsed.values.branch,
1856
+ approvedBy: parsed.values["approved-by"],
1857
+ interactiveConfirm,
1858
+ createdAt: parsed.values["created-at"],
1859
+ dryRun: parsed.values["dry-run"],
1860
+ });
1861
+ if (parsed.values.json) {
1862
+ console.log(JSON.stringify(res, null, 2));
1863
+ return 0;
1864
+ }
1865
+ console.log(res.dryRun ? `DRY RUN — Promotion check passed for "${res.skillName}"` : `Promoted Skill (${res.action}) : ${res.activeRel} (${res.revision})`);
1866
+ console.log(`Authorization Tier : ${res.authorizationTier || "preview"}${res.approvalId ? ` (${res.approvalId})` : ""}`);
1867
+ if (res.keyTrustSource) console.log(`Key Trust Source : ${res.keyTrustSource}`);
1868
+ console.log(`Digest / History : ${res.candidateDigest}${res.historyRel ? ` | ${res.historyRel}` : ""}`);
1869
+ if (res.prBranch) console.log(`PR Review Branch : ${res.prBranch} (${res.prCommitSha}) — push & require PR approval before merging`);
1870
+ if (res.authorizationWarning) console.log(` - [NOTICE] ${res.authorizationWarning}`);
1871
+ return 0;
1872
+ }
1873
+
1874
+ if (subcmd === "history") {
1875
+ const parsed = parseArgs({
1876
+ args: rest,
1877
+ options: {
1878
+ project: { type: "string", short: "p" },
1879
+ name: { type: "string" },
1880
+ json: { type: "boolean", default: false },
1881
+ help: { type: "boolean", short: "h", default: false },
1882
+ },
1883
+ strict: true,
1884
+ allowPositionals: true,
1885
+ });
1886
+ if (parsed.values.help) {
1887
+ printSubHelp("skills");
1888
+ return 0;
1889
+ }
1890
+ const targetName = parsed.values.name || parsed.positionals[0];
1891
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
1892
+ const res = getSkillHistory({ projectDir, skillName: targetName, harnessDir: HARNESS_DIR });
1893
+ if (parsed.values.json) {
1894
+ console.log(JSON.stringify(res, null, 2));
1895
+ return 0;
1896
+ }
1897
+ console.log(`Skill History : ${res.skillName} | active=${res.activeExists} | drift=${res.driftDetected}`);
1898
+ console.log(`Current SHA : ${res.currentSha256 || "(not active)"}`);
1899
+ if (res.revisions.length === 0) {
1900
+ console.log(" (no recorded revisions yet)");
1901
+ return 0;
1902
+ }
1903
+ for (const r of res.revisions) {
1904
+ console.log(
1905
+ ` - ${r.revision} [${r.action}] tier=${r.authorization_tier} appr=${r.approval_ref || "none"} sha=${r.package_sha256.slice(0, 19)} snapOk=${r.snapshotValid}${r.restored_from_revision ? ` from=${r.restored_from_revision}` : ""}`
1906
+ );
1907
+ }
1908
+ return 0;
1909
+ }
1910
+
1911
+ if (subcmd === "rollback") {
1912
+ const parsed = parseArgs({
1913
+ args: rest,
1914
+ options: {
1915
+ project: { type: "string", short: "p" },
1916
+ name: { type: "string" },
1917
+ revision: { type: "string" },
1918
+ approval: { type: "string" },
1919
+ "public-key": { type: "string" },
1920
+ mode: { type: "string" },
1921
+ branch: { type: "string" },
1922
+ interactive: { type: "boolean", default: false },
1923
+ "approved-by": { type: "string" },
1924
+ "created-at": { type: "string" },
1925
+ "dry-run": { type: "boolean", default: false },
1926
+ json: { type: "boolean", default: false },
1927
+ help: { type: "boolean", short: "h", default: false },
1928
+ },
1929
+ strict: true,
1930
+ allowPositionals: true,
1931
+ });
1932
+ if (parsed.values.help) {
1933
+ printSubHelp("skills");
1934
+ return 0;
1935
+ }
1936
+ const skillName = parsed.values.name || parsed.positionals[0];
1937
+ const targetRevision = parsed.values.revision || parsed.positionals[1];
1938
+ if (parsed.values.interactive && parsed.values.mode) {
1939
+ throw new Error("Cannot combine --interactive with --mode; choose one authorization mode.");
1940
+ }
1941
+ if (parsed.values.approval && (parsed.values.mode || parsed.values.interactive)) {
1942
+ throw new Error("Cannot combine --approval with --mode or --interactive; choose one authorization mode.");
1943
+ }
1944
+ const { projectDir } = resolveProjectDir({ project: parsed.values.project, harnessDir: HARNESS_DIR });
1945
+ const authMode = parsed.values.interactive ? "interactive" : parsed.values.mode;
1946
+
1947
+ let interactiveConfirm = null;
1948
+ if (authMode === "interactive" && !parsed.values["dry-run"] && !parsed.values["approved-by"] && !parsed.values.approval) {
1949
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
1950
+ throw new Error(
1951
+ "--interactive requires a real interactive terminal (TTY). Use --approval <APPR-NNNN> or --mode pr-branch in non-interactive sessions."
1952
+ );
1953
+ }
1954
+ const preview = rollbackSkill({
1955
+ projectDir,
1956
+ harnessDir: HARNESS_DIR,
1957
+ skillName,
1958
+ targetRevision,
1959
+ dryRun: true,
1960
+ });
1961
+ const expectedInput = `rollback ${preview.skillName} ${preview.restoredDigest.slice(7, 15)}`;
1962
+ const ok = await promptTtyAuthorization({
1963
+ action: "rollback",
1964
+ skillName: preview.skillName,
1965
+ targetRevision: preview.targetRevision,
1966
+ contentSha256: preview.restoredDigest,
1967
+ expectedInput,
1968
+ });
1969
+ interactiveConfirm = () => ok;
1970
+ }
1971
+
1972
+ const res = rollbackSkill({
1973
+ projectDir,
1974
+ harnessDir: HARNESS_DIR,
1975
+ skillName,
1976
+ targetRevision,
1977
+ approvalId: parsed.values.approval,
1978
+ publicKeyPath: parsed.values["public-key"],
1979
+ mode: authMode,
1980
+ branch: parsed.values.branch,
1981
+ approvedBy: parsed.values["approved-by"],
1982
+ interactiveConfirm,
1983
+ createdAt: parsed.values["created-at"],
1984
+ dryRun: parsed.values["dry-run"],
1985
+ });
1986
+ if (parsed.values.json) {
1987
+ console.log(JSON.stringify(res, null, 2));
1988
+ return 0;
1989
+ }
1990
+ console.log(
1991
+ res.dryRun
1992
+ ? `DRY RUN — Rollback check passed for "${res.skillName}" -> ${res.targetRevision}`
1993
+ : `Rolled Back Skill : ${res.activeRel} -> ${res.restoredFromRevision} (recorded as ${res.newRevision})`
1994
+ );
1995
+ console.log(`Authorization Tier : ${res.authorizationTier || "preview"}${res.approvalId ? ` (${res.approvalId})` : ""}`);
1996
+ if (res.keyTrustSource) console.log(`Key Trust Source : ${res.keyTrustSource}`);
1997
+ console.log(`Restored SHA-256 : ${res.restoredDigest}`);
1998
+ if (res.prBranch) console.log(`PR Review Branch : ${res.prBranch} (${res.prCommitSha}) — push & require PR approval before merging`);
1999
+ if (res.authorizationWarning) console.log(` - [NOTICE] ${res.authorizationWarning}`);
2000
+ return 0;
2001
+ }
2002
+
2003
+ throw new Error(`Unknown skills subcommand "${subcmd}".`);
2004
+ }
2005
+
2006
+ async function handleSkills(args) {
2007
+ if (args.length === 0 || args[0] === "-h" || args[0] === "--help") {
2008
+ printSubHelp("skills");
2009
+ return 0;
2010
+ }
2011
+ const [subcmd, ...rest] = args;
2012
+ if (["draft", "propose-update", "keygen", "sign", "promote", "history", "rollback"].includes(subcmd)) {
2013
+ return handleSkillsLifecycle(subcmd, rest);
2014
+ }
2015
+ if (!["list", "show", "validate", "lint"].includes(subcmd)) {
2016
+ throw new Error(
2017
+ `Unknown skills subcommand "${subcmd}". Expected: list, show, validate, lint, draft, propose-update, keygen, sign, promote, history, or rollback.`
2018
+ );
2019
+ }
2020
+
2021
+ const parsed = parseArgs({
2022
+ args: rest,
2023
+ options: {
2024
+ project: { type: "string", short: "p" },
2025
+ "global-dir": { type: "string" },
2026
+ name: { type: "string" },
2027
+ "include-drafts": { type: "boolean", default: false },
2028
+ strict: { type: "boolean", default: false },
2029
+ json: { type: "boolean", default: false },
2030
+ help: { type: "boolean", short: "h", default: false },
2031
+ },
2032
+ strict: true,
2033
+ allowPositionals: subcmd === "show",
2034
+ });
2035
+
2036
+ if (parsed.values.help) {
2037
+ printSubHelp("skills");
2038
+ return 0;
2039
+ }
2040
+ if (parsed.values.strict && subcmd !== "lint") {
2041
+ throw new Error("--strict is only supported with 'geloforge skills lint'.");
2042
+ }
2043
+ if (parsed.values.name && subcmd !== "show") {
2044
+ throw new Error("--name is only supported with 'geloforge skills show'.");
2045
+ }
2046
+
2047
+ const loc = resolveProjectForSkills({
2048
+ project: parsed.values.project,
2049
+ harnessDir: HARNESS_DIR,
2050
+ });
2051
+ const discovery = discoverSkills({
2052
+ projectDir: loc.projectDir,
2053
+ globalSkillsDir: parsed.values["global-dir"],
2054
+ proposalsDir: loc.proposalsDir,
2055
+ includeDrafts: parsed.values["include-drafts"],
2056
+ });
2057
+
2058
+ if (subcmd === "list") {
2059
+ const payload = {
2060
+ projectDir: discovery.projectDir,
2061
+ globalSkillsDir: discovery.globalSkillsDir,
2062
+ globalSourceLabel: discovery.globalSourceLabel,
2063
+ skills: discovery.visibleSkills.map(summarizeSkillForJson),
2064
+ quarantinedCount: discovery.quarantinedSkills.length,
2065
+ conflicts: discovery.conflicts,
2066
+ rootErrors: discovery.rootErrors,
2067
+ rootWarnings: discovery.rootWarnings,
2068
+ };
2069
+ if (parsed.values.json) {
2070
+ console.log(JSON.stringify(payload, null, 2));
2071
+ return discovery.rootErrors.length > 0 ? 1 : 0;
2072
+ }
2073
+ console.log(`Project Root : ${discovery.projectDir || "(none — global skills only)"}`);
2074
+ console.log(`Global Root : ${discovery.globalSkillsDir || "(disabled)"} (${discovery.globalSourceLabel})`);
2075
+ console.log(`Skills Found : ${discovery.visibleSkills.length} listed | ${discovery.quarantinedSkills.length} quarantined draft(s)`);
2076
+ if (discovery.visibleSkills.length === 0) {
2077
+ console.log(' (none found — create ".agents/skills/<name>/SKILL.md" or set GELOFORGE_SKILLS_DIR)');
2078
+ } else {
2079
+ for (const s of discovery.visibleSkills) {
2080
+ const status = s.blocked ? "BLOCKED" : s.valid ? "valid" : "invalid";
2081
+ const desc = s.hasSecrets
2082
+ ? "[REDACTED]"
2083
+ : String(s.frontmatter?.description || "(missing description)").replace(/\s+/g, " ").trim();
2084
+ const shortDesc = desc.length > 72 ? `${desc.slice(0, 69)}...` : desc;
2085
+ console.log(` - ${s.name} [${s.source}, ${status}, ~${s.estimatedTokens} tok] — ${shortDesc}`);
2086
+ }
2087
+ }
2088
+ if (!parsed.values["include-drafts"] && discovery.quarantinedSkills.length > 0) {
2089
+ console.log(` (Pass --include-drafts to view ${discovery.quarantinedSkills.length} quarantined draft skill(s) under ${loc.proposalsDir}/skills/)`);
2090
+ }
2091
+ for (const c of discovery.conflicts) console.log(` - [CONFLICT] ${c.message}`);
2092
+ for (const w of discovery.rootWarnings) console.log(` - [WARN] ${w}`);
2093
+ for (const e of discovery.rootErrors) console.error(` - [ERR] ${e}`);
2094
+ return discovery.rootErrors.length > 0 ? 1 : 0;
2095
+ }
2096
+
2097
+ if (subcmd === "show") {
2098
+ const targetName = parsed.values.name || parsed.positionals[0];
2099
+ if (!targetName) {
2100
+ throw new Error("Missing skill name for 'geloforge skills show <name>'.");
2101
+ }
2102
+ const found = discovery.visibleSkills.find((s) => s.name === targetName || s.folderName === targetName);
2103
+ if (!found) {
2104
+ const qFound = discovery.quarantinedSkills.find((s) => s.name === targetName || s.folderName === targetName);
2105
+ if (qFound) {
2106
+ throw new Error(
2107
+ `Skill "${targetName}" is quarantined under ${qFound.displayPath} and excluded from active skills. Pass --include-drafts to inspect it safely.`
2108
+ );
2109
+ }
2110
+ throw new Error(`Skill "${targetName}" not found in project or global skills directories.`);
2111
+ }
2112
+ const lintRes = lintSkill(found);
2113
+ const bodyOut = found.hasSecrets
2114
+ ? "[REDACTED: skill contains secret content or secret files and cannot be displayed verbatim]"
2115
+ : found.body;
2116
+ if (parsed.values.json) {
2117
+ console.log(
2118
+ JSON.stringify(
2119
+ {
2120
+ ...summarizeSkillForJson(found),
2121
+ frontmatter: found.hasSecrets ? null : found.frontmatter,
2122
+ body: bodyOut,
2123
+ lint: lintRes,
2124
+ disclaimer: STATIC_LINT_DISCLAIMER,
2125
+ },
2126
+ null,
2127
+ 2
2128
+ )
2129
+ );
2130
+ return found.valid && !lintRes.hasCriticalOrError ? 0 : 1;
2131
+ }
2132
+
2133
+ console.log(`Skill : ${found.name} [${found.source}, ${found.trustTier}]`);
2134
+ console.log(`Path : ${found.displayPath}/SKILL.md (${found.contentDigest})`);
2135
+ console.log(`Status : ${found.blocked ? "BLOCKED" : found.valid ? "valid" : "invalid"} | ~${found.estimatedTokens} est. tokens`);
2136
+ if (found.frontmatter?.license) console.log(`License : ${found.frontmatter.license}`);
2137
+ if (found.frontmatter?.compatibility) console.log(`Compat : ${found.frontmatter.compatibility}`);
2138
+ if (found.tags.length > 0) console.log(`Tags : ${found.tags.join(", ")}`);
2139
+ if (found.triggers.length > 0) console.log(`Triggers : ${found.triggers.join(", ")}`);
2140
+ console.log(`References : ${found.resources.references.join(", ") || "(none)"}`);
2141
+ console.log(`Templates : ${found.resources.templates.join(", ") || "(none)"}`);
2142
+ if (found.resources.scripts.length > 0) {
2143
+ console.log(`Scripts : ${found.resources.scripts.join(", ")} (NEVER auto-executed by GeloForge)`);
2144
+ }
2145
+ for (const f of lintRes.findings) {
2146
+ console.log(` - [${f.severity.toUpperCase()} ${f.ruleId}] ${f.message}`);
2147
+ }
2148
+ console.log("");
2149
+ console.log(bodyOut);
2150
+ return found.valid && !lintRes.hasCriticalOrError ? 0 : 1;
2151
+ }
2152
+
2153
+ if (subcmd === "validate") {
2154
+ const pool = [...discovery.allSkills];
2155
+ if (parsed.values["include-drafts"]) {
2156
+ pool.push(...discovery.quarantinedSkills);
2157
+ }
2158
+ const invalidSkills = pool.filter((s) => !s.valid);
2159
+ const valid = discovery.rootErrors.length === 0 && invalidSkills.length === 0;
2160
+ const payload = {
2161
+ valid,
2162
+ projectDir: discovery.projectDir,
2163
+ globalSkillsDir: discovery.globalSkillsDir,
2164
+ checkedCount: pool.length,
2165
+ invalidCount: invalidSkills.length,
2166
+ rootErrors: discovery.rootErrors,
2167
+ rootWarnings: discovery.rootWarnings,
2168
+ conflicts: discovery.conflicts,
2169
+ skills: pool.map(summarizeSkillForJson),
2170
+ };
2171
+ if (parsed.values.json) {
2172
+ console.log(JSON.stringify(payload, null, 2));
2173
+ return valid ? 0 : 1;
2174
+ }
2175
+ console.log(`Skills Validation : ${valid ? "PASS" : "FAIL"}`);
2176
+ console.log(`Checked Packages : ${pool.length} | Invalid: ${invalidSkills.length} | Conflicts: ${discovery.conflicts.length}`);
2177
+ for (const e of discovery.rootErrors) console.error(` - [ERR ROOT] ${e}`);
2178
+ for (const w of discovery.rootWarnings) console.log(` - [WARN] ${w}`);
2179
+ for (const c of discovery.conflicts) console.log(` - [CONFLICT] ${c.message}`);
2180
+ for (const s of pool) {
2181
+ if (s.errors.length === 0 && s.warnings.length === 0) continue;
2182
+ for (const err of s.errors) {
2183
+ console.error(` - [ERR ${err.code}] ${err.file}: ${err.message}`);
2184
+ if (err.remediation) console.error(` Fix: ${err.remediation}`);
2185
+ }
2186
+ for (const warn of s.warnings) {
2187
+ console.log(` - [WARN ${warn.code}] ${warn.file}: ${warn.message}`);
2188
+ }
2189
+ }
2190
+ return valid ? 0 : 1;
2191
+ }
2192
+
2193
+ // lint
2194
+ const report = lintDiscoveredSkills(discovery, {
2195
+ strict: parsed.values.strict,
2196
+ includeDrafts: parsed.values["include-drafts"],
2197
+ });
2198
+ if (parsed.values.json) {
2199
+ console.log(JSON.stringify(report, null, 2));
2200
+ return report.passed ? 0 : 1;
2201
+ }
2202
+ console.log(`Skills Lint : ${report.passed ? "PASS" : "FAIL"}${report.strict ? " (strict)" : ""}`);
2203
+ console.log(
2204
+ `Counts : critical=${report.counts.critical} | high=${report.counts.high} | error=${report.counts.error} | warning=${report.counts.warning}`
2205
+ );
2206
+ console.log(`Disclaimer : ${report.disclaimer}`);
2207
+ for (const e of report.rootErrors) console.error(` - [CRITICAL ROOT] ${e}`);
2208
+ for (const w of report.rootWarnings) console.log(` - [WARN ROOT] ${w}`);
2209
+ for (const c of report.conflicts) console.log(` - [CONFLICT] ${c.message}`);
2210
+ for (const sr of report.skills) {
2211
+ for (const f of sr.findings) {
2212
+ const printer = f.severity === "critical" || f.severity === "error" ? console.error : console.log;
2213
+ printer(` - [${f.severity.toUpperCase()} ${f.ruleId}] ${f.file}: ${f.message}`);
2214
+ if (f.remediation) printer(` Fix: ${f.remediation}`);
2215
+ }
2216
+ }
2217
+ return report.passed ? 0 : 1;
2218
+ }
2219
+
2220
+ async function main() {
2221
+ const argv = process.argv.slice(2);
2222
+ if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {
2223
+ printMainHelp();
2224
+ process.exit(0);
2225
+ }
2226
+ if (argv[0] === "-v" || argv[0] === "--version") {
2227
+ console.log(getVersion());
2228
+ process.exit(0);
2229
+ }
2230
+
2231
+ const [command, ...rest] = argv;
2232
+ try {
2233
+ let code = 0;
2234
+ switch (command) {
2235
+ case "init":
2236
+ code = handleInit(rest);
2237
+ break;
2238
+ case "adopt":
2239
+ code = handleAdopt(rest);
2240
+ break;
2241
+ case "task":
2242
+ code = handleTask(rest);
2243
+ break;
2244
+ case "evidence":
2245
+ code = handleEvidence(rest);
2246
+ break;
2247
+ case "verify":
2248
+ code = handleVerify(rest);
2249
+ break;
2250
+ case "validate":
2251
+ code = handleValidate(rest);
2252
+ break;
2253
+ case "context":
2254
+ code = handleContext(rest);
2255
+ break;
2256
+ case "skills":
2257
+ code = await handleSkills(rest);
2258
+ break;
2259
+ case "handoff":
2260
+ code = handleHandoff(rest);
2261
+ break;
2262
+ case "checkpoint":
2263
+ code = handleCheckpoint(rest);
2264
+ break;
2265
+ case "recommend":
2266
+ code = handleRecommend(rest);
2267
+ break;
2268
+ case "status":
2269
+ code = handleStatus(rest);
2270
+ break;
2271
+ case "mcp":
2272
+ code = await handleMcp(rest);
2273
+ break;
2274
+ default:
2275
+ console.error(`ERROR: Unknown command "${command}". Run "geloforge --help" for usage.`);
2276
+ process.exit(1);
2277
+ }
2278
+ process.exitCode = code;
2279
+ } catch (err) {
2280
+ console.error(`ERROR: ${redactSecretContent(err.message)}`);
2281
+ process.exitCode = 1;
2282
+ }
2283
+ }
2284
+
2285
+ // npm links the executable through node_modules/.bin on POSIX.
2286
+ const entryPath = process.argv[1];
2287
+ const isDirectRun = entryPath && fs.existsSync(entryPath) &&
2288
+ fs.realpathSync(entryPath) === fs.realpathSync(__filename);
2289
+ if (isDirectRun) {
2290
+ await main();
2291
+ }