harnessed 4.26.0 → 4.27.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/dist/cli.mjs CHANGED
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  import { existsSync, mkdirSync, renameSync, writeFileSync, readFileSync, readdirSync, statSync } from 'fs';
3
3
  import { homedir } from 'os';
4
- import { join, resolve, dirname, sep, win32, relative } from 'path';
4
+ import { join, resolve, dirname, basename, sep, win32, relative } from 'path';
5
5
  import { Type } from '@sinclair/typebox';
6
- import { readFile, readdir, unlink, writeFile, stat, rm, cp, mkdir, access, rename, appendFile } from 'fs/promises';
6
+ import { readFile, readdir, unlink, writeFile, stat, rm, cp, mkdir, access, rename, appendFile, copyFile, chmod } from 'fs/promises';
7
7
  import { Value } from '@sinclair/typebox/value';
8
8
  import lockfile from 'proper-lockfile';
9
9
  import { parse, LineCounter, parseDocument, isSeq, isScalar } from 'yaml';
10
10
  import { Ajv } from 'ajv';
11
11
  import * as ajvFormatsNs from 'ajv-formats';
12
12
  import { execFileSync, spawnSync, spawn, exec, execSync, execFile } from 'child_process';
13
- import { fileURLToPath } from 'url';
13
+ import { pathToFileURL, fileURLToPath } from 'url';
14
14
  import { createHash } from 'crypto';
15
15
  import { Parser } from 'expr-eval';
16
16
  import { query } from '@anthropic-ai/claude-agent-sdk';
