oc-harness-setup 1.0.1 → 1.1.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.
package/bin/cli.js CHANGED
@@ -21,6 +21,7 @@ import {
21
21
  import { homedir } from 'node:os';
22
22
  import path from 'node:path';
23
23
  import { createInterface } from 'node:readline/promises';
24
+ import { createEvolve } from './evolve.mjs';
24
25
 
25
26
  // Node floor: import.meta.dirname needs Node 20.11+; the supported floor is
26
27
  // 22 (package.json engines + README + CI). Fail fast with a clear message
@@ -36,7 +37,7 @@ if (!Number.isInteger(NODE_MAJOR) || NODE_MAJOR < 22) {
36
37
  const PKG_NAME = 'oc-harness-setup';
37
38
  const PKG_ROOT = path.resolve(import.meta.dirname, '..');
38
39
  const MANIFEST_FILE = 'oc-harness-setup.manifest.json';
39
- const COPY_DIRS = ['agents', 'commands', 'skills', 'reference', 'scripts', '.docs', 'state-seed'];
40
+ const COPY_DIRS = ['agents', 'commands', 'skills', 'reference', 'scripts', '.docs', 'state-seed', 'playbooks'];
40
41
  const COPY_FILES = ['AGENTS.md', 'GLOSSARY.md', 'gitignore.template'];
41
42
  // npm renames a shipped root dotfile (`.gitignore` → `.npmignore`) on pack/
42
43
  // install, so the pack ships `gitignore.template` and the installer aliases it
@@ -69,14 +70,23 @@ const DENY_OWNED = ['policies'];
69
70
  const UNION_KEYS = ['plugins'];
70
71
  const DISTRO_PLUGIN_IDS = ['oc-flight-deck'];
71
72
 
72
- // `plugins` element truth for OpenCode 2.2.0, measured against the installed
73
- // host (`opencode v2.2.0`, `opencode debug config`): an entry must be a
74
- // specifier STRING — an npm name, `name@version`, `github:owner/repo#ref
75
- // ::path:pkg`, or a local `.ts` path. The 1.x `[specifier, options]` tuple is
76
- // DROPPED by the 2.2.0 schema (so the plugin silently stops loading), and a
77
- // non-string is dropped too. A tuple is therefore reduced to its specifier —
78
- // 2.2.0 has nowhere to express the options — and every entry that cannot be
79
- // expressed is reported, never written into a config the host would ignore.
73
+ // `plugins` element truth for the current V2 schema. The live config.json
74
+ // defines plugins[] items as a string OR Config.Plugin.EntryEncoded — an
75
+ // object `{ package: string, options?: object, additionalProperties: false }`
76
+ // — and the live plugins doc shows that object form. Specifier strings cover
77
+ // npm names, `name@version`, `github:owner/repo#ref::path:pkg`, local paths,
78
+ // and `.ts`/`.js` files. The 1.x `[specifier, options]` tuple is DROPPED by the
79
+ // V2 schema, so a tuple is reduced to its specifier and the reduction is
80
+ // reported; under the existing migration contract its options cannot be
81
+ // carried and are never silently erased. Anything unrepresentable is reported,
82
+ // not written.
83
+ function isV2PluginObject(entry) {
84
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return false;
85
+ if (typeof entry.package !== 'string' || !entry.package.trim()) return false;
86
+ if (entry.options !== undefined && (!entry.options || typeof entry.options !== 'object' || Array.isArray(entry.options))) return false;
87
+ return Object.keys(entry).every((k) => k === 'package' || k === 'options');
88
+ }
89
+
80
90
  function pluginSpecifier(entry) {
81
91
  if (typeof entry === 'string') {
82
92
  const s = entry.trim();
@@ -85,6 +95,9 @@ function pluginSpecifier(entry) {
85
95
  if (Array.isArray(entry) && typeof entry[0] === 'string' && entry[0].trim()) {
86
96
  return entry[0].trim();
87
97
  }
98
+ // A V2 object is identified by its `package`, so a string and an object for
99
+ // the same plugin dedupe to one entry instead of comparing by JS form.
100
+ if (isV2PluginObject(entry)) return entry.package.trim();
88
101
  return null;
89
102
  }
90
103
 
@@ -97,21 +110,34 @@ function pluginIdOf(spec) {
97
110
  return at > 0 ? s.slice(0, at) : s;
98
111
  }
99
112
 
100
- // Reduce, dedupe (order preserved), and report 1.x plugin entries so a re-run
113
+ // Reduce, dedupe (order preserved), and report plugin entries so a re-run
101
114
  // produces byte-identical output and nothing the host would drop survives.
115
+ // Valid objects ride through unchanged: their `options` are the adopter's
116
+ // data, not ours to flatten. Dedupe keys on the BARE package id via pluginIdOf,
117
+ // so `foo@1.2.3` and {package:'foo'} are one plugin. The union is
118
+ // [distro, adopter], so a collision replaces the earlier value IN ITS SLOT:
119
+ // the later adopter entry wins (its options survive) and the relative order
120
+ // of non-colliding distro entries is untouched.
102
121
  function normalizePluginEntries(entries) {
103
122
  const out = [];
123
+ const slotOf = new Map();
104
124
  for (const entry of entries) {
105
125
  const spec = pluginSpecifier(entry);
106
126
  if (spec === null) {
107
- log('merge', `dropped an unrepresentable plugins entry ${JSON.stringify(entry)} — OpenCode 2.2.0 accepts specifier strings only`);
127
+ log('merge', `dropped an unrepresentable plugins entry ${JSON.stringify(entry)} — OpenCode V2 accepts specifier strings and {package, options} objects only`);
108
128
  continue;
109
129
  }
110
130
  if (Array.isArray(entry)) {
111
- log('merge', `normalized the 1.x plugin tuple ${JSON.stringify(entry)} → "${spec}" (OpenCode 2.2.0 drops tuple entries; per-plugin options cannot be carried)`);
131
+ log('merge', `normalized the 1.x plugin tuple ${JSON.stringify(entry)} → "${spec}" (OpenCode V2 drops tuple entries; per-plugin options cannot be carried)`);
132
+ }
133
+ const value = isV2PluginObject(entry) ? entry : spec;
134
+ const id = pluginIdOf(spec);
135
+ if (slotOf.has(id)) {
136
+ out[slotOf.get(id)] = value; // later entry wins; keep the first slot
137
+ } else {
138
+ slotOf.set(id, out.length);
139
+ out.push(value);
112
140
  }
113
- if (out.includes(spec)) continue;
114
- out.push(spec);
115
141
  }
116
142
  return out;
117
143
  }
@@ -196,6 +222,13 @@ usage:
196
222
  oc-harness-setup --dry-run print the manifest only; touch nothing
197
223
  oc-harness-setup --ci print-only, refuse to mutate, exit 0
198
224
  oc-harness-setup setup --uninstall remove exactly the manifest-listed files
225
+ oc-harness-setup --list-stages print stage ids and titles, touch nothing
226
+ oc-harness-setup setup --stage <id> run through that stage, then stop
227
+ oc-harness-setup setup --from <id> start at that stage, run to the end
228
+ oc-harness-setup setup --ask ask the two default-yes policy questions
229
+ oc-harness-setup evolve <kind> <id> add a skill, command, agent or playbook
230
+ --title <text> --description <text>
231
+ --body <file|-> --dry-run --force
199
232
  oc-harness-setup --version print the package version`);
200
233
  }
201
234
 
@@ -305,14 +338,14 @@ function preflight() {
305
338
  if (host.major < 2) {
306
339
  bail(
307
340
  `OpenCode ${host.raw} speaks the 1.x config dialect (@opencode-ai/* plugins, an object \`permission\` block), not the 2.2.0 shape this package writes ` +
308
- '(plugins[] of specifier strings, permissions[] of {action,resource,effect}, policies[] with tool.use). Nothing was written. ' +
341
+ '(plugins[] of specifier strings or {package, options} objects, permissions[] of {action,resource,effect}, policies[] with tool.use). Nothing was written. ' +
309
342
  'Upgrade first (opencode upgrade), then re-run setup.'
310
343
  );
311
344
  }
312
345
  if (host.minor < 2) {
313
346
  console.warn(
314
347
  `[warn] preflight: OpenCode ${host.raw} is below the 2.2.0 this package is tested on. The merge writes the 2.2-shaped config ` +
315
- '(plugins[] as specifier strings, permissions[] of {action,resource,effect}, policies[] with tool.use); ' +
348
+ '(plugins[] as specifier strings or {package, options} objects, permissions[] of {action,resource,effect}, policies[] with tool.use); ' +
316
349
  'on 2.0/2.1 those blocks may be partly ignored, so the deny gate is not proven on this host. ' +
317
350
  'The install proceeds — upgrade to 2.2.0 or newer when you can.'
318
351
  );
@@ -731,15 +764,17 @@ const isPlainObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
731
764
  // adopter may adopt, never a replacement for their own. Plain objects merge, so
732
765
  // a subkey the adopter never set still arrives; every collided leaf keeps the
733
766
  // adopter's value and is named in `collisions` so the report can cite it.
734
- function adoptInstallOwned(distro, user, key, pathParts, collisions) {
767
+ function adoptInstallOwned(distro, user, key, pathParts, collisions, policy = 'keep') {
735
768
  const d = distro[key];
736
769
  const u = user[key];
737
770
  if (isPlainObject(d) && isPlainObject(u)) {
738
- for (const sub of Object.keys(u)) adoptInstallOwned(d, u, sub, [...pathParts, sub], collisions);
771
+ for (const sub of Object.keys(u)) adoptInstallOwned(d, u, sub, [...pathParts, sub], collisions, policy);
739
772
  return;
740
773
  }
741
774
  if (JSON.stringify(d) !== JSON.stringify(u)) collisions.push(pathParts.join('.'));
742
- distro[key] = u;
775
+ // 'keep' is today's contract: the adopter's value wins on a collision.
776
+ // 'replace' is the --ask answer that declines it; the shipped default stays.
777
+ if (policy === 'keep') distro[key] = u;
743
778
  }
744
779
 
745
780
  // Deny-owning blocks are additive without being softenable: the adopter's own
@@ -752,7 +787,7 @@ function unionDenyLast(distro, user) {
752
787
  return [...u.filter((r) => !d.some((x) => same(x, r))), ...d];
753
788
  }
754
789
 
755
- function mergeJsonc(configDir, backupPath, manifest, retiredSkills = new Set(), prior = null) {
790
+ function mergeJsonc(configDir, backupPath, manifest, retiredSkills = new Set(), prior = null, collisionPolicy = 'keep') {
756
791
  const distroPath = path.join(PKG_ROOT, 'opencode.jsonc');
757
792
  if (!existsSync(distroPath)) {
758
793
  log('merge', 'note: this package ships no opencode.jsonc — no merge to do');
@@ -798,7 +833,7 @@ function mergeJsonc(configDir, backupPath, manifest, retiredSkills = new Set(),
798
833
  continue;
799
834
  }
800
835
  if (INSTALL_OWNED.includes(k)) {
801
- adoptInstallOwned(merged, user, k, [k], ownedCollisions);
836
+ adoptInstallOwned(merged, user, k, [k], ownedCollisions, collisionPolicy);
802
837
  preserved.push(k);
803
838
  continue;
804
839
  }
@@ -845,17 +880,20 @@ function mergeJsonc(configDir, backupPath, manifest, retiredSkills = new Set(),
845
880
  if (!Array.isArray(user[k])) {
846
881
  merged[k] = user[k]; // adopter's non-array value wins verbatim
847
882
  } else {
848
- // `plugins` is the only union key, and it is the one whose element
849
- // shape changed in 2.2.0: normalize before the union so dedupe works
850
- // on strings (a tuple would never compare equal across runs and
851
- // would accumulate).
883
+ // `plugins` is the only union key. Its V2 items are strings or
884
+ // {package, options} objects, so normalize the [distro, adopter]
885
+ // array by bare package id before the union: a tuple would never
886
+ // compare equal across runs and would accumulate. A later adopter
887
+ // entry with the same id wins in the earlier entry's slot.
852
888
  merged[k] = normalizePluginEntries([
853
889
  ...(Array.isArray(merged[k]) ? merged[k] : []),
854
890
  ...user[k],
855
891
  ]);
856
892
  }
857
893
  if (k === 'plugins' && priorIsOlder && Array.isArray(merged[k])) {
858
- const isDistroPlugin = (e) => DISTRO_PLUGIN_IDS.includes(pluginIdOf(e));
894
+ // A V2 object's identity is its `package`; route every entry through
895
+ // pluginSpecifier first so an object for a retired id is dropped too.
896
+ const isDistroPlugin = (e) => DISTRO_PLUGIN_IDS.includes(pluginIdOf(pluginSpecifier(e) ?? e));
859
897
  for (const d of merged[k].filter(isDistroPlugin)) {
860
898
  log('merge', `dropped the retired distro plugin ${pluginIdOf(d)} (this version ships no plugin; your own plugin entries are kept)`);
861
899
  }
@@ -947,7 +985,7 @@ function doctorPlan() {
947
985
  function runDoctor(configDir) {
948
986
  const script = path.join(configDir, 'scripts', 'harness-doctor.mjs');
949
987
  if (!existsSync(script)) {
950
- console.warn(`[doctor] WARNING: ${script} not found — harness-doctor did NOT run, so the 18 laws are UNVERIFIED.`);
988
+ console.warn(`[doctor] WARNING: ${script} not found — harness-doctor did NOT run, so the 19 laws are UNVERIFIED.`);
951
989
  return { code: 0, skipped: true };
952
990
  }
953
991
  log('doctor', `running ${script}`);
@@ -978,23 +1016,43 @@ function printManifest(configDir, files, backupPath, doctor, prior = null) {
978
1016
  console.log(' default_agent: "orchestrator", references registry)');
979
1017
  console.log(' + your keys kept, your value wins on a collision · permissions: harness allows, yours, harness denies last');
980
1018
  console.log(' state-seed/ -> state/ : shipped seed maps to live state/ (an edited state file is kept, the seeded copy lands as <name>.new)');
981
- console.log(` doctor plan : harness-doctor, 18 laws — ${doctor}`);
1019
+ console.log(` doctor plan : harness-doctor, 19 laws — ${doctor}`);
982
1020
  console.log('----------------------------------------------------------------------------');
983
1021
  }
984
1022
 
985
- async function confirmProceed() {
986
- const rl = createInterface({ input: process.stdin, output: process.stdout });
1023
+ // The consent gate keeps its exact prompt and answer rule. The optional rl is
1024
+ // shared with --ask so three questions read one stdin stream in order; without
1025
+ // it the gate still owns a temporary interface, as before.
1026
+ async function confirmProceed(rl) {
1027
+ if (!rl) {
1028
+ const own = createInterface({ input: process.stdin, output: process.stdout });
1029
+ try {
1030
+ return await confirmProceed(own);
1031
+ } finally {
1032
+ own.close();
1033
+ }
1034
+ }
987
1035
  let answer = '';
988
1036
  try {
989
1037
  answer = (await rl.question('Type y to continue (anything else aborts; nothing is touched): ')).trim().toLowerCase();
990
1038
  } catch {
991
1039
  answer = ''; // stdin closed (EOF) — treat as abort
992
- } finally {
993
- rl.close();
994
1040
  }
995
1041
  return answer === 'y' || answer === 'yes';
996
1042
  }
997
1043
 
1044
+ // --ask adds exactly two yes/no questions. Bare Enter is yes, so the default
1045
+ // path is byte-for-byte today's result.
1046
+ async function askYesNo(rl, text) {
1047
+ let answer = '';
1048
+ try {
1049
+ answer = (await rl.question(`${text} [Y/n] `)).trim().toLowerCase();
1050
+ } catch {
1051
+ answer = '';
1052
+ }
1053
+ return answer !== 'n' && answer !== 'no';
1054
+ }
1055
+
998
1056
  /* -------------------------------- uninstall -------------------------------- */
999
1057
 
1000
1058
  function uninstall(configDir, opts = {}) {
@@ -1195,7 +1253,7 @@ function uninstall(configDir, opts = {}) {
1195
1253
  console.log(` ${preserved} post-install edit-copy(ies) written beside the restored file(s) as <name>.replaced-<ts> (listed above).`);
1196
1254
  }
1197
1255
  if (manifest.doctorSkipped) {
1198
- console.log(' note: this install skipped the doctor — the 18 laws were never verified.');
1256
+ console.log(' note: this install skipped the doctor — the 19 laws were never verified.');
1199
1257
  }
1200
1258
  }
1201
1259
 
@@ -1345,12 +1403,196 @@ function validateJsoncInputs(configDir, backupPath) {
1345
1403
  }
1346
1404
  }
1347
1405
 
1406
+ /* ---------------------------- stage registry ---------------------------- */
1407
+
1408
+ const STAGES_FILE = 'stages.yaml';
1409
+
1410
+ function yamlScalar(s) {
1411
+ const t = String(s).trim();
1412
+ if ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'"))) return t.slice(1, -1);
1413
+ return t;
1414
+ }
1415
+
1416
+ // Constrained reader for the shipped data file. Anything outside the small
1417
+ // shape is a hard error — a typo in the registry must not silently reorder the
1418
+ // install. Code holds one copy of the order: this file.
1419
+ function loadStages() {
1420
+ const p = path.join(PKG_ROOT, STAGES_FILE);
1421
+ if (!existsSync(p)) bail(`${STAGES_FILE} is missing from this package build — refusing to guess the stage order`);
1422
+ const stages = [];
1423
+ let version = null;
1424
+ let cur = null;
1425
+ let listKey = null;
1426
+ for (const raw of readFileSync(p, 'utf8').split(/\r?\n/)) {
1427
+ const t = raw.replace(/(^|\s)#.*$/, '').trim();
1428
+ if (!t) continue;
1429
+ let m = t.match(/^version:\s*(.+)$/);
1430
+ if (m) { version = yamlScalar(m[1]); continue; }
1431
+ if (t === 'stages:') continue;
1432
+ m = t.match(/^-\s+id:\s*(.+)$/);
1433
+ if (m) { cur = { id: yamlScalar(m[1]), title: '', steps: [], checks: [] }; stages.push(cur); listKey = null; continue; }
1434
+ m = t.match(/^title:\s*(.+)$/);
1435
+ if (m && cur) { cur.title = yamlScalar(m[1]); listKey = null; continue; }
1436
+ m = t.match(/^(steps|checks):\s*$/);
1437
+ if (m && cur) { listKey = m[1]; continue; }
1438
+ m = t.match(/^-\s+(.+)$/);
1439
+ if (m && cur && listKey) { cur[listKey].push(yamlScalar(m[1])); continue; }
1440
+ bail(`${STAGES_FILE}: unexpected line: ${raw}`);
1441
+ }
1442
+ if (!version || !stages.length) bail(`${STAGES_FILE}: missing version or stages`);
1443
+ const ids = stages.map((s) => s.id);
1444
+ if (new Set(ids).size !== ids.length) bail(`${STAGES_FILE}: duplicate stage id`);
1445
+ for (const s of stages) {
1446
+ if (!s.title) bail(`${STAGES_FILE}: stage ${s.id} has no title`);
1447
+ if (!s.steps.length && !s.checks.length) bail(`${STAGES_FILE}: stage ${s.id} owns no steps`);
1448
+ }
1449
+ return { version, stages, ids };
1450
+ }
1451
+
1452
+ function stageIndexOf(ids, id, flag) {
1453
+ const i = ids.indexOf(id);
1454
+ if (i < 0) {
1455
+ console.error(`[error] unknown stage id "${id}" for ${flag}; valid ids: ${ids.join(', ')}`);
1456
+ process.exitCode = 2;
1457
+ }
1458
+ return i;
1459
+ }
1460
+
1461
+ // Progress only. It never gates work: a plain setup runs every stage even when
1462
+ // an earlier run left a state file behind.
1463
+ function writeStageState(ctx, registry) {
1464
+ const dir = path.join(ctx.configDir, 'state');
1465
+ mkdirSync(dir, { recursive: true });
1466
+ const now = new Date().toISOString();
1467
+ const lines = [
1468
+ 'version: 1',
1469
+ `updated: ${now}`,
1470
+ `collision_policy: ${ctx.collisionPolicy}`,
1471
+ `install_playbooks: ${ctx.installPlaybooks ? 'true' : 'false'}`,
1472
+ 'stages:',
1473
+ ];
1474
+ for (const s of registry.stages) {
1475
+ const ran = ctx.executed.get(s.id);
1476
+ lines.push(` - id: ${s.id}`);
1477
+ lines.push(` status: ${ran ? 'done' : 'skipped'}`);
1478
+ lines.push(` at: ${ran ? ran.at : now}`);
1479
+ }
1480
+ writeFileSync(path.join(dir, 'setup-state.yaml'), `${lines.join('\n')}\n`);
1481
+ }
1482
+
1483
+ // Pure derivation of everything the write stage needs from the destination.
1484
+ // The plan stage calls it for its own display and consent gate; a --from start
1485
+ // that skips plan calls the SAME function silently, so no stage can leave the
1486
+ // write inputs null. No printing, no prompting, no mutation here.
1487
+ function derivePlanInputs(configDir) {
1488
+ const files = collectIncoming(configDir);
1489
+ const prior = readManifest(configDir); // read-only
1490
+ const newBackupPath = nextBackupPath(configDir);
1491
+ // R4(d): a re-run must never re-point the original backup — that snapshot
1492
+ // has already been mutated, so restoring from it would be a lie.
1493
+ const backupPath = prior && prior.backupPath ? prior.backupPath : newBackupPath;
1494
+ return { files, prior, newBackupPath, backupPath };
1495
+ }
1496
+
1497
+ // Each body is the original pipeline call sequence, split at the stage seams.
1498
+ // A returned number is a final exit code; undefined means "continue".
1499
+ const STAGE_BODIES = {
1500
+ preflight: (ctx) => {
1501
+ assertWindows();
1502
+ ctx.host = preflight();
1503
+ },
1504
+ resolve: (ctx) => {
1505
+ ctx.configDir = findConfigDir();
1506
+ warnConfigTargets(ctx.configDir);
1507
+ },
1508
+ plan: async (ctx) => {
1509
+ Object.assign(ctx, derivePlanInputs(ctx.configDir));
1510
+ const hits = lintPackagedSource(ctx.files);
1511
+ if (hits.length) {
1512
+ for (const h of hits) console.error(`[lint] author-leak marker "${h.pattern}" found in ${h.file}`);
1513
+ bail(`author-leak markers found in the packaged source (${hits.length} file(s) listed above) — this package build is corrupted; NOTHING was written. Reinstall from npm.`);
1514
+ }
1515
+ if (!ctx.prior) {
1516
+ 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.');
1517
+ }
1518
+ printManifest(ctx.configDir, ctx.files, ctx.backupPath, doctorPlan(), ctx.prior);
1519
+ if (!(await confirmProceed(ctx.rl))) {
1520
+ console.log('[gate] aborted — nothing was modified.');
1521
+ return 0;
1522
+ }
1523
+ if (ctx.opts.ask) {
1524
+ ctx.collisionPolicy = (await askYesNo(ctx.rl, 'Keep your values for install-owned keys on collision?')) ? 'keep' : 'replace';
1525
+ ctx.installPlaybooks = await askYesNo(ctx.rl, 'Install the playbooks?');
1526
+ if (!ctx.installPlaybooks) {
1527
+ // Templates stay package-internal; this answer gates playbooks only.
1528
+ ctx.files = ctx.files.filter((f) => !String(f.rel).replace(/\\/g, '/').startsWith('playbooks/'));
1529
+ }
1530
+ }
1531
+ validateJsoncInputs(ctx.configDir, ctx.backupPath);
1532
+ return undefined;
1533
+ },
1534
+ write: (ctx) => {
1535
+ sweepTmpLitter(ctx.configDir);
1536
+ const backup = makeBackup(ctx.configDir, ctx.newBackupPath);
1537
+ const manifest = {
1538
+ package: PKG_NAME,
1539
+ version: pkgVersion(),
1540
+ // The host whose dialect the merged config was written for: recorded so
1541
+ // an install's config shapes are auditable against the CLI that read it.
1542
+ // A --from start can skip preflight; reuse the recorded host when the
1543
+ // prior manifest has one, rather than dereferencing a null host.
1544
+ hostVersion: ctx.host?.raw ?? ctx.prior?.hostVersion ?? 'unknown',
1545
+ created: new Date().toISOString(),
1546
+ configDir: ctx.configDir,
1547
+ backupPath: ctx.backupPath,
1548
+ ...(ctx.prior && ctx.prior.backupPath ? { priorBackup: backup } : {}),
1549
+ files: [],
1550
+ };
1551
+ const retiredSkills = retireStale(ctx.configDir, ctx.prior, ctx.files, manifest);
1552
+ if (retiredSkills.size) log('retire', `${retiredSkills.size} stale skill id(s) retired — their allowlist entries are pruned from the merge (${[...retiredSkills].join(', ')})`);
1553
+ ctx.staged = stageFiles(ctx.files, manifest, ctx.prior);
1554
+ carryForwardJournal(manifest, ctx.prior);
1555
+ mergeJsonc(ctx.configDir, backup, manifest, retiredSkills, ctx.prior, ctx.collisionPolicy);
1556
+ // R6: record the skip in the journal so "all 19 laws unrun" is never silent.
1557
+ manifest.doctorSkipped = !existsSync(path.join(ctx.configDir, 'scripts', 'harness-doctor.mjs'));
1558
+ writeManifest(ctx.configDir, manifest);
1559
+ log('manifest', `journal written: ${path.join(ctx.configDir, MANIFEST_FILE)}`);
1560
+ ctx.manifest = manifest;
1561
+ return undefined;
1562
+ },
1563
+ verify: (ctx) => {
1564
+ ctx.doctorResult = runDoctor(ctx.configDir);
1565
+ return ctx.doctorResult.code !== 0 ? 1 : undefined;
1566
+ },
1567
+ report: (ctx) => {
1568
+ console.log();
1569
+ console.log('-------------------------------- summary ---------------------------------');
1570
+ console.log(' installed: agents/, commands/, skills/, reference/, scripts/, .docs/, state/ (from state-seed/), AGENTS.md, GLOSSARY.md + merged opencode.jsonc');
1571
+ if (ctx.staged) {
1572
+ console.log(` policy : ${ctx.staged.updated} updated in place (unmodified package files) · ${ctx.staged.kept} kept + .new written (your files) · ${ctx.staged.added} added · ${ctx.staged.skipped} skipped (identical)`);
1573
+ if (ctx.staged.kept > 0) {
1574
+ console.log(' adopt : the new version of each kept file sits beside it as <name>.new — diff it and move it over when you want it');
1575
+ }
1576
+ }
1577
+ if (ctx.manifest) {
1578
+ console.log(` backup : ${ctx.manifest.backupPath}${ctx.manifest.priorBackup ? `\n snapshot : ${ctx.manifest.priorBackup} (chained — backup() pointer above is the original)` : ''}`);
1579
+ if (ctx.manifest.doctorSkipped) {
1580
+ console.log(' doctor : ⚠ SKIPPED — the 19 laws were NOT verified (journaled as doctorSkipped; re-run setup to verify)');
1581
+ }
1582
+ }
1583
+ console.log(' undo : npx oc-harness-setup setup --uninstall');
1584
+ console.log(' restart : restart your OpenCode session so the new agents/commands/skills load.');
1585
+ console.log('----------------------------------------------------------------------------');
1586
+ return 0;
1587
+ },
1588
+ };
1589
+
1348
1590
  async function setup(opts) {
1349
- assertWindows();
1350
- // F2: --ci / --dry-run promise print-only exit 0 with no mutation — honour
1351
- // them BEFORE preflight(), which bails without the opencode binary (exactly
1352
- // the headless case --ci exists for). Read-only manifest path only.
1591
+ const registry = loadStages();
1592
+ // F2: the print-only promise is preserved exactly, including its position
1593
+ // after assertWindows and before preflight().
1353
1594
  if (opts.ci || opts.dryRun) {
1595
+ assertWindows();
1354
1596
  const configDir = findConfigDir();
1355
1597
  const files = collectIncoming(configDir);
1356
1598
  const prior = readManifest(configDir); // read-only
@@ -1364,101 +1606,114 @@ async function setup(opts) {
1364
1606
  console.log('[ci] refusing to mutate — print-only. Run setup interactively to install.');
1365
1607
  return 0;
1366
1608
  }
1367
- const host = preflight();
1368
- const configDir = findConfigDir();
1369
- warnConfigTargets(configDir);
1370
- const files = collectIncoming(configDir);
1371
-
1372
- // Author-leak lint runs PRE-write, over the PACKAGE source only. A hit aborts
1373
- // before the consent gate, so nothing lands and the adopter's config (which
1374
- // is never linted) can never trip it.
1375
- const hits = lintPackagedSource(files);
1376
- if (hits.length) {
1377
- for (const h of hits) console.error(`[lint] author-leak marker "${h.pattern}" found in ${h.file}`);
1378
- bail(
1379
- `author-leak markers found in the packaged source (${hits.length} file(s) listed above) — this package build is corrupted; NOTHING was written. Reinstall from npm.`
1380
- );
1381
- }
1382
-
1383
- const prior = readManifest(configDir); // read-only
1384
- if (!prior) {
1385
- 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.');
1386
- }
1387
- const newBackupPath = nextBackupPath(configDir);
1388
- // R4(d): a re-run must never re-point the original backup — that snapshot has
1389
- // already been mutated by the previous install, so restoring from it would be
1390
- // a lie. Keep the original pointer; chain the new snapshot as priorBackup.
1391
- const backupPath = prior && prior.backupPath ? prior.backupPath : newBackupPath;
1392
- printManifest(configDir, files, backupPath, doctorPlan(), prior);
1393
-
1394
- // (F2: --dry-run / --ci already returned print-only before preflight.)
1395
- if (!(await confirmProceed())) {
1396
- console.log('[gate] aborted — nothing was modified.');
1397
- return 0;
1398
- }
1399
-
1400
- /* ---------------- mutations begin (all journaled) ---------------- */
1401
- // F1: every parse validated BEFORE the first write — a broken config bails
1402
- // here, before staging overwrites live files.
1403
- validateJsoncInputs(configDir, backupPath);
1404
- // F6: sweep unambiguous installer crash litter before the first write.
1405
- sweepTmpLitter(configDir);
1406
- const backup = makeBackup(configDir, newBackupPath);
1407
- const manifest = {
1408
- package: PKG_NAME,
1409
- version: pkgVersion(),
1410
- // The host whose dialect the merged config was written for: recorded so an
1411
- // install's config shapes are auditable against the CLI that will read them.
1412
- hostVersion: host.raw,
1413
- created: new Date().toISOString(),
1414
- configDir,
1415
- backupPath: backupPath,
1416
- ...(prior && prior.backupPath ? { priorBackup: backup } : {}),
1417
- files: [],
1609
+ const fromIdx = opts.from ? stageIndexOf(registry.ids, opts.from, '--from') : 0;
1610
+ const toIdx = opts.stage ? stageIndexOf(registry.ids, opts.stage, '--stage') : registry.stages.length - 1;
1611
+ if (fromIdx < 0 || toIdx < 0) return 2;
1612
+
1613
+ const ctx = {
1614
+ opts, host: null, configDir: null, files: null, prior: null,
1615
+ newBackupPath: null, backupPath: null, staged: null, manifest: null,
1616
+ doctorResult: null, collisionPolicy: 'keep', installPlaybooks: true,
1617
+ rl: createInterface({ input: process.stdin, output: process.stdout }),
1618
+ executed: new Map(),
1418
1619
  };
1419
-
1420
- const retiredSkills = retireStale(configDir, prior, files, manifest);
1421
- if (retiredSkills.size) log('retire', `${retiredSkills.size} stale skill id(s) retired — their allowlist entries are pruned from the merge (${[...retiredSkills].join(', ')})`);
1422
- const staged = stageFiles(files, manifest, prior);
1423
- carryForwardJournal(manifest, prior);
1424
- // An adopter's own plugins[] entries survive the merge via UNION_KEYS; the
1425
- // distro ships no plugins of its own, so there is nothing to register here.
1426
- mergeJsonc(configDir, backup, manifest, retiredSkills, prior);
1427
-
1428
- // R6: record the skip in the journal so "all 18 laws unrun" is never silent.
1429
- manifest.doctorSkipped = !existsSync(path.join(configDir, 'scripts', 'harness-doctor.mjs'));
1430
- writeManifest(configDir, manifest);
1431
- log('manifest', `journal written: ${path.join(configDir, MANIFEST_FILE)}`);
1432
-
1433
- const doctorResult = runDoctor(configDir);
1434
- if (doctorResult.code !== 0) return 1;
1435
-
1436
- console.log();
1437
- console.log('-------------------------------- summary ---------------------------------');
1438
- console.log(' installed: agents/, commands/, skills/, reference/, scripts/, .docs/, state/ (from state-seed/), AGENTS.md, GLOSSARY.md + merged opencode.jsonc');
1439
- console.log(` policy : ${staged.updated} updated in place (unmodified package files) · ${staged.kept} kept + .new written (your files) · ${staged.added} added · ${staged.skipped} skipped (identical)`);
1440
- if (staged.kept > 0) {
1441
- console.log(' adopt : the new version of each kept file sits beside it as <name>.new — diff it and move it over when you want it');
1442
- }
1443
- console.log(` backup : ${manifest.backupPath}${manifest.priorBackup ? `\n snapshot : ${manifest.priorBackup} (chained — backup() pointer above is the original)` : ''}`);
1444
- if (manifest.doctorSkipped) {
1445
- console.log(' doctor : ⚠ SKIPPED — the 18 laws were NOT verified (journaled as doctorSkipped; re-run setup to verify)');
1620
+ try {
1621
+ // A --from start skips preflight/resolve. Restore the destination, and
1622
+ // derive the plan's read-only inputs here whenever plan will not run —
1623
+ // the same function the plan stage uses, with no print and no prompt.
1624
+ if (opts.from) {
1625
+ ctx.configDir = findConfigDir();
1626
+ if (fromIdx > registry.ids.indexOf('plan')) Object.assign(ctx, derivePlanInputs(ctx.configDir));
1627
+ }
1628
+ let code;
1629
+ for (let i = fromIdx; i <= toIdx; i++) {
1630
+ const stage = registry.stages[i];
1631
+ const body = STAGE_BODIES[stage.id];
1632
+ if (!body) bail(`${STAGES_FILE}: no implementation for stage "${stage.id}"`);
1633
+ const result = await body(ctx);
1634
+ ctx.executed.set(stage.id, { at: new Date().toISOString() });
1635
+ if (result !== undefined) {
1636
+ code = result;
1637
+ break;
1638
+ }
1639
+ }
1640
+ // No state before the write stage: --stage plan must leave the tree alone.
1641
+ // An explicit --from run records its skipped prefix as progress.
1642
+ if (ctx.configDir && (ctx.executed.has('write') || opts.from)) writeStageState(ctx, registry);
1643
+ return code === undefined ? 0 : code;
1644
+ } finally {
1645
+ ctx.rl.close();
1446
1646
  }
1447
- console.log(' undo : npx oc-harness-setup setup --uninstall');
1448
- console.log(' restart : restart your OpenCode session so the new agents/commands/skills load.');
1449
- console.log('----------------------------------------------------------------------------');
1450
- return 0;
1647
+ }
1648
+
1649
+ /* --------------------------------- evolve ---------------------------------- */
1650
+
1651
+ // The engine owns the policy; the CLI only supplies real I/O. runDoctor's
1652
+ // existing {code, skipped} shape becomes the numeric code the engine expects.
1653
+ async function runEvolve(opts) {
1654
+ const evolve = createEvolve({
1655
+ pkgRoot: PKG_ROOT,
1656
+ configDir: findConfigDir(),
1657
+ runDoctor: async (dir) => runDoctor(dir).code,
1658
+ readText: (p) => readFileSync(p, 'utf8'),
1659
+ writeText: (p, text) => installBytes(p, text),
1660
+ log: (line) => console.log(line),
1661
+ });
1662
+ return evolve({
1663
+ kind: opts.kind,
1664
+ id: opts.id,
1665
+ title: opts.title,
1666
+ description: opts.description,
1667
+ body: opts.body,
1668
+ dryRun: !!opts.dryRun,
1669
+ force: !!opts.force,
1670
+ });
1451
1671
  }
1452
1672
 
1453
1673
  /* --------------------------------- entry ---------------------------------- */
1454
1674
 
1455
1675
  function parseArgs(argv) {
1456
- const opts = { command: 'setup', dryRun: false, ci: false, uninstall: false };
1457
- for (const a of argv) {
1676
+ const opts = {
1677
+ command: 'setup', dryRun: false, ci: false, uninstall: false,
1678
+ listStages: false, stage: null, from: null, ask: false,
1679
+ kind: null, id: null, title: null, description: null, body: null, force: false,
1680
+ };
1681
+ let evolveArgs = false;
1682
+ for (let i = 0; i < argv.length; i++) {
1683
+ const a = argv[i];
1684
+ // One parser: evolve's two positionals are read in the same loop as the
1685
+ // existing switches, so every setup flag keeps its current meaning.
1686
+ if (a === 'evolve') {
1687
+ opts.command = 'evolve';
1688
+ evolveArgs = true;
1689
+ continue;
1690
+ }
1691
+ if (evolveArgs && opts.kind === null) { opts.kind = a; continue; }
1692
+ if (evolveArgs && opts.id === null) { opts.id = a; continue; }
1693
+ const take = () => {
1694
+ if (i + 1 >= argv.length) {
1695
+ usage();
1696
+ process.exitCode = 2;
1697
+ return undefined;
1698
+ }
1699
+ return argv[++i];
1700
+ };
1458
1701
  switch (a) {
1459
1702
  case 'setup':
1460
1703
  opts.command = 'setup';
1461
1704
  break;
1705
+ case '--force':
1706
+ case '--title':
1707
+ case '--description':
1708
+ case '--body':
1709
+ if (!evolveArgs) {
1710
+ usage();
1711
+ bail(`unknown argument: ${a}`);
1712
+ return null;
1713
+ }
1714
+ if (a === '--force') opts.force = true;
1715
+ else opts[a.slice(2)] = take();
1716
+ break;
1462
1717
  case '--version':
1463
1718
  case '-v':
1464
1719
  console.log(pkgVersion());
@@ -1473,6 +1728,22 @@ function parseArgs(argv) {
1473
1728
  case '--uninstall':
1474
1729
  opts.uninstall = true;
1475
1730
  break;
1731
+ case '--list-stages':
1732
+ opts.listStages = true;
1733
+ break;
1734
+ case '--ask':
1735
+ opts.ask = true;
1736
+ break;
1737
+ case '--stage':
1738
+ case '--from':
1739
+ if (i + 1 >= argv.length) {
1740
+ usage();
1741
+ bail(`${a} needs a stage id`);
1742
+ return null;
1743
+ }
1744
+ if (a === '--stage') opts.stage = argv[++i];
1745
+ else opts.from = argv[++i];
1746
+ break;
1476
1747
  case '--help':
1477
1748
  case '-h':
1478
1749
  usage();
@@ -1490,6 +1761,21 @@ function parseArgs(argv) {
1490
1761
  async function main() {
1491
1762
  const opts = parseArgs(process.argv.slice(2));
1492
1763
  if (!opts) return;
1764
+ if (opts.command === 'evolve') {
1765
+ if (!opts.kind) {
1766
+ usage();
1767
+ process.exitCode = 2;
1768
+ return;
1769
+ }
1770
+ const code = await runEvolve(opts);
1771
+ if (code !== 0) process.exitCode = code;
1772
+ return;
1773
+ }
1774
+ if (opts.listStages) {
1775
+ const registry = loadStages();
1776
+ for (const s of registry.stages) console.log(`${s.id} ${s.title}`);
1777
+ return;
1778
+ }
1493
1779
  if (opts.uninstall) {
1494
1780
  const configDir = findConfigDir();
1495
1781
  // F3: honour --dry-run / --ci in the uninstall branch — preview only.