oc-harness-setup 0.1.0 → 0.2.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
@@ -8,7 +8,6 @@
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
- * --fleet also register the oc-freedom-fleet plugin
12
11
  *
13
12
  * Exit codes are strictly 0 (ok / clean abort) or 1 (failure).
14
13
  */
@@ -25,10 +24,44 @@ import { createInterface } from 'node:readline/promises';
25
24
  const PKG_NAME = 'oc-harness-setup';
26
25
  const PKG_ROOT = path.resolve(import.meta.dirname, '..');
27
26
  const MANIFEST_FILE = 'oc-harness-setup.manifest.json';
28
- const COPY_DIRS = ['agents', 'commands', 'skills', 'reference', 'scripts'];
29
- const COPY_FILES = ['AGENTS.md'];
30
- const MERGE_KEYS = ['model', 'providers', 'mcp', 'plugins'];
31
- const LINT_PATTERNS = ['c:\\users', 'q:\\', 'nathan', 'ses_', '.secrets'];
27
+ const COPY_DIRS = ['agents', 'commands', 'skills', 'reference', 'scripts', '.docs'];
28
+ const COPY_FILES = ['AGENTS.md', '.gitignore'];
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', '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', '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
+ ];
32
65
 
33
66
  /* ------------------------------ tiny helpers ------------------------------ */
34
67
 
@@ -36,6 +69,16 @@ function log(label, msg) {
36
69
  console.log(`[${label}] ${msg}`);
37
70
  }
38
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
+
39
82
  function usage() {
40
83
  console.log(`oc-harness-setup — install the OpenCode harness into your config dir.
41
84
 
@@ -43,8 +86,7 @@ usage:
43
86
  oc-harness-setup setup full install (default: no args needed)
44
87
  oc-harness-setup --dry-run print the manifest only; touch nothing
45
88
  oc-harness-setup --ci print-only, refuse to mutate, exit 0
46
- oc-harness-setup setup --uninstall remove exactly the manifest-listed files
47
- oc-harness-setup setup --fleet also register plugin oc-freedom-fleet`);
89
+ oc-harness-setup setup --uninstall remove exactly the manifest-listed files`);
48
90
  }
49
91
 
50
92
  class Bail extends Error {}
@@ -198,8 +240,7 @@ function collectIncoming(configDir) {
198
240
 
199
241
  /* -------------------------------- backup ----------------------------------- */
200
242
 
201
- function makeBackup(configDir) {
202
- const backupPath = `${configDir}.bak-oc-harness-setup-${tsStamp()}`;
243
+ function makeBackup(configDir, backupPath) {
203
244
  if (existsSync(configDir)) {
204
245
  if (!statSync(configDir).isDirectory()) {
205
246
  bail(`${configDir} exists but is not a directory — refusing to install over it`);
@@ -212,6 +253,16 @@ function makeBackup(configDir) {
212
253
  return backupPath;
213
254
  }
214
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
+
215
266
  /* ------------------------------ staged copy -------------------------------- */
216
267
 
217
268
  function stageFiles(files, manifest) {
@@ -219,17 +270,26 @@ function stageFiles(files, manifest) {
219
270
  for (const f of files) {
220
271
  const srcHash = sha256File(f.src);
221
272
  let action = 'written';
273
+ let prevHash = null;
222
274
  if (existsSync(f.dest)) {
223
- if (sha256File(f.dest) === srcHash) {
275
+ const destHash = sha256File(f.dest);
276
+ if (destHash === srcHash) {
224
277
  action = 'skip';
225
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)`);
226
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;
227
287
  log('staging', `update ${f.rel} (destination differs — overwriting; backup + manifest protect you)`);
228
288
  }
229
289
  } else {
230
290
  log('staging', `copy ${f.rel}`);
231
291
  }
