oc-harness-setup 0.3.3 → 0.4.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 (136) hide show
  1. package/.docs/unwired-routing.md +16 -15
  2. package/AGENTS.md +105 -68
  3. package/CHANGELOG.md +91 -0
  4. package/GLOSSARY.md +46 -0
  5. package/LICENSE +1 -1
  6. package/README.md +48 -60
  7. package/agents/cleaner.md +86 -0
  8. package/agents/critic.md +79 -0
  9. package/agents/historian.md +92 -0
  10. package/agents/maintainer.md +106 -0
  11. package/agents/ops.md +69 -0
  12. package/agents/orchestrator.md +48 -18
  13. package/agents/researcher.md +72 -0
  14. package/agents/verifier.md +84 -0
  15. package/agents/worker.md +87 -0
  16. package/bin/cli.js +349 -133
  17. package/commands/close.md +11 -0
  18. package/commands/evolve.md +11 -0
  19. package/commands/fast.md +11 -0
  20. package/commands/goal.md +11 -0
  21. package/commands/search.md +11 -0
  22. package/commands/swarm.md +11 -0
  23. package/opencode.jsonc +39 -79
  24. package/package.json +13 -6
  25. package/reference/README.md +12 -14
  26. package/reference/canon.md +71 -0
  27. package/reference/context.md +35 -0
  28. package/reference/enforcement.md +6 -0
  29. package/reference/flow.md +19 -0
  30. package/reference/gates.md +23 -0
  31. package/reference/harness.md +15 -0
  32. package/reference/hygiene.md +13 -0
  33. package/reference/memory.md +13 -0
  34. package/reference/models.md +19 -24
  35. package/reference/phases.md +23 -0
  36. package/reference/repos.md +49 -0
  37. package/reference/tools.md +35 -0
  38. package/scripts/harness-doctor.ps1 +83 -0
  39. package/skills/close/SKILL.md +36 -0
  40. package/skills/evolve/SKILL.md +76 -0
  41. package/skills/fast/SKILL.md +36 -0
  42. package/skills/goal/SKILL.md +65 -0
  43. package/skills/search/SKILL.md +68 -0
  44. package/skills/swarm/SKILL.md +69 -0
  45. package/state-seed/lessons.md +22 -0
  46. package/state-seed/template.md +12 -0
  47. package/agents/build.md +0 -20
  48. package/agents/explore.md +0 -26
  49. package/agents/general.md +0 -19
  50. package/agents/plan.md +0 -29
  51. package/agents/reviewer.md +0 -22
  52. package/agents/vault.md +0 -73
  53. package/commands/build.md +0 -7
  54. package/commands/checkpoint.md +0 -7
  55. package/commands/code-simplify.md +0 -7
  56. package/commands/gauntlet.md +0 -7
  57. package/commands/handoff.md +0 -7
  58. package/commands/keeper.md +0 -7
  59. package/commands/kill.md +0 -11
  60. package/commands/plan.md +0 -7
  61. package/commands/retro.md +0 -15
  62. package/commands/review.md +0 -7
  63. package/commands/ship.md +0 -7
  64. package/commands/spec.md +0 -7
  65. package/commands/test.md +0 -7
  66. package/commands/webperf.md +0 -7
  67. package/reference/auto-mandate.md +0 -11
  68. package/reference/backup-convention.md +0 -9
  69. package/reference/clean-mandate.md +0 -13
  70. package/reference/editor-parity.md +0 -7
  71. package/reference/gc-scripts.md +0 -8
  72. package/reference/intent-routing.md +0 -14
  73. package/reference/lifecycle.md +0 -15
  74. package/reference/model-keeper.md +0 -46
  75. package/reference/model-test.md +0 -176
  76. package/reference/oc-source-map.md +0 -162
  77. package/reference/owner-pin.md +0 -31
  78. package/reference/roster.md +0 -15
  79. package/reference/session-scope.md +0 -9
  80. package/reference/session-state.md +0 -13
  81. package/reference/swarm.md +0 -32
  82. package/scripts/backup-config.ps1 +0 -42
  83. package/scripts/gc-branch.ps1 +0 -196
  84. package/scripts/gc-bump.ps1 +0 -198
  85. package/scripts/gc-clean.ps1 +0 -648
  86. package/scripts/gc-commit.ps1 +0 -143
  87. package/scripts/gc-merge.ps1 +0 -272
  88. package/scripts/gc-pr.ps1 +0 -190
  89. package/scripts/gc-push.ps1 +0 -111
  90. package/scripts/gc-read.ps1 +0 -150
  91. package/scripts/gc-rebase.ps1 +0 -162
  92. package/scripts/gc-release.ps1 +0 -225
  93. package/scripts/gc-stage.ps1 +0 -103
  94. package/scripts/gc-status.ps1 +0 -127
  95. package/scripts/gc-sync.ps1 +0 -65
  96. package/scripts/gc.core.ps1 +0 -715
  97. package/scripts/gc.smoke.ps1 +0 -779
  98. package/scripts/interrupt-session.ps1 +0 -65
  99. package/scripts/logbook/README.md +0 -108
  100. package/scripts/logbook/logbook.test.ts +0 -440
  101. package/scripts/logbook/logbook.ts +0 -797
  102. package/scripts/pirep/README.md +0 -147
  103. package/scripts/pirep/pirep.test.ts +0 -735
  104. package/scripts/pirep/pirep.ts +0 -836
  105. package/scripts/testflight/README.md +0 -112
  106. package/scripts/testflight/testflight.test.ts +0 -512
  107. package/scripts/testflight/testflight.ts +0 -806
  108. package/skills/_shared/SOURCES.md +0 -26
  109. package/skills/_shared/references/accessibility-checklist.md +0 -160
  110. package/skills/_shared/references/definition-of-done.md +0 -67
  111. package/skills/_shared/references/observability-checklist.md +0 -92
  112. package/skills/_shared/references/orchestration-patterns.md +0 -155
  113. package/skills/_shared/references/performance-checklist.md +0 -236
  114. package/skills/_shared/references/security-checklist.md +0 -245
  115. package/skills/_shared/references/testing-patterns.md +0 -235
  116. package/skills/api-and-interface-design/SKILL.md +0 -14
  117. package/skills/browser-testing-with-devtools/SKILL.md +0 -303
  118. package/skills/code-simplification/SKILL.md +0 -14
  119. package/skills/creative-writing/SKILL.md +0 -96
  120. package/skills/debugging-and-error-recovery/SKILL.md +0 -15
  121. package/skills/flight-deck/SKILL.md +0 -17
  122. package/skills/frontend-ui-engineering/SKILL.md +0 -16
  123. package/skills/gauntlet/SKILL.md +0 -21
  124. package/skills/git-ceremony/SKILL.md +0 -27
  125. package/skills/grilling/SKILL.md +0 -18
  126. package/skills/observability-and-instrumentation/SKILL.md +0 -18
  127. package/skills/performance-optimization/SKILL.md +0 -16
  128. package/skills/pilot-report/SKILL.md +0 -18
  129. package/skills/planning-and-task-breakdown/SKILL.md +0 -16
  130. package/skills/security-and-hardening/SKILL.md +0 -18
  131. package/skills/source-driven-development/SKILL.md +0 -16
  132. package/skills/spec-driven-development/SKILL.md +0 -26
  133. package/skills/test-driven-development/SKILL.md +0 -18
  134. package/skills/test-flight/SKILL.md +0 -14
  135. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  136. package/skills/writing-for-agents/SKILL.md +0 -89
