oc-harness-setup 0.1.1 → 0.3.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 (114) hide show
  1. package/.docs/unwired-routing.md +14 -9
  2. package/.gitignore +14 -1
  3. package/AGENTS.md +70 -106
  4. package/README.md +31 -27
  5. package/agents/build.md +10 -12
  6. package/agents/explore.md +14 -8
  7. package/agents/general.md +7 -9
  8. package/agents/orchestrator.md +38 -0
  9. package/agents/plan.md +10 -13
  10. package/agents/reviewer.md +9 -14
  11. package/agents/vault.md +44 -35
  12. package/bin/cli.js +323 -81
  13. package/commands/build.md +2 -8
  14. package/commands/checkpoint.md +3 -1
  15. package/commands/code-simplify.md +3 -9
  16. package/commands/gauntlet.md +7 -0
  17. package/commands/handoff.md +3 -1
  18. package/commands/keeper.md +3 -3
  19. package/commands/kill.md +11 -0
  20. package/commands/plan.md +2 -13
  21. package/commands/retro.md +15 -0
  22. package/commands/review.md +1 -1
  23. package/commands/ship.md +3 -27
  24. package/commands/spec.md +3 -11
  25. package/commands/test.md +2 -9
  26. package/commands/webperf.md +7 -0
  27. package/opencode.jsonc +23 -8
  28. package/package.json +3 -3
  29. package/reference/README.md +14 -14
  30. package/reference/auto-mandate.md +11 -0
  31. package/reference/backup-convention.md +9 -0
  32. package/reference/clean-mandate.md +13 -0
  33. package/reference/editor-parity.md +7 -0
  34. package/reference/gc-scripts.md +8 -0
  35. package/reference/intent-routing.md +14 -0
  36. package/reference/lifecycle.md +15 -0
  37. package/reference/model-keeper.md +30 -10
  38. package/reference/model-test.md +13 -8
  39. package/reference/models.md +25 -14
  40. package/reference/oc-source-map.md +162 -0
  41. package/reference/owner-pin.md +31 -0
  42. package/reference/roster.md +15 -0
  43. package/reference/session-scope.md +9 -0
  44. package/reference/session-state.md +13 -0
  45. package/reference/swarm.md +32 -0
  46. package/scripts/backup-config.ps1 +42 -0
  47. package/scripts/gc-branch.ps1 +196 -0
  48. package/scripts/gc-bump.ps1 +198 -0
  49. package/scripts/gc-clean.ps1 +648 -0
  50. package/scripts/gc-commit.ps1 +143 -0
  51. package/scripts/gc-merge.ps1 +272 -0
  52. package/scripts/gc-pr.ps1 +190 -0
  53. package/scripts/gc-push.ps1 +111 -0
  54. package/scripts/gc-read.ps1 +150 -0
  55. package/scripts/gc-rebase.ps1 +162 -0
  56. package/scripts/gc-release.ps1 +225 -0
  57. package/scripts/gc-stage.ps1 +103 -0
  58. package/scripts/gc-status.ps1 +127 -0
  59. package/scripts/gc-sync.ps1 +65 -0
  60. package/scripts/gc.core.ps1 +715 -0
  61. package/scripts/gc.smoke.ps1 +779 -0
  62. package/scripts/harness-doctor.ps1 +11 -9
  63. package/scripts/interrupt-session.ps1 +65 -0
  64. package/scripts/logbook/README.md +108 -0
  65. package/scripts/logbook/logbook.test.ts +440 -0
  66. package/scripts/logbook/logbook.ts +797 -0
  67. package/scripts/pirep/README.md +147 -0
  68. package/scripts/pirep/pirep.test.ts +735 -0
  69. package/scripts/pirep/pirep.ts +836 -0
  70. package/scripts/testflight/README.md +112 -0
  71. package/scripts/testflight/testflight.test.ts +512 -0
  72. package/scripts/testflight/testflight.ts +806 -0
  73. package/skills/_shared/SOURCES.md +7 -7
  74. package/skills/_shared/references/definition-of-done.md +2 -2
  75. package/skills/_shared/references/orchestration-patterns.md +1 -2
  76. package/skills/_shared/references/security-checklist.md +2 -2
  77. package/skills/api-and-interface-design/SKILL.md +7 -360
  78. package/skills/browser-testing-with-devtools/SKILL.md +303 -0
  79. package/skills/code-simplification/SKILL.md +7 -364
  80. package/skills/creative-writing/SKILL.md +1 -1
  81. package/skills/debugging-and-error-recovery/SKILL.md +8 -309
  82. package/skills/flight-deck/SKILL.md +17 -0
  83. package/skills/frontend-ui-engineering/SKILL.md +8 -320
  84. package/skills/gauntlet/SKILL.md +21 -0
  85. package/skills/git-ceremony/SKILL.md +16 -318
  86. package/skills/grilling/SKILL.md +10 -30
  87. package/skills/observability-and-instrumentation/SKILL.md +9 -229
  88. package/skills/performance-optimization/SKILL.md +8 -488
  89. package/skills/pilot-report/SKILL.md +18 -0
  90. package/skills/planning-and-task-breakdown/SKILL.md +8 -249
  91. package/skills/security-and-hardening/SKILL.md +9 -490
  92. package/skills/source-driven-development/SKILL.md +8 -208
  93. package/skills/spec-driven-development/SKILL.md +15 -234
  94. package/skills/test-driven-development/SKILL.md +8 -388
  95. package/skills/test-flight/SKILL.md +14 -0
  96. package/skills/writing-for-agents/SKILL-MECHANICS.md +3 -3
  97. package/skills/writing-for-agents/SKILL.md +7 -1
  98. package/agents/coder.md +0 -19
  99. package/agents/documenter.md +0 -28
  100. package/agents/keeper.md +0 -22
  101. package/agents/master.md +0 -65
  102. package/agents/researcher.md +0 -21
  103. package/agents/security-auditor.md +0 -20
  104. package/agents/test-engineer.md +0 -20
  105. package/agents/web-performance-auditor.md +0 -19
  106. package/commands/council.md +0 -24
  107. package/commands/doctor.md +0 -18
  108. package/commands/ponytail-audit.md +0 -7
  109. package/commands/ponytail-debt.md +0 -14
  110. package/reference/models.md.example +0 -21
  111. package/scripts/panic/panic.ts +0 -240
  112. package/skills/code-review-and-quality/SKILL.md +0 -396
  113. package/skills/incremental-implementation/SKILL.md +0 -249
  114. package/skills/swarm-orchestration/SKILL.md +0 -54