232
- if (action === 'written') {
292
+ if (action === 'written' || action === 'overwritten') {
233
293
  mkdirSync(path.dirname(f.dest), { recursive: true });
234
294
  const tmp = `${f.dest}.oc-harness-setup-tmp-${process.pid}`;
235
295
  writeFileSync(tmp, readFileSync(f.src));
@@ -237,7 +297,10 @@ function stageFiles(files, manifest) {
237
297
  renameSync(tmp, f.dest);
238
298
  written += 1;
239
299
  }
240
- 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 });
241
304
  }
242
305
  return written;
243
306
  }
@@ -314,67 +377,115 @@ function parseJsonc(text, what) {
314
377
  }
315
378
  }
316
379
 
317
- function describeKey(k, v) {
318
- if (k === 'model') return `model "${v}"`;
319
- if (Array.isArray(v)) return `${k} (${v.length} entr${v.length === 1 ? 'y' : 'ies'})`;
320
- if (v && typeof v === 'object') {
321
- const n = Object.keys(v).length;
322
- return `${k} (${n} entr${n === 1 ? 'y' : 'ies'})`;
323
- }
324
- return `${k} (${JSON.stringify(v)})`;
325
- }
326
-
327
380
  function mergeJsonc(configDir, backupPath, manifest) {
328
381
  const distroPath = path.join(PKG_ROOT, 'opencode.jsonc');
329
- const userPath = path.join(configDir, 'opencode.jsonc');
330
382
  if (!existsSync(distroPath)) {
331
383
  log('merge', 'note: this package ships no opencode.jsonc — no merge to do');
332
384
  return;
333
385
  }
334
- const merged = parseJsonc(
335
- readFileSync(distroPath, 'utf8'),
336
- `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)')
337
401
  );
338
- const kept = [];
339
- if (existsSync(userPath)) {
402
+ const preserved = [];
403
+ if (sourcePath) {
340
404
  const user = parseJsonc(
341
- readFileSync(userPath, 'utf8'),
342
- `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})`
343
407
  );
344
- for (const k of MERGE_KEYS) {
345
- if (user[k] !== undefined) {
346
- merged[k] = user[k];
347
- 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 ?? {}) };
348
442
  } else {
349
- log('merge', `opencode.jsonc: no ${k} in your config — harness default stays`);
443
+ merged[k] = user[k]; // adopter value wins
350
444
  }
445
+ preserved.push(k);
351
446
  }
352
- log('merge', `kept your ${kept.join(', ') || '(nothing — harness defaults only)'}`);
353
447
  } else {
354
- log('merge', 'no existing opencode.jsonc — writing the harness base');
355
- }
356
- const out = `${JSON.stringify(merged, null, 2)}\n`;
448
+ log('merge', 'no existing opencode.jsonc/opencode.json — writing the harness base');
449
+ }
450
+ // JSON.stringify strips comments, including the marker the doctor's Law 11
451
+ // cites as evidence — reinsert it so the merged file still documents the
452
+ // deny gate (the law grades the rules; the marker keeps its cited evidence).
453
+ const denyEvidence =
454
+ ' // Hard stops. `ask` is auto-approved under --auto, so `deny` is the only gate\n' +
455
+ ' // that holds while you are away. Keep this set minimal and last.\n';
456
+ const mergedText = JSON.stringify(merged, null, 2).replace(
457
+ ' "permissions": [\n',
458
+ ` "permissions": [\n${denyEvidence}`
459
+ );
460
+ const out = `${mergedText}\n`;
357
461
  mkdirSync(configDir, { recursive: true });
358
- const tmp = `${userPath}.oc-harness-setup-tmp-${process.pid}`;
462
+ const tmp = `${targetPath}.oc-harness-setup-tmp-${process.pid}`;
359
463
  writeFileSync(tmp, out);
360
- rmSync(userPath, { force: true });
361
- renameSync(tmp, userPath);
464
+ rmSync(targetPath, { force: true });
465
+ renameSync(tmp, targetPath);
362
466
  manifest.files.push({ path: 'opencode.jsonc', hash: sha256Text(out), action: 'merged' });
363
- 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)`);
364
472
  }
365
473
 
366
- /* ------------------------------ placeholder lint --------------------------- */
474
+ /* ------------------------------ author-leak lint --------------------------- */
367
475
 