package/bin/cli.js CHANGED
@@ -8,6 +8,7 @@
8
8
  * --ci refuse to mutate: print the manifest, exit 0
9
9
  * setup --uninstall delete exactly the manifest-listed files, keep
10
10
  * user-modified ones, print the backup restore path
11
+ * --version / -v print the package version, touch nothing
11
12
  *
12
13
  * Exit codes are strictly 0 (ok / clean abort) or 1 (failure).
13
14
  */
@@ -15,7 +16,7 @@ import { spawnSync } from 'node:child_process';
15
16
  import { createHash } from 'node:crypto';
16
17
  import {
17
18
  cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync,
18
- rmSync, statSync, writeFileSync,
19
+ rmdirSync, rmSync, statSync, writeFileSync,
19
20
  } from 'node:fs';
20
21
  import { homedir } from 'node:os';
21
22
  import path from 'node:path';
@@ -24,8 +25,13 @@ import { createInterface } from 'node:readline/promises';
24
25
  const PKG_NAME = 'oc-harness-setup';
25
26
  const PKG_ROOT = path.resolve(import.meta.dirname, '..');
26
27
  const MANIFEST_FILE = 'oc-harness-setup.manifest.json';
27
- const COPY_DIRS = ['agents', 'commands', 'skills', 'reference', 'scripts', '.docs'];
28
- const COPY_FILES = ['AGENTS.md', '.gitignore'];
28
+ const COPY_DIRS = ['agents', 'commands', 'skills', 'reference', 'scripts', '.docs', 'state-seed'];
29
+ const COPY_FILES = ['AGENTS.md', 'GLOSSARY.md', '.gitignore'];
30
+ // Source→destination aliases: the pack ships `state-seed/` (tracked) but the
31
+ // live tree owns `state/` (git-ignored runtime), so every incoming
32
+ // `state-seed/...` file lands at `state/...`. `rel` is ALWAYS the
33
+ // destination-relative path — manifest, journal, and logs use it.
34
+ const DIR_ALIASES = { 'state-seed': 'state' };
29
35
  // Ownership table for the opencode.jsonc merge. Every top-level key falls into
30
36
  // exactly one bucket; there is no "known merge key" list to drift out of date.
31
37
  // INSTALL_OWNED — the distro's value wins outright (runtime policy).
@@ -39,28 +45,33 @@ const COPY_FILES = ['AGENTS.md', '.gitignore'];
39
45
  // allowlist is deny-then-allows; see mergeJsonc).
40
46
  // everything else (known or unknown) — the adopter's value wins; the distro
41
47
  // value stays when the adopter does not define the key.
42
- const INSTALL_OWNED = ['$schema', 'default_agent', 'formatter', 'compaction', 'tool_output', 'media', 'watcher'];
48
+ const INSTALL_OWNED = ['$schema', 'default_agent', 'formatter', 'compaction', 'tool_output', 'media', 'watcher', 'policies'];
43
49
  const UNION_KEYS = ['plugins'];
44
- // Adopter-owned files: shipped copies are skeletons, so an existing destination
45
- // that differs MUST survive an upgrade — overwriting it destroys their data.
46
- const PRESERVE_IF_EXISTS = new Set(['reference/models.md', 'reference/owner-pin.md', 'AGENTS.md', '.gitignore']);
47
- // Author-leak markers — they catch the MAINTAINER's machine leaking into the
48
- // shipped tree (paths, username, session ids). They are linted against the
49
- // package source only, never the adopter's config, so a legitimate
50
+ // Adopter-owned files: a shipped skeleton that the adopter genuinely edited
51
+ // MUST survive an upgrade — overwriting it destroys their data. Genuineness
52
+ // is proven against the prior manifest (see stageFiles): a destination that
53
+ // still matches the prior installed hash is unmodified pack content and IS
54
+ // updated, so a stock 0.3.3 AGENTS.md is replaced by the V9 contract while a
55
+ // genuinely adopter-edited one is kept.
56
+ const PRESERVE_IF_EXISTS = new Set(['reference/models.md', 'AGENTS.md', '.gitignore', 'state/lessons.md', 'state/template.md']);
57
+ // Leak markers — generic shapes, never a concrete machine. They catch the
58
+ // maintainer's workstation leaking into the shipped tree (an absolute
59
+ // user-profile path, a session id). They are linted against the package
60
+ // source only, never the adopter's config, so a legitimate
50
61
  // `{file:~/.secrets/…}` apiKey pointer can never abort an install.
51
62
  //
