pantheon-opencode 2.0.0-beta.6 → 2.0.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 (93) hide show
  1. package/AGENTS.global.md +7 -2
  2. package/AGENTS.md +8 -8
  3. package/CHANGELOG.md +99 -0
  4. package/README.md +171 -510
  5. package/README.pt-BR.md +179 -149
  6. package/bin/pantheon-init.mjs +14 -1
  7. package/commands/pantheon-audit.md +1 -1
  8. package/commands/pantheon-deepwork.md +7 -2
  9. package/commands/pantheon-optimize.md +41 -63
  10. package/commands/pantheon.md +10 -5
  11. package/package.json +4 -3
  12. package/plugin.json +2 -2
  13. package/prompts/optimize-database.prompt.md +5 -5
  14. package/prompts/orchestrate-with-zeus.prompt.md +82 -290
  15. package/prompts/plan-architecture.prompt.md +6 -6
  16. package/prompts/subtask.prompt.md +1 -1
  17. package/pyproject.toml +1 -1
  18. package/scripts/build-agents-md.mjs +10 -10
  19. package/scripts/build-plugin.mjs +26 -0
  20. package/scripts/doctor.mjs +27 -11
  21. package/scripts/hooks/format-multi-language.sh +30 -48
  22. package/scripts/install/opencode-version.mjs +17 -5
  23. package/scripts/install/opencode.mjs +8 -1
  24. package/scripts/jev-live-probe.mjs +1 -1
  25. package/scripts/optimize.mjs +322 -0
  26. package/scripts/prune.mjs +105 -14
  27. package/scripts/release-gates.mjs +19 -5
  28. package/scripts/skill-search.mjs +27 -3
  29. package/scripts/test-opencode-sandbox.sh +44 -15
  30. package/scripts/update.mjs +29 -17
  31. package/skills-lock.json +15 -13
  32. package/src/agents/aphrodite.md +17 -14
  33. package/src/agents/apollo.md +10 -207
  34. package/src/agents/athena.md +30 -34
  35. package/src/agents/demeter.md +2 -0
  36. package/src/agents/hephaestus.md +1 -0
  37. package/src/agents/hermes.md +21 -95
  38. package/src/agents/iris.md +3 -0
  39. package/src/agents/mnemosyne.md +1 -1
  40. package/src/agents/nyx.md +2 -1
  41. package/src/agents/prometheus.md +2 -203
  42. package/src/agents/talos.md +5 -0
  43. package/src/agents/themis.md +93 -84
  44. package/src/agents/zeus.md +44 -263
  45. package/src/instructions/agent-return-format.instructions.md +1 -1
  46. package/src/instructions/memory-protocol.instructions.md +5 -1
  47. package/src/instructions/test-economy.instructions.md +1 -0
  48. package/src/instructions/zeus-anti-stall.instructions.md +3 -3
  49. package/src/instructions/zeus-communication-rules.instructions.md +1 -1
  50. package/src/instructions/zeus-council-synthesis.instructions.md +15 -3
  51. package/src/instructions/zeus-timeout-retry.instructions.md +10 -10
  52. package/src/pantheon/model-command.ts +12 -12
  53. package/src/pantheon/pantheon-decision-catalog.ts +8 -0
  54. package/src/pantheon/skill-search-tool.ts +193 -0
  55. package/src/pantheon/tools.ts +6 -0
  56. package/src/pantheon/tui-version-check.ts +1 -1
  57. package/src/pantheon/update-notifier.ts +13 -8
  58. package/src/pantheon/vision.ts +20 -20
  59. package/src/plugin/index.js +14594 -0
  60. package/src/plugins/tui/dist/tui.d.ts +15 -5
  61. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  62. package/src/plugins/tui/dist/tui.js +1761 -556
  63. package/src/plugins/tui/dist/tui.js.map +1 -1
  64. package/src/plugins/tui/package-lock.json +2 -2
  65. package/src/plugins/tui/package.json +1 -1
  66. package/src/plugins/tui/src/autonomy-state.ts +28 -16
  67. package/src/plugins/tui/src/context-gauge.ts +64 -5
  68. package/src/plugins/tui/src/decision-router-state.ts +49 -2
  69. package/src/plugins/tui/src/index.tsx +69 -26
  70. package/src/plugins/tui/src/pantheon-settings-state.ts +99 -0
  71. package/src/plugins/tui/src/pantheon-settings.tsx +771 -125
  72. package/src/plugins/tui/src/tui-prefs.ts +266 -12
  73. package/src/plugins/tui/src/update-notice.ts +9 -6
  74. package/src/plugins/tui/src/update-status.ts +27 -8
  75. package/src/plugins/tui/src/whats-new-open.ts +4 -4
  76. package/src/plugins/tui/src/whats-new.tsx +119 -17
  77. package/src/routing.yml +9 -0
  78. package/src/skills/README.md +35 -25
  79. package/src/skills/agent-coordination/SKILL.md +6 -6
  80. package/src/skills/artifact-management/SKILL.md +43 -39
  81. package/src/skills/artifact-management/references/artifact-templates.md +103 -48
  82. package/src/skills/auto-continue/references/auto-continue-details.md +13 -13
  83. package/src/skills/code-review-checklist/SKILL.md +6 -6
  84. package/src/skills/fast-path-execution/SKILL.md +54 -0
  85. package/src/skills/incremental-implementation/SKILL.md +13 -13
  86. package/src/skills/memory-bank/references/anti-patterns.md +3 -3
  87. package/src/skills/prompt-refinery/SKILL.md +51 -65
  88. package/src/skills/spec-driven-development/SKILL.md +12 -14
  89. package/src/skills/tdd-with-agents/SKILL.md +23 -10
  90. package/src/skills/test-slicing/SKILL.md +56 -0
  91. package/src/skills/verification-planning/SKILL.md +4 -3
  92. package/src/skills/visual-review-pipeline/SKILL.md +1 -1
  93. package/src/skills/visual-review-pipeline/references/workflow-steps.md +1 -1