package/bin/cli.js CHANGED
@@ -26,8 +26,42 @@ const PKG_ROOT = path.resolve(import.meta.dirname, '..');
26
26
  const MANIFEST_FILE = 'oc-harness-setup.manifest.json';
27
27
  const COPY_DIRS = ['agents', 'commands', 'skills', 'reference', 'scripts', '.docs'];
28
28
  const COPY_FILES = ['AGENTS.md', '.gitignore'];
29
- const MERGE_KEYS = ['model', 'providers', 'mcp', 'plugins'];
30
- const LINT_PATTERNS = ['c:\\users', 'q:\\', 'nathan', 'ses_', '.secrets'];
29
+ // Ownership table for the opencode.jsonc merge. Every top-level key falls into
30
+ // exactly one bucket; there is no "known merge key" list to drift out of date.
31
+ // INSTALL_OWNED — the distro's value wins outright (runtime policy).
32
+ // UNION_KEYS — arrays unioned + deduped (distro entries first).
33
+ // 'references' — object union: distro keys + user-only keys.
34
+ // 'permissions' — ordered union: harness allow/ask rules first, then the
35
+ // adopter's rules, then the harness's hard DENIES last. Under
36
+ // last-match-wins this lets an adopter's deny beat a harness
37
+ // allow while nothing can shadow a harness deny. The `skill`
38
+ // wildcard deny is exempt from the move (its fail-closed
39
+ // allowlist is deny-then-allows; see mergeJsonc).
40
+ // everything else (known or unknown) — the adopter's value wins; the distro
41
+ // value stays when the adopter does not define the key.
42
+ const INSTALL_OWNED = ['$schema', 'default_agent', 'formatter', 'compaction', 'tool_output', 'media', 'watcher'];
43
+ 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
+ // `{file:~/.secrets/…}` apiKey pointer can never abort an install.
51
+ //
52
+ // Every marker is anchored to the AUTHOR's CONCRETE machine — drive `Q:`, user
53
+ // `nathan`, a real `ses_<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. `nathan` also subsumes `C:\Users\nathan`.
60
+ const LINT_PATTERNS = [
61
+ { label: 'q:\\', test: /q:\\/ },
62
+ { label: 'nathan', test: /nathan/ },
63
+ { label: 'ses_<id>', test: /ses_[a-z0-9]{16,}/ },
64
+ ];
31
65
 
32
66
  /* ------------------------------ tiny helpers ------------------------------ */
33
67
 
@@ -35,6 +69,16 @@ function log(label, msg) {
35
69
  console.log(`[${label}] ${msg}`);
36
70
  }
37
71
 