52
- // Every marker is anchored to the author's concrete machine — a drive
53
- // letter, a username, a real session id — never to the product's own vocabulary. The
54
- // harness's safety tooling legitimately ships the generic forms
55
- // (`C:\Users\<name>`, `ses_<id>`, `~/.secrets/…` — redactor regexes and their
56
- // self-test probes), so a bare generic token would abort every correct install.
57
- // A leak of an author path into a secret store is caught by the username/drive
58
- // markers; a bare `.secrets` cannot distinguish product from author and so is
59
- // deliberately not a marker. The username marker also subsumes the full profile path.
63
+ // Every marker is a SHAPE, not a value: a drive letter plus a user-profile
64
+ // path, a session-id token — never the product's own vocabulary. The
65
+ // harness's safety tooling legitimately ships illustrative path fragments
66
+ // and self-test probes, so a bare generic token would abort every correct
67
+ // install; the markers are drawn tight enough to miss them (verified by the
68
+ // packaging audit, which runs these same shapes over the shipped tree).
69
+ // A leak of a concrete workstation path into a secret store is caught by the
70
+ // profile-path marker; a bare `.secrets` cannot distinguish product from
71
+ // author and so is deliberately not a marker.
60
72
  const LINT_PATTERNS = [
61
- { label: 'q:\\', test: /q:\\/ },
62
- { label: 'nathan', test: /nathan/ },
63
- { label: 'ses_<id>', test: /ses_[a-z0-9]{16,}/ },
73
+ { label: 'absolute user path', test: /[a-z]:[\\/]users[\\/]/i },
74
+ { label: 'session id', test: /ses_[a-z0-9]{16,}/ },
64
75
  ];
65
76
 
66
77
  /* ------------------------------ tiny helpers ------------------------------ */
@@ -108,7 +119,8 @@ usage:
108
119
  oc-harness-setup setup full install (default: no args needed)
109
120
  oc-harness-setup --dry-run print the manifest only; touch nothing
110
121
  oc-harness-setup --ci print-only, refuse to mutate, exit 0
111
- oc-harness-setup setup --uninstall remove exactly the manifest-listed files`);
122
+ oc-harness-setup setup --uninstall remove exactly the manifest-listed files
123
+ oc-harness-setup --version print the package version`);
112
124
  }
113
125
 
114
126
  class Bail extends Error {}
@@ -117,6 +129,17 @@ function bail(msg) {
117
129
  throw new Bail(msg);
118
130
  }
119
131
 
132
+ // Windows 10/11 only. This installer writes the Windows config home, runs
133
+ // PowerShell doctors, and registers Windows shell policy — there is no
134
+ // macOS/Linux path. --help and --version return from parseArgs before any
135
+ // dispatch, so they keep working everywhere.
136
+ function assertWindows() {
137
+ if (process.platform !== 'win32') {
138
+ bail('Windows 10/11 only — macOS and Linux are not supported.');
139
+ }
140
+ log('platform', 'Windows detected — running the Windows installer path');
141
+ }
142
+
120
143
  function sha256(buf) {
121
144
  return createHash('sha256').update(buf).digest('hex');
122
145
  }
@@ -211,28 +234,16 @@ function findConfigDir() {
211
234
  log('config', `env OPENCODE_CONFIG_DIR: ${dir}`);
212
235
  return dir;
213
236
  }
214
- if (env.XDG_CONFIG_HOME) {
215
- const p = path.join(env.XDG_CONFIG_HOME, 'opencode');
216
- log('config', `XDG_CONFIG_HOME fallback: ${p}`);
217
- return p;
218
- }
219
- if (process.platform === 'win32' && env.USERPROFILE) {
220
- const p = path.join(env.USERPROFILE, '.config', 'opencode');
221
- log('config', `%USERPROFILE% fallback: ${p}`);
222
- return p;
223
- }
224
- if (env.HOME) {
225
- const p = path.join(env.HOME, '.config', 'opencode');
226
- log('config', `$HOME fallback: ${p}`);
227
- return p;
228
- }
229
- const home = homedir();
230
- if (home) {
231
- const p = path.join(home, '.config', 'opencode');
232
- log('config', `os.homedir() fallback: ${p}`);
237
+ // Windows-only target: the live Windows profile owns the config home.
238
+ // There are no XDG/HOME fallbacks — macOS and Linux are not supported
239
+ // (assertWindows bails before any discovery on those platforms).
240
+ const profile = env.USERPROFILE || homedir();
241
+ if (profile) {
242
+ const p = path.resolve(path.join(profile, '.config', 'opencode'));
243
+ log('config', `profile fallback: ${p}`);
233
244
  return p;
234
245
  }
235
- bail('could not determine the OpenCode config dir. Set OPENCODE_CONFIG_DIR and re-run.');
246
+ bail('could not determine the OpenCode config dir. Set OPENCODE_CONFIG_DIR and re-run (USERPROFILE is absent).');
236
247
  }
237
248
 
238
249
  /* --------------------------- package tree collection ----------------------- */
@@ -253,13 +264,17 @@ function collectIncoming(configDir) {
253
264
  log('staging', `note: ${dirName}/ not present in this package — nothing to copy from it`);
254
265
  continue;
255
266
  }
256
- walkDir(srcDir, (p) =>
267
+ walkDir(srcDir, (p) => {
268
+ const pkgRel = path.relative(PKG_ROOT, p);
269
+ // Alias the destination: state-seed/lessons.md -> state/lessons.md.
270
+ const top = pkgRel.split(path.sep)[0];
271
+ const rel = DIR_ALIASES[top] ? path.join(DIR_ALIASES[top], pkgRel.slice(top.length + 1)) : pkgRel;
257
272
  files.push({
258
- rel: path.relative(PKG_ROOT, p),
273
+ rel,
259
274
  src: p,
260
- dest: path.join(configDir, path.relative(PKG_ROOT, p)),
261
- })
262
- );
275
+ dest: path.join(configDir, rel),
276
+ });
277
+ });
263
278
  }