@@ -1411,21 +1411,38 @@ export function resolveMcpCwd(entry, configPath = '') {
1411
1411
  // ---------------------------------------------------------------------------
1412
1412
 
1413
1413
  /**
1414
- * Prerelease-aware comparison for pantheon versions (X.Y.Z or X.Y.Z-beta.N).
1415
- * A stable release outranks any beta of the same core version. Returns
1416
- * <0, 0, >0 (a - b). The shared compareVersions/parseVersion above ignores
1417
- * the `-beta.N` suffix (it only reads 4 numeric groups), which would make
1418
- * every beta pair compare equal.
1414
+ * Prerelease-aware comparison for pantheon versions (X.Y.Z, X.Y.Z-rc.N, or X.Y.Z-beta.N).
1415
+ * Stable releases outrank RCs and betas of the same core version; RCs outrank betas.
1416
+ * Returns <0, 0, >0 (a - b).
1419
1417
  */
1420
1418
  function comparePantheonVersions(a, b) {
1421
1419
  const parse = (v) => {
1422
1420
  const m = String(v)
1423
1421
  .trim()
1424
- .match(/^(\d+)\.(\d+)\.(\d+)(?:-beta\.(\d+))?$/)
1422
+ .match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/)
1425
1423
  if (!m) return null
1424
+ const prerelease = m[4]
1425
+ if (prerelease === undefined) {
1426
+ return {
1427
+ core: [+m[1], +m[2], +m[3]],
1428
+ tier: Number.POSITIVE_INFINITY,
1429
+ num: Number.POSITIVE_INFINITY,
1430
+ raw: '',
1431
+ }
1432
+ }
1433
+ const preMatch = prerelease.match(/^(rc|beta|alpha)(?:\.(\d+))?$/)
1434
+ let tier = 0
1435
+ let num = 0
1436
+ if (preMatch) {
1437
+ const type = preMatch[1]
1438
+ tier = type === 'rc' ? 2 : type === 'beta' ? 1 : 0
1439
+ num = preMatch[2] !== undefined ? +preMatch[2] : 0
1440
+ }
1426
1441
  return {
1427
1442
  core: [+m[1], +m[2], +m[3]],
1428
- beta: m[4] === undefined ? Number.POSITIVE_INFINITY : +m[4],
1443
+ tier,
1444
+ num,
1445
+ raw: prerelease,
1429
1446
  }
1430
1447
  }
1431
1448
  const pa = parse(a)
@@ -1434,10 +1451,9 @@ function comparePantheonVersions(a, b) {
1434
1451
  for (let i = 0; i < 3; i++) {
1435
1452
  if (pa.core[i] !== pb.core[i]) return pa.core[i] - pb.core[i]
1436
1453
  }
1437
- // Infinity - Infinity is NaN, which would make equal stable versions compare
1438
- // as drift for any caller using a strict === 0 check.
1439
- if (pa.beta === pb.beta) return 0
1440
- return pa.beta < pb.beta ? -1 : 1
1454
+ if (pa.tier !== pb.tier) return pa.tier - pb.tier
1455
+ if (pa.num !== pb.num) return pa.num - pb.num
1456
+ return pa.raw.localeCompare(pb.raw)
1441
1457
  }
1442
1458
 
1443
1459
  /**
@@ -11,55 +11,37 @@ REPO_ROOT="$(cd -- "$SCRIPT_DIR/../.." && pwd)"
11
11
  # Extracts file_path from Edit/Write or file paths from Bash commands.
12
12
  if [ -p /dev/stdin ]; then
13
13
  STDIN_JSON=$(cat)
14
- TOOL_NAME=$(echo "$STDIN_JSON" | python3 -c "
15
- import sys, json
16
- d = json.load(sys.stdin)
17
- print(d.get('tool_name', ''))
18
- " 2>/dev/null || echo "")
19
- # Normalize to lowercase — opencode sends lowercase (edit/write/bash),
20
- # Claude Code protocol may send capitalized (Edit/Write/Bash).
21
- TOOL_NAME_LOWER=$(echo "$TOOL_NAME" | tr '[:upper:]' '[:lower:]')
22
-
23
- case "$TOOL_NAME_LOWER" in
24
- edit|write)
25
- JSON_PATH=$(echo "$STDIN_JSON" | python3 -c "
26
- import sys, json
27
- d = json.load(sys.stdin)
28
- print(d.get('tool_input', {}).get('file_path', ''))
29
- " 2>/dev/null || echo "")
30
- if [ -n "$JSON_PATH" ]; then
31
- FILE_PATH="$JSON_PATH"
32
- fi
33
- ;;
34
- bash)
35
- COMMAND=$(echo "$STDIN_JSON" | python3 -c "
36
- import sys, json
37
- d = json.load(sys.stdin)
38
- print(d.get('tool_input', {}).get('command', ''))
39
- " 2>/dev/null || echo "")
40
- if [ -n "$COMMAND" ]; then
41
- # Extract first file-like path from bash command (supports relative and quoted paths)
42
- CANDIDATE=$(python3 -c "
43
- import re, shlex, sys
44
- command = sys.argv[1]
14
+ EXTRACTED_PATH=$(python3 -c "
15
+ import sys, json, re, shlex
45
16
  try:
46
- tokens = shlex.split(command)
47
- except ValueError:
48
- tokens = command.split()
49
- path_re = re.compile(r'^([^\\n]+\\.[A-Za-z0-9]+)$')
50
- for token in tokens:
51
- if token.startswith('-'):
52
- continue
53
- if path_re.match(token):
54
- print(token)
55
- break
56
- " "$COMMAND" 2>/dev/null || echo "")
57
- if [ -n "$CANDIDATE" ]; then
58
- FILE_PATH="$CANDIDATE"
59
- fi
60
- fi
61
- ;;
62
- esac
17
+ d = json.load(sys.stdin)
18
+ t = str(d.get('tool_name', '')).lower()
19
+ inp = d.get('tool_input', {})
20
+ if not isinstance(inp, dict):
21
+ inp = {}
22
+ fp = ''
23
+ if t in ('edit', 'write', 'hashline_edit'):
24
+ fp = inp.get('file_path', '') or inp.get('filePath', '') or inp.get('path', '')
25
+ elif t == 'bash':
26
+ cmd = inp.get('command', '')
27
+ if cmd:
28
+ try:
29
+ tokens = shlex.split(cmd)
30
+ except ValueError:
31
+ tokens = cmd.split()
32
+ path_re = re.compile(r'^([^\\n]+\\.[A-Za-z0-9]+)$')
33
+ for tok in tokens:
34
+ if not tok.startswith('-') and path_re.match(tok):
35
+ fp = tok
36
+ break
37
+ if fp:
38
+ print(fp)
39
+ except Exception:
40
+ pass
41
+ " <<< "$STDIN_JSON" 2>/dev/null || echo "")
42
+ if [ -n "$EXTRACTED_PATH" ]; then
43
+ FILE_PATH="$EXTRACTED_PATH"
44
+ fi
63
45
  fi
64
46
 
65
47
  FILE_PATH="${FILE_PATH:-${1:-}}"
@@ -1,8 +1,8 @@
1
1
  /** OpenCode host gate shared by the CLI and installer. */
2
2
 
3
3
  import { spawnSync } from 'node:child_process'
4
- import { mkdtempSync, rmSync } from 'node:fs'
5
- import { tmpdir } from 'node:os'
4
+ import { existsSync, mkdtempSync, rmSync } from 'node:fs'
5
+ import { homedir, tmpdir } from 'node:os'
6
6
  import { join } from 'node:path'
7
7
 
8
8
  /**
@@ -202,6 +202,19 @@ function parseHostMajor(text) {
202
202
  return { ambiguous: [...majors].sort((a, b) => a - b) }
203
203
  }
204
204
 
205
+ function resolveCandidateBinary(explicitBinary, env) {
206
+ if (explicitBinary) return explicitBinary
207
+ if (env.OPENCODE_BIN) return env.OPENCODE_BIN
208
+ if (process.platform !== 'win32') {
209
+ const userHome = env.HOME || homedir()
210
+ const standardBin = join(userHome, '.opencode', 'bin', 'opencode')
211
+ if (existsSync(standardBin)) {
212
+ return standardBin
213
+ }
214
+ }
215
+ return 'opencode'
216
+ }
217
+
205
218
  /**
206
219
  * Resolve the target OpenCode generation. There is exactly one, and the probe
207
220
  * must CONFIRM the host is 2.x before any write: there is no generation to fall
@@ -237,11 +250,10 @@ export function resolveOpenCodeVersion(options = {}) {
237
250
  `Invalid OPENCODE_VERSION "${env.OPENCODE_VERSION}" — only "${SUPPORTED_GENERATION}" can be pinned`,
238
251
  )
239
252
  }
240
- const binary = options.binary ?? env.OPENCODE_BIN ?? ''
253
+ const binary = resolveCandidateBinary(options.binary, env)
241
254
  if (/(?:^|[\\/])opencode2(?:\.exe)?$/i.test(binary)) return SUPPORTED_GENERATION
242
255
 
243
- const probe =
244
- options.probe ?? (() => probeHostVersion(binary || 'opencode', options.probeTimeoutMs))
256
+ const probe = options.probe ?? (() => probeHostVersion(binary, options.probeTimeoutMs))
245
257
  let raw
246
258
  try {
247
259
  raw = probe()
@@ -2587,10 +2587,17 @@ async function installPass(
2587
2587
  let healed = raw.replace(/,?\s*"source":\s*"agents\/[A-Za-z0-9_-]+\.md"/g, '')
2588
2588
  // A source-first entry leaves `"name": {,` — repair the orphan.
2589
2589
  healed = healed.replace(/("[A-Za-z0-9_-]+": \{),/g, '$1')
2590
+ if (healed.includes('"plugins":') && !healed.includes('pantheon-opencode')) {
2591
+ const pluginPkg = join(packageDir, 'src', 'plugin')
2592
+ healed = healed.replace(
2593
+ /"plugins":\s*\[/,
2594
+ `"plugins": [\n {\n "package": "${pluginPkg}",\n "options": {}\n },`,
2595
+ )
2596
+ }
2590
2597
  if (healed !== raw) {
2591
2598
  writeFileSync(jsoncPath, healed)
2592
2599
  warning(
2593
- 'Healed the sibling opencode.jsonc: removed stale cwd-relative agent "source" fields ' +
2600
+ 'Healed the sibling opencode.jsonc: synchronized plugins and removed stale cwd-relative agent "source" fields ' +
2594
2601
  '(the field that made agents vanish outside the config dir). Review the file if you hand-edit it.',
2595
2602
  )
2596
2603
  }
@@ -168,7 +168,7 @@ function main(args = process.argv.slice(2)) {
168
168
  rows.push({ state: scenario.state, expect: scenario.expect, got: `ERROR: ${r.raw}` })
169
169
  continue
170
170
  }
171
- const cost = r.data?.cost ?? 0
171
+ const cost = r.data?.data?.cost ?? r.data?.cost ?? 0
172
172
  totalCost += Number(cost) || 0
173
173
  rows.push({ state: scenario.state, expect: scenario.expect, got: answerChoice(r.data), cost })
174
174
  }
@@ -0,0 +1,322 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * optimize.mjs — Pantheon project and deepwork optimizer CLI
4
+ *
5
+ * Scans, cleans, and archives Pantheon workspace artifacts:
6
+ * - Archives or cleans resolved/completed deepwork sessions in .pantheon/deepwork/
7
+ * - Prunes stale backups in .pantheon/backups/ older than threshold
8
+ * - Cleans old debug logs in .pantheon/logs/
9
+ *
10
+ * Usage:
11
+ * pantheon-opencode optimize # dry-run preview (default)
12
+ * pantheon-opencode optimize --apply # archive completed deepwork + clean logs
13
+ * pantheon-opencode optimize --clean # permanently delete completed deepwork
14
+ * pantheon-opencode optimize --age <days> # custom age threshold (default: 7)
15
+ * pantheon-opencode optimize --target <d> # target workspace root
16
+ */
17
+
18
+ import { execSync } from 'node:child_process'
19
+ import {
20
+ existsSync,
21
+ mkdirSync,
22
+ readdirSync,
23
+ readFileSync,
24
+ renameSync,
25
+ rmSync,
26
+ statSync,
27
+ } from 'node:fs'
28
+ import { join, resolve } from 'node:path'
29
+ import { fileURLToPath } from 'node:url'
30
+
31
+ const DEFAULT_DEEPWORK_AGE_DAYS = 7
32
+ const DEFAULT_BACKUP_AGE_DAYS = 14
33
+ const MS_PER_DAY = 86_400_000
34
+
35
+ export function scanDeepwork(targetDir, ageDays = DEFAULT_DEEPWORK_AGE_DAYS) {
36
+ const deepworkDir = join(targetDir, '.pantheon', 'deepwork')
37
+ if (!existsSync(deepworkDir)) return []
38
+
39
+ const now = Date.now()
40
+ const cutoff = now - ageDays * MS_PER_DAY
41
+ const results = []
42
+
43
+ let entries = []
44
+ try {
45
+ entries = readdirSync(deepworkDir, { withFileTypes: true })
46
+ } catch {
47
+ return []
48
+ }
49
+
50
+ for (const entry of entries) {
51
+ if (!entry.isDirectory() || entry.name === 'archive') continue
52
+ const slugDir = join(deepworkDir, entry.name)
53
+
54
+ // Never clean up directories containing tracked git files
55
+ try {
56
+ const gitTracked = execSync(`git ls-files "${slugDir}"`, {
57
+ encoding: 'utf8',
58
+ stdio: ['ignore', 'pipe', 'ignore'],
59
+ }).trim()
60
+ if (gitTracked.length > 0) continue
61
+ } catch {}
62
+
63
+ let isCompleted = false
64
+ let reason = 'in-progress'
65
+ const reviewPath = join(slugDir, 'REVIEW.md')
66
+ const statusPath = join(slugDir, 'STATUS.md')
67
+
68
+ if (existsSync(reviewPath)) {
69
+ try {
70
+ const reviewText = readFileSync(reviewPath, 'utf8')
71
+ if (/APPROVED|PASS|COMPLETE/i.test(reviewText)) {
72
+ isCompleted = true
73
+ reason = 'reviewed and approved'
74
+ }
75
+ } catch {}
76
+ }
77
+
78
+ if (!isCompleted && existsSync(statusPath)) {
79
+ try {
80
+ const statusText = readFileSync(statusPath, 'utf8')
81
+ if (/status:\s*(?:complete|finished|done)/i.test(statusText)) {
82
+ isCompleted = true
83
+ reason = 'status marked complete'
84
+ }
85
+ } catch {}
86
+ }
87
+
88
+ // Check directory modification age
89
+ let mtime = 0
90
+ try {
91
+ mtime = statSync(slugDir).mtimeMs
92
+ } catch {}
93
+
94
+ if (!isCompleted && mtime > 0 && mtime < cutoff) {
95
+ isCompleted = true
96
+ reason = `inactive for >${ageDays} days`
97
+ }
98
+
99
+ results.push({
100
+ slug: entry.name,
101
+ path: slugDir,
102
+ completed: isCompleted,
103
+ reason,
104
+ mtime,
105
+ })
106
+ }
107
+
108
+ return results
109
+ }
110
+
111
+ export function scanBackups(targetDir, ageDays = DEFAULT_BACKUP_AGE_DAYS) {
112
+ const backupsDir = join(targetDir, '.pantheon', 'backups')
113
+ if (!existsSync(backupsDir)) return []
114
+
115
+ const now = Date.now()
116
+ const cutoff = now - ageDays * MS_PER_DAY
117
+ const results = []
118
+
119
+ let entries = []
120
+ try {
121
+ entries = readdirSync(backupsDir, { withFileTypes: true })
122
+ } catch {
123
+ return []
124
+ }
125
+
126
+ const dirs = entries
127
+ .filter((e) => e.isDirectory())
128
+ .map((e) => {
129
+ const p = join(backupsDir, e.name)
130
+ let mtime = 0
131
+ try {
132
+ mtime = statSync(p).mtimeMs
133
+ } catch {}
134
+ return { name: e.name, path: p, mtime }
135
+ })
136
+ .sort((a, b) => b.mtime - a.mtime) // newest first
137
+
138
+ // Keep at least the latest 3 backups regardless of age
139
+ for (let i = 3; i < dirs.length; i++) {
140
+ const item = dirs[i]
141
+ if (item.mtime > 0 && item.mtime < cutoff) {
142
+ results.push(item)
143
+ }
144
+ }
145
+
146
+ return results
147
+ }
148
+
149
+ export function scanLogs(targetDir, ageDays = 7) {
150
+ const logsDir = join(targetDir, '.pantheon', 'logs')
151
+ if (!existsSync(logsDir)) return []
152
+
153
+ const now = Date.now()
154
+ const cutoff = now - ageDays * MS_PER_DAY
155
+ const results = []
156
+
157
+ let entries = []
158
+ try {
159
+ entries = readdirSync(logsDir, { withFileTypes: true })
160
+ } catch {
161
+ return []
162
+ }
163
+
164
+ for (const entry of entries) {
165
+ if (!entry.isFile()) continue
166
+ const p = join(logsDir, entry.name)
167
+ let mtime = 0
168
+ try {
169
+ mtime = statSync(p).mtimeMs
170
+ } catch {}
171
+ if (mtime > 0 && mtime < cutoff) {
172
+ results.push({ name: entry.name, path: p, mtime })
173
+ }
174
+ }
175
+
176
+ return results
177
+ }
178
+
179
+ export function runOptimize(options = {}) {
180
+ const targetDir = resolve(options.target || process.cwd())
181
+ const apply = Boolean(options.apply || options.yes)
182
+ const clean = Boolean(options.clean)
183
+ const ageDays = options.age ? Number(options.age) : DEFAULT_DEEPWORK_AGE_DAYS
184
+
185
+ console.log('Pantheon Optimizer — Workspace Inspection')
186
+ console.log(`Target: ${targetDir}`)
187
+ console.log(
188
+ `Mode: ${apply ? (clean ? 'apply (clean/delete)' : 'apply (archive)') : 'dry-run (preview only)'}`,
189
+ )
190
+ console.log('────────────────────────────────────────────────────────────')
191
+
192
+ const deepworks = scanDeepwork(targetDir, ageDays)
193
+ const completedDeepworks = deepworks.filter((d) => d.completed)
194
+ const activeDeepworks = deepworks.filter((d) => !d.completed)
195
+ const staleBackups = scanBackups(targetDir)
196
+ const staleLogs = scanLogs(targetDir)
197
+
198
+ console.log(`Deepwork sessions: ${deepworks.length} total`)
199
+ if (completedDeepworks.length > 0) {
200
+ console.log(` Resolvable candidates (${completedDeepworks.length}):`)
201
+ for (const d of completedDeepworks) {
202
+ console.log(` - ${d.slug} (${d.reason})`)
203
+ }
204
+ }
205
+ if (activeDeepworks.length > 0) {
206
+ console.log(` Active sessions kept (${activeDeepworks.length}):`)
207
+ for (const d of activeDeepworks) {
208
+ console.log(` - ${d.slug} (in-progress)`)
209
+ }
210
+ }
211
+
212
+ console.log(`Stale backups: ${staleBackups.length} candidates (>14 days, keeping 3 latest)`)
213
+ console.log(`Stale logs: ${staleLogs.length} candidates (>7 days)`)
214
+
215
+ if (!apply) {
216
+ console.log('────────────────────────────────────────────────────────────')
217
+ console.log('[DRY-RUN] No changes made.')
218
+ console.log('To archive resolved deepworks: pantheon-opencode optimize --apply')
219
+ console.log(
220
+ 'To permanently delete resolved deepworks: pantheon-opencode optimize --clean --apply',
221
+ )
222
+ return { ok: true, changed: false }
223
+ }
224
+
225
+ console.log('────────────────────────────────────────────────────────────')
226
+ console.log('Applying optimization plan...')
227
+
228
+ // 1. Deepwork
229
+ if (completedDeepworks.length > 0) {
230
+ if (clean) {
231
+ for (const d of completedDeepworks) {
232
+ try {
233
+ rmSync(d.path, { recursive: true, force: true })
234
+ console.log(` [CLEAN] Removed ${d.slug}`)
235
+ } catch (e) {
236
+ console.error(` [ERROR] Failed to remove ${d.slug}: ${e.message}`)
237
+ }
238
+ }
239
+ } else {
240
+ const archiveDir = join(targetDir, '.pantheon', 'deepwork', 'archive')
241
+ mkdirSync(archiveDir, { recursive: true })
242
+ for (const d of completedDeepworks) {
243
+ try {
244
+ const dest = join(archiveDir, d.slug)
245
+ if (existsSync(dest)) {
246
+ rmSync(dest, { recursive: true, force: true })
247
+ }
248
+ renameSync(d.path, dest)
249
+ console.log(` [ARCHIVE] Moved ${d.slug} -> archive/${d.slug}`)
250
+ } catch (e) {
251
+ console.error(` [ERROR] Failed to archive ${d.slug}: ${e.message}`)
252
+ }
253
+ }
254
+ }
255
+ }
256
+
257
+ // 2. Backups
258
+ for (const b of staleBackups) {
259
+ try {
260
+ rmSync(b.path, { recursive: true, force: true })
261
+ console.log(` [CLEAN] Removed stale backup ${b.name}`)
262
+ } catch (e) {
263
+ console.error(` [ERROR] Failed to remove backup ${b.name}: ${e.message}`)
264
+ }
265
+ }
266
+
267
+ // 3. Logs
268
+ for (const l of staleLogs) {
269
+ try {
270
+ rmSync(l.path, { force: true })
271
+ console.log(` [CLEAN] Removed stale log ${l.name}`)
272
+ } catch (e) {
273
+ console.error(` [ERROR] Failed to remove log ${l.name}: ${e.message}`)
274
+ }
275
+ }
276
+
277
+ console.log('────────────────────────────────────────────────────────────')
278
+ console.log('[OK] Workspace optimization complete.')
279
+ return { ok: true, changed: true }
280
+ }
281
+
282
+ function printUsage() {
283
+ console.log('Usage: pantheon-opencode optimize [options]')
284
+ console.log('')
285
+ console.log('Options:')
286
+ console.log(' --apply, --yes Apply the changes (default: dry-run)')
287
+ console.log(' --clean Delete completed deepwork instead of archiving')
288
+ console.log(' --age <days> Inactivity threshold in days (default: 7)')
289
+ console.log(' --target <dir> Target workspace directory (default: cwd)')
290
+ console.log(' --help Show this help message')
291
+ }
292
+
293
+ // CLI entry point when run directly
294
+ if (process.argv[1] && resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url))) {
295
+ const args = process.argv.slice(2)
296
+ if (args.includes('--help') || args.includes('-h')) {
297
+ printUsage()
298
+ process.exit(0)
299
+ }
300
+
301
+ const options = {
302
+ apply: args.includes('--apply') || args.includes('--yes') || args.includes('-y'),
303
+ clean: args.includes('--clean'),
304
+ }
305
+
306
+ for (let i = 0; i < args.length; i++) {
307
+ if (args[i] === '--age' && args[i + 1]) {
308
+ options.age = Number(args[i + 1])
309
+ i++
310
+ } else if (args[i].startsWith('--age=')) {
311
+ options.age = Number(args[i].split('=')[1])
312
+ } else if (args[i] === '--target' && args[i + 1]) {
313
+ options.target = args[i + 1]
314
+ i++
315
+ } else if (args[i].startsWith('--target=')) {
316
+ options.target = args[i].split('=')[1]
317
+ }
318
+ }
319
+
320
+ const result = runOptimize(options)
321
+ process.exit(result.ok ? 0 : 1)
322
+ }