harnessed 4.25.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.25.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 {
@@ -448,7 +462,13 @@ var init_currentWorkflow_v1 = __esm({
448
462
  evidence: Type.Optional(Type.Array(EvidenceRef)),
449
463
  // G6 — failure counter; incremented only on each ->failed transition (drives
450
464
  // breakLoop detection). 'rejected' is terminal and does NOT increment it.
451
- fail_count: Type.Optional(Type.Integer({ minimum: 0 }))
465
+ fail_count: Type.Optional(Type.Integer({ minimum: 0 })),
466
+ // 4.26.0 (A3 serial-order guard) — seeding-time serial/parallel semantics
467
+ // carried over from the gates plan (fire[].mode/order). Optional: pre-4.26.0
468
+ // envelopes lack them, and the guard no-ops on entries without `mode`
469
+ // (back-compat fail-soft; comet 0.3.9 phase-skip lesson).
470
+ mode: Type.Optional(Type.Union([Type.Literal("serial"), Type.Literal("parallel")])),
471
+ order: Type.Optional(Type.Integer())
452
472
  },
453
473
  { additionalProperties: false }
454
474
  );
@@ -829,19 +849,25 @@ var init_planningScan = __esm({
829
849
  // src/checkpoint/ledger.ts
830
850
  var ledger_exports = {};
831
851
  __export(ledger_exports, {
852
+ findSerialBlockers: () => findSerialBlockers,
832
853
  markSub: () => markSub,
833
854
  nextPending: () => nextPending,
834
855
  seedLedger: () => seedLedger
835
856
  });
836
857
  function seedLedger(plan) {
837
858
  const fireEntries = plan.fire.map(
838
- (f, i) => ({
839
- // missing order → Infinity so explicitly-ordered subs sort ahead while
840
- // unordered ones retain relative input order (stabilized by idx).
841
- order: f.order ?? Number.POSITIVE_INFINITY,
842
- idx: i,
843
- entry: { sub: f.sub, status: "pending", gate_fired: true }
844
- })
859
+ (f, i) => {
860
+ const entry = { sub: f.sub, status: "pending", gate_fired: true };
861
+ if (f.mode === "serial" || f.mode === "parallel") entry.mode = f.mode;
862
+ if (f.order !== void 0) entry.order = f.order;
863
+ return {
864
+ // missing order → Infinity so explicitly-ordered subs sort ahead while
865
+ // unordered ones retain relative input order (stabilized by idx).
866
+ order: f.order ?? Number.POSITIVE_INFINITY,
867
+ idx: i,
868
+ entry
869
+ };
870
+ }
845
871
  );
846
872
  fireEntries.sort((a, b) => a.order - b.order || a.idx - b.idx);
847
873
  const skipEntries = plan.skip.map(
@@ -873,8 +899,17 @@ function markSub(entries, sub, status, opts) {
873
899
  function nextPending(entries) {
874
900
  return entries.find((e) => e.status === "pending")?.sub ?? null;
875
901
  }
902
+ function findSerialBlockers(entries, sub) {
903
+ const target = entries.find((e) => e.sub === sub);
904
+ if (!target) return [];
905
+ const eff = (e) => e.order ?? PARALLEL_MID_ANCHOR;
906
+ const counts = target.mode === "serial" ? (e) => e.mode === "serial" || e.mode === "parallel" : (e) => e.mode === "serial";
907
+ return entries.filter((e) => e.sub !== sub && e.status === "pending" && counts(e) && eff(e) < eff(target)).map((e) => e.sub);
908
+ }
909
+ var PARALLEL_MID_ANCHOR;
876
910
  var init_ledger = __esm({
877
911
  "src/checkpoint/ledger.ts"() {
912
+ PARALLEL_MID_ANCHOR = 50;
878
913
  }
879
914
  });
880
915
 
@@ -2149,16 +2184,20 @@ __export(assetsRoot_exports, {
2149
2184
  compiledAssetsDir: () => compiledAssetsDir,
2150
2185
  computeAssetsRoot: () => computeAssetsRoot,
2151
2186
  getAssetsRoot: () => getAssetsRoot,
2152
- isCompiledModuleUrl: () => isCompiledModuleUrl
2187
+ isCompiledModuleUrl: () => isCompiledModuleUrl,
2188
+ isCompiledRuntime: () => isCompiledRuntime
2153
2189
  });
2190
+ function isCompiledRuntime(url = import.meta.url) {
2191
+ return isCompiledModuleUrl(url);
2192
+ }
2154
2193
  function isCompiledModuleUrl(url) {
2155
2194
  let s = url;
2156
2195
  try {
2157
2196
  s = decodeURIComponent(url);
2158
2197
  } catch {
2159
2198
  }
2160
- const normalized = s.replace(/\\/g, "/").toLowerCase();
2161
- return BUNFS_MARKERS.some((m) => normalized.includes(m));
2199
+ const normalized2 = s.replace(/\\/g, "/").toLowerCase();
2200
+ return BUNFS_MARKERS.some((m) => normalized2.includes(m));
2162
2201
  }
2163
2202
  function computeAssetsRoot(d) {
2164
2203
  const override = d.env.HARNESSED_ASSETS_OVERRIDE;
@@ -3333,25 +3372,25 @@ var init_discipline = __esm({
3333
3372
  );
3334
3373
  }
3335
3374
  });
3336
- async function loadDiscipline(basename2, packageRoot) {
3337
- const cached = _cache.get(basename2);
3375
+ async function loadDiscipline(basename4, packageRoot) {
3376
+ const cached = _cache.get(basename4);
3338
3377
  if (cached) return cached;
3339
- const yamlPath = resolve(packageRoot, "workflows", "disciplines", `${basename2}.yaml`);
3378
+ const yamlPath = resolve(packageRoot, "workflows", "disciplines", `${basename4}.yaml`);
3340
3379
  const raw = await readFile(yamlPath, "utf8");
3341
3380
  const parsedRaw = parse(raw);
3342
3381
  if (!Value.Check(Discipline, parsedRaw)) {
3343
3382
  const errors = [...Value.Errors(Discipline, parsedRaw)].slice(0, 3).map((e) => `${e.path} ${e.message}`).join("; ");
3344
- throw new Error(`Invalid discipline file ${basename2}.yaml: ${errors}`);
3383
+ throw new Error(`Invalid discipline file ${basename4}.yaml: ${errors}`);
3345
3384
  }
3346
3385
  const parsed = parsedRaw;
3347
- _cache.set(basename2, parsed);
3386
+ _cache.set(basename4, parsed);
3348
3387
  return parsed;
3349
3388
  }
3350
3389
  async function loadAllApplied(disciplines_applied, packageRoot) {
3351
3390
  const applied = disciplines_applied && disciplines_applied.length > 0 ? disciplines_applied : DEFAULT_APPLIED;
3352
3391
  const out = /* @__PURE__ */ new Map();
3353
- for (const basename2 of applied) {
3354
- out.set(basename2, await loadDiscipline(basename2, packageRoot));
3392
+ for (const basename4 of applied) {
3393
+ out.set(basename4, await loadDiscipline(basename4, packageRoot));
3355
3394
  }
3356
3395
  return out;
3357
3396
  }
@@ -4101,10 +4140,10 @@ async function runMasterOrchestrator(masterName, context, packageRoot, spawnDriv
4101
4140
  (m) => console.warn(m)
4102
4141
  );
4103
4142
  emitGateTransparency(masterName, master.delegates_to.length, gateEvalled);
4104
- const PARALLEL_MID_ANCHOR = 50;
4143
+ const PARALLEL_MID_ANCHOR2 = 50;
4105
4144
  const firedClauses = gateEvalled.filter((g) => g.passes).map((g) => g.clause);
4106
- const serialLeading = firedClauses.filter((c) => c.mode === "serial" && (c.order ?? 0) < PARALLEL_MID_ANCHOR).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
4107
- const serialTrailing = firedClauses.filter((c) => c.mode === "serial" && (c.order ?? 0) >= PARALLEL_MID_ANCHOR).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
4145
+ const serialLeading = firedClauses.filter((c) => c.mode === "serial" && (c.order ?? 0) < PARALLEL_MID_ANCHOR2).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
4146
+ const serialTrailing = firedClauses.filter((c) => c.mode === "serial" && (c.order ?? 0) >= PARALLEL_MID_ANCHOR2).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
4108
4147
  const parallelClauses = firedClauses.filter((c) => (c.mode ?? "parallel") === "parallel");
4109
4148
  const serialN = serialLeading.length + serialTrailing.length;
4110
4149
  const parallelN = parallelClauses.length;
@@ -6265,13 +6304,110 @@ var init_version_check = __esm({
6265
6304
  }
6266
6305
  });
6267
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
+
6268
6400
  // src/cli/lib/check-update.ts
6269
6401
  var check_update_exports = {};
6270
6402
  __export(check_update_exports, {
6271
6403
  checkUpdate: () => checkUpdate
6272
6404
  });
6273
- async function checkUpdate(installed = package_default.version, fetch = fetchLatestVersion) {
6274
- 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();
6275
6411
  if (!latest) {
6276
6412
  return { name: "update", status: "pass", message: "update check skipped (npm unreachable)" };
6277
6413
  }
@@ -6336,6 +6472,171 @@ var init_doctor_registry = __esm({
6336
6472
  ];
6337
6473
  }
6338
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
+ });
6339
6640
  async function confirmAt(level, ctx) {
6340
6641
  if (level === "L4" && !ctx.opts.system) {
6341
6642
  if (!ctx.opts.nonInteractive) {
@@ -6453,6 +6754,10 @@ function stripQuotes(token) {
6453
6754
  return { bare: token, quoted: false };
6454
6755
  }
6455
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
+ }
6456
6761
  let root = null;
6457
6762
  const tokens = raw.split(/\s+/).filter((t2) => t2.length > 0);
6458
6763
  const out = tokens.map((token) => {
@@ -6470,9 +6775,14 @@ function hookScriptMarker(raw) {
6470
6775
  const { bare: bare2 } = stripQuotes(token);
6471
6776
  if (isRelativeFileToken(bare2)) {
6472
6777
  const seg = bare2.split(/[\\/]/);
6473
- 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;
6474
6781
  }
6475
6782
  }
6783
+ for (const token of raw.split(/\s+/)) {
6784
+ if (stripQuotes(token).bare === INJECT_IDENTITY) return INJECT_IDENTITY;
6785
+ }
6476
6786
  return null;
6477
6787
  }
6478
6788
  function entryCommands(entry) {
@@ -6519,9 +6829,10 @@ function detectCcHookInstalled(settingsRaw, ev, raw, matcher, deps) {
6519
6829
  const matching = arr.filter((e) => entryMatchesRegistration(e, raw, resolved, marker));
6520
6830
  return matching.length === 1 && isDesiredHookEntry(matching[0] ?? {}, matcher, resolved);
6521
6831
  }
6522
- var ABSOLUTE_RE;
6832
+ var INJECT_IDENTITY, ABSOLUTE_RE;
6523
6833
  var init_hookEntry = __esm({
6524
6834
  "src/installers/lib/hookEntry.ts"() {
6835
+ INJECT_IDENTITY = "inject-state";
6525
6836
  ABSOLUTE_RE = /^([A-Za-z]:[\\/]|[\\/])/;
6526
6837
  }
6527
6838
  });
@@ -6684,7 +6995,11 @@ var init_ccHookAdd2 = __esm({
6684
6995
  const ev = install.hook_event;
6685
6996
  const matcher = install.hook_matcher;
6686
6997
  const cmd = install.hook_command;
6687
- const cmdDeps = { assetsRoot: getAssetsRoot, exists: existsSync };
6998
+ const cmdDeps = {
6999
+ assetsRoot: getAssetsRoot,
7000
+ exists: existsSync,
7001
+ compiledExecPath: () => isCompiledRuntime() ? process.execPath : null
7002
+ };
6688
7003
  const resolvedCmd = resolveHookCommand(cmd, cmdDeps);
6689
7004
  const marker = hookScriptMarker(cmd);
6690
7005
  const arr = settings.hooks[ev] ?? [];
@@ -9295,6 +9610,287 @@ var init_auto_install = __esm({
9295
9610
  }
9296
9611
  });
9297
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
+
9298
9894
  // src/cli/lib/migration-report.ts
9299
9895
  var migration_report_exports = {};
9300
9896
  __export(migration_report_exports, {
@@ -9710,12 +10306,38 @@ async function absorbIntentFor(sub) {
9710
10306
  } catch {
9711
10307
  }
9712
10308
  }
10309
+ async function serialOrderBlockers(sub) {
10310
+ try {
10311
+ const { readCurrentWorkflow: readCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
10312
+ const { findSerialBlockers: findSerialBlockers2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
10313
+ const wf = await readCurrentWorkflow2();
10314
+ return findSerialBlockers2(wf?.sub_progress ?? [], sub);
10315
+ } catch (e) {
10316
+ console.warn(`[harnessed] serial-order guard skipped (fail-soft): ${e.message}`);
10317
+ return [];
10318
+ }
10319
+ }
10320
+ function enforceSerialOrder(action, sub, blockers, force) {
10321
+ if (blockers.length === 0) return true;
10322
+ if (!force) {
10323
+ console.error(
10324
+ `[harnessed] checkpoint ${action} BLOCKED: ${sub} \u2014 ${blockers.length} earlier serial-sequence sub(s) still pending (serial-order guard, fail-closed):`
10325
+ );
10326
+ for (const b of blockers) console.error(` - ${b} (complete or fail it first)`);
10327
+ console.error(" (re-run with --force to jump the sequence deliberately)");
10328
+ return false;
10329
+ }
10330
+ console.warn(
10331
+ `[harnessed] serial-order guard overridden (--force): ${action} ${sub} ahead of pending sub(s) ${blockers.join(", ")}`
10332
+ );
10333
+ return true;
10334
+ }
9713
10335
  function registerCheckpoint(program2) {
9714
10336
  program2.command("checkpoint <action> <sub>").description(
9715
10337
  "Record workflow progress: intent | start | complete | fail <sub-workflow> (writes to ~/.claude/harnessed/checkpoints/)"
9716
10338
  ).option("--summary <text>", "short summary stored as the checkpoint lastTask").option("--plan <json>", "gates plan JSON (start only) \u2014 seeds the sub-progress ledger").option(
9717
10339
  "--force",
9718
- "complete only \u2014 override a missing-artifact evidence block (records overridden)"
10340
+ "complete/fail \u2014 override a fail-closed guard: the missing-artifact evidence block (complete; records overridden) or the serial-order guard"
9719
10341
  ).option(
9720
10342
  "--tokens <n>",
9721
10343
  "complete only \u2014 conversation token count; auto-compacts the ledger when >= the shouldCompact threshold (Phase 14)"
@@ -9835,6 +10457,10 @@ function registerCheckpoint(program2) {
9835
10457
  return;
9836
10458
  }
9837
10459
  if (action === "complete") {
10460
+ if (!enforceSerialOrder("complete", sub, await serialOrderBlockers(sub), opts.force)) {
10461
+ process.exit(1);
10462
+ return;
10463
+ }
9838
10464
  const { checkArtifacts: checkArtifacts2 } = await Promise.resolve().then(() => (init_evidence(), evidence_exports));
9839
10465
  const { mutateSubProgress: mutateSubProgress3 } = await Promise.resolve().then(() => (init_state(), state_exports));
9840
10466
  const { getAssetsRoot: getAssetsRoot2 } = await Promise.resolve().then(() => (init_assetsRoot(), assetsRoot_exports));
@@ -9924,6 +10550,10 @@ function registerCheckpoint(program2) {
9924
10550
  process.exit(0);
9925
10551
  return;
9926
10552
  }
10553
+ if (!enforceSerialOrder("fail", sub, await serialOrderBlockers(sub), opts.force)) {
10554
+ process.exit(1);
10555
+ return;
10556
+ }
9927
10557
  const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
9928
10558
  await mutateSubProgress2((e) => markIfSeeded(e, sub, "failed"));
9929
10559
  await absorbIntentFor(sub);
@@ -10182,93 +10812,19 @@ function fireEntry(clause, master) {
10182
10812
  return entry;
10183
10813
  }
10184
10814
 
10185
- // src/cli/gc.ts
10186
- init_i18n();
10187
- init_backup();
10188
- var DURATION_RE = /^(\d+)([dhmw])$/;
10189
- function parseDuration(s) {
10190
- const m = DURATION_RE.exec(s);
10191
- if (!m) return null;
10192
- const n = Number.parseInt(m[1] ?? "0", 10);
10193
- const unit = m[2];
10194
- const ms = unit === "d" ? 864e5 : unit === "h" ? 36e5 : unit === "m" ? 6e4 : 6048e5;
10195
- return n * ms;
10196
- }
10197
- async function dirSizeKb(dir) {
10198
- let total = 0;
10199
- const stack = [dir];
10200
- while (stack.length > 0) {
10201
- const cur = stack.pop();
10202
- if (!cur) break;
10203
- const entries = await readdir(cur, { withFileTypes: true });
10204
- for (const e of entries) {
10205
- const p7 = join(cur, e.name);
10206
- if (e.isDirectory()) stack.push(p7);
10207
- else if (e.isFile()) {
10208
- const st = await stat(p7);
10209
- total += st.size;
10210
- }
10211
- }
10212
- }
10213
- return Math.round(total / 1024);
10214
- }
10215
- function registerGc(program2) {
10216
- program2.command("gc").description(
10217
- "Garbage-collect old backup snapshots (immediate by default \u2014 use --dry-run for preview)"
10218
- ).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) => {
10219
- const dryRun = opts.dryRun === true;
10220
- const olderMs = parseDuration(opts.olderThan ?? "30d");
10221
- if (olderMs == null) {
10222
- console.error(
10223
- `${t("gc.invalid_duration", { value: opts.olderThan ?? "" })}
10224
- ${t("gc.invalid_duration.fix")}`
10225
- );
10226
- process.exit(1);
10227
- return;
10228
- }
10229
- const keepLast = Number.parseInt(opts.keepLast ?? "0", 10);
10230
- const root = getBackupRoot();
10231
- 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 () => {
10232
10822
  try {
10233
- 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);
10234
10826
  } catch {
10235
- console.log(t("gc.no_backups", { root }));
10236
- return;
10237
10827
  }
10238
- const cutoff = Date.now() - olderMs;
10239
- const kept = new Set(keepLast > 0 ? dirs.slice(-keepLast) : []);
10240
- const candidates = [];
10241
- for (const ts of dirs) {
10242
- if (kept.has(ts)) continue;
10243
- const path = join(root, ts);
10244
- const iso = ts.replace(/T(\d{2})-(\d{2})-(\d{2})/, "T$1:$2:$3");
10245
- const t2 = Date.parse(iso);
10246
- if (Number.isNaN(t2) || t2 > cutoff) continue;
10247
- let manifest = "(unknown)";
10248
- try {
10249
- const meta = JSON.parse(
10250
- await readFile(join(path, "metadata.json"), "utf8")
10251
- );
10252
- manifest = meta.manifest;
10253
- } catch {
10254
- }
10255
- const sizeKb = await dirSizeKb(path);
10256
- candidates.push({ ts, path, manifest, sizeKb });
10257
- }
10258
- if (candidates.length === 0) {
10259
- console.log(
10260
- t("gc.no_old_snapshots", { cutoff: opts.olderThan ?? "", keptCount: kept.size })
10261
- );
10262
- return;
10263
- }
10264
- const totalKb = candidates.reduce((a, c) => a + c.sizeKb, 0);
10265
- const key = dryRun ? "gc.summary_will_delete" : "gc.summary_deleting";
10266
- console.log(t(key, { count: candidates.length, sizeKb: totalKb }));
10267
- for (const c of candidates) {
10268
- console.log(` ${c.ts} ${c.manifest} (${c.sizeKb} KB)`);
10269
- if (!dryRun) await rm(c.path, { recursive: true, force: true });
10270
- }
10271
- if (dryRun) console.log(t("gc.dry_run_rerun_hint"));
10272
10828
  });
10273
10829
  }
10274
10830
 
@@ -10489,6 +11045,12 @@ function registerStatus(program2) {
10489
11045
  for (const l of lines) console.log(l);
10490
11046
  return;
10491
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
+ }
10492
11054
  const state = await readState(process.cwd());
10493
11055
  const names = Object.keys(state.installed).sort();
10494
11056
  if (names.length === 0) {
@@ -10596,14 +11158,14 @@ var QA = [
10596
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" },
10597
11159
  { q: "\u2464 user \u4E0D\u77E5 upstream \u8FD8\u80FD\u7406\u89E3\u8BE5\u88C5\u914D\u5417?", f: "q5_user_understanding" }
10598
11160
  ];
10599
- function basename(upstream) {
11161
+ function basename2(upstream) {
10600
11162
  return (upstream.split("/").pop() ?? upstream).replace(/\.git$/, "");
10601
11163
  }
10602
11164
  function registerManifestAdd(program2) {
10603
11165
  program2.command("manifest-add <upstream>").description(
10604
11166
  "Add a new upstream adapter (EE-5 5-question merge gate; immediate by default \u2014 use --dry-run for preview)"
10605
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) => {
10606
- const name = raw.name ?? basename(upstream);
11168
+ const name = raw.name ?? basename2(upstream);
10607
11169
  const category = raw.category ?? "skill-packs";
10608
11170
  const outPath = `manifests/${category}/${name}.ee5-answers.json`;
10609
11171
  if (raw.nonInteractive) {
@@ -11529,8 +12091,9 @@ async function makeIdempotentProbe(manifestPaths) {
11529
12091
 
11530
12092
  // src/cli/lib/version-banner.ts
11531
12093
  init_package();
12094
+ init_assetsRoot();
11532
12095
  init_version_check();
11533
- function versionBannerLines(installed, latest) {
12096
+ function versionBannerLines(installed, latest, updateHint = "npm install -g harnessed@latest") {
11534
12097
  const lines = [`harnessed setup v${installed}`];
11535
12098
  if (latest === null) {
11536
12099
  lines.push(" could not check latest version");
@@ -11538,7 +12101,7 @@ function versionBannerLines(installed, latest) {
11538
12101
  }
11539
12102
  const cmp = compareVersions(installed, latest);
11540
12103
  if (cmp === "behind") {
11541
- 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}`);
11542
12105
  } else if (cmp === "current") {
11543
12106
  lines.push(`\u2713 latest (v${latest})`);
11544
12107
  } else if (cmp === "ahead") {
@@ -11554,8 +12117,10 @@ var BANNER_ART = [
11554
12117
  ];
11555
12118
  async function printSetupVersionBanner() {
11556
12119
  for (const line of BANNER_ART) console.log(line);
11557
- const latest = await fetchLatestVersion();
11558
- 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);
11559
12124
  }
11560
12125
 
11561
12126
  // src/cli/setup.ts
@@ -12477,6 +13042,61 @@ ${t("install.manifest_not_found.fix", { name: resolvedName })}`
12477
13042
  init_package();
12478
13043
  init_harnessedRoot();
12479
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
+ }
12480
13100
  function npmExecutable2() {
12481
13101
  return process.platform === "win32" ? "npm.cmd" : "npm";
12482
13102
  }
@@ -12495,7 +13115,7 @@ function changelogTop() {
12495
13115
  }
12496
13116
  }
12497
13117
  function registerUpdate(program2) {
12498
- 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) => {
12499
13119
  if (opts.migrationReport === true) {
12500
13120
  const { collectMigrationReport: collectMigrationReport2 } = await Promise.resolve().then(() => (init_migration_report(), migration_report_exports));
12501
13121
  const items = collectMigrationReport2(process.cwd(), getHarnessedRoot());
@@ -12507,6 +13127,11 @@ function registerUpdate(program2) {
12507
13127
  }
12508
13128
  process.exit(0);
12509
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
+ }
12510
13135
  const { compareVersions: compareVersions2, fetchLatestVersion: fetchLatestVersion2 } = await Promise.resolve().then(() => (init_version_check(), version_check_exports));
12511
13136
  const latest = await fetchLatestVersion2();
12512
13137
  if (!latest) {
@@ -12523,6 +13148,12 @@ function registerUpdate(program2) {
12523
13148
  process.exit(0);
12524
13149
  }
12525
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
+ }
12526
13157
  console.log(`[harnessed] updating ${package_default.version} \u2192 ${latest} ...`);
12527
13158
  execFileSync(npmExecutable2(), ["i", "-g", "harnessed@latest"], {
12528
13159
  stdio: "inherit",
@@ -12626,6 +13257,7 @@ registerLearn(program);
12626
13257
  registerUpdate(program);
12627
13258
  registerReleasePreflight(program);
12628
13259
  registerRetro(program);
13260
+ registerInjectState(program);
12629
13261
  var bare = parseBareInvocation(process.argv.slice(2));
12630
13262
  if (bare.here) {
12631
13263
  void runHere({ json: bare.json });