264
279
  for (const f of COPY_FILES) {
265
280
  const src = path.join(PKG_ROOT, f);
@@ -299,26 +314,66 @@ function nextBackupPath(configDir) {
299
314
 
300
315
  /* ------------------------------ staged copy -------------------------------- */
301
316
 
302
- function stageFiles(files, manifest) {
317
+ function stageFiles(files, manifest, prior, configDir) {
318
+ // Prior manifests spell paths with either separator; incoming rels use the
319
+ // platform join. Compare on normalized slashes so a prior entry still
320
+ // matches its incoming path (journaling keeps each entry's own spelling).
321
+ const norm = (p) => String(p).replace(/\\/g, '/');
322
+ const priorByPath = new Map(
323
+ (prior && Array.isArray(prior.files) ? prior.files : []).map((f) => [norm(f.path), f])
324
+ );
303
325
  let written = 0;
304
326
  for (const f of files) {
305
327
  const srcHash = sha256File(f.src);
306
328
  let action = 'written';
307
329
  let prevHash = null;
330
+ let archivedTo = null;
308
331
  if (existsSync(f.dest)) {
309
332
  const destHash = sha256File(f.dest);
310
333
  if (destHash === srcHash) {
311
334
  action = 'skip';
312
335
  log('staging', `skip ${f.rel} (already identical — rerun-safe)`);
313
336
  } else if (PRESERVE_IF_EXISTS.has(f.rel)) {
314
- action = 'preserved';
315
- log('staging', `preserve ${f.rel} (exists and differs — kept; harness will not overwrite adopter-owned files)`);
337
+ // Upgrade rule: preserve only a GENUINELY adopter-edited file, i.e.
338
+ // one that differs from the prior manifest hash. A destination that
339
+ // still matches the prior installed hash is unmodified pack content —
340
+ // update it, so a stock 0.3.3 AGENTS.md is replaced by the V9 contract
341
+ // while an adopter-edited AGENTS.md is kept. No prior record means we
342
+ // cannot prove it is stock, so preserve (never destroy unknown data).
343
+ const p = priorByPath.get(norm(f.rel));
344
+ if (p && p.hash && destHash === p.hash) {
345
+ action = 'overwritten';
346
+ prevHash = destHash;
347
+ log('staging', `update ${f.rel} (matches the prior installed hash — unmodified pack content, overwriting; backup + manifest protect you)`);
348
+ } else {
349
+ action = 'preserved';
350
+ log('staging', `preserve ${f.rel} (exists and differs from the prior install — kept; harness will not overwrite adopter-owned files)`);
351
+ }
316
352
  } else {
317
- // A genuine overwrite: journal it so --uninstall can put the original
318
- // back from the pre-install backup instead of deleting the harness copy.
319
- action = 'overwritten';
320
- prevHash = destHash;
321
- log('staging', `update ${f.rel} (destination differs — overwriting; backup + manifest protect you)`);
353
+ // Safe-upgrade rule: a destination the user edited since install
354
+ // (its bytes differ from the prior manifest hash) is archived before
355
+ // the overwrite, so a user-modified 0.3.x file that the new distro
356
+ // still ships — e.g. agents/orchestrator.md — is never silently
357
+ // destroyed. Unmodified pack content (or no prior record) overwrites
358
+ // normally; the pre-install backup still protects it. Files in
359
+ // PRESERVE_IF_EXISTS never reach this branch (kept above, never
360
+ // archived). Same archive root and nextFreePath as retireStale.
361
+ const p = priorByPath.get(norm(f.rel));
362
+ if (p && p.hash && destHash !== p.hash) {
363
+ const dest2 = nextFreePath(path.join(configDir, 'state', 'archive', 'legacy-0.3.x', f.rel));
364
+ mkdirSync(path.dirname(dest2), { recursive: true });
365
+ renameSync(f.dest, dest2);
366
+ archivedTo = path.relative(configDir, dest2);
367
+ action = 'overwritten';
368
+ prevHash = destHash;
369
+ log('staging', `archive ${f.rel} → ${archivedTo} (you edited the old file — pre-upgrade bytes moved aside; writing the new file)`);
370
+ } else {
371
+ // A genuine overwrite: journal it so --uninstall can put the original
372
+ // back from the pre-install backup instead of deleting the harness copy.
373
+ action = 'overwritten';
374
+ prevHash = destHash;
375
+ log('staging', `update ${f.rel} (destination differs — overwriting; backup + manifest protect you)`);
376
+ }
322
377
  }
323
378
  } else {
324
379
  log('staging', `copy ${f.rel}`);
@@ -333,11 +388,126 @@ function stageFiles(files, manifest) {
333
388
  // Preserved entries journal the SRC hash on purpose: --uninstall deletes
334
389
  // only on an exact match, so a preserved destination (bytes differ from
335
390
  // src) reads as modified → kept, not deleted.
336
- manifest.files.push(prevHash ? { path: f.rel, hash: srcHash, prevHash, action } : { path: f.rel, hash: srcHash, action });
391
+ if (archivedTo) {
392
+ manifest.files.push({ path: f.rel, hash: srcHash, prevHash, action, archivedTo });
393
+ } else if (prevHash) {
394
+ manifest.files.push({ path: f.rel, hash: srcHash, prevHash, action });
395
+ } else {
396
+ manifest.files.push({ path: f.rel, hash: srcHash, action });
397
+ }
337
398
  }
338
399
  return written;
339
400
  }
340
401
 
402
+ // A prior `skills/<id>/...` path belongs to skill <id>; anything else is not
403
+ // a skill path (null). Used to prune stale skill allowlist entries after an
404
+ // upgrade retires or archives the skill's files.
405
+ function skillIdOf(rel) {
406
+ const parts = String(rel).split(/[\\/]/);
407
+ return parts[0] === 'skills' && parts.length > 2 ? parts[1] : null;
408
+ }
409
+
410
+ // Prune directories left empty, up to (not including) the config dir: a
411
+ // stale empty `skills/old/` would otherwise trip the doctor's skill laws (a
412
+ // directory with no SKILL.md). Non-empty parents (adopter files inside) stop
413
+ // the climb and are kept.
414
+ function pruneEmptyParents(base, dir) {
415
+ while (dir !== base && dir.startsWith(base + path.sep)) {
416
+ let ents;
417
+ try {
418
+ ents = readdirSync(dir);
419
+ } catch {
420
+ break;
421
+ }
422
+ if (ents.length) break;
423
+ try {
424
+ rmdirSync(dir);
425
+ } catch {
426
+ break;
427
+ }
428
+ log('retire', `pruned empty dir ${path.relative(base, dir)} (left empty)`);
429
+ dir = path.dirname(dir);
430
+ }
431
+ }
432
+
433
+ // Upgrade sweep: retire pack files the new distro no longer ships (old agent
434
+ // roster, old skills/commands/references/scripts). Runs BEFORE staging, so a
435
+ // retired path can never collide with an incoming one. Returns the Set of
436
+ // retired skill IDs (missing, retired, or archived) so the merge can prune
437
+ // their stale allowlist entries. For every prior manifest entry NOT in the
438
+ // incoming destination set: `merged` entries (opencode.jsonc) are ignored;
439
+ // anything else is resolved inside the config dir. A destination that is
440
+ // already gone just contributes its skill ID. Unmodified pack content (bytes
441
+ // still equal the prior entry hash) is deleted and journaled as
442
+ // { path, hash, action: 'retired' }. Modified content (the adopter owns the
443
+ // bytes) is MOVED out of the active tree into the runtime-ignored
444
+ // `state/archive/legacy-0.3.x/<rel>` (nextFreePath on collision) and
445
+ // journaled as { path, hash, action: 'archived', archivedTo } — nothing is
446
+ // destroyed. Unreadable entries are kept and the reason is logged.
447
+ // --uninstall restores both kinds from the pre-install backup.
448
+ function retireStale(configDir, prior, files, manifest) {
449
+ const retiredSkills = new Set();
450
+ if (!prior || !Array.isArray(prior.files)) return retiredSkills;
451
+ // Incoming rels use the platform join while a prior manifest may spell the
452
+ // same path with the other separator — compare on normalized slashes so a
453
+ // prior entry that the distro still ships is not mistaken for stale.
454
+ // Journaling keeps each entry's own spelling.
455
+ const norm = (p) => String(p).replace(/\\/g, '/');
456
+ const incoming = new Set(files.map((f) => norm(f.rel)));
457
+ const base = path.resolve(configDir);
458
+ for (const entry of prior.files) {
459
+ const rel = String(entry.path || '');
460
+ if (!rel || incoming.has(norm(rel))) continue;
461
+ if (entry.action === 'merged') continue;
462
+ if (entry.action === 'retired' || entry.action === 'archived') {
463
+ // An earlier run already settled this path; its skill stays pruned.
464
+ const settled = skillIdOf(rel);
465
+ if (settled) retiredSkills.add(settled);
466
+ continue;
467
+ }
468
+ const resolved = path.resolve(base, rel);
469
+ if (resolved !== base && !resolved.startsWith(base + path.sep)) {
470
+ log('retire', `skip ${rel} (escapes the config dir — refusing)`);
471
+ continue;
472
+ }
473
+ const skillId = skillIdOf(rel);
474
+ if (!existsSync(resolved)) {
475
+ if (skillId) retiredSkills.add(skillId);
476
+ log('retire', `absent ${rel} (already gone — nothing to retire)`);
477
+ continue;
478
+ }
479
+ try {
480
+ if (!statSync(resolved).isFile()) {
481
+ log('retire', `keep ${rel} (not a file — refusing)`);
482
+ continue;
483
+ }
484
+ } catch {
485
+ log('retire', `keep ${rel} (unreadable — refusing)`);
486
+ continue;
487
+ }
488
+ if (entry.hash && sha256File(resolved) === entry.hash) {
489
+ rmSync(resolved, { force: true });
490
+ manifest.files.push({ path: rel, hash: entry.hash, action: 'retired' });
491
+ if (skillId) retiredSkills.add(skillId);
492
+ log('retire', `retired ${rel} (unmodified pack content from the prior install — journaled for uninstall restore)`);
493
+ pruneEmptyParents(base, path.dirname(resolved));
494
+ } else if (entry.hash) {
495
+ const archivedTo = path.join('state', 'archive', 'legacy-0.3.x', rel);
496
+ const dest = nextFreePath(path.join(base, archivedTo));
497
+ mkdirSync(path.dirname(dest), { recursive: true });
498
+ renameSync(resolved, dest);
499
+ const relArchivedTo = path.relative(base, dest);
500
+ manifest.files.push({ path: rel, hash: entry.hash, action: 'archived', archivedTo: relArchivedTo });
501
+ if (skillId) retiredSkills.add(skillId);
502
+ log('retire', `archived ${rel} → ${relArchivedTo} (modified since install — moved out of the active tree; journaled for uninstall restore)`);
503
+ pruneEmptyParents(base, path.dirname(resolved));
504
+ } else {
505
+ log('retire', `keep ${rel} (no prior hash to compare — adopter owns it now)`);
506
+ }
507
+ }
508
+ return retiredSkills;
509
+ }
510
+
341
511
  /* ---------------------------- opencode.jsonc merge ------------------------- */
342
512
 
343
513
  function stripJsonc(text) {
@@ -410,7 +580,7 @@ function parseJsonc(text, what) {
410
580
  }
411
581
  }
412
582
 
413
- function mergeJsonc(configDir, backupPath, manifest) {
583
+ function mergeJsonc(configDir, backupPath, manifest, retiredSkills = new Set()) {
414
584
  const distroPath = path.join(PKG_ROOT, 'opencode.jsonc');
415
585
  if (!existsSync(distroPath)) {
416
586
  log('merge', 'note: this package ships no opencode.jsonc — no merge to do');
@@ -463,7 +633,25 @@ function mergeJsonc(configDir, backupPath, manifest) {
463
633
  const isHardDeny = (p) => !!p && p.effect === 'deny' && p.action !== 'skill';
464
634
  const distroHead = distroPerms.filter((p) => !isHardDeny(p));
465
635
  const distroTail = distroPerms.filter(isHardDeny);
466
- const userOnly = userPerms.filter((p) => !distroPerms.some((d) => sameRule(d, p)));
636
+ // Stale skill allows die with their skills: an adopter allow for a
637
+ // retired/archived skill would otherwise dangle (Law 14 fails a
638
+ // dangling allow). Custom adopter allows for live skills pass through.
639
+ const droppedStaleAllows = [];
640
+ const userOnly = userPerms.filter((p) => {
641
+ if (distroPerms.some((d) => sameRule(d, p))) return false;
642
+ if (
643
+ p && p.action === 'skill' && p.effect === 'allow' &&
644
+ typeof p.resource === 'string' && p.resource !== '*' &&
645
+ retiredSkills.has(p.resource)
646
+ ) {
647
+ droppedStaleAllows.push(p.resource);
648
+ return false;
649
+ }
650
+ return true;
651
+ });
652
+ if (droppedStaleAllows.length) {
653
+ log('merge', `dropped stale skill allows for retired skills: ${droppedStaleAllows.join(', ')}`);
654
+ }
467
655
  merged.permissions = [...distroHead, ...userOnly, ...distroTail];
468
656
  } else if (UNION_KEYS.includes(k)) {
469
657
  merged[k] = Array.isArray(user[k])
@@ -523,50 +711,6 @@ function lintPackagedSource(files) {
523
711
  return hits;
524
712
  }
525
713
 
526
- /* ------------------------------- plugin gate ------------------------------- */
527
-
528
- function registerPlugins() {
529
- const list = ['oc-flight-deck'];
530
- for (const p of list) {
531
- log('plugin', `opencode plugin add ${p}`);
532
- const res = exec('opencode', ['plugin', 'add', p], false);
533
- if (res.error || res.status !== 0) {
534
- log(
535
- 'plugin',
536
- `'opencode plugin add ${p}' failed (${res.error ? 'not found' : `exit ${res.status}`}) — add it manually later; the config is already installed`
537
- );
538
- } else {
539
- log('plugin', `${p} registered`);
540
- }
541
- }
542
- return list;
543
- }
544
-
545
- // The doctor's Law 6 grades `opencode plugin list`, but right after `plugin
546
- // add` on a fresh config the registry can lag the file write by minutes - the
547
- // doctor would grade an empty list and fail. Poll the list (bounded: up to 10
548
- // attempts, 6 s apart) until every requested name appears in a row, mirroring
549
- // the doctor's own row-contains-name check. Warning-only on expiry - exit
550
- // codes are unchanged (the doctor grades; a re-run is idempotent).
551
- async function waitForPluginRegistration(plugins, configDir) {
552
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
553
- for (let attempt = 1; attempt <= 10; attempt++) {
554
- const res = exec('opencode', ['plugin', 'list'], true);
555
- const rows = (res.stdout || '').split(/\r?\n/).filter((l) => l.trim() !== '');
556
- const missing = plugins.filter((name) => !rows.some((row) => row.includes(name)));
557
- const state = res.error || res.status !== 0
558
- ? `list failed (${res.error ? 'not found' : `exit ${res.status}`})`
559
- : `${rows.length} row(s), missing: ${missing.length ? missing.join(', ') : 'none'}`;
560
- log('plugin', `registration wait ${attempt}/10 (${configDir}) - ${state}`);
561
- if (!missing.length) {
562
- for (const name of plugins) log('plugin', `${name} appears in the registry`);
563
- return;
564
- }
565
- if (attempt < 10) await sleep(6000);
566
- }
567
- console.warn(`[plugin] WARNING: plugin registry did not confirm ${plugins.join(', ')} within 60s - the doctor will grade it; re-run setup (idempotent) if it fails`);
568
- }
569
-
570
714
  /* --------------------------------- doctor ---------------------------------- */
571
715
 
572
716
  function pwshProbe() {
@@ -577,12 +721,12 @@ function pwshProbe() {
577
721
  function doctorPlan() {
578
722
  return pwshProbe().usable
579
723
  ? 'run scripts/harness-doctor.ps1 via pwsh'
580
- : 'pwsh missing — doctor SKIPPED, 16 laws UNVERIFIED (warned + journaled)';
724
+ : 'pwsh missing — doctor SKIPPED, 18 laws UNVERIFIED (warned + journaled)';
581
725
  }
582
726
 
583
727
  function runDoctor(configDir, probe) {
584
728
  if (!probe.usable) {
585
- console.warn('[doctor] WARNING: pwsh (PowerShell 7) was not found — harness-doctor did NOT run, so the 16 laws are UNVERIFIED.');
729
+ console.warn('[doctor] WARNING: pwsh (PowerShell 7) was not found — harness-doctor did NOT run, so the 18 laws are UNVERIFIED.');
586
730
  console.warn('[doctor] Your config still landed, and the skip is recorded in the manifest. To verify later:');
587
731
  console.log(' winget install --id Microsoft.PowerShell --source winget (Windows)');
588
732
  console.log(' brew install --cask powershell (macOS)');
@@ -591,7 +735,7 @@ function runDoctor(configDir, probe) {
591
735
  }
592
736
  const script = path.join(configDir, 'scripts', 'harness-doctor.ps1');
593
737
  if (!existsSync(script)) {
594
- console.warn(`[doctor] WARNING: ${script} not found — harness-doctor did NOT run, so the 16 laws are UNVERIFIED.`);
738
+ console.warn(`[doctor] WARNING: ${script} not found — harness-doctor did NOT run, so the 18 laws are UNVERIFIED.`);
595
739
  return { code: 0, skipped: true };
596
740
  }
597
741
  log('doctor', `running ${script}`);
@@ -616,10 +760,12 @@ function printManifest(configDir, files, backupPath, doctor) {
616
760
  console.log(` destination config dir : ${configDir}`);
617
761
  console.log(` incoming files : ${files.length} (${newCount} new, ${sameCount} already identical — rerun-safe)`);
618
762
  console.log(` backup path : ${backupPath}`);
619
- console.log(' opencode.jsonc merge : distro base (permissions/deny block, skill allowlist,');
763
+ console.log(' opencode.jsonc merge : distro base (permissions/deny block, policies block, skill allowlist,');
620
764
  console.log(' default_agent: "orchestrator", references registry)');
621
765
  console.log(' + your keys kept · permissions: harness allows, yours, harness denies last');
622
- console.log(' plugin registration : oc-flight-deck (via \'opencode plugin add\')');
766
+ console.log(' state-seed/ -> state/ : shipped seed maps to live state/ (existing state/lessons.md,');
767
+ console.log(' state/template.md preserved when genuinely edited)');
768
+ console.log(' doctor plan : harness-doctor, 18 laws');
623
769
  console.log(` doctor plan : ${doctor}`);
624
770
  console.log('----------------------------------------------------------------------------');
625
771
  }
@@ -642,6 +788,7 @@ async function confirmProceed() {
642
788
  function uninstall(configDir, opts = {}) {
643
789
  // F3: --dry-run / --ci preview what would be removed and return 0 without
644
790
  // deleting (setup --uninstall --dry-run must touch nothing).
791
+ assertWindows();
645
792
  const preview = !!(opts.preview || opts.dryRun || opts.ci);
646
793
  const manifestPath = path.join(configDir, MANIFEST_FILE);
647
794
  if (!existsSync(manifestPath)) {
@@ -671,6 +818,62 @@ function uninstall(configDir, opts = {}) {
671
818
  log('uninstall', `skip ${rel} (escapes the config dir — refusing)`);
672
819
  continue;
673
820
  }
821
+ if (entry.action === 'retired') {
822
+ // An upgrade retired this path: it is gone from the new distro. If the
823
+ // adopter never recreated it, put the pre-install original back from
824
+ // the backup; if they recreated it, it is theirs now — keep it.
825
+ if (!existsSync(resolved)) {
826
+ const original = backupRoot ? path.join(backupRoot, rel) : null;
827
+ if (original && existsSync(original)) {
828
+ if (preview) {
829
+ restored += 1;
830
+ log('uninstall', `would restore ${rel} (retired by upgrade — your pre-install file, from ${manifest.backupPath})`);
831
+ } else {
832
+ mkdirSync(path.dirname(resolved), { recursive: true });
833
+ cpSync(original, resolved, { force: true });
834
+ restored += 1;
835
+ log('uninstall', `restored ${rel} (retired by upgrade — your pre-install file, from ${manifest.backupPath})`);
836
+ }
837
+ } else {
838
+ missing += 1;
839
+ log('uninstall', `missing ${rel} (retired by upgrade and no backup holds it — nothing to restore)`);
840
+ }
841
+ } else {
842
+ kept += 1;
843
+ log('uninstall', `kept ${rel} (you recreated it after the upgrade retired it — keeping)`);
844
+ }
845
+ continue;
846
+ }
847
+ if (entry.action === 'archived') {
848
+ // An upgrade archived this path (you had modified it): the live bytes
849
+ // moved to state/archive/ and the active path went away. If the active
850
+ // path is still absent, put the pre-install original back from the
851
+ // backup; if you recreated it, it is yours now — keep it. Either way
852
+ // the archive path is reported so your bytes stay findable.
853
+ const archivedTo = entry.archivedTo ? String(entry.archivedTo) : null;
854
+ const archiveNote = archivedTo ? ` (your modified bytes live at ${archivedTo})` : '';
855
+ if (!existsSync(resolved)) {
856
+ const original = backupRoot ? path.join(backupRoot, rel) : null;
857
+ if (original && existsSync(original)) {
858
+ if (preview) {
859
+ restored += 1;
860
+ log('uninstall', `would restore ${rel} (archived by upgrade — your pre-install file, from ${manifest.backupPath})${archiveNote}`);
861
+ } else {
862
+ mkdirSync(path.dirname(resolved), { recursive: true });
863
+ cpSync(original, resolved, { force: true });
864
+ restored += 1;
865
+ log('uninstall', `restored ${rel} (archived by upgrade — your pre-install file, from ${manifest.backupPath})${archiveNote}`);
866
+ }
867
+ } else {
868
+ missing += 1;
869
+ log('uninstall', `missing ${rel} (archived by upgrade and no backup holds it — nothing to restore)${archiveNote}`);
870
+ }
871
+ } else {
872
+ kept += 1;
873
+ log('uninstall', `kept ${rel} (you recreated it after the upgrade archived it — keeping)${archiveNote}`);
874
+ }
875
+ continue;
876
+ }
674
877
  if (!existsSync(resolved)) {
675
878
  missing += 1;
676
879
  continue;
@@ -678,8 +881,11 @@ function uninstall(configDir, opts = {}) {
678
881
  if (entry.action === 'overwritten' || entry.action === 'merged') {
679
882
  // A genuine overwrite comes back from the pre-install backup; the merged
680
883
  // opencode.jsonc is never deleted — restore the adopter's original, or
681
- // leave the harness copy in place when no backup holds it.
884
+ // leave the harness copy in place when no backup holds it. An
885
+ // `archivedTo` entry additionally keeps the pre-upgrade bytes in the
886
+ // runtime archive and says so.
682
887
  const original = backupRoot ? path.join(backupRoot, rel) : null;
888
+ const archiveNote = entry.archivedTo ? ` (pre-upgrade archive kept at ${entry.archivedTo})` : null;
683
889
  if (original && existsSync(original)) {
684
890
  // Restoring is only reversible if the bytes being replaced survive. When
685
891
  // the current file is not the one the installer wrote (hash differs, or
@@ -699,11 +905,11 @@ function uninstall(configDir, opts = {}) {
699
905
  }
700
906
  if (preview) {
701
907
  restored += 1;
702
- log('uninstall', `would restore ${rel} (your pre-install file, from ${manifest.backupPath})`);
908
+ log('uninstall', `would restore ${rel} (your pre-install file, from ${manifest.backupPath})${archiveNote || ''}`);
703
909
  } else {
704
910
  cpSync(original, resolved, { force: true });
705
911
  restored += 1;
706
- log('uninstall', `restored ${rel} (your pre-install file, from ${manifest.backupPath})`);
912
+ log('uninstall', `restored ${rel} (your pre-install file, from ${manifest.backupPath})${archiveNote || ''}`);
707
913
  }
708
914
  } else if (entry.action === 'merged' && entry.hash && sha256File(resolved) === entry.hash) {
709
915
  // F5: installer-created merge output (adopter had only opencode.json,
@@ -751,12 +957,7 @@ function uninstall(configDir, opts = {}) {
751
957
  console.log(` ${preserved} post-install edit-copy(ies) written beside the restored file(s) as <name>.replaced-<ts> (listed above).`);
752
958
  }
753
959
  if (manifest.doctorSkipped) {
754
- console.log(' note: this install skipped the doctor — the 16 laws were never verified.');
755
- }
756
- if (Array.isArray(manifest.plugins) && manifest.plugins.length) {
757
- console.log(
758
- ` plugins left registered: ${manifest.plugins.join(', ')} — remove with 'opencode plugin remove <name>' if unwanted.`
759
- );
960
+ console.log(' note: this install skipped the doctor — the 18 laws were never verified.');
760
961
  }
761
962
  }
762
963
 
@@ -776,8 +977,10 @@ function carryForwardJournal(manifest, prior) {
776
977
  if (!prior || !Array.isArray(prior.files)) return;
777
978
  const before = new Map(prior.files.map((f) => [String(f.path), f]));
778
979
  for (const e of manifest.files) {
980
+ if (e.action === 'retired' || e.action === 'archived') continue; // a retirement/archive is this run's truth, never downgraded
779
981
  const p = before.get(String(e.path));
780
982
  if (!p) continue;
983
+ if (p.action === 'retired' || p.action === 'archived') continue; // a path the prior run settled that this run re-ships is fresh staging, not a settlement
781
984
  if (p.action === 'overwritten') {
782
985
  e.action = 'overwritten';
783
986
  e.prevHash = p.prevHash || e.prevHash;
@@ -785,6 +988,17 @@ function carryForwardJournal(manifest, prior) {
785
988
  e.action = 'preserved';
786
989
  }
787
990
  }
991
+ // A re-run must not forget what an earlier run settled: those paths are
992
+ // already deleted or archived and absent from this run's staging, but
993
+ // --uninstall still needs them to restore the pre-install originals from
994
+ // the backup chain.
995
+ const now = new Set(manifest.files.map((f) => String(f.path)));
996
+ for (const p of prior.files) {
997
+ if ((p.action === 'retired' || p.action === 'archived') && !now.has(String(p.path))) {
998
+ manifest.files.push(p);
999
+ now.add(String(p.path));
1000
+ }
1001
+ }
788
1002
  }
789
1003
 
790
1004
  function readManifest(configDir) {
@@ -883,6 +1097,7 @@ function validateJsoncInputs(configDir, backupPath) {
883
1097
  }
884
1098
 
885
1099
  async function setup(opts) {
1100
+ assertWindows();
886
1101
  // F2: --ci / --dry-run promise print-only exit 0 with no mutation — honour
887
1102
  // them BEFORE preflight(), which bails without the opencode binary (exactly
888
1103
  // the headless case --ci exists for). Read-only manifest path only.
@@ -917,6 +1132,9 @@ async function setup(opts) {
917
1132
  }
918
1133
 
919
1134
  const prior = readManifest(configDir); // read-only
1135
+ if (!prior) {
1136
+ console.warn('[warn] no prior install manifest — old 0.3.x files are not auto-retired; review them manually before relying on a clean tree.');
1137
+ }
920
1138
  const newBackupPath = nextBackupPath(configDir);
921
1139
  // R4(d): a re-run must never re-point the original backup — that snapshot has
922
1140
  // already been mutated by the previous install, so restoring from it would be
@@ -945,24 +1163,18 @@ async function setup(opts) {
945
1163
  configDir,
946
1164
  backupPath: backupPath,
947
1165
  ...(prior && prior.backupPath ? { priorBackup: backup } : {}),
948
- plugins: ['oc-flight-deck'],
949
1166
  files: [],
950
1167
  };
951
1168
 
952
- stageFiles(files, manifest);
1169
+ const retiredSkills = retireStale(configDir, prior, files, manifest);
1170
+ if (retiredSkills.size) log('retire', `${retiredSkills.size} stale skill id(s) retired — their allowlist entries are pruned from the merge (${[...retiredSkills].join(', ')})`);
1171
+ stageFiles(files, manifest, prior, configDir);
953
1172
  carryForwardJournal(manifest, prior);
954
- // Register plugins BEFORE the merge: on a fresh dir `opencode plugin add`
955
- // installs the plugin, but once the merged opencode.jsonc lists it, add
956
- // no-ops with "already configured" and nothing lands in `opencode plugin
957
- // list` — the doctor's Law 6 grades exactly that list.
958
- registerPlugins();
959
- mergeJsonc(configDir, backup, manifest);
960
-
961
- // Right after a fresh `plugin add` the registry can lag by minutes; wait
962
- // (bounded) for it to settle so the doctor's Law 6 grades a settled list.
963
- await waitForPluginRegistration(manifest.plugins, configDir);
964
-
965
- // R6: record the skip in the journal so "all 16 laws unrun" is never silent.
1173
+ // An adopter's own plugins[] entries survive the merge via UNION_KEYS; the
1174
+ // distro ships no plugins of its own, so there is nothing to register here.
1175
+ mergeJsonc(configDir, backup, manifest, retiredSkills);
1176
+
1177
+ // R6: record the skip in the journal so "all 18 laws unrun" is never silent.
966
1178
  manifest.doctorSkipped = !doctorProbe.usable || !existsSync(path.join(configDir, 'scripts', 'harness-doctor.ps1'));
967
1179
  writeManifest(configDir, manifest);
968
1180
  log('manifest', `journal written: ${path.join(configDir, MANIFEST_FILE)}`);
@@ -972,11 +1184,10 @@ async function setup(opts) {
972
1184
 
973
1185
  console.log();
974
1186
  console.log('-------------------------------- summary ---------------------------------');
975
- console.log(' installed: agents/, commands/, skills/, reference/, scripts/, AGENTS.md + merged opencode.jsonc');
976
- console.log(' plugins : oc-flight-deck');
1187
+ console.log(' installed: agents/, commands/, skills/, reference/, scripts/, .docs/, state/ (from state-seed/), AGENTS.md, GLOSSARY.md + merged opencode.jsonc');
977
1188
  console.log(` backup : ${manifest.backupPath}${manifest.priorBackup ? `\n snapshot : ${manifest.priorBackup} (chained — backup() pointer above is the original)` : ''}`);
978
1189
  if (manifest.doctorSkipped) {
979
- console.log(' doctor : ⚠ SKIPPED — the 16 laws were NOT verified (journaled as doctorSkipped; install PowerShell 7 and re-run to verify)');
1190
+ console.log(' doctor : ⚠ SKIPPED — the 18 laws were NOT verified (journaled as doctorSkipped; install PowerShell 7 and re-run to verify)');
980
1191
  }
981
1192
  console.log(' undo : npx oc-harness-setup setup --uninstall');
982
1193
  console.log(' restart : restart your OpenCode session so the new agents/commands/skills load.');
@@ -993,6 +1204,11 @@ function parseArgs(argv) {
993
1204
  case 'setup':
994
1205
  opts.command = 'setup';
995
1206
  break;
1207
+ case '--version':
1208
+ case '-v':
1209
+ console.log(pkgVersion());
1210
+ process.exitCode = 0;
1211
+ return null;
996
1212
  case '--dry-run':
997
1213
  opts.dryRun = true;
998
1214
  break;