@@ -38,7 +38,7 @@ var init_package = __esm({
38
38
  "package.json"() {
39
39
  package_default = {
40
40
  name: "harnessed",
41
- version: "4.26.0",
41
+ version: "4.27.0",
42
42
  description: "AI coding harness package manager + composition orchestrator",
43
43
  type: "module",
44
44
  license: "Apache-2.0",
@@ -140,6 +140,20 @@ var init_package = __esm({
140
140
  };
141
141
  }
142
142
  });
143
+
144
+ // src/installers/lib/platform.ts
145
+ var platform_exports = {};
146
+ __export(platform_exports, {
147
+ claudeDescriptor: () => claudeDescriptor,
148
+ codexDescriptor: () => codexDescriptor,
149
+ detectPlatform: () => detectPlatform,
150
+ getCommandsDir: () => getCommandsDir,
151
+ getMcpConfigPath: () => getMcpConfigPath,
152
+ getPluginsRegistry: () => getPluginsRegistry,
153
+ getSettingsPath: () => getSettingsPath,
154
+ getSkillsDir: () => getSkillsDir,
155
+ harnessSkillsDirs: () => harnessSkillsDirs
156
+ });
143
157
  function claudeDescriptor(home = homedir()) {
144
158
  const claudeHome = join(home, ".claude");
145
159
  return {
@@ -2170,16 +2184,20 @@ __export(assetsRoot_exports, {
2170
2184
  compiledAssetsDir: () => compiledAssetsDir,
2171
2185
  computeAssetsRoot: () => computeAssetsRoot,
2172
2186
  getAssetsRoot: () => getAssetsRoot,
2173
- isCompiledModuleUrl: () => isCompiledModuleUrl
2187
+ isCompiledModuleUrl: () => isCompiledModuleUrl,
2188
+ isCompiledRuntime: () => isCompiledRuntime
2174
2189
  });
2190
+ function isCompiledRuntime(url = import.meta.url) {
2191
+ return isCompiledModuleUrl(url);
2192
+ }
2175
2193
  function isCompiledModuleUrl(url) {
2176
2194
  let s = url;
2177
2195
  try {
2178
2196
  s = decodeURIComponent(url);
2179
2197
  } catch {
2180
2198
  }
2181
- const normalized = s.replace(/\\/g, "/").toLowerCase();
2182
- return BUNFS_MARKERS.some((m) => normalized.includes(m));
2199
+ const normalized2 = s.replace(/\\/g, "/").toLowerCase();
2200
+ return BUNFS_MARKERS.some((m) => normalized2.includes(m));
2183
2201
  }
2184
2202
  function computeAssetsRoot(d) {
2185
2203
  const override = d.env.HARNESSED_ASSETS_OVERRIDE;
@@ -3354,25 +3372,25 @@ var init_discipline = __esm({
3354
3372
  );
3355
3373
  }
3356
3374
  });
3357
- async function loadDiscipline(basename2, packageRoot) {
3358
- const cached = _cache.get(basename2);
3375
+ async function loadDiscipline(basename4, packageRoot) {
3376
+ const cached = _cache.get(basename4);
3359
3377
  if (cached) return cached;
3360
- const yamlPath = resolve(packageRoot, "workflows", "disciplines", `${basename2}.yaml`);
3378
+ const yamlPath = resolve(packageRoot, "workflows", "disciplines", `${basename4}.yaml`);
3361
3379
  const raw = await readFile(yamlPath, "utf8");
3362
3380
  const parsedRaw = parse(raw);
3363
3381
  if (!Value.Check(Discipline, parsedRaw)) {
3364
3382
  const errors = [...Value.Errors(Discipline, parsedRaw)].slice(0, 3).map((e) => `${e.path} ${e.message}`).join("; ");
3365
- throw new Error(`Invalid discipline file ${basename2}.yaml: ${errors}`);
3383
+ throw new Error(`Invalid discipline file ${basename4}.yaml: ${errors}`);
3366
3384
  }
3367
3385
  const parsed = parsedRaw;
3368
- _cache.set(basename2, parsed);
3386
+ _cache.set(basename4, parsed);
3369
3387
  return parsed;
3370
3388
  }
3371
3389
  async function loadAllApplied(disciplines_applied, packageRoot) {
3372
3390
  const applied = disciplines_applied && disciplines_applied.length > 0 ? disciplines_applied : DEFAULT_APPLIED;
3373
3391
  const out = /* @__PURE__ */ new Map();
3374
- for (const basename2 of applied) {
3375
- out.set(basename2, await loadDiscipline(basename2, packageRoot));
3392
+ for (const basename4 of applied) {
3393
+ out.set(basename4, await loadDiscipline(basename4, packageRoot));
3376
3394
  }
3377
3395
  return out;
3378
3396
  }
@@ -6286,13 +6304,110 @@ var init_version_check = __esm({
6286
6304
  }
6287
6305
  });
6288
6306
 
6307
+ // src/cli/lib/update-check-cache.ts
6308
+ var update_check_cache_exports = {};
6309
+ __export(update_check_cache_exports, {
6310
+ DEFAULT_UPDATE_CHECK_TIMEOUT_MS: () => DEFAULT_UPDATE_CHECK_TIMEOUT_MS,
6311
+ DEFAULT_UPDATE_CHECK_TTL_MS: () => DEFAULT_UPDATE_CHECK_TTL_MS,
6312
+ fetchGitHubLatestVersion: () => fetchGitHubLatestVersion,
6313
+ resolveLatestCached: () => resolveLatestCached,
6314
+ resolveLatestCachedDefault: () => resolveLatestCachedDefault
6315
+ });
6316
+ function parseCache(text) {
6317
+ try {
6318
+ const c = JSON.parse(text);
6319
+ if (typeof c.latest === "string" && typeof c.ts === "number") {
6320
+ return { latest: c.latest, ts: c.ts, source: c.source === "github" ? "github" : "npm" };
6321
+ }
6322
+ } catch {
6323
+ }
6324
+ return null;
6325
+ }
6326
+ async function resolveLatestCached(d) {
6327
+ const ttl = d.ttlMs ?? DEFAULT_UPDATE_CHECK_TTL_MS;
6328
+ const timeout = d.timeoutMs ?? DEFAULT_UPDATE_CHECK_TIMEOUT_MS;
6329
+ let cachePath = null;
6330
+ try {
6331
+ cachePath = d.cachePath();
6332
+ const cached = parseCache(await readFile(cachePath, "utf8"));
6333
+ if (cached && d.now() - cached.ts < ttl) return cached.latest;
6334
+ } catch {
6335
+ }
6336
+ const compiled = d.isCompiled();
6337
+ const latest = compiled ? await d.fetchGitHub(timeout) : await d.fetchNpm();
6338
+ if (latest !== null && cachePath !== null) {
6339
+ try {
6340
+ await mkdir(dirname(cachePath), { recursive: true });
6341
+ await writeFile(
6342
+ cachePath,
6343
+ `${JSON.stringify({ latest, ts: d.now(), source: compiled ? "github" : "npm" })}
6344
+ `,
6345
+ "utf8"
6346
+ );
6347
+ } catch {
6348
+ }
6349
+ }
6350
+ return latest;
6351
+ }
6352
+ async function fetchGitHubLatestVersion(timeoutMs) {
6353
+ try {
6354
+ const ac = new AbortController();
6355
+ const timer = setTimeout(() => ac.abort(), timeoutMs);
6356
+ try {
6357
+ const res = await fetch("https://api.github.com/repos/easyinplay/harnessed/releases/latest", {
6358
+ signal: ac.signal,
6359
+ headers: { "user-agent": `harnessed/${package_default.version}` }
6360
+ });
6361
+ if (!res.ok) return null;
6362
+ const body = await res.json();
6363
+ const v = (body.tag_name ?? "").replace(/^v/, "");
6364
+ return /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(v) ? v : null;
6365
+ } finally {
6366
+ clearTimeout(timer);
6367
+ }
6368
+ } catch {
6369
+ return null;
6370
+ }
6371
+ }
6372
+ function envTimeoutMs() {
6373
+ const raw = Number.parseInt(process.env.HARNESSED_UPDATE_CHECK_TIMEOUT_MS ?? "", 10);
6374
+ return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_UPDATE_CHECK_TIMEOUT_MS;
6375
+ }
6376
+ function resolveLatestCachedDefault() {
6377
+ return resolveLatestCached({
6378
+ // lazy: detectPlatform() only runs when this resolver actually executes
6379
+ // inside a real CLI run (never at import time).
6380
+ cachePath: () => join(detectPlatform().stateRoot, "update-check.json"),
6381
+ now: () => Date.now(),
6382
+ timeoutMs: envTimeoutMs(),
6383
+ isCompiled: () => isCompiledRuntime(),
6384
+ fetchNpm: () => fetchLatestVersion(),
6385
+ fetchGitHub: (t2) => fetchGitHubLatestVersion(t2)
6386
+ });
6387
+ }
6388
+ var DEFAULT_UPDATE_CHECK_TTL_MS, DEFAULT_UPDATE_CHECK_TIMEOUT_MS;
6389
+ var init_update_check_cache = __esm({
6390
+ "src/cli/lib/update-check-cache.ts"() {
6391
+ init_package();
6392
+ init_platform();
6393
+ init_assetsRoot();
6394
+ init_version_check();
6395
+ DEFAULT_UPDATE_CHECK_TTL_MS = 24 * 60 * 60 * 1e3;
6396
+ DEFAULT_UPDATE_CHECK_TIMEOUT_MS = 2e3;
6397
+ }
6398
+ });
6399
+
6289
6400
  // src/cli/lib/check-update.ts
6290
6401
  var check_update_exports = {};
6291
6402
  __export(check_update_exports, {
6292
6403
  checkUpdate: () => checkUpdate
6293
6404
  });
6294
- async function checkUpdate(installed = package_default.version, fetch = fetchLatestVersion) {
6295
- const latest = await fetch();
6405
+ async function defaultResolver() {
6406
+ const { resolveLatestCachedDefault: resolveLatestCachedDefault2 } = await Promise.resolve().then(() => (init_update_check_cache(), update_check_cache_exports));
6407
+ return resolveLatestCachedDefault2();
6408
+ }
6409
+ async function checkUpdate(installed = package_default.version, fetch2 = defaultResolver) {
6410
+ const latest = await fetch2();
6296
6411
  if (!latest) {
6297
6412
  return { name: "update", status: "pass", message: "update check skipped (npm unreachable)" };
6298
6413
  }
@@ -6357,6 +6472,171 @@ var init_doctor_registry = __esm({
6357
6472
  ];
6358
6473
  }
6359
6474
  });
6475
+
6476
+ // src/cli/gc.ts
6477
+ var gc_exports = {};
6478
+ __export(gc_exports, {
6479
+ gcCompiledArtifacts: () => gcCompiledArtifacts,
6480
+ registerGc: () => registerGc
6481
+ });
6482
+ async function gcCompiledArtifacts(opts) {
6483
+ const removed = [];
6484
+ const kept = [];
6485
+ const keep = new Set(opts.keepVersions);
6486
+ try {
6487
+ const assetsDir = join(opts.stateRoot, "assets");
6488
+ for (const e of await readdir(assetsDir, { withFileTypes: true })) {
6489
+ if (!e.isDirectory()) continue;
6490
+ const p7 = join(assetsDir, e.name);
6491
+ if (keep.has(e.name)) {
6492
+ kept.push(p7);
6493
+ continue;
6494
+ }
6495
+ removed.push(p7);
6496
+ if (!opts.dryRun) await rm(p7, { recursive: true, force: true });
6497
+ }
6498
+ } catch {
6499
+ }
6500
+ try {
6501
+ const backupDir = join(opts.stateRoot, "bin-backup");
6502
+ const vers = (await readdir(backupDir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name).sort();
6503
+ for (const v of vers.slice(0, -1)) {
6504
+ const p7 = join(backupDir, v);
6505
+ removed.push(p7);
6506
+ if (!opts.dryRun) await rm(p7, { recursive: true, force: true });
6507
+ }
6508
+ const newest = vers[vers.length - 1];
6509
+ if (newest) kept.push(join(backupDir, newest));
6510
+ } catch {
6511
+ }
6512
+ if (opts.execPath) {
6513
+ try {
6514
+ const dir = dirname(opts.execPath);
6515
+ const base = basename(opts.execPath);
6516
+ for (const e of await readdir(dir, { withFileTypes: true })) {
6517
+ if (!e.isFile() || !e.name.startsWith(`${base}.bak-`)) continue;
6518
+ const p7 = join(dir, e.name);
6519
+ removed.push(p7);
6520
+ if (!opts.dryRun) await rm(p7, { force: true });
6521
+ }
6522
+ } catch {
6523
+ }
6524
+ }
6525
+ return { removed, kept };
6526
+ }
6527
+ function parseDuration(s) {
6528
+ const m = DURATION_RE.exec(s);
6529
+ if (!m) return null;
6530
+ const n = Number.parseInt(m[1] ?? "0", 10);
6531
+ const unit = m[2];
6532
+ const ms = unit === "d" ? 864e5 : unit === "h" ? 36e5 : unit === "m" ? 6e4 : 6048e5;
6533
+ return n * ms;
6534
+ }
6535
+ async function dirSizeKb(dir) {
6536
+ let total = 0;
6537
+ const stack = [dir];
6538
+ while (stack.length > 0) {
6539
+ const cur = stack.pop();
6540
+ if (!cur) break;
6541
+ const entries = await readdir(cur, { withFileTypes: true });
6542
+ for (const e of entries) {
6543
+ const p7 = join(cur, e.name);
6544
+ if (e.isDirectory()) stack.push(p7);
6545
+ else if (e.isFile()) {
6546
+ const st = await stat(p7);
6547
+ total += st.size;
6548
+ }
6549
+ }
6550
+ }
6551
+ return Math.round(total / 1024);
6552
+ }
6553
+ function registerGc(program2) {
6554
+ program2.command("gc").description(
6555
+ "Garbage-collect old backup snapshots (immediate by default \u2014 use --dry-run for preview)"
6556
+ ).option("--older-than <duration>", "delete snapshots older than (e.g. 30d / 24h / 4w)", "30d").option("--keep-last <N>", "always keep the most recent N snapshots", "0").option("--dry-run", "preview only \u2014 do not delete (opt-in for advanced users)").action(async (opts) => {
6557
+ const dryRun = opts.dryRun === true;
6558
+ const olderMs = parseDuration(opts.olderThan ?? "30d");
6559
+ if (olderMs == null) {
6560
+ console.error(
6561
+ `${t("gc.invalid_duration", { value: opts.olderThan ?? "" })}
6562
+ ${t("gc.invalid_duration.fix")}`
6563
+ );
6564
+ process.exit(1);
6565
+ return;
6566
+ }
6567
+ const keepLast = Number.parseInt(opts.keepLast ?? "0", 10);
6568
+ const root = getBackupRoot();
6569
+ let dirs;
6570
+ try {
6571
+ dirs = (await readdir(root, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name).sort();
6572
+ } catch {
6573
+ console.log(t("gc.no_backups", { root }));
6574
+ return;
6575
+ }
6576
+ const cutoff = Date.now() - olderMs;
6577
+ const kept = new Set(keepLast > 0 ? dirs.slice(-keepLast) : []);
6578
+ const candidates = [];
6579
+ for (const ts of dirs) {
6580
+ if (kept.has(ts)) continue;
6581
+ const path = join(root, ts);
6582
+ const iso = ts.replace(/T(\d{2})-(\d{2})-(\d{2})/, "T$1:$2:$3");
6583
+ const t2 = Date.parse(iso);
6584
+ if (Number.isNaN(t2) || t2 > cutoff) continue;
6585
+ let manifest = "(unknown)";
6586
+ try {
6587
+ const meta = JSON.parse(
6588
+ await readFile(join(path, "metadata.json"), "utf8")
6589
+ );
6590
+ manifest = meta.manifest;
6591
+ } catch {
6592
+ }
6593
+ const sizeKb = await dirSizeKb(path);
6594
+ candidates.push({ ts, path, manifest, sizeKb });
6595
+ }
6596
+ if (candidates.length === 0) {
6597
+ console.log(
6598
+ t("gc.no_old_snapshots", { cutoff: opts.olderThan ?? "", keptCount: kept.size })
6599
+ );
6600
+ return;
6601
+ }
6602
+ const totalKb = candidates.reduce((a, c) => a + c.sizeKb, 0);
6603
+ const key = dryRun ? "gc.summary_will_delete" : "gc.summary_deleting";
6604
+ console.log(t(key, { count: candidates.length, sizeKb: totalKb }));
6605
+ for (const c of candidates) {
6606
+ console.log(` ${c.ts} ${c.manifest} (${c.sizeKb} KB)`);
6607
+ if (!dryRun) await rm(c.path, { recursive: true, force: true });
6608
+ }
6609
+ if (dryRun) console.log(t("gc.dry_run_rerun_hint"));
6610
+ try {
6611
+ const { isCompiledRuntime: isCompiledRuntime2 } = await Promise.resolve().then(() => (init_assetsRoot(), assetsRoot_exports));
6612
+ if (isCompiledRuntime2() || process.env.HARNESSED_GC_COMPILED === "1") {
6613
+ const { detectPlatform: detectPlatform2 } = await Promise.resolve().then(() => (init_platform(), platform_exports));
6614
+ const r = await gcCompiledArtifacts({
6615
+ keepVersions: [package_default.version],
6616
+ stateRoot: detectPlatform2().stateRoot,
6617
+ execPath: isCompiledRuntime2() ? process.execPath : null,
6618
+ dryRun
6619
+ });
6620
+ if (r.removed.length > 0) {
6621
+ console.log(
6622
+ ` compiled artifacts ${dryRun ? "to remove" : "removed"}: ${r.removed.length}`
6623
+ );
6624
+ for (const p7 of r.removed) console.log(` ${p7}`);
6625
+ }
6626
+ }
6627
+ } catch {
6628
+ }
6629
+ });
6630
+ }
6631
+ var DURATION_RE;
6632
+ var init_gc = __esm({
6633
+ "src/cli/gc.ts"() {
6634
+ init_package();
6635
+ init_i18n();
6636
+ init_backup();
6637
+ DURATION_RE = /^(\d+)([dhmw])$/;
6638
+ }
6639
+ });
6360
6640
  async function confirmAt(level, ctx) {
6361
6641
  if (level === "L4" && !ctx.opts.system) {
6362
6642
  if (!ctx.opts.nonInteractive) {
@@ -6474,6 +6754,10 @@ function stripQuotes(token) {
6474
6754
  return { bare: token, quoted: false };
6475
6755
  }
6476
6756
  function resolveHookCommand(raw, deps) {
6757
+ if (deps.compiledExecPath && hookScriptMarker(raw) === INJECT_IDENTITY) {
6758
+ const exe = deps.compiledExecPath();
6759
+ if (exe) return `"${exe.replace(/\\/g, "/")}" ${INJECT_IDENTITY}`;
6760
+ }
6477
6761
  let root = null;
6478
6762
  const tokens = raw.split(/\s+/).filter((t2) => t2.length > 0);
6479
6763
  const out = tokens.map((token) => {
@@ -6491,9 +6775,14 @@ function hookScriptMarker(raw) {
6491
6775
  const { bare: bare2 } = stripQuotes(token);
6492
6776
  if (isRelativeFileToken(bare2)) {
6493
6777
  const seg = bare2.split(/[\\/]/);
6494
- return seg[seg.length - 1] ?? null;
6778
+ const base = seg[seg.length - 1] ?? null;
6779
+ if (base?.includes(INJECT_IDENTITY)) return INJECT_IDENTITY;
6780
+ return base;
6495
6781
  }
6496
6782
  }
6783
+ for (const token of raw.split(/\s+/)) {
6784
+ if (stripQuotes(token).bare === INJECT_IDENTITY) return INJECT_IDENTITY;
6785
+ }
6497
6786
  return null;
6498
6787
  }
6499
6788
  function entryCommands(entry) {
@@ -6540,9 +6829,10 @@ function detectCcHookInstalled(settingsRaw, ev, raw, matcher, deps) {
6540
6829
  const matching = arr.filter((e) => entryMatchesRegistration(e, raw, resolved, marker));
6541
6830
  return matching.length === 1 && isDesiredHookEntry(matching[0] ?? {}, matcher, resolved);
6542
6831
  }
6543
- var ABSOLUTE_RE;
6832
+ var INJECT_IDENTITY, ABSOLUTE_RE;
6544
6833
  var init_hookEntry = __esm({
6545
6834
  "src/installers/lib/hookEntry.ts"() {
6835
+ INJECT_IDENTITY = "inject-state";
6546
6836
  ABSOLUTE_RE = /^([A-Za-z]:[\\/]|[\\/])/;
6547
6837
  }
6548
6838
  });
@@ -6705,7 +6995,11 @@ var init_ccHookAdd2 = __esm({
6705
6995
  const ev = install.hook_event;
6706
6996
  const matcher = install.hook_matcher;
6707
6997
  const cmd = install.hook_command;
6708
- const cmdDeps = { assetsRoot: getAssetsRoot, exists: existsSync };
6998
+ const cmdDeps = {
6999
+ assetsRoot: getAssetsRoot,
7000
+ exists: existsSync,
7001
+ compiledExecPath: () => isCompiledRuntime() ? process.execPath : null
7002
+ };
6709
7003
  const resolvedCmd = resolveHookCommand(cmd, cmdDeps);
6710
7004
  const marker = hookScriptMarker(cmd);
6711
7005
  const arr = settings.hooks[ev] ?? [];
@@ -9316,6 +9610,287 @@ var init_auto_install = __esm({
9316
9610
  }
9317
9611
  });
9318
9612
 
9613
+ // src/cli/lib/selfUpdateBinary.ts
9614
+ var selfUpdateBinary_exports = {};
9615
+ __export(selfUpdateBinary_exports, {
9616
+ RELEASES_LATEST_URL: () => RELEASES_LATEST_URL,
9617
+ assetNameFor: () => assetNameFor,
9618
+ execDirWritable: () => execDirWritable,
9619
+ realSelfUpdateDeps: () => realSelfUpdateDeps,
9620
+ resolveLatestRelease: () => resolveLatestRelease,
9621
+ runBinarySelfUpdate: () => runBinarySelfUpdate
9622
+ });
9623
+ function assetNameFor(platform, arch) {
9624
+ const plat = { win32: "windows", darwin: "darwin", linux: "linux" }[platform] ?? platform;
9625
+ const ext = platform === "win32" ? ".exe" : "";
9626
+ return `harnessed-${plat}-${arch}${ext}`;
9627
+ }
9628
+ function normalized(p7) {
9629
+ return p7.replace(/\\/g, "/");
9630
+ }
9631
+ async function sha256File(p7) {
9632
+ const buf = await readFile(p7);
9633
+ return createHash("sha256").update(buf).digest("hex");
9634
+ }
9635
+ function parseShaText(text) {
9636
+ const m = /^([0-9a-fA-F]{64})\b/.exec(text.trim());
9637
+ return m?.[1]?.toLowerCase() ?? null;
9638
+ }
9639
+ async function runBinarySelfUpdate(deps, opts) {
9640
+ const rename5 = deps.fsOps?.rename ?? rename;
9641
+ const copyFile$1 = deps.fsOps?.copyFile ?? copyFile;
9642
+ const unlink2 = deps.fsOps?.unlink ?? unlink;
9643
+ if (normalized(deps.execPath).includes("/node_modules/")) {
9644
+ return { status: "refused", reason: "binary lives under node_modules (npm-managed)" };
9645
+ }
9646
+ const asset = assetNameFor(deps.platform, deps.arch);
9647
+ const execDir = dirname(deps.execPath);
9648
+ const execBase = basename(deps.execPath);
9649
+ const ext = deps.platform === "win32" ? ".exe" : "";
9650
+ const tempPath = join(execDir, `.harnessed-update-${deps.pid}${ext}`);
9651
+ const bakPath = join(execDir, `${execBase}.bak-${deps.currentVersion}`);
9652
+ let targetVersion = null;
9653
+ let assetUrl = null;
9654
+ let shaUrl = null;
9655
+ let sourceAsset = null;
9656
+ let sourceSha = null;
9657
+ if (deps.sourceDir) {
9658
+ sourceAsset = join(deps.sourceDir, asset);
9659
+ sourceSha = join(deps.sourceDir, `${asset}.sha256`);
9660
+ } else {
9661
+ const rel = await deps.resolveRelease();
9662
+ if (rel === null) {
9663
+ return {
9664
+ status: "error",
9665
+ message: "could not reach GitHub releases to resolve the latest binary \u2014 check the network or use the npm channel (`npm i -g harnessed@latest`)"
9666
+ };
9667
+ }
9668
+ if ("error" in rel) {
9669
+ return {
9670
+ status: "error",
9671
+ message: `${rel.error} \u2014 the release may still be publishing (retry in a few minutes) or use the npm channel (\`npm i -g harnessed@latest\`)`
9672
+ };
9673
+ }
9674
+ targetVersion = rel.version;
9675
+ assetUrl = rel.assetUrl;
9676
+ shaUrl = rel.shaUrl;
9677
+ if (opts.check) {
9678
+ return {
9679
+ status: "checked",
9680
+ installed: deps.currentVersion,
9681
+ latest: rel.version,
9682
+ cmp: compareVersions(deps.currentVersion, rel.version)
9683
+ };
9684
+ }
9685
+ const cmp = compareVersions(deps.currentVersion, rel.version);
9686
+ if (cmp !== "behind") {
9687
+ return { status: "current", version: deps.currentVersion };
9688
+ }
9689
+ }
9690
+ if (opts.dryRun) {
9691
+ const backupDir2 = "bin-backup/<oldver>/ under the harnessed state root";
9692
+ const steps = [
9693
+ deps.sourceDir ? `copy ${sourceAsset} \u2192 ${tempPath} (local source dir \u2014 rehearsal seam)` : `download ${assetUrl ?? `latest ${asset}`} \u2192 ${tempPath}`,
9694
+ `verify sha256 against ${deps.sourceDir ? sourceSha : shaUrl ?? `${asset}.sha256`}`,
9695
+ ...deps.platform === "win32" ? [] : ["chmod 755 the downloaded binary"],
9696
+ "smoke: spawn `--version` on the new binary",
9697
+ `rename ${deps.execPath} \u2192 ${bakPath} (same-dir, same-volume)`,
9698
+ `rename ${tempPath} \u2192 ${deps.execPath}`,
9699
+ `copy the .bak to ${backupDir2} (rollback net)`,
9700
+ "delete the .bak (fail-soft \u2014 kept on Windows EPERM or when the backup copy failed)"
9701
+ ];
9702
+ return { status: "dry-run", steps };
9703
+ }
9704
+ try {
9705
+ if (deps.sourceDir && sourceAsset) {
9706
+ await copyFile(sourceAsset, tempPath);
9707
+ } else if (assetUrl) {
9708
+ await deps.downloadTo(assetUrl, tempPath);
9709
+ }
9710
+ } catch (e) {
9711
+ await unlink2(tempPath).catch(() => {
9712
+ });
9713
+ return { status: "error", message: `download failed: ${e.message}` };
9714
+ }
9715
+ try {
9716
+ const shaText = deps.sourceDir ? await readFile(sourceSha ?? "", "utf8") : await deps.fetchShaText(shaUrl ?? "");
9717
+ const expected = parseShaText(shaText);
9718
+ if (!expected) throw new Error(`malformed .sha256 content`);
9719
+ const actual = await sha256File(tempPath);
9720
+ if (actual !== expected) {
9721
+ throw new Error(
9722
+ `sha256 mismatch \u2014 expected ${expected.slice(0, 12)}\u2026, got ${actual.slice(0, 12)}\u2026`
9723
+ );
9724
+ }
9725
+ } catch (e) {
9726
+ await unlink2(tempPath).catch(() => {
9727
+ });
9728
+ return {
9729
+ status: "error",
9730
+ message: `integrity verification failed: ${e.message} \u2014 aborted; original binary untouched`
9731
+ };
9732
+ }
9733
+ try {
9734
+ if (deps.platform !== "win32") await chmod(tempPath, 493);
9735
+ const out = (await deps.smoke(tempPath)).trim();
9736
+ const m = /^(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/.exec(out);
9737
+ if (!m) throw new Error(`--version smoke returned unexpected output: ${out.slice(0, 80)}`);
9738
+ targetVersion = targetVersion ?? m[1] ?? null;
9739
+ } catch (e) {
9740
+ await unlink2(tempPath).catch(() => {
9741
+ });
9742
+ return {
9743
+ status: "error",
9744
+ message: `new binary failed the --version smoke: ${e.message} \u2014 aborted; original binary untouched`
9745
+ };
9746
+ }
9747
+ try {
9748
+ await rename5(deps.execPath, bakPath);
9749
+ } catch (e) {
9750
+ await unlink2(tempPath).catch(() => {
9751
+ });
9752
+ return {
9753
+ status: "error",
9754
+ message: `could not move the current binary aside: ${e.message} \u2014 original untouched`
9755
+ };
9756
+ }
9757
+ try {
9758
+ await rename5(tempPath, deps.execPath);
9759
+ } catch (e) {
9760
+ try {
9761
+ await rename5(bakPath, deps.execPath);
9762
+ return {
9763
+ status: "error",
9764
+ message: `swap failed (${e.message}) \u2014 rolled back to the previous binary`
9765
+ };
9766
+ } catch (rb) {
9767
+ return {
9768
+ status: "error",
9769
+ message: `CRITICAL: swap failed AND rollback failed (${rb.message}). Restore manually: copy "${bakPath}" "${deps.execPath}"`
9770
+ };
9771
+ }
9772
+ }
9773
+ let backupDir = null;
9774
+ let copied = false;
9775
+ try {
9776
+ const dir = join(deps.stateRoot(), "bin-backup", deps.currentVersion);
9777
+ await mkdir(dir, { recursive: true });
9778
+ await copyFile$1(bakPath, join(dir, execBase));
9779
+ backupDir = dir;
9780
+ copied = true;
9781
+ } catch (e) {
9782
+ deps.log(
9783
+ `warning: could not copy the previous binary to bin-backup (${e.message}) \u2014 keeping ${bakPath} as the rollback net`
9784
+ );
9785
+ }
9786
+ let bakRemoved = false;
9787
+ if (copied) {
9788
+ try {
9789
+ await unlink2(bakPath);
9790
+ bakRemoved = true;
9791
+ } catch {
9792
+ }
9793
+ }
9794
+ return {
9795
+ status: "updated",
9796
+ from: deps.currentVersion,
9797
+ to: targetVersion ?? "(unknown)",
9798
+ bakPath,
9799
+ bakRemoved,
9800
+ backupDir
9801
+ };
9802
+ }
9803
+ async function fetchWithTimeout(url, timeoutMs) {
9804
+ const ac = new AbortController();
9805
+ const timer = setTimeout(() => ac.abort(), timeoutMs);
9806
+ try {
9807
+ return await fetch(url, {
9808
+ signal: ac.signal,
9809
+ headers: { "user-agent": `harnessed/${package_default.version}` }
9810
+ });
9811
+ } finally {
9812
+ clearTimeout(timer);
9813
+ }
9814
+ }
9815
+ async function resolveLatestRelease(platform = process.platform, arch = process.arch) {
9816
+ try {
9817
+ const res = await fetchWithTimeout(RELEASES_LATEST_URL, 1e4);
9818
+ if (!res.ok) return null;
9819
+ const body = await res.json();
9820
+ const version = (body.tag_name ?? "").replace(/^v/, "");
9821
+ if (!/^\d+\.\d+\.\d+/.test(version)) return null;
9822
+ const asset = assetNameFor(platform, arch);
9823
+ const found = body.assets?.find((a) => a.name === asset);
9824
+ const sha = body.assets?.find((a) => a.name === `${asset}.sha256`);
9825
+ if (!found?.browser_download_url) {
9826
+ return { error: `asset ${asset} not found on release v${version}` };
9827
+ }
9828
+ if (!sha?.browser_download_url) {
9829
+ return { error: `asset ${asset}.sha256 not found on release v${version}` };
9830
+ }
9831
+ return { version, assetUrl: found.browser_download_url, shaUrl: sha.browser_download_url };
9832
+ } catch {
9833
+ return null;
9834
+ }
9835
+ }
9836
+ function realSelfUpdateDeps() {
9837
+ return {
9838
+ execPath: process.execPath,
9839
+ platform: process.platform,
9840
+ arch: process.arch,
9841
+ currentVersion: package_default.version,
9842
+ sourceDir: process.env.HARNESSED_UPDATE_SOURCE_DIR?.trim() || null,
9843
+ resolveRelease: () => resolveLatestRelease(),
9844
+ downloadTo: async (url, dest) => {
9845
+ const res = await fetchWithTimeout(url, 12e4);
9846
+ if (!res.ok) throw new Error(`HTTP ${res.status} downloading ${url}`);
9847
+ const buf = Buffer.from(await res.arrayBuffer());
9848
+ await writeFile(dest, buf);
9849
+ },
9850
+ fetchShaText: async (url) => {
9851
+ const res = await fetchWithTimeout(url, 3e4);
9852
+ if (!res.ok) throw new Error(`HTTP ${res.status} fetching ${url}`);
9853
+ return res.text();
9854
+ },
9855
+ smoke: async (bin) => {
9856
+ const { execFile: execFile2 } = await import('child_process');
9857
+ const { promisify: promisify3 } = await import('util');
9858
+ const { stdout: stdout2 } = await promisify3(execFile2)(bin, ["--version"], {
9859
+ timeout: 3e4,
9860
+ windowsHide: true
9861
+ });
9862
+ return stdout2;
9863
+ },
9864
+ // Lazy thunk — detectPlatform() only runs when the compiled path actually
9865
+ // reaches the bin-backup step (assetsRoot.ts:31-33 discipline).
9866
+ stateRoot: () => detectPlatform().stateRoot,
9867
+ log: (l) => console.warn(l),
9868
+ pid: process.pid
9869
+ };
9870
+ }
9871
+ async function execDirWritable(execPath) {
9872
+ try {
9873
+ await access(
9874
+ dirname(execPath),
9875
+ 2
9876
+ /* W_OK */
9877
+ );
9878
+ return true;
9879
+ } catch {
9880
+ return false;
9881
+ }
9882
+ }
9883
+ var OWNER_REPO, RELEASES_LATEST_URL;
9884
+ var init_selfUpdateBinary = __esm({
9885
+ "src/cli/lib/selfUpdateBinary.ts"() {
9886
+ init_package();
9887
+ init_platform();
9888
+ init_version_check();
9889
+ OWNER_REPO = "easyinplay/harnessed";
9890
+ RELEASES_LATEST_URL = `https://api.github.com/repos/${OWNER_REPO}/releases/latest`;
9891
+ }
9892
+ });
9893
+
9319
9894
  // src/cli/lib/migration-report.ts
9320
9895
  var migration_report_exports = {};
9321
9896
  __export(migration_report_exports, {
@@ -10237,93 +10812,19 @@ function fireEntry(clause, master) {
10237
10812
  return entry;
10238
10813
  }
10239
10814
 
10240
- // src/cli/gc.ts
10241
- init_i18n();
10242
- init_backup();
10243
- var DURATION_RE = /^(\d+)([dhmw])$/;
10244
- function parseDuration(s) {
10245
- const m = DURATION_RE.exec(s);
10246
- if (!m) return null;
10247
- const n = Number.parseInt(m[1] ?? "0", 10);
10248
- const unit = m[2];
10249
- const ms = unit === "d" ? 864e5 : unit === "h" ? 36e5 : unit === "m" ? 6e4 : 6048e5;
10250
- return n * ms;
10251
- }
10252
- async function dirSizeKb(dir) {
10253
- let total = 0;
10254
- const stack = [dir];
10255
- while (stack.length > 0) {
10256
- const cur = stack.pop();
10257
- if (!cur) break;
10258
- const entries = await readdir(cur, { withFileTypes: true });
10259
- for (const e of entries) {
10260
- const p7 = join(cur, e.name);
10261
- if (e.isDirectory()) stack.push(p7);
10262
- else if (e.isFile()) {
10263
- const st = await stat(p7);
10264
- total += st.size;
10265
- }
10266
- }
10267
- }
10268
- return Math.round(total / 1024);
10269
- }
10270
- function registerGc(program2) {
10271
- program2.command("gc").description(
10272
- "Garbage-collect old backup snapshots (immediate by default \u2014 use --dry-run for preview)"
10273
- ).option("--older-than <duration>", "delete snapshots older than (e.g. 30d / 24h / 4w)", "30d").option("--keep-last <N>", "always keep the most recent N snapshots", "0").option("--dry-run", "preview only \u2014 do not delete (opt-in for advanced users)").action(async (opts) => {
10274
- const dryRun = opts.dryRun === true;
10275
- const olderMs = parseDuration(opts.olderThan ?? "30d");
10276
- if (olderMs == null) {
10277
- console.error(
10278
- `${t("gc.invalid_duration", { value: opts.olderThan ?? "" })}
10279
- ${t("gc.invalid_duration.fix")}`
10280
- );
10281
- process.exit(1);
10282
- return;
10283
- }
10284
- const keepLast = Number.parseInt(opts.keepLast ?? "0", 10);
10285
- const root = getBackupRoot();
10286
- let dirs;
10815
+ // src/cli.ts
10816
+ init_gc();
10817
+
10818
+ // src/cli/injectStateCmd.ts
10819
+ init_assetsRoot();
10820
+ function registerInjectState(program2) {
10821
+ program2.command("inject-state").description("(internal) per-turn <workflow-state> hook output \u2014 used by the perturn hook").action(async () => {
10287
10822
  try {
10288
- dirs = (await readdir(root, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name).sort();
10823
+ const mjs = join(getAssetsRoot(), "bin", "harnessed-inject-state.mjs");
10824
+ if (!existsSync(mjs)) return;
10825
+ await import(pathToFileURL(mjs).href);
10289
10826
  } catch {
10290
- console.log(t("gc.no_backups", { root }));
10291
- return;
10292
- }
10293
- const cutoff = Date.now() - olderMs;
10294
- const kept = new Set(keepLast > 0 ? dirs.slice(-keepLast) : []);
10295
- const candidates = [];
10296
- for (const ts of dirs) {
10297
- if (kept.has(ts)) continue;
10298
- const path = join(root, ts);
10299
- const iso = ts.replace(/T(\d{2})-(\d{2})-(\d{2})/, "T$1:$2:$3");
10300
- const t2 = Date.parse(iso);
10301
- if (Number.isNaN(t2) || t2 > cutoff) continue;
10302
- let manifest = "(unknown)";
10303
- try {
10304
- const meta = JSON.parse(
10305
- await readFile(join(path, "metadata.json"), "utf8")
10306
- );
10307
- manifest = meta.manifest;
10308
- } catch {
10309
- }
10310
- const sizeKb = await dirSizeKb(path);
10311
- candidates.push({ ts, path, manifest, sizeKb });
10312
10827
  }
10313
- if (candidates.length === 0) {
10314
- console.log(
10315
- t("gc.no_old_snapshots", { cutoff: opts.olderThan ?? "", keptCount: kept.size })
10316
- );
10317
- return;
10318
- }
10319
- const totalKb = candidates.reduce((a, c) => a + c.sizeKb, 0);
10320
- const key = dryRun ? "gc.summary_will_delete" : "gc.summary_deleting";
10321
- console.log(t(key, { count: candidates.length, sizeKb: totalKb }));
10322
- for (const c of candidates) {
10323
- console.log(` ${c.ts} ${c.manifest} (${c.sizeKb} KB)`);
10324
- if (!dryRun) await rm(c.path, { recursive: true, force: true });
10325
- }
10326
- if (dryRun) console.log(t("gc.dry_run_rerun_hint"));
10327
10828
  });
10328
10829
  }
10329
10830
 
@@ -10544,6 +11045,12 @@ function registerStatus(program2) {
10544
11045
  for (const l of lines) console.log(l);
10545
11046
  return;
10546
11047
  }
11048
+ try {
11049
+ const { checkUpdate: checkUpdate2 } = await Promise.resolve().then(() => (init_check_update(), check_update_exports));
11050
+ const upd = await checkUpdate2();
11051
+ if (upd.status === "warn") console.log(`\u26A0 ${upd.message} \u2014 ${upd.fix ?? ""}`);
11052
+ } catch {
11053
+ }
10547
11054
  const state = await readState(process.cwd());
10548
11055
  const names = Object.keys(state.installed).sort();
10549
11056
  if (names.length === 0) {
@@ -10651,14 +11158,14 @@ var QA = [
10651
11158
  { q: "\u2463 \u662F import \u6982\u5FF5 (\u53EF\u63A7) \u8FD8\u662F import \u522B\u4EBA\u4EA7\u54C1\u8EAB\u4EFD (\u9AD8\u8026\u5408)?", f: "q4_concept_vs_identity" },
10652
11159
  { q: "\u2464 user \u4E0D\u77E5 upstream \u8FD8\u80FD\u7406\u89E3\u8BE5\u88C5\u914D\u5417?", f: "q5_user_understanding" }
10653
11160
  ];
10654
- function basename(upstream) {
11161
+ function basename2(upstream) {
10655
11162
  return (upstream.split("/").pop() ?? upstream).replace(/\.git$/, "");
10656
11163
  }
10657
11164
  function registerManifestAdd(program2) {
10658
11165
  program2.command("manifest-add <upstream>").description(
10659
11166
  "Add a new upstream adapter (EE-5 5-question merge gate; immediate by default \u2014 use --dry-run for preview)"
10660
11167
  ).option("--category <cat>", "manifest category (skill-packs | tools)", "skill-packs").option("--name <name>", "short adapter name (defaults to <upstream> basename)").option("--dry-run", "preview only \u2014 do not write JSON (opt-in for advanced users)").option("--non-interactive", "CI/scripts \u2014 WARN-only dry-run").action(async (upstream, raw) => {
10661
- const name = raw.name ?? basename(upstream);
11168
+ const name = raw.name ?? basename2(upstream);
10662
11169
  const category = raw.category ?? "skill-packs";
10663
11170
  const outPath = `manifests/${category}/${name}.ee5-answers.json`;
10664
11171
  if (raw.nonInteractive) {
@@ -11584,8 +12091,9 @@ async function makeIdempotentProbe(manifestPaths) {
11584
12091
 
11585
12092
  // src/cli/lib/version-banner.ts
11586
12093
  init_package();
12094
+ init_assetsRoot();
11587
12095
  init_version_check();
11588
- function versionBannerLines(installed, latest) {
12096
+ function versionBannerLines(installed, latest, updateHint = "npm install -g harnessed@latest") {
11589
12097
  const lines = [`harnessed setup v${installed}`];
11590
12098
  if (latest === null) {
11591
12099
  lines.push(" could not check latest version");
@@ -11593,7 +12101,7 @@ function versionBannerLines(installed, latest) {
11593
12101
  }
11594
12102
  const cmp = compareVersions(installed, latest);
11595
12103
  if (cmp === "behind") {
11596
- lines.push(`\u26A0 update available: ${installed} \u2192 ${latest} \u2014 npm install -g harnessed@latest`);
12104
+ lines.push(`\u26A0 update available: ${installed} \u2192 ${latest} \u2014 ${updateHint}`);
11597
12105
  } else if (cmp === "current") {
11598
12106
  lines.push(`\u2713 latest (v${latest})`);
11599
12107
  } else if (cmp === "ahead") {
@@ -11609,8 +12117,10 @@ var BANNER_ART = [
11609
12117
  ];
11610
12118
  async function printSetupVersionBanner() {
11611
12119
  for (const line of BANNER_ART) console.log(line);
11612
- const latest = await fetchLatestVersion();
11613
- for (const line of versionBannerLines(package_default.version, latest)) console.log(line);
12120
+ const { resolveLatestCachedDefault: resolveLatestCachedDefault2 } = await Promise.resolve().then(() => (init_update_check_cache(), update_check_cache_exports));
12121
+ const latest = await resolveLatestCachedDefault2();
12122
+ const hint = isCompiledRuntime() ? "harnessed update" : void 0;
12123
+ for (const line of versionBannerLines(package_default.version, latest, hint)) console.log(line);
11614
12124
  }
11615
12125
 
11616
12126
  // src/cli/setup.ts
@@ -12532,6 +13042,61 @@ ${t("install.manifest_not_found.fix", { name: resolvedName })}`
12532
13042
  init_package();
12533
13043
  init_harnessedRoot();
12534
13044
  init_assetsRoot();
13045
+ async function runCompiledFlow(opts) {
13046
+ const { realSelfUpdateDeps: realSelfUpdateDeps2, runBinarySelfUpdate: runBinarySelfUpdate2 } = await Promise.resolve().then(() => (init_selfUpdateBinary(), selfUpdateBinary_exports));
13047
+ const r = await runBinarySelfUpdate2(realSelfUpdateDeps2(), {
13048
+ dryRun: opts.dryRun === true,
13049
+ check: opts.check === true
13050
+ });
13051
+ switch (r.status) {
13052
+ case "refused":
13053
+ console.warn(`[harnessed] binary self-update refused: ${r.reason} \u2014 using the npm flow`);
13054
+ return false;
13055
+ case "checked":
13056
+ console.log(` installed: ${r.installed}
13057
+ latest: ${r.latest}
13058
+ status: ${r.cmp}`);
13059
+ process.exit(0);
13060
+ return true;
13061
+ case "dry-run":
13062
+ console.log("[harnessed] update --dry-run (compiled binary) \u2014 would run:");
13063
+ for (const s of r.steps) console.log(` - ${s}`);
13064
+ process.exit(0);
13065
+ return true;
13066
+ case "current":
13067
+ console.log(`[harnessed] already up to date (${r.version}).`);
13068
+ process.exit(0);
13069
+ return true;
13070
+ case "updated": {
13071
+ console.log(`[harnessed] updated ${r.from} \u2192 ${r.to}.`);
13072
+ if (r.backupDir) console.log(` previous binary kept at: ${r.backupDir}`);
13073
+ if (!r.bakRemoved)
13074
+ console.log(
13075
+ ` note: ${r.bakPath} left in place (running image / rollback net) \u2014 gc sweeps it later`
13076
+ );
13077
+ try {
13078
+ const { gcCompiledArtifacts: gcCompiledArtifacts2 } = await Promise.resolve().then(() => (init_gc(), gc_exports));
13079
+ const { detectPlatform: detectPlatform2 } = await Promise.resolve().then(() => (init_platform(), platform_exports));
13080
+ await gcCompiledArtifacts2({
13081
+ keepVersions: [r.from, r.to],
13082
+ stateRoot: detectPlatform2().stateRoot,
13083
+ execPath: null
13084
+ // never sweep .bak in the same run that created it
13085
+ });
13086
+ } catch {
13087
+ }
13088
+ console.log(
13089
+ `[harnessed] restart Claude Code so the new version + hooks take effect. Manual rollback if needed: copy the binary back from the bin-backup dir above.`
13090
+ );
13091
+ process.exit(0);
13092
+ return true;
13093
+ }
13094
+ case "error":
13095
+ console.warn(`[harnessed] update failed: ${r.message}`);
13096
+ process.exit(1);
13097
+ return true;
13098
+ }
13099
+ }
12535
13100
  function npmExecutable2() {
12536
13101
  return process.platform === "win32" ? "npm.cmd" : "npm";
12537
13102
  }
@@ -12550,7 +13115,7 @@ function changelogTop() {
12550
13115
  }
12551
13116
  }
12552
13117
  function registerUpdate(program2) {
12553
- program2.command("update").description("Update harnessed to the latest version (and, with --upstreams, the base plugins)").option("--check", "report installed/latest version without installing").option("--upstreams", "re-run the base manifests to upgrade upstream plugins").option("--all", "alias for --upstreams (self + upstreams)").option("--migration-report", "read-only inventory of stale harnessed state (deletes nothing)").action(async (opts) => {
13118
+ program2.command("update").description("Update harnessed to the latest version (and, with --upstreams, the base plugins)").option("--check", "report installed/latest version without installing").option("--upstreams", "re-run the base manifests to upgrade upstream plugins").option("--all", "alias for --upstreams (self + upstreams)").option("--migration-report", "read-only inventory of stale harnessed state (deletes nothing)").option("--dry-run", "preview what the update would do without writing anything").action(async (opts) => {
12554
13119
  if (opts.migrationReport === true) {
12555
13120
  const { collectMigrationReport: collectMigrationReport2 } = await Promise.resolve().then(() => (init_migration_report(), migration_report_exports));
12556
13121
  const items = collectMigrationReport2(process.cwd(), getHarnessedRoot());
@@ -12562,6 +13127,11 @@ function registerUpdate(program2) {
12562
13127
  }
12563
13128
  process.exit(0);
12564
13129
  }
13130
+ const { isCompiledRuntime: isCompiledRuntime2 } = await Promise.resolve().then(() => (init_assetsRoot(), assetsRoot_exports));
13131
+ if (isCompiledRuntime2()) {
13132
+ const handled = await runCompiledFlow(opts);
13133
+ if (handled) return;
13134
+ }
12565
13135
  const { compareVersions: compareVersions2, fetchLatestVersion: fetchLatestVersion2 } = await Promise.resolve().then(() => (init_version_check(), version_check_exports));
12566
13136
  const latest = await fetchLatestVersion2();
12567
13137
  if (!latest) {
@@ -12578,6 +13148,12 @@ function registerUpdate(program2) {
12578
13148
  process.exit(0);
12579
13149
  }
12580
13150
  if (cmp === "behind") {
13151
+ if (opts.dryRun === true) {
13152
+ console.log(
13153
+ `[harnessed] update --dry-run \u2014 would run: npm i -g harnessed@latest (${package_default.version} \u2192 ${latest})`
13154
+ );
13155
+ process.exit(0);
13156
+ }
12581
13157
  console.log(`[harnessed] updating ${package_default.version} \u2192 ${latest} ...`);
12582
13158
  execFileSync(npmExecutable2(), ["i", "-g", "harnessed@latest"], {
12583
13159
  stdio: "inherit",
@@ -12681,6 +13257,7 @@ registerLearn(program);
12681
13257
  registerUpdate(program);
12682
13258
  registerReleasePreflight(program);
12683
13259
  registerRetro(program);
13260
+ registerInjectState(program);
12684
13261
  var bare = parseBareInvocation(process.argv.slice(2));
12685
13262
  if (bare.here) {
12686
13263
  void runHere({ json: bare.json });