368
- 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) {
369
481
  const hits = [];
370
482
  for (const f of files) {
371
- if (!existsSync(f.dest)) continue;
372
- 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.
373
487
  for (const pat of LINT_PATTERNS) {
374
- if (low.includes(pat)) {
375
- hits.push({ file: f.rel, pattern: pat });
376
- break;
377
- }
488
+ if (pat.test.test(low)) hits.push({ file: f.rel, pattern: pat.label });
378
489
  }
379
490
  }
380
491
  return hits;
@@ -382,8 +493,8 @@ function lintCopiedFiles(files) {
382
493
 
383
494
  /* ------------------------------- plugin gate ------------------------------- */
384
495
 
385
- function registerPlugins(fleet) {
386
- const list = ['oc-flight-deck', ...(fleet ? ['oc-freedom-fleet'] : [])];
496
+ function registerPlugins() {
497
+ const list = ['oc-flight-deck'];
387
498
  for (const p of list) {
388
499
  log('plugin', `opencode plugin add ${p}`);
389
500
  const res = exec('opencode', ['plugin', 'add', p], false);
@@ -401,43 +512,47 @@ function registerPlugins(fleet) {
401
512
 
402
513
  /* --------------------------------- doctor ---------------------------------- */
403
514
 
404
- function doctorPlan() {
515
+ function pwshProbe() {
405
516
  const probe = exec('pwsh', ['-NoProfile', '-Command', 'exit 0'], true);
406
- return probe.error || probe.status !== 0
407
- ? 'pwsh missing — doctor skipped, install note printed'
408
- : 'run scripts/harness-doctor.ps1 via pwsh';
517
+ return { usable: !(probe.error || probe.status !== 0) };
409
518
  }
410
519
 
411
- function runDoctor(configDir) {
412
- const probe = exec('pwsh', ['-NoProfile', '-Command', 'exit 0'], true);
413
- if (probe.error || probe.status !== 0) {
414
- log('doctor', 'pwsh is not on PATH — /doctor cannot run here. Config still lands.');
415
- console.log(' PowerShell 7 is optional here but powers /doctor — install:');
520
+ function doctorPlan() {
521
+ return pwshProbe().usable
522
+ ? 'run scripts/harness-doctor.ps1 via pwsh'
523
+ : 'pwsh missing — doctor SKIPPED, 16 laws UNVERIFIED (warned + journaled)';
524
+ }
525
+
526
+ function runDoctor(configDir, probe) {
527
+ if (!probe.usable) {
528
+ console.warn('[doctor] WARNING: pwsh (PowerShell 7) was not found — harness-doctor did NOT run, so the 16 laws are UNVERIFIED.');
529
+ console.warn('[doctor] Your config still landed, and the skip is recorded in the manifest. To verify later:');
416
530
  console.log(' winget install --id Microsoft.PowerShell --source winget (Windows)');
417
531
  console.log(' brew install --cask powershell (macOS)');
418
- return 0;
532
+ console.log(' then re-run: npx oc-harness-setup setup');
533
+ return { code: 0, skipped: true };
419
534
  }
420
535
  const script = path.join(configDir, 'scripts', 'harness-doctor.ps1');
421
536
  if (!existsSync(script)) {
422
- log('doctor', `note: ${script} not found — doctor skipped`);
423
- return 0;
537
+ console.warn(`[doctor] WARNING: ${script} not found — harness-doctor did NOT run, so the 16 laws are UNVERIFIED.`);
538
+ return { code: 0, skipped: true };
424
539
  }
425
540
  log('doctor', `running ${script}`);
426
- const res = exec('pwsh', ['-NoProfile', '-File', script], false);
541
+ const res = exec('pwsh', ['-NoProfile', '-File', script, '-ConfigDir', configDir], false);
427
542
  if (res.error || res.status !== 0) {
428
543
  log(
429
544
  'doctor',
430
545
  `harness-doctor exited ${res.error ? 'with an error' : `${res.status}`} — fix the issue, then re-run setup (idempotent)`
431
546
  );
432
- return 1;
547
+ return { code: 1, skipped: false };
433
548
  }
434
549
  log('doctor', 'harness-doctor passed');
435
- return 0;
550
+ return { code: 0, skipped: false };
436
551
  }
437
552
 
438
553
  /* --------------------------- manifest print (gate) ------------------------- */
439
554
 
440
- function printManifest(configDir, files, backupPath, fleet, doctor) {
555
+ function printManifest(configDir, files, backupPath, doctor) {
441
556
  const newCount = files.filter((f) => !existsSync(f.dest)).length;
442
557
  const sameCount = files.length - newCount;
443
558
  console.log('----------------------------- install manifest -----------------------------');
@@ -446,8 +561,8 @@ function printManifest(configDir, files, backupPath, fleet, doctor) {
446
561
  console.log(` backup path : ${backupPath}`);
447
562
  console.log(' opencode.jsonc merge : distro base (permissions/deny block, skill allowlist,');
448
563
  console.log(' default_agent: "master", references registry)');
449
- console.log(` + your keys re-injected: ${MERGE_KEYS.join(', ')}`);
450
- console.log(` plugin registration : oc-flight-deck${fleet ? ' + oc-freedom-fleet' : ''} (via 'opencode plugin add')`);
564
+ console.log(' + your keys kept · permissions: harness allows, yours, harness denies last');
565
+ console.log(' plugin registration : oc-flight-deck (via \'opencode plugin add\')');
451
566
  console.log(` doctor plan : ${doctor}`);
452
567
  console.log('----------------------------------------------------------------------------');
453
568
  }
@@ -483,8 +598,11 @@ function uninstall(configDir) {
483
598
  const base = path.resolve(configDir);
484
599
  const files = Array.isArray(manifest.files) ? manifest.files : [];
485
600
  if (!files.length) bail(`manifest at ${manifestPath} lists no files — refusing a blind cleanup.`);
601
+ const backupRoot = manifest.backupPath ? path.resolve(String(manifest.backupPath)) : null;
486
602
  let removed = 0;
603
+ let restored = 0;
487
604
  let kept = 0;
605
+ let preserved = 0;
488
606
  let missing = 0;
489
607
  for (const entry of files) {
490
608
  const rel = String(entry.path || '');
@@ -497,6 +615,32 @@ function uninstall(configDir) {
497
615
  missing += 1;
498
616
  continue;
499
617
  }
618
+ if (entry.action === 'overwritten' || entry.action === 'merged') {
619
+ // A genuine overwrite comes back from the pre-install backup; the merged
620
+ // opencode.jsonc is never deleted — restore the adopter's original, or
621
+ // leave the harness copy in place when no backup holds it.
622
+ const original = backupRoot ? path.join(backupRoot, rel) : null;
623
+ if (original && existsSync(original)) {
624
+ // Restoring is only reversible if the bytes being replaced survive. When
625
+ // the current file is not the one the installer wrote (hash differs, or
626
+ // none was journaled) it holds post-install edits — copy it aside before
627
+ // the restore overwrites it. Byte-identical installer output needs no
628
+ // copy.
629
+ if (!entry.hash || sha256File(resolved) !== entry.hash) {
630
+ const keep = nextFreePath(`${resolved}.replaced-${tsStamp()}`);
631
+ cpSync(resolved, keep);
632
+ preserved += 1;
633
+ log('uninstall', `kept ${path.relative(base, keep)} (your post-install edits — copied before restore)`);
634
+ }
635
+ cpSync(original, resolved, { force: true });
636
+ restored += 1;
637
+ log('uninstall', `restored ${rel} (your pre-install file, from ${manifest.backupPath})`);
638
+ } else {
639
+ kept += 1;
640
+ log('uninstall', `kept ${rel} (WARNING: no backup at ${original || '(no backupPath recorded)'} — not deleted)`);
641
+ }
642
+ continue;
643
+ }
500
644
  if (entry.hash && sha256File(resolved) === entry.hash) {
501
645
  rmSync(resolved, { force: true });
502
646
  removed += 1;
@@ -507,9 +651,16 @@ function uninstall(configDir) {
507
651
  }
508
652
  }
509
653
  rmSync(manifestPath, { force: true });
510
- log('uninstall', `removed ${removed}, kept ${kept} modified, already-missing ${missing}`);
654
+ log('uninstall', `removed ${removed}, restored ${restored} overwritten, kept ${kept} modified, preserved ${preserved} edit-copies, already-missing ${missing}`);
511
655
  console.log(` backup (pre-install config dir): ${manifest.backupPath || '(none recorded)'}`);
656
+ if (manifest.priorBackup) console.log(` later snapshot (kept for the chain): ${manifest.priorBackup}`);
512
657
  console.log(' to restore it fully, replace the current config dir with that backup.');
658
+ if (preserved > 0) {
659
+ console.log(` ${preserved} post-install edit-copy(ies) written beside the restored file(s) as <name>.replaced-<ts> (listed above).`);
660
+ }
661
+ if (manifest.doctorSkipped) {
662
+ console.log(' note: this install skipped the doctor — the 16 laws were never verified.');
663
+ }
513
664
  if (Array.isArray(manifest.plugins) && manifest.plugins.length) {
514
665
  console.log(
515
666
  ` plugins left registered: ${manifest.plugins.join(', ')} — remove with 'opencode plugin remove <name>' if unwanted.`
@@ -524,13 +675,89 @@ function writeManifest(configDir, manifest) {
524
675
  writeFileSync(path.join(configDir, MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\n`);
525
676
  }
526
677
 
678
+ // R4: a re-run must not erase what an earlier run knew. A file this run sees as
679
+ // "skip" may have been an overwrite two runs ago; downgrading it to "skip" would
680
+ // make --uninstall delete the adopter's original instead of restoring it. Keep
681
+ // the earliest truth: overwritten stays overwritten (with the ORIGINAL prevHash),
682
+ // preserved stays preserved.
683
+ function carryForwardJournal(manifest, prior) {
684
+ if (!prior || !Array.isArray(prior.files)) return;
685
+ const before = new Map(prior.files.map((f) => [String(f.path), f]));
686
+ for (const e of manifest.files) {
687
+ const p = before.get(String(e.path));
688
+ if (!p) continue;
689
+ if (p.action === 'overwritten') {
690
+ e.action = 'overwritten';
691
+ e.prevHash = p.prevHash || e.prevHash;
692
+ } else if (p.action === 'preserved' && e.action !== 'overwritten') {
693
+ e.action = 'preserved';
694
+ }
695
+ }
696
+ }
697
+
698
+ function readManifest(configDir) {
699
+ const p = path.join(configDir, MANIFEST_FILE);
700
+ if (!existsSync(p)) return null;
701
+ try {
702
+ const m = JSON.parse(readFileSync(p, 'utf8'));
703
+ return m && typeof m === 'object' ? m : null;
704
+ } catch {
705
+ return null; // an unreadable manifest is not a reason to abort — a fresh one is written
706
+ }
707
+ }
708
+
709
+ function warnConfigTargets(configDir) {
710
+ if (process.env.OPENCODE_CONFIG) {
711
+ console.warn(
712
+ `[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.`
713
+ );
714
+ }
715
+ const own = new Set([
716
+ path.resolve(configDir, 'opencode.jsonc'),
717
+ path.resolve(configDir, 'opencode.json'),
718
+ ]);
719
+ let dir = path.resolve(process.cwd());
720
+ for (;;) {
721
+ for (const name of ['opencode.jsonc', 'opencode.json']) {
722
+ const p = path.join(dir, name);
723
+ if (existsSync(p) && !own.has(path.resolve(p))) {
724
+ console.warn(
725
+ `[warn] project config ${p} outranks the global config — it may shadow this merge for sessions started in ${dir} or below (warn only; nothing changes).`
726
+ );
727
+ return;
728
+ }
729
+ }
730
+ const parent = path.dirname(dir);
731
+ if (parent === dir) return;
732
+ dir = parent;
733
+ }
734
+ }
735
+
527
736
  async function setup(opts) {
528
737
  preflight();
529
738
  const configDir = findConfigDir();
739
+ warnConfigTargets(configDir);
530
740
  const files = collectIncoming(configDir);
531
- const backupPath = `${configDir}.bak-oc-harness-setup-${tsStamp()}`;
532
- const doctor = doctorPlan(); // read-only probe
533
- printManifest(configDir, files, backupPath, opts.fleet, doctor);
741
+
742
+ // Author-leak lint runs PRE-write, over the PACKAGE source only. A hit aborts
743
+ // before the consent gate, so nothing lands and the adopter's config (which
744
+ // is never linted) can never trip it.
745
+ const hits = lintPackagedSource(files);
746
+ if (hits.length) {
747
+ for (const h of hits) console.error(`[lint] author-leak marker "${h.pattern}" found in ${h.file}`);
748
+ bail(
749
+ `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.`
750
+ );
751
+ }
752
+
753
+ const prior = readManifest(configDir); // read-only
754
+ const newBackupPath = nextBackupPath(configDir);
755
+ // R4(d): a re-run must never re-point the original backup — that snapshot has
756
+ // already been mutated by the previous install, so restoring from it would be
757
+ // a lie. Keep the original pointer; chain the new snapshot as priorBackup.
758
+ const backupPath = prior && prior.backupPath ? prior.backupPath : newBackupPath;
759
+ const doctorProbe = pwshProbe(); // read-only probe
760
+ printManifest(configDir, files, backupPath, doctorPlan());
534
761
 
535
762
  if (opts.dryRun) {
536
763
  console.log('[dry-run] manifest only — nothing was touched.');
@@ -546,42 +773,43 @@ async function setup(opts) {
546
773
  }
547
774
 
548
775
  /* ---------------- mutations begin (all journaled) ---------------- */
549
- const backup = makeBackup(configDir);
776
+ const backup = makeBackup(configDir, newBackupPath);
550
777
  const manifest = {
551
778
  package: PKG_NAME,
552
779
  version: pkgVersion(),
553
780
  created: new Date().toISOString(),
554
781
  configDir,
555
- backupPath: backup,
556
- plugins: ['oc-flight-deck', ...(opts.fleet ? ['oc-freedom-fleet'] : [])],
782
+ backupPath: backupPath,
783
+ ...(prior && prior.backupPath ? { priorBackup: backup } : {}),
784
+ plugins: ['oc-flight-deck'],
557
785
  files: [],
558
786
  };
559
787
 
560
788
  stageFiles(files, manifest);
789
+ carryForwardJournal(manifest, prior);
790
+ // Register plugins BEFORE the merge: on a fresh dir `opencode plugin add`
791
+ // installs the plugin, but once the merged opencode.jsonc lists it, add
792
+ // no-ops with "already configured" and nothing lands in `opencode plugin
793
+ // list` — the doctor's Law 6 grades exactly that list.
794
+ registerPlugins();
561
795
  mergeJsonc(configDir, backup, manifest);
562
796
 
563
- const hits = lintCopiedFiles(files);
564
- if (hits.length) {
565
- // Journal first — uninstall must know exactly what landed.
566
- writeManifest(configDir, manifest);
567
- for (const h of hits) console.error(`[lint] placeholder pattern "${h.pattern}" found in ${h.file}`);
568
- bail(
569
- `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}`
570
- );
571
- }
572
-
797
+ // R6: record the skip in the journal so "all 16 laws unrun" is never silent.
798
+ manifest.doctorSkipped = !doctorProbe.usable || !existsSync(path.join(configDir, 'scripts', 'harness-doctor.ps1'));
573
799
  writeManifest(configDir, manifest);
574
800
  log('manifest', `journal written: ${path.join(configDir, MANIFEST_FILE)}`);
575
801
 
576
- registerPlugins(opts.fleet);
577
- const doctorOk = runDoctor(configDir);
578
- if (doctorOk !== 0) return 1;
802
+ const doctorResult = runDoctor(configDir, doctorProbe);
803
+ if (doctorResult.code !== 0) return 1;
579
804
 
580
805
  console.log();
581
806
  console.log('-------------------------------- summary ---------------------------------');
582
807
  console.log(' installed: agents/, commands/, skills/, reference/, scripts/, AGENTS.md + merged opencode.jsonc');
583
- console.log(` plugins : oc-flight-deck${opts.fleet ? ', oc-freedom-fleet' : ''}`);
584
- console.log(` backup : ${backup}`);
808
+ console.log(' plugins : oc-flight-deck');
809
+ console.log(` backup : ${manifest.backupPath}${manifest.priorBackup ? `\n snapshot : ${manifest.priorBackup} (chained — backup() pointer above is the original)` : ''}`);
810
+ if (manifest.doctorSkipped) {
811
+ console.log(' doctor : ⚠ SKIPPED — the 16 laws were NOT verified (journaled as doctorSkipped; install PowerShell 7 and re-run to verify)');
812
+ }
585
813
  console.log(' undo : npx oc-harness-setup setup --uninstall');
586
814
  console.log(' restart : restart your OpenCode session so the new agents/commands/skills load.');
587
815
  console.log('----------------------------------------------------------------------------');
@@ -591,7 +819,7 @@ async function setup(opts) {
591
819
  /* --------------------------------- entry ---------------------------------- */
592
820
 
593
821
  function parseArgs(argv) {
594
- const opts = { command: 'setup', dryRun: false, ci: false, uninstall: false, fleet: false };
822
+ const opts = { command: 'setup', dryRun: false, ci: false, uninstall: false };
595
823
  for (const a of argv) {
596
824
  switch (a) {
597
825
  case 'setup':
@@ -606,9 +834,6 @@ function parseArgs(argv) {
606
834
  case '--uninstall':
607
835
  opts.uninstall = true;
608
836
  break;
609
- case '--fleet':
610
- opts.fleet = true;
611
- break;
612
837
  case '--help':
613
838
  case '-h':
614
839
  usage();
@@ -14,5 +14,6 @@ From `~/.config/opencode`, run `pwsh -File scripts\harness-doctor.ps1` and repor
14
14
  - Law 14 skill-allowlist set equality: allow entries and local skill IDs agree in both directions.
15
15
  - Law 15 agent/command frontmatter: `agents/*.md` carry description+steps, `commands/*.md` carry description.
16
16
  - Law 16 skill-loadable: every skill directory carries a `SKILL.md` with name+description and no YAML-breaking plain scalar.
17
+ - On a real regression or drift, recommend `/report` as the next action: it runs `scripts\harness-report.ps1` and returns a redacted, prefilled issue URL for the product repo. The doctor itself still writes nothing; `/report` also writes nothing by default - it prints the redacted body and the prefilled URL to the console, and only a run that passes `-OutFile <path>` writes that body to disk. Nothing is filed unless the human submits it.
17
18
 
18
19
  Close with: verdict (clean / drift / real regression), the exact commands run, files changed (normally none), and the next action.
@@ -4,4 +4,4 @@ agent: keeper
4
4
  subagent: true
5
5
  ---
6
6
 
7
- Refresh the model picture: compare `reference/models.md.example` and the model bindings in the file-based `agents\*.md` definitions against the live catalogs, pricing, and variants, following the canonical protocol in `reference/model-keeper.md`. Apply only evidence-backed changes; keep the catalog, bindings, and config parsing consistent. Report changes, sources, and uncertainty — or a clean no-change result.
7
+ Refresh the model picture: compare `reference/models.md` and the model bindings in the file-based `agents\*.md` definitions against the live catalogs, pricing, and variants, following the canonical protocol in `reference/model-keeper.md`. Apply only evidence-backed changes; keep the catalog, bindings, and config parsing consistent. Report changes, sources, and uncertainty — or a clean no-change result.