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