72
+ // Never reuse a taken path when preserving bytes: copying onto an existing file
73
+ // would destroy the very copy we are trying to keep.
74
+ function nextFreePath(base) {
75
+ if (!existsSync(base)) return base;
76
+ for (let i = 2; ; i++) {
77
+ const p = `${base}-${i}`;
78
+ if (!existsSync(p)) return p;
79
+ }
80
+ }
81
+
38
82
  function usage() {
39
83
  console.log(`oc-harness-setup — install the OpenCode harness into your config dir.
40
84
 
@@ -196,8 +240,7 @@ function collectIncoming(configDir) {
196
240
 
197
241
  /* -------------------------------- backup ----------------------------------- */
198
242
 
199
- function makeBackup(configDir) {
200
- const backupPath = `${configDir}.bak-oc-harness-setup-${tsStamp()}`;
243
+ function makeBackup(configDir, backupPath) {
201
244
  if (existsSync(configDir)) {
202
245
  if (!statSync(configDir).isDirectory()) {
203
246
  bail(`${configDir} exists but is not a directory — refusing to install over it`);
@@ -210,6 +253,16 @@ function makeBackup(configDir) {
210
253
  return backupPath;
211
254
  }
212
255
 
256
+ // A second-resolution stamp can repeat on a fast re-run. If that path already
257
+ // exists it may be the PRESERVED ORIGINAL snapshot, and cpSync into an existing
258
+ // dir would overwrite pristine bytes — so never reuse a taken path.
259
+ function nextBackupPath(configDir) {
260
+ const stamp = tsStamp();
261
+ let p = `${configDir}.bak-oc-harness-setup-${stamp}`;
262
+ for (let i = 2; existsSync(p); i++) p = `${configDir}.bak-oc-harness-setup-${stamp}-${i}`;
263
+ return p;
264
+ }
265
+
213
266
  /* ------------------------------ staged copy -------------------------------- */
214
267
 
215
268
  function stageFiles(files, manifest) {
@@ -217,17 +270,26 @@ function stageFiles(files, manifest) {
217
270
  for (const f of files) {
218
271
  const srcHash = sha256File(f.src);
219
272
  let action = 'written';
273
+ let prevHash = null;
220
274
  if (existsSync(f.dest)) {
221
- if (sha256File(f.dest) === srcHash) {
275
+ const destHash = sha256File(f.dest);
276
+ if (destHash === srcHash) {
222
277
  action = 'skip';
223
278
  log('staging', `skip ${f.rel} (already identical — rerun-safe)`);
279
+ } else if (PRESERVE_IF_EXISTS.has(f.rel)) {
280
+ action = 'preserved';
281
+ log('staging', `preserve ${f.rel} (exists and differs — kept; harness will not overwrite adopter-owned files)`);
224
282
  } else {
283
+ // A genuine overwrite: journal it so --uninstall can put the original
284
+ // back from the pre-install backup instead of deleting the harness copy.
285
+ action = 'overwritten';
286
+ prevHash = destHash;
225
287
  log('staging', `update ${f.rel} (destination differs — overwriting; backup + manifest protect you)`);
226
288
  }
227
289
  } else {
228
290
  log('staging', `copy ${f.rel}`);
229
291
  }
230
- if (action === 'written') {
292
+ if (action === 'written' || action === 'overwritten') {
231
293
  mkdirSync(path.dirname(f.dest), { recursive: true });
232
294
  const tmp = `${f.dest}.oc-harness-setup-tmp-${process.pid}`;
233
295
  writeFileSync(tmp, readFileSync(f.src));
@@ -235,7 +297,10 @@ function stageFiles(files, manifest) {
235
297
  renameSync(tmp, f.dest);
236
298
  written += 1;
237
299
  }
238
- manifest.files.push({ path: f.rel, hash: srcHash, action });
300
+ // Preserved entries journal the SRC hash on purpose: --uninstall deletes
301
+ // only on an exact match, so a preserved destination (bytes differ from
302
+ // src) reads as modified → kept, not deleted.
303
+ manifest.files.push(prevHash ? { path: f.rel, hash: srcHash, prevHash, action } : { path: f.rel, hash: srcHash, action });
239
304
  }
240
305
  return written;
241
306
  }
@@ -312,44 +377,75 @@ function parseJsonc(text, what) {
312
377
  }
313
378
  }
314
379
 
315
- function describeKey(k, v) {
316
- if (k === 'model') return `model "${v}"`;
317
- if (Array.isArray(v)) return `${k} (${v.length} entr${v.length === 1 ? 'y' : 'ies'})`;
318
- if (v && typeof v === 'object') {
319
- const n = Object.keys(v).length;
320
- return `${k} (${n} entr${n === 1 ? 'y' : 'ies'})`;
321
- }
322
- return `${k} (${JSON.stringify(v)})`;
323
- }
324
-
325
380
  function mergeJsonc(configDir, backupPath, manifest) {
326
381
  const distroPath = path.join(PKG_ROOT, 'opencode.jsonc');
327
- const userPath = path.join(configDir, 'opencode.jsonc');
328
382
  if (!existsSync(distroPath)) {
329
383
  log('merge', 'note: this package ships no opencode.jsonc — no merge to do');
330
384
  return;
331
385
  }
332
- const merged = parseJsonc(
333
- readFileSync(distroPath, 'utf8'),
334
- `the shipped opencode.jsonc (this package build looks broken)`
386
+ // Output is always opencode.jsonc (the canonical file the doctor grades).
387
+ // Input prefers the adopter's opencode.jsonc; when only opencode.json exists
388
+ // we merge THAT, rather than ignoring the adopter's real config.
389
+ const targetPath = path.join(configDir, 'opencode.jsonc');
390
+ const jsonPath = path.join(configDir, 'opencode.json');
391
+ const sourcePath = existsSync(targetPath) ? targetPath : existsSync(jsonPath) ? jsonPath : null;
392
+ if (sourcePath === jsonPath) {
393
+ console.warn(
394
+ `[warn] merge: found ${jsonPath} but no opencode.jsonc — merging it into a freshly written opencode.jsonc. ` +
395
+ 'Your opencode.json is left untouched; reconcile or remove it so the two cannot drift.'
396
+ );
397
+ }
398
+
399
+ const merged = structuredClone(
400
+ parseJsonc(readFileSync(distroPath, 'utf8'), 'the shipped opencode.jsonc (this package build looks broken)')
335
401
  );
336
- const kept = [];
337
- if (existsSync(userPath)) {
402
+ const preserved = [];
403
+ if (sourcePath) {
338
404
  const user = parseJsonc(
339
- readFileSync(userPath, 'utf8'),
340
- `your existing opencode.jsonc — aborting before any write; your config is untouched (backup: ${backupPath})`
405
+ readFileSync(sourcePath, 'utf8'),
406
+ `your existing ${path.basename(sourcePath)} — aborting before any write; your config is untouched (backup: ${backupPath})`
341
407
  );
342
- for (const k of MERGE_KEYS) {
343
- if (user[k] !== undefined) {
344
- merged[k] = user[k];
345
- kept.push(describeKey(k, user[k]));
408
+ const userPerms = Array.isArray(user.permissions) ? user.permissions : null;
409
+ if (user.permissions !== undefined && !userPerms) {
410
+ console.warn('[warn] merge: your "permissions" is not an array (v2 expects an array of {action,resource,effect}) — harness denies kept; fix your rules manually.');
411
+ }
412
+ for (const k of Object.keys(user)) {
413
+ if (INSTALL_OWNED.includes(k)) continue; // distro value wins outright
414
+ if (k === 'permissions') {
415
+ if (!userPerms) continue;
416
+ // Ordered union, deny-last. Under last-match-wins an adopter's rule must
417
+ // sit AFTER the harness's allow/ask rules (whose leading `shell *` allow
418
+ // would otherwise neutralise an adopter `shell … deny`), and every
419
+ // harness HARD DENY must stay after both so nothing can shadow it
420
+ // (Law 12). The `skill` action is exempt from the move: its fail-closed
421
+ // allowlist is `skill * → deny` FOLLOWED by one allow per local skill
422
+ // (Law 9 requires the wildcard deny; Law 12 exempts the action), so
423
+ // moving that deny last would deny every known skill. Skill rules keep
424
+ // their shipped relative order in the head.
425
+ // Rules identical to a harness rule are dropped from the adopter's side
426
+ // and kept from the harness's, so a re-run reproduces the same array
427
+ // exactly (a plain concat would double it on every run).
428
+ const distroPerms = Array.isArray(merged.permissions) ? merged.permissions : [];
429
+ const sameRule = (a, b) => JSON.stringify(a) === JSON.stringify(b);
430
+ const isHardDeny = (p) => !!p && p.effect === 'deny' && p.action !== 'skill';
431
+ const distroHead = distroPerms.filter((p) => !isHardDeny(p));
432
+ const distroTail = distroPerms.filter(isHardDeny);
433
+ const userOnly = userPerms.filter((p) => !distroPerms.some((d) => sameRule(d, p)));
434
+ merged.permissions = [...distroHead, ...userOnly, ...distroTail];
435
+ } else if (UNION_KEYS.includes(k)) {
436
+ merged[k] = Array.isArray(user[k])
437
+ ? [...new Set([...(Array.isArray(merged[k]) ? merged[k] : []), ...user[k]])]
438
+ : user[k];
439
+ } else if (k === 'references') {
440
+ // Object union: distro keys + user-only keys.
441
+ merged.references = { ...(user.references ?? {}), ...(merged.references ?? {}) };
346
442
  } else {
347
- log('merge', `opencode.jsonc: no ${k} in your config — harness default stays`);
443
+ merged[k] = user[k]; // adopter value wins
348
444
  }
445
+ preserved.push(k);
349
446
  }
350
- log('merge', `kept your ${kept.join(', ') || '(nothing — harness defaults only)'}`);
351
447
  } else {
352
- log('merge', 'no existing opencode.jsonc — writing the harness base');
448
+ log('merge', 'no existing opencode.jsonc/opencode.json — writing the harness base');
353
449
  }
354
450
  // JSON.stringify strips comments, including the marker the doctor's Law 11
355
451
  // cites as evidence — reinsert it so the merged file still documents the
@@ -363,26 +459,33 @@ function mergeJsonc(configDir, backupPath, manifest) {
363
459
  );
364
460
  const out = `${mergedText}\n`;
365
461
  mkdirSync(configDir, { recursive: true });
366
- const tmp = `${userPath}.oc-harness-setup-tmp-${process.pid}`;
462
+ const tmp = `${targetPath}.oc-harness-setup-tmp-${process.pid}`;
367
463
  writeFileSync(tmp, out);
368
- rmSync(userPath, { force: true });
369
- renameSync(tmp, userPath);
464
+ rmSync(targetPath, { force: true });
465
+ renameSync(tmp, targetPath);
370
466
  manifest.files.push({ path: 'opencode.jsonc', hash: sha256Text(out), action: 'merged' });
371
- log('merge', `rewrote ${userPath} (distro base with permissions/deny, skill allowlist, default_agent "master", references; your model/providers/mcp/plugins re-injected)`);
467
+ log(
468
+ 'merge',
469
+ `ownership — install-owned (distro wins): ${INSTALL_OWNED.join(', ')} · union: ${[...UNION_KEYS, 'references'].join(', ')} · your keys preserved: ${preserved.length}${preserved.length ? ` (${preserved.join(', ')})` : ''}`
470
+ );
471
+ log('merge', `rewrote ${targetPath} (distro base + your keys; permissions = harness allows, yours, harness denies last)`);
372
472
  }
373
473
 
374
- /* ------------------------------ placeholder lint --------------------------- */
474
+ /* ------------------------------ author-leak lint --------------------------- */
375
475
 
376
- function lintCopiedFiles(files) {
476
+ // Lints the PACKAGE source (files[].src) and nothing else. The adopter's config
477
+ // is never a lint target, so a valid config — including a DOCS-SANCTIONED
478
+ // `{file:~/.secrets/…}` apiKey pointer — can never trip this abort. Called
479
+ // pre-write, so a hit aborts before anything lands.
480
+ function lintPackagedSource(files) {
377
481
  const hits = [];
378
482
  for (const f of files) {
379
- if (!existsSync(f.dest)) continue;
380
- const low = readFileSync(f.dest, 'utf8').toLowerCase();
483
+ if (!f.src || !existsSync(f.src)) continue;
484
+ const low = readFileSync(f.src, 'utf8').toLowerCase();
485
+ // No `break`: a file can carry more than one marker, and reporting only the
486
+ // first hides the rest of the leak.
381
487
  for (const pat of LINT_PATTERNS) {
382
- if (low.includes(pat)) {
383
- hits.push({ file: f.rel, pattern: pat });
384
- break;
385
- }
488
+ if (pat.test.test(low)) hits.push({ file: f.rel, pattern: pat.label });
386
489
  }
387
490
  }
388
491
  return hits;
@@ -407,28 +510,57 @@ function registerPlugins() {
407
510
  return list;
408
511
  }
409
512
 
513
+ // The doctor's Law 6 grades `opencode plugin list`, but right after `plugin
514
+ // add` on a fresh config the registry can lag the file write by minutes - the
515
+ // doctor would grade an empty list and fail. Poll the list (bounded: up to 10
516
+ // attempts, 6 s apart) until every requested name appears in a row, mirroring
517
+ // the doctor's own row-contains-name check. Warning-only on expiry - exit
518
+ // codes are unchanged (the doctor grades; a re-run is idempotent).
519
+ async function waitForPluginRegistration(plugins, configDir) {
520
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
521
+ for (let attempt = 1; attempt <= 10; attempt++) {
522
+ const res = exec('opencode', ['plugin', 'list'], true);
523
+ const rows = (res.stdout || '').split(/\r?\n/).filter((l) => l.trim() !== '');
524
+ const missing = plugins.filter((name) => !rows.some((row) => row.includes(name)));
525
+ const state = res.error || res.status !== 0
526
+ ? `list failed (${res.error ? 'not found' : `exit ${res.status}`})`
527
+ : `${rows.length} row(s), missing: ${missing.length ? missing.join(', ') : 'none'}`;
528
+ log('plugin', `registration wait ${attempt}/10 (${configDir}) - ${state}`);
529
+ if (!missing.length) {
530
+ for (const name of plugins) log('plugin', `${name} appears in the registry`);
531
+ return;
532
+ }
533
+ if (attempt < 10) await sleep(6000);
534
+ }
535
+ 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`);
536
+ }
537
+
410
538
  /* --------------------------------- doctor ---------------------------------- */
411
539
 
412
- function doctorPlan() {
540
+ function pwshProbe() {
413
541
  const probe = exec('pwsh', ['-NoProfile', '-Command', 'exit 0'], true);
414
- return probe.error || probe.status !== 0
415
- ? 'pwsh missing — doctor skipped, install note printed'
416
- : 'run scripts/harness-doctor.ps1 via pwsh';
542
+ return { usable: !(probe.error || probe.status !== 0) };
417
543
  }
418
544
 
419
- function runDoctor(configDir) {
420
- const probe = exec('pwsh', ['-NoProfile', '-Command', 'exit 0'], true);
421
- if (probe.error || probe.status !== 0) {
422
- log('doctor', 'pwsh is not on PATH — /doctor cannot run here. Config still lands.');
423
- console.log(' PowerShell 7 is optional here but powers /doctor — install:');
545
+ function doctorPlan() {
546
+ return pwshProbe().usable
547
+ ? 'run scripts/harness-doctor.ps1 via pwsh'
548
+ : 'pwsh missing — doctor SKIPPED, 16 laws UNVERIFIED (warned + journaled)';
549
+ }
550
+
551
+ function runDoctor(configDir, probe) {
552
+ if (!probe.usable) {
553
+ console.warn('[doctor] WARNING: pwsh (PowerShell 7) was not found — harness-doctor did NOT run, so the 16 laws are UNVERIFIED.');
554
+ console.warn('[doctor] Your config still landed, and the skip is recorded in the manifest. To verify later:');
424
555
  console.log(' winget install --id Microsoft.PowerShell --source winget (Windows)');
425
556
  console.log(' brew install --cask powershell (macOS)');
426
- return 0;
557
+ console.log(' then re-run: npx oc-harness-setup setup');
558
+ return { code: 0, skipped: true };
427
559
  }
428
560
  const script = path.join(configDir, 'scripts', 'harness-doctor.ps1');
429
561
  if (!existsSync(script)) {
430
- log('doctor', `note: ${script} not found — doctor skipped`);
431
- return 0;
562
+ console.warn(`[doctor] WARNING: ${script} not found — harness-doctor did NOT run, so the 16 laws are UNVERIFIED.`);
563
+ return { code: 0, skipped: true };
432
564
  }
433
565
  log('doctor', `running ${script}`);
434
566
  const res = exec('pwsh', ['-NoProfile', '-File', script, '-ConfigDir', configDir], false);
@@ -437,10 +569,10 @@ function runDoctor(configDir) {
437
569
  'doctor',
438
570
  `harness-doctor exited ${res.error ? 'with an error' : `${res.status}`} — fix the issue, then re-run setup (idempotent)`
439
571
  );
440
- return 1;
572
+ return { code: 1, skipped: false };
441
573
  }
442
574
  log('doctor', 'harness-doctor passed');
443
- return 0;
575
+ return { code: 0, skipped: false };
444
576
  }
445
577
 
446
578
  /* --------------------------- manifest print (gate) ------------------------- */
@@ -453,8 +585,8 @@ function printManifest(configDir, files, backupPath, doctor) {
453
585
  console.log(` incoming files : ${files.length} (${newCount} new, ${sameCount} already identical — rerun-safe)`);
454
586
  console.log(` backup path : ${backupPath}`);
455
587
  console.log(' opencode.jsonc merge : distro base (permissions/deny block, skill allowlist,');
456
- console.log(' default_agent: "master", references registry)');
457
- console.log(` + your keys re-injected: ${MERGE_KEYS.join(', ')}`);
588
+ console.log(' default_agent: "orchestrator", references registry)');
589
+ console.log(' + your keys kept · permissions: harness allows, yours, harness denies last');
458
590
  console.log(' plugin registration : oc-flight-deck (via \'opencode plugin add\')');
459
591
  console.log(` doctor plan : ${doctor}`);
460
592
  console.log('----------------------------------------------------------------------------');
@@ -491,8 +623,11 @@ function uninstall(configDir) {
491
623
  const base = path.resolve(configDir);
492
624
  const files = Array.isArray(manifest.files) ? manifest.files : [];
493
625
  if (!files.length) bail(`manifest at ${manifestPath} lists no files — refusing a blind cleanup.`);
626
+ const backupRoot = manifest.backupPath ? path.resolve(String(manifest.backupPath)) : null;
494
627
  let removed = 0;
628
+ let restored = 0;
495
629
  let kept = 0;
630
+ let preserved = 0;
496
631
  let missing = 0;
497
632
  for (const entry of files) {
498
633
  const rel = String(entry.path || '');
@@ -505,6 +640,32 @@ function uninstall(configDir) {
505
640
  missing += 1;
506
641
  continue;
507
642
  }
643
+ if (entry.action === 'overwritten' || entry.action === 'merged') {
644
+ // A genuine overwrite comes back from the pre-install backup; the merged
645
+ // opencode.jsonc is never deleted — restore the adopter's original, or
646
+ // leave the harness copy in place when no backup holds it.
647
+ const original = backupRoot ? path.join(backupRoot, rel) : null;
648
+ if (original && existsSync(original)) {
649
+ // Restoring is only reversible if the bytes being replaced survive. When
650
+ // the current file is not the one the installer wrote (hash differs, or
651
+ // none was journaled) it holds post-install edits — copy it aside before
652
+ // the restore overwrites it. Byte-identical installer output needs no
653
+ // copy.
654
+ if (!entry.hash || sha256File(resolved) !== entry.hash) {
655
+ const keep = nextFreePath(`${resolved}.replaced-${tsStamp()}`);
656
+ cpSync(resolved, keep);
657
+ preserved += 1;
658
+ log('uninstall', `kept ${path.relative(base, keep)} (your post-install edits — copied before restore)`);
659
+ }
660
+ cpSync(original, resolved, { force: true });
661
+ restored += 1;
662
+ log('uninstall', `restored ${rel} (your pre-install file, from ${manifest.backupPath})`);
663
+ } else {
664
+ kept += 1;
665
+ log('uninstall', `kept ${rel} (WARNING: no backup at ${original || '(no backupPath recorded)'} — not deleted)`);
666
+ }
667
+ continue;
668
+ }
508
669
  if (entry.hash && sha256File(resolved) === entry.hash) {
509
670
  rmSync(resolved, { force: true });
510
671
  removed += 1;
@@ -515,9 +676,16 @@ function uninstall(configDir) {
515
676
  }
516
677
  }
517
678
  rmSync(manifestPath, { force: true });
518
- log('uninstall', `removed ${removed}, kept ${kept} modified, already-missing ${missing}`);
679
+ log('uninstall', `removed ${removed}, restored ${restored} overwritten, kept ${kept} modified, preserved ${preserved} edit-copies, already-missing ${missing}`);
519
680
  console.log(` backup (pre-install config dir): ${manifest.backupPath || '(none recorded)'}`);
681
+ if (manifest.priorBackup) console.log(` later snapshot (kept for the chain): ${manifest.priorBackup}`);
520
682
  console.log(' to restore it fully, replace the current config dir with that backup.');
683
+ if (preserved > 0) {
684
+ console.log(` ${preserved} post-install edit-copy(ies) written beside the restored file(s) as <name>.replaced-<ts> (listed above).`);
685
+ }
686
+ if (manifest.doctorSkipped) {
687
+ console.log(' note: this install skipped the doctor — the 16 laws were never verified.');
688
+ }
521
689
  if (Array.isArray(manifest.plugins) && manifest.plugins.length) {
522
690
  console.log(
523
691
  ` plugins left registered: ${manifest.plugins.join(', ')} — remove with 'opencode plugin remove <name>' if unwanted.`
@@ -532,13 +700,89 @@ function writeManifest(configDir, manifest) {
532
700
  writeFileSync(path.join(configDir, MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\n`);
533
701
  }
534
702
 
703
+ // R4: a re-run must not erase what an earlier run knew. A file this run sees as
704
+ // "skip" may have been an overwrite two runs ago; downgrading it to "skip" would
705
+ // make --uninstall delete the adopter's original instead of restoring it. Keep
706
+ // the earliest truth: overwritten stays overwritten (with the ORIGINAL prevHash),
707
+ // preserved stays preserved.
708
+ function carryForwardJournal(manifest, prior) {
709
+ if (!prior || !Array.isArray(prior.files)) return;
710
+ const before = new Map(prior.files.map((f) => [String(f.path), f]));
711
+ for (const e of manifest.files) {
712
+ const p = before.get(String(e.path));
713
+ if (!p) continue;
714
+ if (p.action === 'overwritten') {
715
+ e.action = 'overwritten';
716
+ e.prevHash = p.prevHash || e.prevHash;
717
+ } else if (p.action === 'preserved' && e.action !== 'overwritten') {
718
+ e.action = 'preserved';
719
+ }
720
+ }
721
+ }
722
+
723
+ function readManifest(configDir) {
724
+ const p = path.join(configDir, MANIFEST_FILE);
725
+ if (!existsSync(p)) return null;
726
+ try {
727
+ const m = JSON.parse(readFileSync(p, 'utf8'));
728
+ return m && typeof m === 'object' ? m : null;
729
+ } catch {
730
+ return null; // an unreadable manifest is not a reason to abort — a fresh one is written
731
+ }
732
+ }
733
+
734
+ function warnConfigTargets(configDir) {
735
+ if (process.env.OPENCODE_CONFIG) {
736
+ console.warn(
737
+ `[warn] OPENCODE_CONFIG is set (${process.env.OPENCODE_CONFIG}) — it loads ABOVE the global config and may shadow this merge; check 'opencode debug config' after install.`
738
+ );
739
+ }
740
+ const own = new Set([
741
+ path.resolve(configDir, 'opencode.jsonc'),
742
+ path.resolve(configDir, 'opencode.json'),
743
+ ]);
744
+ let dir = path.resolve(process.cwd());
745
+ for (;;) {
746
+ for (const name of ['opencode.jsonc', 'opencode.json']) {
747
+ const p = path.join(dir, name);
748
+ if (existsSync(p) && !own.has(path.resolve(p))) {
749
+ console.warn(
750
+ `[warn] project config ${p} outranks the global config — it may shadow this merge for sessions started in ${dir} or below (warn only; nothing changes).`
751
+ );
752
+ return;
753
+ }
754
+ }
755
+ const parent = path.dirname(dir);
756
+ if (parent === dir) return;
757
+ dir = parent;
758
+ }
759
+ }
760
+
535
761
  async function setup(opts) {
536
762
  preflight();
537
763
  const configDir = findConfigDir();
764
+ warnConfigTargets(configDir);
538
765
  const files = collectIncoming(configDir);
539
- const backupPath = `${configDir}.bak-oc-harness-setup-${tsStamp()}`;
540
- const doctor = doctorPlan(); // read-only probe
541
- printManifest(configDir, files, backupPath, doctor);
766
+
767
+ // Author-leak lint runs PRE-write, over the PACKAGE source only. A hit aborts
768
+ // before the consent gate, so nothing lands and the adopter's config (which
769
+ // is never linted) can never trip it.
770
+ const hits = lintPackagedSource(files);
771
+ if (hits.length) {
772
+ for (const h of hits) console.error(`[lint] author-leak marker "${h.pattern}" found in ${h.file}`);
773
+ bail(
774
+ `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.`
775
+ );
776
+ }
777
+
778
+ const prior = readManifest(configDir); // read-only
779
+ const newBackupPath = nextBackupPath(configDir);
780
+ // R4(d): a re-run must never re-point the original backup — that snapshot has
781
+ // already been mutated by the previous install, so restoring from it would be
782
+ // a lie. Keep the original pointer; chain the new snapshot as priorBackup.
783
+ const backupPath = prior && prior.backupPath ? prior.backupPath : newBackupPath;
784
+ const doctorProbe = pwshProbe(); // read-only probe
785
+ printManifest(configDir, files, backupPath, doctorPlan());
542
786
 
543
787
  if (opts.dryRun) {
544
788
  console.log('[dry-run] manifest only — nothing was touched.');
@@ -554,18 +798,20 @@ async function setup(opts) {
554
798
  }
555
799
 
556
800
  /* ---------------- mutations begin (all journaled) ---------------- */
557
- const backup = makeBackup(configDir);
801
+ const backup = makeBackup(configDir, newBackupPath);
558
802
  const manifest = {
559
803
  package: PKG_NAME,
560
804
  version: pkgVersion(),
561
805
  created: new Date().toISOString(),
562
806
  configDir,
563
- backupPath: backup,
807
+ backupPath: backupPath,
808
+ ...(prior && prior.backupPath ? { priorBackup: backup } : {}),
564
809
  plugins: ['oc-flight-deck'],
565
810
  files: [],
566
811
  };
567
812
 
568
813
  stageFiles(files, manifest);
814
+ carryForwardJournal(manifest, prior);
569
815
  // Register plugins BEFORE the merge: on a fresh dir `opencode plugin add`
570
816
  // installs the plugin, but once the merged opencode.jsonc lists it, add
571
817
  // no-ops with "already configured" and nothing lands in `opencode plugin
@@ -573,30 +819,26 @@ async function setup(opts) {
573
819
  registerPlugins();
574
820
  mergeJsonc(configDir, backup, manifest);
575
821
 
576
- const hits = lintCopiedFiles([
577
- ...files,
578
- { rel: 'opencode.jsonc (merged)', dest: path.join(configDir, 'opencode.jsonc') },
579
- ]);
580
- if (hits.length) {
581
- // Journal first — uninstall must know exactly what landed.
582
- writeManifest(configDir, manifest);
583
- for (const h of hits) console.error(`[lint] placeholder pattern "${h.pattern}" found in ${h.file}`);
584
- bail(
585
- `placeholder data found in the shipped tree (${hits.length} file(s) listed above) — this package build is corrupted; stop and reinstall from npm. Restore your config from: ${backup}`
586
- );
587
- }
822
+ // Right after a fresh `plugin add` the registry can lag by minutes; wait
823
+ // (bounded) for it to settle so the doctor's Law 6 grades a settled list.
824
+ await waitForPluginRegistration(manifest.plugins, configDir);
588
825
 
826
+ // R6: record the skip in the journal so "all 16 laws unrun" is never silent.
827
+ manifest.doctorSkipped = !doctorProbe.usable || !existsSync(path.join(configDir, 'scripts', 'harness-doctor.ps1'));
589
828
  writeManifest(configDir, manifest);
590
829
  log('manifest', `journal written: ${path.join(configDir, MANIFEST_FILE)}`);
591
830
 
592
- const doctorOk = runDoctor(configDir);
593
- if (doctorOk !== 0) return 1;
831
+ const doctorResult = runDoctor(configDir, doctorProbe);
832
+ if (doctorResult.code !== 0) return 1;
594
833
 
595
834
  console.log();
596
835
  console.log('-------------------------------- summary ---------------------------------');
597
836
  console.log(' installed: agents/, commands/, skills/, reference/, scripts/, AGENTS.md + merged opencode.jsonc');
598
837
  console.log(' plugins : oc-flight-deck');
599
- console.log(` backup : ${backup}`);
838
+ console.log(` backup : ${manifest.backupPath}${manifest.priorBackup ? `\n snapshot : ${manifest.priorBackup} (chained — backup() pointer above is the original)` : ''}`);
839
+ if (manifest.doctorSkipped) {
840
+ console.log(' doctor : ⚠ SKIPPED — the 16 laws were NOT verified (journaled as doctorSkipped; install PowerShell 7 and re-run to verify)');
841
+ }
600
842
  console.log(' undo : npx oc-harness-setup setup --uninstall');
601
843
  console.log(' restart : restart your OpenCode session so the new agents/commands/skills load.');
602
844
  console.log('----------------------------------------------------------------------------');
package/commands/build.md CHANGED
@@ -1,13 +1,7 @@
1
1
  ---
2
2
  description: Implement the request with the smallest working change
3
3
  agent: build
4
+ subagent: true
4
5
  ---
5
6
 
6
- Build `$ARGUMENTS`. Define "done" first, then implement with the smallest correct diff.
7
-
8
- - Pick the local skill that fits: `spec-driven-development` for a new or specified feature, `incremental-implementation` for the build loop, `test-driven-development` when tests should come first, and `debugging-and-error-recovery` for hard bugs. For UI, consult `frontend-ui-engineering`; for API boundaries, use `api-and-interface-design`.
9
- - Inspect before editing; understand the real flow, then stop at the first rung that holds.
10
- - Preserve safety, validation, security, accessibility, reversibility, and anything the user explicitly asked for — never lean these away.
11
- - Run the narrow check that proves the change and report: files changed, what you ran, what it proved, and residual risk.
12
- - Mark deliberate shortcuts with `lean: <ceiling>; revisit when <trigger>` so `/ponytail-debt` can collect them.
13
- - For work that splits at natural seams, spawn helpers in parallel with one writer per artifact; follow the `swarm-orchestration` skill.
7
+ Implement `$ARGUMENTS` inside the supplied scope. Define done, inspect first, make the smallest coherent change, run the narrow proving check, and return changed files and evidence, adding residual risk and anything unverified only when they have real content, omit otherwise. Do not widen scope or delegate.
@@ -1,5 +1,7 @@
1
1
  ---
2
2
  description: Write or refresh this session's checkpoint
3
+ agent: orchestrator
4
+ subagent: false
3
5
  ---
4
6
 
5
- Update `checkpoint.md` in this session's state directory (`~/.opencode/state/sessions/<session-id>/`): goal, status (done / now / next), key files, blockers. `$ARGUMENTS` is optional scope. Keep it short; append a timestamped entry if the file exists.
7
+ Update `session.yaml` in this session's state directory with goal, done, now, next, key files, and blockers. Append one timestamped event to `events.yaml`. `$ARGUMENTS` optionally narrows the checkpoint. Keep it terse; never create Markdown state files.
@@ -1,13 +1,7 @@
1
1
  ---
2
2
  description: Simplify current changes by cutting unnecessary complexity
3
- agent: coder
3
+ agent: general
4
+ subagent: true
4
5
  ---
5
6
 
6
- Simplify `$ARGUMENTS` (default: the current changes) by applying the Ponytail ladder in `AGENTS.md` and the local `code-simplification` skill: the laziest change that actually works.
7
-
8
- 1. First **review** the target for what can be cut — tags `delete` (dead code, unused flags), `stdlib` (reinvented standard library), `native` (platform features replaced by custom code), `yagni` (speculative flexibility), `shrink` (over-abstraction). Or run `/ponytail-audit --diff` first if the diff is large.
9
- 2. Then **apply** the safe cuts: one writer per artifact, smallest diff, no behavior change unless removing the behavior is the point.
10
- 3. Preserve the lean safety floor: validation, security, accessibility, reversibility, and explicit user requirements are never cut.
11
- 4. Run the check that proves behavior is unchanged (or correctly simpler) and report: what was cut, lines/dependencies removed, what you ran, and what it proved.
12
-
13
- Mark anything you deliberately deferred with `lean: <ceiling>; revisit when <trigger>`. Route correctness, security, and performance findings to `/review` — this command cuts complexity only.
7
+ Simplify `$ARGUMENTS` (default: current changes) using `code-simplification`. Remove dead or speculative machinery and prefer standard or native behavior while preserving requirements, safety, accessibility, and reversibility. Run the proving check and report what was removed and the evidence, adding residual risk only when it has real content, omit otherwise. Do not pursue unrelated defects.
@@ -0,0 +1,7 @@
1
+ ---
2
+ description: Closed-loop challenge engine - drive $ARGUMENTS to a defined green (challenge, revise, re-challenge)
3
+ agent: orchestrator
4
+ subagent: false
5
+ ---
6
+
7
+ Run the explicit `gauntlet` workflow against `$ARGUMENTS` (default: current changes). Pre-register acceptance evidence, dispatch bounded challenge and repair rounds, keep challengers read-only and one writer per artifact, then report the terminal verdict and evidence. Never move the acceptance bar mid-loop.
@@ -1,5 +1,7 @@
1
1
  ---
2
2
  description: Write a handoff for a fresh session
3
+ agent: orchestrator
4
+ subagent: false
3
5
  ---
4
6
 
5
- Write `handoff.md` in this session's state directory for a fresh session to continue from: goal, current state, exact next steps, files to read first, open decisions. `$ARGUMENTS` is optional scope.
7
+ Write `session.yaml.handoff` in this session's state directory: goal, current state, exact next steps, files to read first, and open decisions. `$ARGUMENTS` optionally narrows the handoff. Never create Markdown state files.