harnessed 5.0.12 → 5.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +27 -1
  2. package/README-zh.md +1 -28
  3. package/README.md +1 -28
  4. package/bin/harnessed-check-docs.mjs +15 -0
  5. package/bin/harnessed-update-reminder-worker.mjs +2819 -151
  6. package/bin/harnessed-update-reminder.mjs +665 -69
  7. package/dist/cli.mjs +1528 -590
  8. package/dist/cli.mjs.map +1 -1
  9. package/dist/index.mjs +1 -1
  10. package/dist/index.mjs.map +1 -1
  11. package/messages/en.json +15 -1
  12. package/messages/zh-Hans.json +15 -1
  13. package/package.json +1 -2
  14. package/workflows/auto/SKILL.md +10 -18
  15. package/workflows/auto/SKILL.zh-Hans.md +8 -18
  16. package/workflows/discuss/auto/SKILL.md +4 -7
  17. package/workflows/discuss/auto/SKILL.zh-Hans.md +2 -7
  18. package/workflows/discuss/phase/SKILL.md +4 -7
  19. package/workflows/discuss/phase/SKILL.zh-Hans.md +2 -7
  20. package/workflows/discuss/strategic/SKILL.md +4 -8
  21. package/workflows/discuss/strategic/SKILL.zh-Hans.md +2 -8
  22. package/workflows/discuss/subtask/SKILL.md +4 -7
  23. package/workflows/discuss/subtask/SKILL.zh-Hans.md +2 -7
  24. package/workflows/harnessed-update/SKILL.md +9 -8
  25. package/workflows/harnessed-update/SKILL.zh-Hans.md +7 -8
  26. package/workflows/host-primitives.yaml +8 -8
  27. package/workflows/host-primitives.zh-Hans.yaml +8 -8
  28. package/workflows/plan/ai-integration/SKILL.md +7 -7
  29. package/workflows/plan/ai-integration/SKILL.zh-Hans.md +7 -7
  30. package/workflows/plan/architecture/SKILL.md +7 -13
  31. package/workflows/plan/architecture/SKILL.zh-Hans.md +7 -13
  32. package/workflows/plan/auto/SKILL.md +8 -14
  33. package/workflows/plan/auto/SKILL.zh-Hans.md +8 -14
  34. package/workflows/plan/phase/SKILL.md +7 -13
  35. package/workflows/plan/phase/SKILL.zh-Hans.md +7 -13
  36. package/workflows/plan/secure/SKILL.md +7 -7
  37. package/workflows/plan/secure/SKILL.zh-Hans.md +7 -7
  38. package/workflows/plan/spec/SKILL.md +7 -7
  39. package/workflows/plan/spec/SKILL.zh-Hans.md +7 -7
  40. package/workflows/plan/ui/SKILL.md +7 -7
  41. package/workflows/plan/ui/SKILL.zh-Hans.md +7 -7
  42. package/workflows/research/SKILL.md +7 -7
  43. package/workflows/research/SKILL.zh-Hans.md +7 -7
  44. package/workflows/retro/SKILL.md +8 -15
  45. package/workflows/retro/SKILL.zh-Hans.md +7 -15
  46. package/workflows/ship/auto/SKILL.md +8 -14
  47. package/workflows/ship/auto/SKILL.zh-Hans.md +8 -14
  48. package/workflows/ship/preflight/SKILL.md +7 -9
  49. package/workflows/ship/preflight/SKILL.zh-Hans.md +7 -9
  50. package/workflows/task/auto/SKILL.md +8 -15
  51. package/workflows/task/auto/SKILL.zh-Hans.md +8 -15
  52. package/workflows/task/clarify/SKILL.md +2 -10
  53. package/workflows/task/clarify/SKILL.zh-Hans.md +2 -10
  54. package/workflows/task/code/SKILL.md +7 -15
  55. package/workflows/task/code/SKILL.zh-Hans.md +7 -15
  56. package/workflows/task/deliver/SKILL.md +7 -17
  57. package/workflows/task/deliver/SKILL.zh-Hans.md +7 -17
  58. package/workflows/task/test/SKILL.md +7 -14
  59. package/workflows/task/test/SKILL.zh-Hans.md +7 -14
  60. package/workflows/verify/auto/SKILL.md +9 -14
  61. package/workflows/verify/auto/SKILL.zh-Hans.md +9 -14
  62. package/workflows/verify/code-review/SKILL.md +8 -13
  63. package/workflows/verify/code-review/SKILL.zh-Hans.md +8 -13
  64. package/workflows/verify/design/SKILL.md +8 -12
  65. package/workflows/verify/design/SKILL.zh-Hans.md +7 -12
  66. package/workflows/verify/eval-review/SKILL.md +8 -12
  67. package/workflows/verify/eval-review/SKILL.zh-Hans.md +7 -12
  68. package/workflows/verify/multispec/SKILL.md +8 -15
  69. package/workflows/verify/multispec/SKILL.zh-Hans.md +7 -15
  70. package/workflows/verify/paranoid/SKILL.md +7 -14
  71. package/workflows/verify/paranoid/SKILL.zh-Hans.md +7 -14
  72. package/workflows/verify/progress/SKILL.md +8 -13
  73. package/workflows/verify/progress/SKILL.zh-Hans.md +8 -13
  74. package/workflows/verify/qa/SKILL.md +7 -13
  75. package/workflows/verify/qa/SKILL.zh-Hans.md +7 -13
  76. package/workflows/verify/second-opinion/SKILL.md +8 -12
  77. package/workflows/verify/second-opinion/SKILL.zh-Hans.md +7 -12
  78. package/workflows/verify/security/SKILL.md +8 -12
  79. package/workflows/verify/security/SKILL.zh-Hans.md +7 -12
  80. package/workflows/verify/simplify/SKILL.md +8 -12
  81. package/workflows/verify/simplify/SKILL.zh-Hans.md +7 -12
  82. package/workflows/verify/validate-phase/SKILL.md +8 -12
  83. package/workflows/verify/validate-phase/SKILL.zh-Hans.md +7 -12
  84. package/README-en.md +0 -659
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync, existsSync, mkdirSync, readdirSync, writeFileSync, appendFileSync, accessSync, constants, statSync, unlinkSync, realpathSync, renameSync, openSync, closeSync, fsyncSync, rmSync, mkdtempSync, lstatSync, readSync, utimesSync, createReadStream, createWriteStream } from 'fs';
2
+ import { readFileSync, existsSync, mkdirSync, readdirSync, writeFileSync, appendFileSync, accessSync, constants, statSync, unlinkSync, realpathSync, renameSync, rmSync, openSync, closeSync, fsyncSync, fstatSync, readSync, mkdtempSync, createWriteStream, lstatSync, utimesSync, createReadStream } from 'fs';
3
3
  import { homedir, tmpdir } from 'os';
4
4
  import { join, dirname, resolve, basename, isAbsolute, relative, sep, win32, posix } from 'path';
5
5
  import { Type } from '@sinclair/typebox';
@@ -12,6 +12,7 @@ import { LineCounter, parseDocument, parse, isSeq, isAlias, isScalar, stringify,
12
12
  import { Ajv } from 'ajv';
13
13
  import * as ajvFormatsNs from 'ajv-formats';
14
14
  import { spawnSync, execFileSync, spawn, execFile, exec } from 'child_process';
15
+ import { Argument, InvalidArgumentError, Option } from 'commander';
15
16
  import { AsyncLocalStorage } from 'async_hooks';
16
17
  import { promisify, isDeepStrictEqual } from 'util';
17
18
  import { Parser } from 'expr-eval';
@@ -24,7 +25,6 @@ import { pipeline } from 'stream/promises';
24
25
  import { stdout, stdin } from 'process';
25
26
  import * as readline from 'readline/promises';
26
27
  import { parse as parse$1 } from 'smol-toml';
27
- import { InvalidArgumentError, Option } from 'commander';
28
28
 
29
29
  var __defProp = Object.defineProperty;
30
30
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -42,7 +42,7 @@ var init_package = __esm({
42
42
  "package.json"() {
43
43
  package_default = {
44
44
  name: "harnessed",
45
- version: "5.0.12",
45
+ version: "5.0.14",
46
46
  description: "AI coding harness package manager + composition orchestrator",
47
47
  type: "module",
48
48
  license: "Apache-2.0",
@@ -95,7 +95,6 @@ var init_package = __esm({
95
95
  "schemas",
96
96
  "CHANGELOG.md",
97
97
  "README.md",
98
- "README-en.md",
99
98
  "README-zh.md",
100
99
  "LICENSE",
101
100
  "NOTICE",
@@ -1739,7 +1738,20 @@ var init_en = __esm({
1739
1738
  "manifest_add.gate_passed_wrote": "[manifest-add] EE-5 gate passed; wrote {{path}}",
1740
1739
  "manifest_add.gate_passed_dry_run": "[manifest-add] EE-5 gate passed (dry-run); would write {{path}}",
1741
1740
  "resume.fail": "\u2717 {{error}}",
1742
- "resume.corrupt": "\u2717 {{error}}\n path: {{path}}"
1741
+ "resume.corrupt": "\u2717 {{error}}\n path: {{path}}",
1742
+ "auto_update.consent_on": "[harnessed] auto-update ON",
1743
+ "auto_update.consent_off": "[harnessed] auto-update OFF",
1744
+ "auto_update.preferences_replaced": "[harnessed] the preferences file was unreadable (invalid JSON) \u2014 it has been replaced.",
1745
+ "auto_update.reminder_off_note": `[harnessed] the update reminder is OFF \u2014 the "new version available" notice will not be printed. Use 'harnessed auto-update status' to check on it.`,
1746
+ "auto_update.path.host": " host: {{host}}",
1747
+ "auto_update.path.preferences": " preferences: {{path}}",
1748
+ "auto_update.path.status": " status: {{path}}",
1749
+ "auto_update.error.unsupported_host": "unsupported host: {{host}} (expected claude or codex)",
1750
+ "auto_update.error.runtime": "could not resolve the {{host}} update-reminder runtime",
1751
+ "auto_update.notice.updated_from": "harnessed updated {{from}} -> {{to}}.",
1752
+ "auto_update.notice.updated_to": "harnessed updated to {{to}}.",
1753
+ "auto_update.notice.restart": "Restart {{host}} so the new version + hooks take effect.",
1754
+ "auto_update.notice.codex_trust": "Codex hooks still need your trust confirmed \u2014 approve the harness hook registration in Codex (or run 'harnessed setup' there)."
1743
1755
  };
1744
1756
  }
1745
1757
  });
@@ -3448,7 +3460,7 @@ function renderHumanTable(records) {
3448
3460
  }
3449
3461
  }
3450
3462
  function pipeToJq(filterExpr, lines) {
3451
- return new Promise((resolve40, reject) => {
3463
+ return new Promise((resolve42, reject) => {
3452
3464
  const child = spawn("jq", [filterExpr], {
3453
3465
  stdio: ["pipe", "inherit", "inherit"],
3454
3466
  windowsHide: true
@@ -3457,12 +3469,12 @@ function pipeToJq(filterExpr, lines) {
3457
3469
  const e = err2;
3458
3470
  if (e.code === "ENOENT") {
3459
3471
  console.error(t("audit_log.jq_missing"));
3460
- resolve40(1);
3472
+ resolve42(1);
3461
3473
  } else {
3462
3474
  reject(err2);
3463
3475
  }
3464
3476
  });
3465
- child.on("close", (code2) => resolve40(code2 ?? 0));
3477
+ child.on("close", (code2) => resolve42(code2 ?? 0));
3466
3478
  child.stdin.on("error", (err2) => {
3467
3479
  if (err2.code !== "EPIPE") reject(err2);
3468
3480
  });
@@ -3540,6 +3552,550 @@ var init_audit_log = __esm({
3540
3552
  ];
3541
3553
  }
3542
3554
  });
3555
+ function autoUpdateStatusPath(stateRoot) {
3556
+ return join(stateRoot, AUTO_UPDATE_STATUS_FILE);
3557
+ }
3558
+ function isFiniteNumber(value) {
3559
+ return typeof value === "number" && Number.isFinite(value);
3560
+ }
3561
+ function isPlainObject(value) {
3562
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3563
+ }
3564
+ function isValidDateMs(value) {
3565
+ return isFiniteNumber(value) && !Number.isNaN(new Date(value).getTime());
3566
+ }
3567
+ function parseProgress(value) {
3568
+ if (!isPlainObject(value)) return null;
3569
+ const { received, total, updatedAt } = value;
3570
+ if (!isFiniteNumber(received) || received < 0) return null;
3571
+ if (!isFiniteNumber(total) || total < 0) return null;
3572
+ if (!isValidDateMs(updatedAt)) return null;
3573
+ return { received, total, updatedAt };
3574
+ }
3575
+ function parseResult(value) {
3576
+ if (!isPlainObject(value)) return null;
3577
+ const { version, status, reason, message, at } = value;
3578
+ if (typeof version !== "string") return null;
3579
+ if (typeof status !== "string" || !RESULT_STATUSES.includes(status))
3580
+ return null;
3581
+ if (reason !== void 0 && typeof reason !== "string") return null;
3582
+ if (message !== void 0 && typeof message !== "string") return null;
3583
+ if (!isValidDateMs(at)) return null;
3584
+ const result = { version, status, at };
3585
+ if (typeof reason === "string") result.reason = reason;
3586
+ if (typeof message === "string") result.message = message;
3587
+ return result;
3588
+ }
3589
+ function parseNotice(value) {
3590
+ if (!isPlainObject(value)) return null;
3591
+ const { from, to, changelog, restart, at } = value;
3592
+ if (typeof from !== "string" || typeof to !== "string") return null;
3593
+ if (typeof changelog !== "string" || typeof restart !== "string") return null;
3594
+ if (!isValidDateMs(at)) return null;
3595
+ const consumedAt = typeof value.consumedAt === "number" && Number.isFinite(value.consumedAt) && value.consumedAt >= 0 ? value.consumedAt : 0;
3596
+ return { from, to, changelog, restart, at, consumedAt };
3597
+ }
3598
+ function parseStatus(value) {
3599
+ if (!isPlainObject(value)) return null;
3600
+ if (value.schemaVersion !== 1) return null;
3601
+ const consent = value.consent;
3602
+ if (!isPlainObject(consent)) return null;
3603
+ if (typeof consent.autoUpdate !== "boolean" || typeof consent.enabled !== "boolean") return null;
3604
+ if (typeof value.channel !== "string" || !CHANNELS.includes(value.channel))
3605
+ return null;
3606
+ if (typeof value.installed !== "string") return null;
3607
+ if (value.latest !== null && typeof value.latest !== "string") return null;
3608
+ if (typeof value.state !== "string" || !AUTO_UPDATE_STATES.includes(value.state))
3609
+ return null;
3610
+ const progress = parseProgress(value.progress);
3611
+ if (!progress) return null;
3612
+ const lastResult = value.lastResult === null ? null : parseResult(value.lastResult);
3613
+ if (value.lastResult !== null && !lastResult) return null;
3614
+ if (!Array.isArray(value.history)) return null;
3615
+ const history = [];
3616
+ for (const entry of value.history) {
3617
+ const parsed = parseResult(entry);
3618
+ if (!parsed) return null;
3619
+ history.push(parsed);
3620
+ }
3621
+ const notice = value.notice === null ? null : parseNotice(value.notice);
3622
+ if (value.notice !== null && !notice) return null;
3623
+ return {
3624
+ schemaVersion: 1,
3625
+ consent: { autoUpdate: consent.autoUpdate, enabled: consent.enabled },
3626
+ channel: value.channel,
3627
+ installed: value.installed,
3628
+ latest: value.latest,
3629
+ state: value.state,
3630
+ progress,
3631
+ lastResult,
3632
+ history,
3633
+ notice
3634
+ };
3635
+ }
3636
+ function readAutoUpdateStatus(path) {
3637
+ let text;
3638
+ try {
3639
+ text = readFileSync(path, "utf8");
3640
+ } catch {
3641
+ return null;
3642
+ }
3643
+ let parsed;
3644
+ try {
3645
+ parsed = JSON.parse(text);
3646
+ } catch {
3647
+ return null;
3648
+ }
3649
+ return parseStatus(parsed);
3650
+ }
3651
+ function writeAutoUpdateStatus(path, status) {
3652
+ const dir = dirname(path);
3653
+ mkdirSync(dir, { recursive: true });
3654
+ const tmp = `${path}.${process.pid}.${++tmpCounter}.tmp`;
3655
+ try {
3656
+ writeFileSync(tmp, `${JSON.stringify(status, null, 2)}
3657
+ `, "utf8");
3658
+ renameSync(tmp, path);
3659
+ } catch (error) {
3660
+ try {
3661
+ rmSync(tmp, { force: true });
3662
+ } catch {
3663
+ }
3664
+ throw error;
3665
+ }
3666
+ }
3667
+ function formatMegabytes(bytes) {
3668
+ return (bytes / 1024 / 1024).toFixed(1);
3669
+ }
3670
+ function formatTimestamp(at) {
3671
+ return new Date(at).toISOString().replace(/\.000Z$/, "Z");
3672
+ }
3673
+ function formatAutoUpdateStatus(status, now) {
3674
+ if (!status) {
3675
+ return ["auto-update: off", "installed: unknown latest: unknown state: idle"].join("\n");
3676
+ }
3677
+ const lines = [`auto-update: ${status.consent.autoUpdate ? "on" : "off"}`];
3678
+ const latest = status.latest ?? "unknown";
3679
+ let second = `installed: ${status.installed} latest: ${latest} state: ${status.state}`;
3680
+ if (status.progress.total > 0) {
3681
+ second += ` (${formatMegabytes(status.progress.received)} MB / ${formatMegabytes(status.progress.total)} MB)`;
3682
+ }
3683
+ lines.push(second);
3684
+ if (status.lastResult) {
3685
+ const { status: resultStatus, version, reason, at } = status.lastResult;
3686
+ const stamp = Number.isNaN(new Date(at).getTime()) ? now : at;
3687
+ const reasonText = reason ? REASON_TEXT[reason] ?? reason : "ok";
3688
+ lines.push(`last: ${resultStatus} ${version} (${reasonText}) at ${formatTimestamp(stamp)}`);
3689
+ }
3690
+ return lines.join("\n");
3691
+ }
3692
+ var AUTO_UPDATE_STATUS_FILE, AUTO_UPDATE_STATUS_PATH_ENV, AUTO_UPDATE_STATES, CHANNELS, RESULT_STATUSES, tmpCounter, REASON_TEXT;
3693
+ var init_autoUpdateStatus = __esm({
3694
+ "src/cli/lib/autoUpdateStatus.ts"() {
3695
+ AUTO_UPDATE_STATUS_FILE = "auto-update-status.json";
3696
+ AUTO_UPDATE_STATUS_PATH_ENV = "HARNESSED_AUTO_UPDATE_STATUS_PATH";
3697
+ AUTO_UPDATE_STATES = [
3698
+ "idle",
3699
+ "downloading",
3700
+ "verifying",
3701
+ "swapping",
3702
+ "handover",
3703
+ "updated",
3704
+ "failed",
3705
+ "skipped"
3706
+ ];
3707
+ CHANNELS = ["binary", "npm", "bun", "node"];
3708
+ RESULT_STATUSES = ["updated", "failed", "skipped"];
3709
+ tmpCounter = 0;
3710
+ REASON_TEXT = {
3711
+ "npm-channel": "npm channel \u2014 auto-update needs the binary channel"
3712
+ };
3713
+ }
3714
+ });
3715
+ function readRaw(path) {
3716
+ let descriptor;
3717
+ try {
3718
+ descriptor = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
3719
+ const info = fstatSync(descriptor);
3720
+ if (!info.isFile() || info.size > MAX_PREFERENCES_BYTES) return { kind: "unreadable" };
3721
+ const buffer = Buffer.alloc(info.size);
3722
+ const bytes = readSync(descriptor, buffer, 0, buffer.length, 0);
3723
+ return { kind: "parsed", value: JSON.parse(buffer.toString("utf8", 0, bytes)) };
3724
+ } catch (error) {
3725
+ if (error.code === "ENOENT") return { kind: "missing" };
3726
+ return { kind: "unreadable" };
3727
+ } finally {
3728
+ if (descriptor !== void 0) {
3729
+ try {
3730
+ closeSync(descriptor);
3731
+ } catch {
3732
+ }
3733
+ }
3734
+ }
3735
+ }
3736
+ function readUpdateReminderPreferencesFile(path) {
3737
+ const raw = readRaw(path);
3738
+ if (raw.kind === "missing") {
3739
+ return {
3740
+ preferences: { enabled: true, autoUpdate: false, unreadable: false },
3741
+ missing: true,
3742
+ document: null
3743
+ };
3744
+ }
3745
+ if (raw.kind === "unreadable") {
3746
+ return {
3747
+ preferences: { enabled: false, autoUpdate: false, unreadable: true },
3748
+ missing: false,
3749
+ document: null
3750
+ };
3751
+ }
3752
+ const value = raw.value;
3753
+ const record = typeof value === "object" && value !== null ? value : {};
3754
+ return {
3755
+ preferences: {
3756
+ enabled: record.enabled === true,
3757
+ // `autoUpdate` is INDEPENDENT of `enabled` — two separate consents.
3758
+ // Only a strict `true` counts; anything else is off.
3759
+ autoUpdate: record.autoUpdate === true,
3760
+ unreadable: false
3761
+ },
3762
+ missing: false,
3763
+ document: typeof value === "object" && value !== null ? record : null
3764
+ };
3765
+ }
3766
+ var MAX_PREFERENCES_BYTES;
3767
+ var init_updateReminderPreferences = __esm({
3768
+ "src/cli/lib/updateReminderPreferences.ts"() {
3769
+ MAX_PREFERENCES_BYTES = 64 * 1024;
3770
+ }
3771
+ });
3772
+
3773
+ // src/cli/lib/autoUpdateNotice.ts
3774
+ var autoUpdateNotice_exports = {};
3775
+ __export(autoUpdateNotice_exports, {
3776
+ consumeAutoUpdateNotice: () => consumeAutoUpdateNotice,
3777
+ formatAutoUpdateNotice: () => formatAutoUpdateNotice,
3778
+ isPrintableAutoUpdateNotice: () => isPrintableAutoUpdateNotice,
3779
+ readAutoUpdateNotice: () => readAutoUpdateNotice,
3780
+ writeAutoUpdateNotice: () => writeAutoUpdateNotice
3781
+ });
3782
+ function readAutoUpdateNotice(statusPath) {
3783
+ return readAutoUpdateStatus(statusPath)?.notice ?? null;
3784
+ }
3785
+ function isPrintableAutoUpdateNotice(notice) {
3786
+ if (!notice) return false;
3787
+ if (notice.to.trim() === "") return false;
3788
+ return (notice.consumedAt ?? 0) === 0;
3789
+ }
3790
+ function formatAutoUpdateNotice(notice) {
3791
+ const host = notice.restart.trim() || "Claude Code";
3792
+ const from = notice.from.trim();
3793
+ const lines = [];
3794
+ lines.push(
3795
+ from ? t("auto_update.notice.updated_from", { from, to: notice.to }) : t("auto_update.notice.updated_to", { to: notice.to })
3796
+ );
3797
+ const changelog = notice.changelog.trim();
3798
+ if (changelog) lines.push("", changelog);
3799
+ lines.push("", t("auto_update.notice.restart", { host }));
3800
+ if (host === "Codex") {
3801
+ lines.push(t("auto_update.notice.codex_trust"));
3802
+ }
3803
+ return lines.join("\n");
3804
+ }
3805
+ function writeAutoUpdateNotice(statusPath, notice) {
3806
+ const status = readAutoUpdateStatus(statusPath);
3807
+ if (!status) return false;
3808
+ try {
3809
+ writeAutoUpdateStatus(statusPath, { ...status, notice });
3810
+ return true;
3811
+ } catch {
3812
+ return false;
3813
+ }
3814
+ }
3815
+ function consumeAutoUpdateNotice(statusPath, now) {
3816
+ const status = readAutoUpdateStatus(statusPath);
3817
+ const notice = status?.notice;
3818
+ if (!status || !notice) return false;
3819
+ if ((notice.consumedAt ?? 0) !== 0) return false;
3820
+ if (notice.to.trim() === "") return false;
3821
+ try {
3822
+ writeAutoUpdateStatus(statusPath, { ...status, notice: { ...notice, consumedAt: now } });
3823
+ return true;
3824
+ } catch {
3825
+ return false;
3826
+ }
3827
+ }
3828
+ var init_autoUpdateNotice = __esm({
3829
+ "src/cli/lib/autoUpdateNotice.ts"() {
3830
+ init_i18n();
3831
+ init_autoUpdateStatus();
3832
+ }
3833
+ });
3834
+ var init_updateReminderCache = __esm({
3835
+ "src/cli/lib/updateReminderCache.ts"() {
3836
+ }
3837
+ });
3838
+ var init_updateReminderHookMain = __esm({
3839
+ "src/cli/updateReminderHookMain.ts"() {
3840
+ init_autoUpdateNotice();
3841
+ init_autoUpdateStatus();
3842
+ init_updateReminderCache();
3843
+ }
3844
+ });
3845
+ function canonicalStateRoot(hostId) {
3846
+ const override = process.env.HARNESSED_ROOT_OVERRIDE?.trim();
3847
+ if (override) return resolve(override);
3848
+ const nativeHome = hostId === "codex" ? process.env.CODEX_HOME?.trim() || join(homedir(), ".codex") : process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), ".claude");
3849
+ return resolve(join(nativeHome, "harnessed"));
3850
+ }
3851
+ var init_stateRoot = __esm({
3852
+ "src/platform/stateRoot.ts"() {
3853
+ }
3854
+ });
3855
+ function resolveUpdateReminderRuntime(options = {}) {
3856
+ const args = [...options.args ?? process.argv.slice(2)];
3857
+ if (args[0] === UPDATE_REMINDER_OPERATION || args[0] === UPDATE_REMINDER_WORKER_OPERATION)
3858
+ args.shift();
3859
+ let host = "claude";
3860
+ let explicitStateRoot;
3861
+ let platformSpecified = false;
3862
+ for (let index = 0; index < args.length; index += 2) {
3863
+ const flag = args[index];
3864
+ const value = args[index + 1];
3865
+ if (!flag || value === void 0 || [flag, value].some(
3866
+ (argument) => Array.from(argument).some((character) => character < " " || character === "\x7F")
3867
+ ))
3868
+ return null;
3869
+ if (flag === "--platform") {
3870
+ if (platformSpecified || value !== "claude" && value !== "codex") return null;
3871
+ platformSpecified = true;
3872
+ host = value;
3873
+ } else if (flag === "--state-root") {
3874
+ if (explicitStateRoot !== void 0 || !isAbsolute(value)) return null;
3875
+ explicitStateRoot = resolve(value);
3876
+ } else return null;
3877
+ }
3878
+ const nativeHome = resolve(
3879
+ (host === "codex" ? process.env.CODEX_HOME?.trim() : process.env.CLAUDE_CONFIG_DIR) || join(homedir(), host === "codex" ? ".codex" : ".claude")
3880
+ );
3881
+ const stateRoot = explicitStateRoot ?? canonicalStateRoot(host);
3882
+ const channel = options.compiled ? "binary" : process.versions.bun ? "bun" : "npm";
3883
+ const source = channel === "binary" ? BINARY_SOURCE : `${channel}:harnessed`;
3884
+ const fingerprint = createHash("sha256").update(
3885
+ JSON.stringify([
3886
+ host === "codex" ? stateRoot : nativeHome,
3887
+ process.execPath,
3888
+ package_default.version,
3889
+ source
3890
+ ])
3891
+ ).digest("hex");
3892
+ return {
3893
+ stateRoot,
3894
+ nativeHome,
3895
+ cachePath: join(stateRoot, `update-reminder-${host}.json`),
3896
+ preferencesPath: join(stateRoot, UPDATE_REMINDER_PREFERENCES_FILE),
3897
+ // The auto-update status file of THIS host — the hook reads the pending
3898
+ // update notice from it, the worker writes the run state into it.
3899
+ statusPath: autoUpdateStatusPath(stateRoot),
3900
+ installed: package_default.version,
3901
+ identity: {
3902
+ host,
3903
+ runtime: options.compiled ? "binary" : process.versions.bun ? "bun" : "node",
3904
+ channel,
3905
+ source,
3906
+ fingerprint
3907
+ },
3908
+ worker: {
3909
+ executable: process.execPath,
3910
+ args: [
3911
+ options.compiled ? UPDATE_REMINDER_WORKER_OPERATION : join(dirname(fileURLToPath(import.meta.url)), "harnessed-update-reminder-worker.mjs"),
3912
+ "--platform",
3913
+ host,
3914
+ ...explicitStateRoot ? ["--state-root", explicitStateRoot] : []
3915
+ ]
3916
+ }
3917
+ };
3918
+ }
3919
+ var UPDATE_REMINDER_OPERATION, UPDATE_REMINDER_WORKER_OPERATION, UPDATE_REMINDER_PREFERENCES_FILE, BINARY_SOURCE;
3920
+ var init_updateReminderEntrypoint = __esm({
3921
+ "src/compile/updateReminderEntrypoint.ts"() {
3922
+ init_package();
3923
+ init_autoUpdateStatus();
3924
+ init_updateReminderPreferences();
3925
+ init_updateReminderHookMain();
3926
+ init_stateRoot();
3927
+ UPDATE_REMINDER_OPERATION = "update-reminder";
3928
+ UPDATE_REMINDER_WORKER_OPERATION = "update-reminder-worker";
3929
+ UPDATE_REMINDER_PREFERENCES_FILE = "update-reminder-preferences.json";
3930
+ BINARY_SOURCE = "https://api.github.com/repos/easyinplay/harnessed/releases/latest";
3931
+ }
3932
+ });
3933
+
3934
+ // src/cli/autoUpdateCmd.ts
3935
+ var autoUpdateCmd_exports = {};
3936
+ __export(autoUpdateCmd_exports, {
3937
+ mergeAutoUpdateStatus: () => mergeAutoUpdateStatus,
3938
+ registerAutoUpdate: () => registerAutoUpdate,
3939
+ resolveAutoUpdateHostId: () => resolveAutoUpdateHostId,
3940
+ resolveAutoUpdatePaths: () => resolveAutoUpdatePaths,
3941
+ runAutoUpdate: () => runAutoUpdate,
3942
+ setAutoUpdateConsent: () => setAutoUpdateConsent
3943
+ });
3944
+ function resolveAutoUpdateHostId(platform) {
3945
+ if (platform !== void 0) {
3946
+ if (platform !== "claude" && platform !== "codex") {
3947
+ throw new Error(t("auto_update.error.unsupported_host", { host: platform }));
3948
+ }
3949
+ return platform;
3950
+ }
3951
+ const detected = detectPlatform().id;
3952
+ return detected === "codex" ? "codex" : "claude";
3953
+ }
3954
+ function toStatusChannel(channel) {
3955
+ return channel === "binary" || channel === "bun" || channel === "npm" || channel === "node" ? channel : "npm";
3956
+ }
3957
+ function resolveAutoUpdatePaths(platform) {
3958
+ const hostId = resolveAutoUpdateHostId(platform);
3959
+ const runtime = resolveUpdateReminderRuntime({
3960
+ args: ["--platform", hostId],
3961
+ compiled: isCompiledRuntime()
3962
+ });
3963
+ if (!runtime) {
3964
+ throw new Error(t("auto_update.error.runtime", { host: hostId }));
3965
+ }
3966
+ const stateRoot = canonicalStateRoot(hostId);
3967
+ return {
3968
+ hostId,
3969
+ stateRoot,
3970
+ preferencesPath: join(stateRoot, UPDATE_REMINDER_PREFERENCES_FILE),
3971
+ statusPath: autoUpdateStatusPath(stateRoot),
3972
+ channel: toStatusChannel(runtime.identity.channel),
3973
+ installed: runtime.installed
3974
+ };
3975
+ }
3976
+ function writePreferences(path, document) {
3977
+ mkdirSync(dirname(path), { recursive: true });
3978
+ const tmp = `${path}.${process.pid}.tmp`;
3979
+ try {
3980
+ writeFileSync(tmp, `${JSON.stringify(document, null, 2)}
3981
+ `, "utf8");
3982
+ renameSync(tmp, path);
3983
+ } catch (error) {
3984
+ try {
3985
+ rmSync(tmp, { force: true });
3986
+ } catch {
3987
+ }
3988
+ throw error;
3989
+ }
3990
+ }
3991
+ function setAutoUpdateConsent(path, autoUpdate) {
3992
+ const file = readUpdateReminderPreferencesFile(path);
3993
+ const document = file.document && !Array.isArray(file.document) ? file.document : null;
3994
+ const base = document ? { schemaVersion: 1, ...document } : { schemaVersion: 1, enabled: true };
3995
+ writePreferences(path, { ...base, autoUpdate });
3996
+ return {
3997
+ corrupt: file.preferences.unreadable,
3998
+ created: file.missing,
3999
+ enabled: base.enabled === true
4000
+ };
4001
+ }
4002
+ function mergeAutoUpdateStatus(paths, consent, status) {
4003
+ const base = status ?? {
4004
+ schemaVersion: 1,
4005
+ consent: { autoUpdate: consent.autoUpdate, enabled: consent.enabled },
4006
+ channel: paths.channel,
4007
+ installed: paths.installed,
4008
+ latest: null,
4009
+ state: "idle",
4010
+ progress: { received: 0, total: 0, updatedAt: 0 },
4011
+ lastResult: null,
4012
+ history: [],
4013
+ notice: null
4014
+ };
4015
+ return {
4016
+ ...base,
4017
+ consent: { autoUpdate: consent.autoUpdate, enabled: consent.enabled },
4018
+ channel: paths.channel
4019
+ };
4020
+ }
4021
+ function printPaths(paths) {
4022
+ console.log(t("auto_update.path.host", { host: paths.hostId }));
4023
+ console.log(t("auto_update.path.preferences", { path: paths.preferencesPath }));
4024
+ console.log(t("auto_update.path.status", { path: paths.statusPath }));
4025
+ }
4026
+ function setConsent(paths, autoUpdate) {
4027
+ const outcome = setAutoUpdateConsent(paths.preferencesPath, autoUpdate);
4028
+ console.log(t(autoUpdate ? "auto_update.consent_on" : "auto_update.consent_off"));
4029
+ if (outcome.corrupt) {
4030
+ console.log(t("auto_update.preferences_replaced"));
4031
+ }
4032
+ printPaths(paths);
4033
+ if (!outcome.enabled) {
4034
+ console.log(t("auto_update.reminder_off_note"));
4035
+ }
4036
+ }
4037
+ function printStatus(paths, json2) {
4038
+ const preferences = readUpdateReminderPreferencesFile(paths.preferencesPath);
4039
+ const status = readAutoUpdateStatus(paths.statusPath);
4040
+ const merged = mergeAutoUpdateStatus(
4041
+ paths,
4042
+ {
4043
+ autoUpdate: preferences.preferences.autoUpdate,
4044
+ enabled: preferences.preferences.enabled
4045
+ },
4046
+ status
4047
+ );
4048
+ if (json2) {
4049
+ console.log(
4050
+ JSON.stringify(
4051
+ {
4052
+ ...merged,
4053
+ host: paths.hostId,
4054
+ preferencesPath: paths.preferencesPath,
4055
+ statusPath: paths.statusPath
4056
+ },
4057
+ null,
4058
+ 2
4059
+ )
4060
+ );
4061
+ return;
4062
+ }
4063
+ console.log(formatAutoUpdateStatus(merged, Date.now()));
4064
+ printPaths(paths);
4065
+ }
4066
+ async function runAutoUpdate(action, opts) {
4067
+ let paths;
4068
+ try {
4069
+ paths = resolveAutoUpdatePaths(opts.platform);
4070
+ } catch (error) {
4071
+ console.warn(`[harnessed] ${error instanceof Error ? error.message : String(error)}`);
4072
+ process.exitCode = 1;
4073
+ return;
4074
+ }
4075
+ if (action === "status") {
4076
+ printStatus(paths, opts.json === true);
4077
+ return;
4078
+ }
4079
+ setConsent(paths, action === "on");
4080
+ }
4081
+ function registerAutoUpdate(program2) {
4082
+ program2.command("auto-update").description("Turn the background auto-update on or off, or show its consent + last run status").addArgument(
4083
+ new Argument("<action>", "on | off | status").choices(["on", "off", "status"])
4084
+ ).option("--platform <host>", "target host: claude | codex").option("--json", "emit the merged status as one JSON object").action(async (action, opts) => {
4085
+ await runAutoUpdate(action, opts);
4086
+ });
4087
+ }
4088
+ var init_autoUpdateCmd = __esm({
4089
+ "src/cli/autoUpdateCmd.ts"() {
4090
+ init_updateReminderEntrypoint();
4091
+ init_i18n();
4092
+ init_assetsRoot();
4093
+ init_platform();
4094
+ init_stateRoot();
4095
+ init_autoUpdateStatus();
4096
+ init_updateReminderPreferences();
4097
+ }
4098
+ });
3543
4099
  function getBackupRoot(hostContext) {
3544
4100
  return hostContext ? join(hostContext.platform.stateRoot, "backups") : harnessedSubdir("backups");
3545
4101
  }
@@ -3897,69 +4453,191 @@ function registerCheckDocs(program2) {
3897
4453
  "Documentation-discipline gate over .planning/ (STATE digest limit + archive cadence + ROADMAP pointer-not-narrative). Exits 2 on a blocking violation, 1 on advisory-only."
3898
4454
  ).option("--json", "output JSON instead of human-readable").option("--cwd <dir>", "repo root holding .planning/ (default: current directory)").option("--max-state-lines <n>", `STATE.md digest ceiling (default ${DEFAULT_MAX_STATE_LINES})`).option("--hook", "PreToolUse mode: read the tool payload on stdin, gate only git commit").option("--platform <id>", "(hook) host harness; codex \u2192 verdict as JSON on stdout, exit 0").action((opts) => runCheckDocsCommand(opts));
3899
4455
  }
3900
- var DEFAULT_MAX_STATE_LINES, KEY_DECISIONS_SECTION_RE, KEY_DECISIONS_SECTION_LIMIT, HISTORICAL_ERRATA_RE, ROADMAP_NARRATIVE_SIGNALS;
3901
- var init_checkDocs = __esm({
3902
- "src/cli/checkDocs.ts"() {
3903
- init_i18n();
3904
- init_ablation();
3905
- DEFAULT_MAX_STATE_LINES = 100;
3906
- KEY_DECISIONS_SECTION_RE = /^##\s+.*关键决议\s*ship\s*总结/gm;
3907
- KEY_DECISIONS_SECTION_LIMIT = 1;
3908
- HISTORICAL_ERRATA_RE = /W-[1-9]\s+errata|sister\s+review\s+M[1-9]\s+修正/;
3909
- ROADMAP_NARRATIVE_SIGNALS = [
3910
- { id: "commit-hash", test: hasCommitHash },
3911
- { id: "test-tally", test: (l) => /\b\d{2,}\s*\/\s*0\b/.test(l) },
3912
- { id: "ci-verdict", test: (l) => /\bCI\s+(green|red|绿|红)/i.test(l) },
3913
- { id: "lesson", test: (l) => /(教训|lesson\s*[::]|lessons?\s+learned)/i.test(l) }
3914
- ];
4456
+ var DEFAULT_MAX_STATE_LINES, KEY_DECISIONS_SECTION_RE, KEY_DECISIONS_SECTION_LIMIT, HISTORICAL_ERRATA_RE, ROADMAP_NARRATIVE_SIGNALS;
4457
+ var init_checkDocs = __esm({
4458
+ "src/cli/checkDocs.ts"() {
4459
+ init_i18n();
4460
+ init_ablation();
4461
+ DEFAULT_MAX_STATE_LINES = 100;
4462
+ KEY_DECISIONS_SECTION_RE = /^##\s+.*关键决议\s*ship\s*总结/gm;
4463
+ KEY_DECISIONS_SECTION_LIMIT = 1;
4464
+ HISTORICAL_ERRATA_RE = /W-[1-9]\s+errata|sister\s+review\s+M[1-9]\s+修正/;
4465
+ ROADMAP_NARRATIVE_SIGNALS = [
4466
+ { id: "commit-hash", test: hasCommitHash },
4467
+ { id: "test-tally", test: (l) => /\b\d{2,}\s*\/\s*0\b/.test(l) },
4468
+ { id: "ci-verdict", test: (l) => /\bCI\s+(green|red|绿|红)/i.test(l) },
4469
+ { id: "lesson", test: (l) => /(教训|lesson\s*[::]|lessons?\s+learned)/i.test(l) }
4470
+ ];
4471
+ }
4472
+ });
4473
+
4474
+ // src/platform/runDeps.ts
4475
+ function captureRunDeps() {
4476
+ const stdout2 = [];
4477
+ const stderr = [];
4478
+ const deps = {
4479
+ exit(code2) {
4480
+ throw new ExitError(code2);
4481
+ },
4482
+ log: (...args) => {
4483
+ stdout2.push(args.map(String).join(" "));
4484
+ },
4485
+ error: (...args) => {
4486
+ stderr.push(args.map(String).join(" "));
4487
+ },
4488
+ warn: (...args) => {
4489
+ stderr.push(args.map(String).join(" "));
4490
+ }
4491
+ };
4492
+ return { deps, stdout: stdout2, stderr };
4493
+ }
4494
+ var ExitError, defaultRunDeps;
4495
+ var init_runDeps = __esm({
4496
+ "src/platform/runDeps.ts"() {
4497
+ ExitError = class extends Error {
4498
+ constructor(code2) {
4499
+ super(`process.exit(${code2})`);
4500
+ this.code = code2;
4501
+ this.name = "ExitError";
4502
+ }
4503
+ code;
4504
+ };
4505
+ defaultRunDeps = {
4506
+ exit(code2) {
4507
+ return process.exit(code2);
4508
+ },
4509
+ log: (...args) => {
4510
+ console.log(...args);
4511
+ },
4512
+ error: (...args) => {
4513
+ console.error(...args);
4514
+ },
4515
+ warn: (...args) => {
4516
+ console.warn(...args);
4517
+ }
4518
+ };
4519
+ }
4520
+ });
4521
+
4522
+ // src/workflow/lib/promiseExtract.ts
4523
+ function extractPromise(text) {
4524
+ const match = text.match(PROMISE_PATTERN);
4525
+ return match ? match[1] : null;
4526
+ }
4527
+ var PROMISE_PATTERN;
4528
+ var init_promiseExtract = __esm({
4529
+ "src/workflow/lib/promiseExtract.ts"() {
4530
+ PROMISE_PATTERN = /<promise>([^<]+)<\/promise>/;
4531
+ }
4532
+ });
4533
+
4534
+ // src/workflow/lib/fallbackHandlers.ts
4535
+ function handleMaxIterationsExceeded(err2, fallback, ctx) {
4536
+ const yamlShort = fallback.message.replace(
4537
+ /\{\{\s*args\.max_iterations\s*\}\}/g,
4538
+ String(ctx.maxIterations)
4539
+ );
4540
+ const truncated = (ctx.lastMessage ?? "<empty>").slice(0, 500);
4541
+ const uxText = `\u274C ralph-loop max-iterations exceeded (${err2.iterations}/${ctx.maxIterations}).
4542
+ Sub-task: ${ctx.subtaskSummary}
4543
+ Workflow: ${ctx.workflowName} / phase ${ctx.phaseId}
4544
+ Last subagent output (truncated): ${truncated}
4545
+ The subagent attempted ${err2.iterations} iterations without emitting verbatim "<promise>COMPLETE</promise>".
4546
+ This indicates one of:
4547
+ 1. Sub-task is genuinely incomplete (escalate to user / re-scope)
4548
+ 2. Subagent is stuck in a loop (review prompt / system instructions)
4549
+ 3. max-iterations too low (override via --max-iterations <N>, hard upper limit 100)
4550
+ Manual options:
4551
+ A) Continue with current state: \`harnessed workflow resume --skip-completion-gate\`
4552
+ B) Re-run from last checkpoint: \`harnessed workflow resume --from-checkpoint\`
4553
+ C) Abort cleanly: exit 1
4554
+ Exit code: ${fallback.exit_code}
4555
+ ${yamlShort}`;
4556
+ console.error(uxText);
4557
+ throw new WorkflowHaltError(
4558
+ `ralph-loop max-iterations exceeded (${err2.iterations}/${ctx.maxIterations}) for ${ctx.workflowName} / phase ${ctx.phaseId}`,
4559
+ fallback.exit_code
4560
+ );
4561
+ }
4562
+ var WorkflowHaltError;
4563
+ var init_fallbackHandlers = __esm({
4564
+ "src/workflow/lib/fallbackHandlers.ts"() {
4565
+ WorkflowHaltError = class extends Error {
4566
+ constructor(message, exitCode) {
4567
+ super(message);
4568
+ this.exitCode = exitCode;
4569
+ this.name = "WorkflowHaltError";
4570
+ }
4571
+ exitCode;
4572
+ };
4573
+ }
4574
+ });
4575
+
4576
+ // src/workflow/lib/ralphLoop.ts
4577
+ function isComplete(output) {
4578
+ let env;
4579
+ try {
4580
+ env = JSON.parse(output);
4581
+ } catch {
4582
+ return extractPromise(output) === "COMPLETE";
4583
+ }
4584
+ const succeeded = env.subtype === "success";
4585
+ const status = env.structured_output?.status;
4586
+ if (status === "COMPLETE") return succeeded;
4587
+ if (status === "PARTIAL" || status === "BLOCKED") return false;
4588
+ if (succeeded) return true;
4589
+ return extractPromise(env.text ?? env.result ?? "") === "COMPLETE";
4590
+ }
4591
+ async function ralphLoopWrap(spawn10, maxIter) {
4592
+ let last = "";
4593
+ let sessionId;
4594
+ for (let i = 0; i < maxIter; i++) {
4595
+ last = await spawn10(sessionId, (id) => {
4596
+ sessionId = id;
4597
+ });
4598
+ if (isComplete(last)) return last;
4599
+ }
4600
+ throw new MaxIterationsExceededError(maxIter);
4601
+ }
4602
+ var MaxIterationsExceededError;
4603
+ var init_ralphLoop = __esm({
4604
+ "src/workflow/lib/ralphLoop.ts"() {
4605
+ init_promiseExtract();
4606
+ init_fallbackHandlers();
4607
+ MaxIterationsExceededError = class extends Error {
4608
+ constructor(iterations) {
4609
+ super(`ralph-loop max-iterations exceeded after ${iterations} attempts`);
4610
+ this.iterations = iterations;
4611
+ this.name = "MaxIterationsExceededError";
4612
+ }
4613
+ iterations;
4614
+ };
3915
4615
  }
3916
4616
  });
3917
4617
 
3918
- // src/platform/runDeps.ts
3919
- function captureRunDeps() {
3920
- const stdout2 = [];
3921
- const stderr = [];
3922
- const deps = {
3923
- exit(code2) {
3924
- throw new ExitError(code2);
3925
- },
3926
- log: (...args) => {
3927
- stdout2.push(args.map(String).join(" "));
3928
- },
3929
- error: (...args) => {
3930
- stderr.push(args.map(String).join(" "));
3931
- },
3932
- warn: (...args) => {
3933
- stderr.push(args.map(String).join(" "));
4618
+ // src/checkpoint/completionClaim.ts
4619
+ var completionClaim_exports = {};
4620
+ __export(completionClaim_exports, {
4621
+ verifyCompletionClaim: () => verifyCompletionClaim
4622
+ });
4623
+ async function verifyCompletionClaim(input) {
4624
+ if (input.resultFile) {
4625
+ let text;
4626
+ try {
4627
+ text = await readFile(input.resultFile, "utf8");
4628
+ } catch {
4629
+ return { verdict: "incomplete", source: input.resultFile };
3934
4630
  }
3935
- };
3936
- return { deps, stdout: stdout2, stderr };
4631
+ return { verdict: isComplete(text) ? "complete" : "incomplete", source: input.resultFile };
4632
+ }
4633
+ if (typeof input.result === "string" && input.result.trim() !== "") {
4634
+ return { verdict: isComplete(input.result) ? "complete" : "incomplete", source: "--result" };
4635
+ }
4636
+ return { verdict: "not_provided", source: null };
3937
4637
  }
3938
- var ExitError, defaultRunDeps;
3939
- var init_runDeps = __esm({
3940
- "src/platform/runDeps.ts"() {
3941
- ExitError = class extends Error {
3942
- constructor(code2) {
3943
- super(`process.exit(${code2})`);
3944
- this.code = code2;
3945
- this.name = "ExitError";
3946
- }
3947
- code;
3948
- };
3949
- defaultRunDeps = {
3950
- exit(code2) {
3951
- return process.exit(code2);
3952
- },
3953
- log: (...args) => {
3954
- console.log(...args);
3955
- },
3956
- error: (...args) => {
3957
- console.error(...args);
3958
- },
3959
- warn: (...args) => {
3960
- console.warn(...args);
3961
- }
3962
- };
4638
+ var init_completionClaim = __esm({
4639
+ "src/checkpoint/completionClaim.ts"() {
4640
+ init_ralphLoop();
3963
4641
  }
3964
4642
  });
3965
4643
 
@@ -4143,7 +4821,7 @@ function resolveWindowsBin(bin, env = process.env, isFile = (p8) => existsSync(p
4143
4821
  const candidates = extname(bin) ? [""] : exts;
4144
4822
  for (const dir of dirs) {
4145
4823
  for (const ext of candidates) {
4146
- const p8 = join17(dir, `${bin}${ext}`);
4824
+ const p8 = join21(dir, `${bin}${ext}`);
4147
4825
  if (isFile(p8)) return p8;
4148
4826
  }
4149
4827
  }
@@ -4158,10 +4836,10 @@ function planWindowsSpawn(bin, args, resolved) {
4158
4836
  const line = [escapeCommand(resolved), ...args.map((a) => escapeArgument(a))].join(" ");
4159
4837
  return { command: "cmd.exe", args: ["/d", "/s", "/c", `"${line}"`], verbatim: true };
4160
4838
  }
4161
- var extname, join17, META;
4839
+ var extname, join21, META;
4162
4840
  var init_winSpawn = __esm({
4163
4841
  "src/installers/lib/winSpawn.ts"() {
4164
- ({ extname, join: join17 } = win32);
4842
+ ({ extname, join: join21 } = win32);
4165
4843
  META = /([()\][%!^"`<>&|;, *?])/g;
4166
4844
  }
4167
4845
  });
@@ -4184,7 +4862,7 @@ function withHostInstallEnv(env, hostContext) {
4184
4862
  return { ...result, ...pins };
4185
4863
  }
4186
4864
  function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3, hostContext) {
4187
- return new Promise((resolve40) => {
4865
+ return new Promise((resolve42) => {
4188
4866
  const isWin = (hostContext?.os ?? process.platform) === "win32";
4189
4867
  const envOpts = hostContext ? { env: withHostInstallEnv(process.env, hostContext) } : {};
4190
4868
  const stdio = ["ignore", "pipe", "pipe"];
@@ -4212,17 +4890,17 @@ function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3, hostContext) {
4212
4890
  });
4213
4891
  const timer = setTimeout(() => {
4214
4892
  killProcessTree(child);
4215
- resolve40({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
4893
+ resolve42({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
4216
4894
  }, timeoutMs);
4217
4895
  child.on("error", (e) => {
4218
4896
  clearTimeout(timer);
4219
4897
  const enoent = e.code === "ENOENT";
4220
4898
  const msg = enoent && bin === "codex" ? "codex CLI not found on PATH \u2014 install Codex CLI or re-run setup on the claude platform" : e.message;
4221
- resolve40({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
4899
+ resolve42({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
4222
4900
  });
4223
4901
  child.on("close", (code2) => {
4224
4902
  clearTimeout(timer);
4225
- resolve40({ exitCode: code2 ?? -1, stdout: stdout2, stderr });
4903
+ resolve42({ exitCode: code2 ?? -1, stdout: stdout2, stderr });
4226
4904
  });
4227
4905
  });
4228
4906
  }
@@ -4504,9 +5182,62 @@ var init_readClaudeConfig = __esm({
4504
5182
  init_codexPlugins();
4505
5183
  }
4506
5184
  });
5185
+
5186
+ // src/platform/lockContention.ts
5187
+ function isLockContention(error) {
5188
+ return error?.code === "ELOCKED";
5189
+ }
5190
+ function isLockNotHeld(error) {
5191
+ const code2 = error?.code;
5192
+ return code2 === "ERELEASED" || code2 === "ENOTACQUIRED";
5193
+ }
5194
+ function lockBackoffDelay(attempt, budget) {
5195
+ return Math.min(budget.minTimeout * 2 ** attempt, budget.maxTimeout);
5196
+ }
5197
+ async function acquireWithContentionRetry(acquire, budget) {
5198
+ for (let attempt = 0; ; attempt += 1) {
5199
+ try {
5200
+ return await acquire();
5201
+ } catch (error) {
5202
+ if (!isLockContention(error) || attempt >= budget.retries) throw error;
5203
+ await sleep(lockBackoffDelay(attempt, budget));
5204
+ }
5205
+ }
5206
+ }
5207
+ async function releaseLockIdempotently(release) {
5208
+ try {
5209
+ await release();
5210
+ } catch (error) {
5211
+ if (!isLockNotHeld(error)) throw error;
5212
+ }
5213
+ }
5214
+ var sleep;
5215
+ var init_lockContention = __esm({
5216
+ "src/platform/lockContention.ts"() {
5217
+ sleep = (ms) => new Promise((resolve42) => {
5218
+ setTimeout(resolve42, ms);
5219
+ });
5220
+ }
5221
+ });
4507
5222
  function lockRoots(hostContext) {
4508
5223
  return [join(hostContext?.nativeHome ?? detectPlatform().homeDir, "harnessed")];
4509
5224
  }
5225
+ function lockTarget2(root) {
5226
+ return join(root, ".settings-transaction.lock");
5227
+ }
5228
+ async function acquireSettingsLock(root) {
5229
+ const target = lockTarget2(root);
5230
+ return acquireWithContentionRetry(
5231
+ () => lockfile.lock(target, {
5232
+ stale: 6e4,
5233
+ // One attempt only — the retry loop owns the backoff.
5234
+ retries: 0,
5235
+ lockfilePath: target,
5236
+ realpath: false
5237
+ }),
5238
+ SETTINGS_TRANSACTION_LOCK_RETRIES
5239
+ );
5240
+ }
4510
5241
  async function withSettingsTransactionLock(hostContext, work) {
4511
5242
  const active = heldLocks.getStore();
4512
5243
  const roots = lockRoots(hostContext);
@@ -4517,31 +5248,25 @@ async function withSettingsTransactionLock(hostContext, work) {
4517
5248
  for (const root of roots) {
4518
5249
  if (next.has(root)) continue;
4519
5250
  await mkdir(root, { recursive: true });
4520
- releases.push(
4521
- await lockfile.lock(root, {
4522
- stale: 6e4,
4523
- retries: {
4524
- retries: 20,
4525
- factor: 1.3,
4526
- minTimeout: 50,
4527
- maxTimeout: 250,
4528
- randomize: true
4529
- },
4530
- lockfilePath: join(root, ".settings-transaction.lock")
4531
- })
4532
- );
5251
+ releases.push(await acquireSettingsLock(root));
4533
5252
  next.add(root);
4534
5253
  }
4535
5254
  return await heldLocks.run(next, work);
4536
5255
  } finally {
4537
- for (const release of releases.reverse()) await release();
5256
+ for (const release of releases.reverse()) await releaseLockIdempotently(release);
4538
5257
  }
4539
5258
  }
4540
- var heldLocks;
5259
+ var heldLocks, SETTINGS_TRANSACTION_LOCK_RETRIES;
4541
5260
  var init_settingsTransactionLock = __esm({
4542
5261
  "src/cli/lib/settingsTransactionLock.ts"() {
5262
+ init_lockContention();
4543
5263
  init_platform();
4544
5264
  heldLocks = new AsyncLocalStorage();
5265
+ SETTINGS_TRANSACTION_LOCK_RETRIES = {
5266
+ retries: 30,
5267
+ minTimeout: 250,
5268
+ maxTimeout: 4e3
5269
+ };
4545
5270
  }
4546
5271
  });
4547
5272
  function settingsOwnershipReceiptPath(hostContext) {
@@ -5293,135 +6018,13 @@ function assertionDelta(diff) {
5293
6018
  var execFileP, TDD_EVIDENCE_ARTIFACT, RED_MARKER, GREEN_MARKER, SKIP_DECLARATION, SCOPE, ASSERTION_TOKEN;
5294
6019
  var init_tddBoundary = __esm({
5295
6020
  "src/checkpoint/tddBoundary.ts"() {
5296
- execFileP = promisify(execFile);
5297
- TDD_EVIDENCE_ARTIFACT = "tdd-evidence.md";
5298
- RED_MARKER = /\b(red|fail(?:s|ed|ing|ure)?)\b/i;
5299
- GREEN_MARKER = /\b(green|pass(?:es|ed|ing)?)\b/i;
5300
- SKIP_DECLARATION = /\bSKIPPED\b\s*[—–:-]\s*\S+/i;
5301
- SCOPE = ["--", "."];
5302
- ASSERTION_TOKEN = /\b(expect|assert\w*|should|toBe\w*|toEqual|toThrow|toMatch)\b|\.to\./;
5303
- }
5304
- });
5305
-
5306
- // src/workflow/lib/promiseExtract.ts
5307
- function extractPromise(text) {
5308
- const match = text.match(PROMISE_PATTERN);
5309
- return match ? match[1] : null;
5310
- }
5311
- var PROMISE_PATTERN;
5312
- var init_promiseExtract = __esm({
5313
- "src/workflow/lib/promiseExtract.ts"() {
5314
- PROMISE_PATTERN = /<promise>([^<]+)<\/promise>/;
5315
- }
5316
- });
5317
-
5318
- // src/workflow/lib/fallbackHandlers.ts
5319
- function handleMaxIterationsExceeded(err2, fallback, ctx) {
5320
- const yamlShort = fallback.message.replace(
5321
- /\{\{\s*args\.max_iterations\s*\}\}/g,
5322
- String(ctx.maxIterations)
5323
- );
5324
- const truncated = (ctx.lastMessage ?? "<empty>").slice(0, 500);
5325
- const uxText = `\u274C ralph-loop max-iterations exceeded (${err2.iterations}/${ctx.maxIterations}).
5326
- Sub-task: ${ctx.subtaskSummary}
5327
- Workflow: ${ctx.workflowName} / phase ${ctx.phaseId}
5328
- Last subagent output (truncated): ${truncated}
5329
- The subagent attempted ${err2.iterations} iterations without emitting verbatim "<promise>COMPLETE</promise>".
5330
- This indicates one of:
5331
- 1. Sub-task is genuinely incomplete (escalate to user / re-scope)
5332
- 2. Subagent is stuck in a loop (review prompt / system instructions)
5333
- 3. max-iterations too low (override via --max-iterations <N>, hard upper limit 100)
5334
- Manual options:
5335
- A) Continue with current state: \`harnessed workflow resume --skip-completion-gate\`
5336
- B) Re-run from last checkpoint: \`harnessed workflow resume --from-checkpoint\`
5337
- C) Abort cleanly: exit 1
5338
- Exit code: ${fallback.exit_code}
5339
- ${yamlShort}`;
5340
- console.error(uxText);
5341
- throw new WorkflowHaltError(
5342
- `ralph-loop max-iterations exceeded (${err2.iterations}/${ctx.maxIterations}) for ${ctx.workflowName} / phase ${ctx.phaseId}`,
5343
- fallback.exit_code
5344
- );
5345
- }
5346
- var WorkflowHaltError;
5347
- var init_fallbackHandlers = __esm({
5348
- "src/workflow/lib/fallbackHandlers.ts"() {
5349
- WorkflowHaltError = class extends Error {
5350
- constructor(message, exitCode) {
5351
- super(message);
5352
- this.exitCode = exitCode;
5353
- this.name = "WorkflowHaltError";
5354
- }
5355
- exitCode;
5356
- };
5357
- }
5358
- });
5359
-
5360
- // src/workflow/lib/ralphLoop.ts
5361
- function isComplete(output) {
5362
- let env;
5363
- try {
5364
- env = JSON.parse(output);
5365
- } catch {
5366
- return extractPromise(output) === "COMPLETE";
5367
- }
5368
- const succeeded = env.subtype === "success";
5369
- const status = env.structured_output?.status;
5370
- if (status === "COMPLETE") return succeeded;
5371
- if (status === "PARTIAL" || status === "BLOCKED") return false;
5372
- if (succeeded) return true;
5373
- return extractPromise(env.text ?? env.result ?? "") === "COMPLETE";
5374
- }
5375
- async function ralphLoopWrap(spawn10, maxIter) {
5376
- let last = "";
5377
- let sessionId;
5378
- for (let i = 0; i < maxIter; i++) {
5379
- last = await spawn10(sessionId, (id) => {
5380
- sessionId = id;
5381
- });
5382
- if (isComplete(last)) return last;
5383
- }
5384
- throw new MaxIterationsExceededError(maxIter);
5385
- }
5386
- var MaxIterationsExceededError;
5387
- var init_ralphLoop = __esm({
5388
- "src/workflow/lib/ralphLoop.ts"() {
5389
- init_promiseExtract();
5390
- init_fallbackHandlers();
5391
- MaxIterationsExceededError = class extends Error {
5392
- constructor(iterations) {
5393
- super(`ralph-loop max-iterations exceeded after ${iterations} attempts`);
5394
- this.iterations = iterations;
5395
- this.name = "MaxIterationsExceededError";
5396
- }
5397
- iterations;
5398
- };
5399
- }
5400
- });
5401
-
5402
- // src/checkpoint/completionClaim.ts
5403
- var completionClaim_exports = {};
5404
- __export(completionClaim_exports, {
5405
- verifyCompletionClaim: () => verifyCompletionClaim
5406
- });
5407
- async function verifyCompletionClaim(input) {
5408
- if (input.resultFile) {
5409
- let text;
5410
- try {
5411
- text = await readFile(input.resultFile, "utf8");
5412
- } catch {
5413
- return { verdict: "incomplete", source: input.resultFile };
5414
- }
5415
- return { verdict: isComplete(text) ? "complete" : "incomplete", source: input.resultFile };
5416
- }
5417
- if (typeof input.result === "string" && input.result.trim() !== "") {
5418
- return { verdict: isComplete(input.result) ? "complete" : "incomplete", source: "--result" };
5419
- }
5420
- return { verdict: "not_provided", source: null };
5421
- }
5422
- var init_completionClaim = __esm({
5423
- "src/checkpoint/completionClaim.ts"() {
5424
- init_ralphLoop();
6021
+ execFileP = promisify(execFile);
6022
+ TDD_EVIDENCE_ARTIFACT = "tdd-evidence.md";
6023
+ RED_MARKER = /\b(red|fail(?:s|ed|ing|ure)?)\b/i;
6024
+ GREEN_MARKER = /\b(green|pass(?:es|ed|ing)?)\b/i;
6025
+ SKIP_DECLARATION = /\bSKIPPED\b\s*[—–:-]\s*\S+/i;
6026
+ SCOPE = ["--", "."];
6027
+ ASSERTION_TOKEN = /\b(expect|assert\w*|should|toBe\w*|toEqual|toThrow|toMatch)\b|\.to\./;
5425
6028
  }
5426
6029
  });
5427
6030
 
@@ -6513,6 +7116,8 @@ var init_intentKind = __esm({
6513
7116
  // src/cli/checkpoint.ts
6514
7117
  var checkpoint_exports = {};
6515
7118
  __export(checkpoint_exports, {
7119
+ parsePlan: () => parsePlan,
7120
+ parseWaitSeconds: () => parseWaitSeconds,
6516
7121
  registerCheckpoint: () => registerCheckpoint,
6517
7122
  runCheckpointAdopt: () => runCheckpointAdopt,
6518
7123
  runCheckpointComplete: () => runCheckpointComplete,
@@ -6542,7 +7147,18 @@ async function parsePlan(raw) {
6542
7147
  };
6543
7148
  if (typeof p8.master === "string") plan.master = p8.master;
6544
7149
  if (p8.parallelism && typeof p8.parallelism === "object" && !Array.isArray(p8.parallelism)) {
6545
- plan.parallelism = p8.parallelism;
7150
+ const par = p8.parallelism;
7151
+ const parallelism = {
7152
+ escalate_to_teams: typeof par.escalate_to_teams === "boolean" ? par.escalate_to_teams : false,
7153
+ reason: typeof par.reason === "string" ? par.reason : null
7154
+ };
7155
+ if (typeof par.teams_active === "boolean") parallelism.teams_active = par.teams_active;
7156
+ if (par.transport === "subagent" || par.transport === "teammate") {
7157
+ parallelism.transport = par.transport;
7158
+ }
7159
+ if (par.result_contract === "result-file") parallelism.result_contract = par.result_contract;
7160
+ if (typeof par.bounded_wait === "boolean") parallelism.bounded_wait = par.bounded_wait;
7161
+ plan.parallelism = parallelism;
6546
7162
  }
6547
7163
  return plan;
6548
7164
  }
@@ -6586,6 +7202,28 @@ function enforceSerialOrder(action, sub, blockers, force, deps = defaultRunDeps)
6586
7202
  );
6587
7203
  return true;
6588
7204
  }
7205
+ function parseWaitSeconds(raw) {
7206
+ if (raw === void 0) return null;
7207
+ const trimmed = raw.trim();
7208
+ if (!/^\d+$/.test(trimmed)) return null;
7209
+ const seconds = Number(trimmed);
7210
+ if (!Number.isInteger(seconds) || seconds < 0 || seconds > RESULT_WAIT_MAX_SECONDS) return null;
7211
+ return seconds;
7212
+ }
7213
+ function sleep2(ms) {
7214
+ return new Promise((resolve42) => setTimeout(resolve42, ms));
7215
+ }
7216
+ async function waitForResultClaim(resultFile, seconds, pollMs) {
7217
+ const { verifyCompletionClaim: verifyCompletionClaim2 } = await Promise.resolve().then(() => (init_completionClaim(), completionClaim_exports));
7218
+ const deadline = Date.now() + seconds * 1e3;
7219
+ for (; ; ) {
7220
+ const claim = await verifyCompletionClaim2({ resultFile });
7221
+ if (claim.verdict === "complete") return true;
7222
+ const remaining = deadline - Date.now();
7223
+ if (remaining <= 0) return false;
7224
+ await sleep2(Math.min(pollMs, remaining));
7225
+ }
7226
+ }
6589
7227
  async function runCheckpointStart(sub, opts, deps = defaultRunDeps) {
6590
7228
  const { activatePhase: activatePhase2 } = await Promise.resolve().then(() => (init_engineHook(), engineHook_exports));
6591
7229
  try {
@@ -6685,6 +7323,28 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
6685
7323
  deps.exit(1);
6686
7324
  return;
6687
7325
  }
7326
+ const waitSeconds = opts.wait ?? 0;
7327
+ let waitTimeoutMessage;
7328
+ if (waitSeconds > 0) {
7329
+ const resultFile = opts.resultFile;
7330
+ if (!resultFile) {
7331
+ deps.error(
7332
+ "[harnessed] checkpoint complete: --wait \u5FC5\u987B\u642D\u914D --result-file \u2014\u2014 \u6CA1\u6709\u53EF\u7B49\u5F85\u7684\u7ED3\u679C\u6587\u4EF6"
7333
+ );
7334
+ deps.exit(2);
7335
+ return;
7336
+ }
7337
+ const pollMs = opts.waitPollMs ?? RESULT_WAIT_POLL_MS;
7338
+ deps.log(
7339
+ `[harnessed] \u7B49\u5F85 ${waitSeconds}s \u5185 ${resultFile} \u643A\u5E26\u5B8C\u6210\u6807\u8BB0\uFF08\u6BCF ${pollMs}ms \u8F6E\u8BE2\u4E00\u6B21\uFF09`
7340
+ );
7341
+ const ready = await waitForResultClaim(resultFile, waitSeconds, pollMs);
7342
+ if (ready) {
7343
+ deps.log(`[harnessed] \u7ED3\u679C\u6587\u4EF6\u5DF2\u5C31\u7EEA: ${resultFile}`);
7344
+ } else {
7345
+ waitTimeoutMessage = `result-wait-timeout: \u7B49\u5F85 ${waitSeconds}s \u540E ${resultFile} \u4ECD\u672A\u643A\u5E26\u5B8C\u6210\u6807\u8BB0\uFF08\u65E2\u6CA1\u6709 verbatim <promise>COMPLETE</promise>\uFF0C\u4E5F\u6CA1\u6709\u7ED3\u6784\u5316 COMPLETE \u72B6\u6001\uFF09`;
7346
+ }
7347
+ }
6688
7348
  const { checkArtifacts: checkArtifacts2 } = await Promise.resolve().then(() => (init_evidence(), evidence_exports));
6689
7349
  const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
6690
7350
  const { getAssetsRoot: getAssetsRoot3 } = await Promise.resolve().then(() => (init_assetsRoot(), assetsRoot_exports));
@@ -6716,7 +7376,19 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
6716
7376
  `\u26A0\uFE0F [harnessed] completion promise unverified for ${sub} \u2014 no --result/--result-file supplied, so the promise gate is unarmed for this completion (artifact + boundary gates still applied).`
6717
7377
  );
6718
7378
  }
6719
- const allMissing = [...result.missing, ...syncResult.missing, ...boundaryBlocks, ...claimBlocks];
7379
+ const waitBlocks = waitTimeoutMessage !== void 0 ? [waitTimeoutMessage] : [];
7380
+ const allMissing = [
7381
+ ...result.missing,
7382
+ ...syncResult.missing,
7383
+ ...boundaryBlocks,
7384
+ ...claimBlocks,
7385
+ ...waitBlocks
7386
+ ];
7387
+ if (waitTimeoutMessage !== void 0 && opts.force) {
7388
+ deps.warn(
7389
+ `[harnessed] checkpoint complete ${waitTimeoutMessage}\uFF08--force: \u5DF2\u8BB0\u4E3A audited override\uFF09`
7390
+ );
7391
+ }
6720
7392
  if (allMissing.length > 0 && !opts.force) {
6721
7393
  deps.error(
6722
7394
  `[harnessed] checkpoint complete BLOCKED: ${sub} \u2014 ${allMissing.length} item(s) missing (evidence guard + .planning/ sync, fail-closed):`
@@ -7081,6 +7753,9 @@ function registerCheckpoint(program2) {
7081
7753
  ).option(
7082
7754
  "--result-file <path>",
7083
7755
  "complete only \u2014 same as --result but read from a file (quoting-safe on Windows); wins over --result"
7756
+ ).option(
7757
+ "--wait <seconds>",
7758
+ `complete only \u2014 bounded wait (integer seconds, 0..${RESULT_WAIT_MAX_SECONDS}) for --result-file to carry the completion marker (polled every 2s); on timeout the completion fails closed with result-wait-timeout`
7084
7759
  ).option(
7085
7760
  "--reason <text>",
7086
7761
  "reopen only \u2014 why the sub is coming back (required); recorded on the ledger entry and surfaced by the per-turn injector"
@@ -7102,6 +7777,13 @@ function registerCheckpoint(program2) {
7102
7777
  process.exit(1);
7103
7778
  return;
7104
7779
  }
7780
+ if (opts.wait !== void 0 && action !== "complete") {
7781
+ console.error(
7782
+ `[harnessed] checkpoint ${action}: --wait \u53EA\u5BF9 \`checkpoint complete\` \u6709\u6548`
7783
+ );
7784
+ process.exit(2);
7785
+ return;
7786
+ }
7105
7787
  if (action === "adopt") {
7106
7788
  await runCheckpointAdopt(opts);
7107
7789
  return;
@@ -7149,7 +7831,33 @@ function registerCheckpoint(program2) {
7149
7831
  return;
7150
7832
  }
7151
7833
  if (action === "complete") {
7152
- await runCheckpointComplete(sub, opts);
7834
+ let waitSeconds;
7835
+ if (opts.wait !== void 0) {
7836
+ const parsed = parseWaitSeconds(opts.wait);
7837
+ if (parsed === null) {
7838
+ console.error(
7839
+ `[harnessed] checkpoint complete: --wait \u53D6\u503C\u65E0\u6548 "${opts.wait}" \u2014\u2014 \u9700\u8981 0..${RESULT_WAIT_MAX_SECONDS} \u4E4B\u95F4\u7684\u6574\u6570\u79D2`
7840
+ );
7841
+ process.exit(2);
7842
+ return;
7843
+ }
7844
+ if (!opts.resultFile) {
7845
+ console.error(
7846
+ "[harnessed] checkpoint complete: --wait \u5FC5\u987B\u642D\u914D --result-file \u2014\u2014 \u6CA1\u6709\u53EF\u7B49\u5F85\u7684\u7ED3\u679C\u6587\u4EF6"
7847
+ );
7848
+ process.exit(2);
7849
+ return;
7850
+ }
7851
+ waitSeconds = parsed;
7852
+ }
7853
+ await runCheckpointComplete(sub, {
7854
+ ...opts.summary !== void 0 ? { summary: opts.summary } : {},
7855
+ ...opts.force !== void 0 ? { force: opts.force } : {},
7856
+ ...opts.tokens !== void 0 ? { tokens: opts.tokens } : {},
7857
+ ...opts.result !== void 0 ? { result: opts.result } : {},
7858
+ ...opts.resultFile !== void 0 ? { resultFile: opts.resultFile } : {},
7859
+ ...waitSeconds !== void 0 ? { wait: waitSeconds } : {}
7860
+ });
7153
7861
  return;
7154
7862
  }
7155
7863
  if (action === "reopen") {
@@ -7160,7 +7868,7 @@ function registerCheckpoint(program2) {
7160
7868
  }
7161
7869
  );
7162
7870
  }
7163
- var ACTIONS;
7871
+ var ACTIONS, RESULT_WAIT_MAX_SECONDS, RESULT_WAIT_POLL_MS;
7164
7872
  var init_checkpoint = __esm({
7165
7873
  "src/cli/checkpoint.ts"() {
7166
7874
  init_path_guard();
@@ -7168,6 +7876,8 @@ var init_checkpoint = __esm({
7168
7876
  init_runDeps();
7169
7877
  init_ledger();
7170
7878
  ACTIONS = ["start", "complete", "fail", "reopen", "intent", "adopt"];
7879
+ RESULT_WAIT_MAX_SECONDS = 600;
7880
+ RESULT_WAIT_POLL_MS = 2e3;
7171
7881
  }
7172
7882
  });
7173
7883
 
@@ -7311,8 +8021,8 @@ function compute(d) {
7311
8021
  }
7312
8022
  const gitFirst = d.where("git")[0];
7313
8023
  if (gitFirst && /git\.exe$/i.test(gitFirst)) {
7314
- const root = dirname12(dirname12(gitFirst));
7315
- for (const cand of [join30(root, "bin", "bash.exe"), join30(root, "usr", "bin", "bash.exe")]) {
8024
+ const root = dirname15(dirname15(gitFirst));
8025
+ for (const cand of [join34(root, "bin", "bash.exe"), join34(root, "usr", "bin", "bash.exe")]) {
7316
8026
  if (d.exists(cand) && usable(cand)) return { path: cand, source: "git-derived", wslOnPath };
7317
8027
  }
7318
8028
  }
@@ -7320,13 +8030,13 @@ function compute(d) {
7320
8030
  d.env.ProgramFiles,
7321
8031
  d.env.ProgramW6432,
7322
8032
  d.env["ProgramFiles(x86)"],
7323
- d.env.LOCALAPPDATA ? join30(d.env.LOCALAPPDATA, "Programs") : void 0
8033
+ d.env.LOCALAPPDATA ? join34(d.env.LOCALAPPDATA, "Programs") : void 0
7324
8034
  ];
7325
8035
  for (const base of bases) {
7326
8036
  if (!base) continue;
7327
8037
  for (const cand of [
7328
- join30(base, "Git", "bin", "bash.exe"),
7329
- join30(base, "Git", "usr", "bin", "bash.exe")
8038
+ join34(base, "Git", "bin", "bash.exe"),
8039
+ join34(base, "Git", "usr", "bin", "bash.exe")
7330
8040
  ]) {
7331
8041
  if (d.exists(cand) && usable(cand))
7332
8042
  return { path: cand, source: "standard-location", wslOnPath };
@@ -7339,10 +8049,10 @@ function compute(d) {
7339
8049
  }
7340
8050
  return { path: "bash", source: "path-fallback" };
7341
8051
  }
7342
- var dirname12, join30, WSL_STUB_RE, cache4;
8052
+ var dirname15, join34, WSL_STUB_RE, cache4;
7343
8053
  var init_resolveBash = __esm({
7344
8054
  "src/installers/lib/resolveBash.ts"() {
7345
- ({ dirname: dirname12, join: join30 } = win32);
8055
+ ({ dirname: dirname15, join: join34 } = win32);
7346
8056
  WSL_STUB_RE = /[\\/](windows[\\/](system32|sysnative|syswow64)|microsoft[\\/]windowsapps)[\\/]bash\.exe$/i;
7347
8057
  cache4 = null;
7348
8058
  }
@@ -7724,21 +8434,39 @@ var init_check_token_budget = __esm({
7724
8434
  PER_SKILL_THRESHOLD = 5e3;
7725
8435
  }
7726
8436
  });
8437
+ function isEnabledValue(value) {
8438
+ if (typeof value !== "string") return false;
8439
+ const normalized2 = value.trim().toLowerCase();
8440
+ return normalized2 === "1" || normalized2 === "true";
8441
+ }
8442
+ function resolveAgentTeamsStatus(input) {
8443
+ const { envValue, settingsValue } = input;
8444
+ const envOn = isEnabledValue(envValue);
8445
+ const settingsOn = isEnabledValue(settingsValue);
8446
+ const status = {
8447
+ active: envOn || settingsOn,
8448
+ source: envOn ? "env" : settingsOn ? "settings" : "none"
8449
+ };
8450
+ if (envValue !== void 0) status.envValue = envValue;
8451
+ if (settingsValue !== void 0) status.settingsValue = settingsValue;
8452
+ return status;
8453
+ }
7727
8454
  async function checkAgentTeams() {
7728
8455
  const envValue = process.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS;
7729
- const envOn = envValue === "1";
7730
8456
  let settingsValue;
7731
- let settingsOn = false;
7732
8457
  try {
7733
8458
  const path = getSettingsPath();
7734
8459
  const raw = path === null ? "{}" : await readFile(path, "utf8");
7735
8460
  const data = JSON.parse(raw);
7736
8461
  settingsValue = data.env?.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS;
7737
- settingsOn = settingsValue === "1";
7738
8462
  } catch {
7739
8463
  }
7740
- const detected = { env: envOn, settingsJson: settingsOn };
7741
- if (envOn || settingsOn) {
8464
+ const detected = {
8465
+ env: isEnabledValue(envValue),
8466
+ settingsJson: isEnabledValue(settingsValue)
8467
+ };
8468
+ const status = resolveAgentTeamsStatus({ envValue, settingsValue });
8469
+ if (status.active) {
7742
8470
  return { status: "pass", detected, envValue, settingsValue };
7743
8471
  }
7744
8472
  return {
@@ -7791,6 +8519,123 @@ var init_check_agent_teams_doctor = __esm({
7791
8519
  }
7792
8520
  });
7793
8521
 
8522
+ // src/platform/runtime.ts
8523
+ function isBunRuntime(versions = process.versions, compiled) {
8524
+ return typeof versions.bun === "string" && versions.bun.trim().length > 0 && !(compiled ?? isCompiledRuntime());
8525
+ }
8526
+ function bunExecutable() {
8527
+ return isBunRuntime() ? process.execPath : process.platform === "win32" ? "bun.exe" : "bun";
8528
+ }
8529
+ var init_runtime = __esm({
8530
+ "src/platform/runtime.ts"() {
8531
+ init_assetsRoot();
8532
+ }
8533
+ });
8534
+
8535
+ // src/cli/lib/version-check.ts
8536
+ var version_check_exports = {};
8537
+ __export(version_check_exports, {
8538
+ compareVersionNames: () => compareVersionNames,
8539
+ compareVersions: () => compareVersions,
8540
+ fetchLatestBunVersion: () => fetchLatestBunVersion,
8541
+ fetchLatestNpmVersion: () => fetchLatestNpmVersion,
8542
+ fetchLatestVersion: () => fetchLatestVersion
8543
+ });
8544
+ function parse3(v) {
8545
+ const m = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(v.trim());
8546
+ if (!m) return null;
8547
+ return { nums: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] ?? null };
8548
+ }
8549
+ function compareVersions(installed2, latest) {
8550
+ const a = parse3(installed2);
8551
+ const b = parse3(latest);
8552
+ if (!a || !b) return "unknown";
8553
+ for (let i = 0; i < 3; i++) {
8554
+ const ai = a.nums[i] ?? 0;
8555
+ const bi = b.nums[i] ?? 0;
8556
+ if (ai < bi) return "behind";
8557
+ if (ai > bi) return "ahead";
8558
+ }
8559
+ if (a.pre && !b.pre) return "behind";
8560
+ if (!a.pre && b.pre) return "ahead";
8561
+ if (a.pre && b.pre && a.pre !== b.pre) return a.pre < b.pre ? "behind" : "ahead";
8562
+ return "current";
8563
+ }
8564
+ function compareVersionNames(a, b) {
8565
+ const relation = compareVersions(a, b);
8566
+ if (relation === "ahead") return 1;
8567
+ if (relation === "behind") return -1;
8568
+ if (relation === "current") return 0;
8569
+ const segments = (v) => v.split(".").map((part) => {
8570
+ const n = Number.parseInt(part, 10);
8571
+ return Number.isNaN(n) ? 0 : n;
8572
+ });
8573
+ const as = segments(a);
8574
+ const bs = segments(b);
8575
+ for (let i = 0; i < Math.max(as.length, bs.length); i++) {
8576
+ const diff = (as[i] ?? 0) - (bs[i] ?? 0);
8577
+ if (diff !== 0) return diff;
8578
+ }
8579
+ return 0;
8580
+ }
8581
+ function npmExecutable() {
8582
+ return process.platform === "win32" ? "npm.cmd" : "npm";
8583
+ }
8584
+ async function defaultRunner() {
8585
+ if (process.platform === "win32") {
8586
+ const { stdout: stdout3 } = await execAsync("npm view harnessed version", {
8587
+ timeout: 8e3,
8588
+ windowsHide: true
8589
+ });
8590
+ return stdout3;
8591
+ }
8592
+ const { stdout: stdout2 } = await execFileAsync(npmExecutable(), ["view", "harnessed", "version"], {
8593
+ timeout: 8e3,
8594
+ windowsHide: true
8595
+ });
8596
+ return stdout2;
8597
+ }
8598
+ async function fetchLatestVersion(runner) {
8599
+ try {
8600
+ if (runner !== void 0) return await fetchLatestNpmVersion(runner);
8601
+ return isBunRuntime() ? await fetchLatestBunVersion() : await fetchLatestNpmVersion();
8602
+ } catch {
8603
+ return null;
8604
+ }
8605
+ }
8606
+ async function fetchLatestNpmVersion(runner = defaultRunner) {
8607
+ try {
8608
+ const out = (await runner()).trim();
8609
+ return /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(out) ? out : null;
8610
+ } catch {
8611
+ return null;
8612
+ }
8613
+ }
8614
+ async function defaultBunRunner() {
8615
+ const { stdout: stdout2 } = await execFileAsync(
8616
+ bunExecutable(),
8617
+ ["info", "harnessed@latest", "version", "--json"],
8618
+ { timeout: 8e3, windowsHide: true, shell: false }
8619
+ );
8620
+ return stdout2;
8621
+ }
8622
+ async function fetchLatestBunVersion(runner = defaultBunRunner) {
8623
+ try {
8624
+ const version = JSON.parse(await runner());
8625
+ return typeof version === "string" && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version) ? version : null;
8626
+ } catch {
8627
+ return null;
8628
+ }
8629
+ }
8630
+ var execFileAsync, execAsync;
8631
+ var init_version_check = __esm({
8632
+ "src/cli/lib/version-check.ts"() {
8633
+ init_runtime();
8634
+ execFileAsync = promisify(execFile);
8635
+ execAsync = promisify(exec);
8636
+ }
8637
+ });
8638
+
7794
8639
  // src/cli/lib/check-planning-with-files.ts
7795
8640
  var check_planning_with_files_exports = {};
7796
8641
  __export(check_planning_with_files_exports, {
@@ -7833,15 +8678,15 @@ async function checkPlanningWithFiles() {
7833
8678
  );
7834
8679
  try {
7835
8680
  const entries = await readdir(root, { withFileTypes: true });
7836
- for (const version of entries) {
7837
- if (!version.isDirectory() || !/^\d+\.\d+/.test(version.name)) continue;
7838
- const versionRoot = join(root, version.name);
8681
+ const versions = entries.filter((entry) => entry.isDirectory() && /^\d+\.\d+/.test(entry.name)).map((entry) => entry.name).sort((a, b) => compareVersionNames(b, a));
8682
+ for (const version of versions) {
8683
+ const versionRoot = join(root, version);
7839
8684
  for (const candidate of [join(versionRoot, "skills", "planning-with-files"), versionRoot]) {
7840
8685
  if (await hasPlanningContent(candidate)) {
7841
8686
  return {
7842
8687
  name: "planning-with-files plugin",
7843
8688
  status: "pass",
7844
- message: `local planning-with-files content detected (version ${version.name}; SKILL.md, scripts and templates); runtime execution not verified`
8689
+ message: `local planning-with-files content detected (version ${version}; SKILL.md, scripts and templates); runtime execution not verified`
7845
8690
  };
7846
8691
  }
7847
8692
  }
@@ -7867,6 +8712,7 @@ var REMEDIATION, INSTALL_COMMANDS;
7867
8712
  var init_check_planning_with_files = __esm({
7868
8713
  "src/cli/lib/check-planning-with-files.ts"() {
7869
8714
  init_platform();
8715
+ init_version_check();
7870
8716
  REMEDIATION = "install via `claude plugin marketplace add OthmanAdi/planning-with-files && claude plugin install planning-with-files` (requires >=2.2.0 per R20.15 + D-15)";
7871
8717
  INSTALL_COMMANDS = [
7872
8718
  "claude plugin marketplace add OthmanAdi/planning-with-files",
@@ -7918,9 +8764,9 @@ async function checkMattpocockSkills() {
7918
8764
  if (getPluginsRegistry() !== null) {
7919
8765
  try {
7920
8766
  const entries = await readdir(pluginRoot, { withFileTypes: true });
7921
- for (const version of entries) {
7922
- if (!version.isDirectory() || !/^\d+\.\d+/.test(version.name)) continue;
7923
- const root = join(pluginRoot, version.name, "skills");
8767
+ const versions = entries.filter((entry) => entry.isDirectory() && /^\d+\.\d+/.test(entry.name)).map((entry) => entry.name).sort((a, b) => compareVersionNames(b, a));
8768
+ for (const version of versions) {
8769
+ const root = join(pluginRoot, version, "skills");
7924
8770
  const indicator = await findIndicator(root);
7925
8771
  if (indicator) return contentDetected(indicator, root);
7926
8772
  }
@@ -7949,6 +8795,7 @@ var REMEDIATION2, INDICATORS;
7949
8795
  var init_check_mattpocock_skills = __esm({
7950
8796
  "src/cli/lib/check-mattpocock-skills.ts"() {
7951
8797
  init_platform();
8798
+ init_version_check();
7952
8799
  REMEDIATION2 = "install via `npx skills@latest add mattpocock/skills` (or git clone https://github.com/mattpocock/skills ~/.claude/skills/mattpocock-skills); methodology fallback already inline in role-prompts.yaml per v3.6.0 Phase 1 \u2014 install is optional but enables /grill-with-docs /tdd /diagnosing-bugs etc. SlashCommand acceleration";
7953
8800
  INDICATORS = ["tdd", "diagnosing-bugs", "grill-with-docs", "diagnose"];
7954
8801
  }
@@ -8384,112 +9231,13 @@ async function checkSkillIntegrity() {
8384
9231
  } catch {
8385
9232
  return { name, status: "pass", message: "skipped (environment not auditable)" };
8386
9233
  }
8387
- }
8388
- var init_check_skill_integrity = __esm({
8389
- "src/cli/lib/check-skill-integrity.ts"() {
8390
- init_assetsRoot();
8391
- init_platform();
8392
- init_scan_nested();
8393
- init_skillIntegrity();
8394
- }
8395
- });
8396
-
8397
- // src/platform/runtime.ts
8398
- function isBunRuntime(versions = process.versions, compiled) {
8399
- return typeof versions.bun === "string" && versions.bun.trim().length > 0 && !(compiled ?? isCompiledRuntime());
8400
- }
8401
- function bunExecutable() {
8402
- return isBunRuntime() ? process.execPath : process.platform === "win32" ? "bun.exe" : "bun";
8403
- }
8404
- var init_runtime = __esm({
8405
- "src/platform/runtime.ts"() {
8406
- init_assetsRoot();
8407
- }
8408
- });
8409
-
8410
- // src/cli/lib/version-check.ts
8411
- var version_check_exports = {};
8412
- __export(version_check_exports, {
8413
- compareVersions: () => compareVersions,
8414
- fetchLatestBunVersion: () => fetchLatestBunVersion,
8415
- fetchLatestNpmVersion: () => fetchLatestNpmVersion,
8416
- fetchLatestVersion: () => fetchLatestVersion
8417
- });
8418
- function parse3(v) {
8419
- const m = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(v.trim());
8420
- if (!m) return null;
8421
- return { nums: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] ?? null };
8422
- }
8423
- function compareVersions(installed2, latest) {
8424
- const a = parse3(installed2);
8425
- const b = parse3(latest);
8426
- if (!a || !b) return "unknown";
8427
- for (let i = 0; i < 3; i++) {
8428
- const ai = a.nums[i] ?? 0;
8429
- const bi = b.nums[i] ?? 0;
8430
- if (ai < bi) return "behind";
8431
- if (ai > bi) return "ahead";
8432
- }
8433
- if (a.pre && !b.pre) return "behind";
8434
- if (!a.pre && b.pre) return "ahead";
8435
- if (a.pre && b.pre && a.pre !== b.pre) return a.pre < b.pre ? "behind" : "ahead";
8436
- return "current";
8437
- }
8438
- function npmExecutable() {
8439
- return process.platform === "win32" ? "npm.cmd" : "npm";
8440
- }
8441
- async function defaultRunner() {
8442
- if (process.platform === "win32") {
8443
- const { stdout: stdout3 } = await execAsync("npm view harnessed version", {
8444
- timeout: 8e3,
8445
- windowsHide: true
8446
- });
8447
- return stdout3;
8448
- }
8449
- const { stdout: stdout2 } = await execFileAsync(npmExecutable(), ["view", "harnessed", "version"], {
8450
- timeout: 8e3,
8451
- windowsHide: true
8452
- });
8453
- return stdout2;
8454
- }
8455
- async function fetchLatestVersion(runner) {
8456
- try {
8457
- if (runner !== void 0) return await fetchLatestNpmVersion(runner);
8458
- return isBunRuntime() ? await fetchLatestBunVersion() : await fetchLatestNpmVersion();
8459
- } catch {
8460
- return null;
8461
- }
8462
- }
8463
- async function fetchLatestNpmVersion(runner = defaultRunner) {
8464
- try {
8465
- const out = (await runner()).trim();
8466
- return /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(out) ? out : null;
8467
- } catch {
8468
- return null;
8469
- }
8470
- }
8471
- async function defaultBunRunner() {
8472
- const { stdout: stdout2 } = await execFileAsync(
8473
- bunExecutable(),
8474
- ["info", "harnessed@latest", "version", "--json"],
8475
- { timeout: 8e3, windowsHide: true, shell: false }
8476
- );
8477
- return stdout2;
8478
- }
8479
- async function fetchLatestBunVersion(runner = defaultBunRunner) {
8480
- try {
8481
- const version = JSON.parse(await runner());
8482
- return typeof version === "string" && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version) ? version : null;
8483
- } catch {
8484
- return null;
8485
- }
8486
- }
8487
- var execFileAsync, execAsync;
8488
- var init_version_check = __esm({
8489
- "src/cli/lib/version-check.ts"() {
8490
- init_runtime();
8491
- execFileAsync = promisify(execFile);
8492
- execAsync = promisify(exec);
9234
+ }
9235
+ var init_check_skill_integrity = __esm({
9236
+ "src/cli/lib/check-skill-integrity.ts"() {
9237
+ init_assetsRoot();
9238
+ init_platform();
9239
+ init_scan_nested();
9240
+ init_skillIntegrity();
8493
9241
  }
8494
9242
  });
8495
9243
 
@@ -9761,7 +10509,7 @@ async function withAppServer(deps, body) {
9761
10509
  const call = (method, params) => {
9762
10510
  if (closed) return Promise.reject(closed);
9763
10511
  const id = nextId++;
9764
- return new Promise((resolve40, reject) => {
10512
+ return new Promise((resolve42, reject) => {
9765
10513
  const timer = setTimeout(() => {
9766
10514
  pending.delete(id);
9767
10515
  reject(new RpcError("timeout", `${method} timed out after ${timeoutMs}ms`));
@@ -9769,7 +10517,7 @@ async function withAppServer(deps, body) {
9769
10517
  pending.set(id, {
9770
10518
  resolve: (v) => {
9771
10519
  clearTimeout(timer);
9772
- resolve40(v);
10520
+ resolve42(v);
9773
10521
  },
9774
10522
  reject: (e) => {
9775
10523
  clearTimeout(timer);
@@ -11235,7 +11983,7 @@ function realSpawn(req) {
11235
11983
  };
11236
11984
  }
11237
11985
  function runOnce(req, spawnFn, timeoutMs, onThreadId) {
11238
- return new Promise((resolve40, reject) => {
11986
+ return new Promise((resolve42, reject) => {
11239
11987
  const events = [];
11240
11988
  let garbageLines = 0;
11241
11989
  let stderr = "";
@@ -11256,7 +12004,7 @@ function runOnce(req, spawnFn, timeoutMs, onThreadId) {
11256
12004
  if (settled || !exited || openStreams > 0) return;
11257
12005
  settled = true;
11258
12006
  clearTimeout(timer);
11259
- resolve40({ exitCode: exited.code, signal: exited.signal, events, garbageLines, stderr });
12007
+ resolve42({ exitCode: exited.code, signal: exited.signal, events, garbageLines, stderr });
11260
12008
  };
11261
12009
  const fail2 = (err2) => {
11262
12010
  if (settled) return;
@@ -12650,6 +13398,25 @@ var init_capabilityResolver = __esm({
12650
13398
  CAPABILITY_CMD_TEMPLATE = /\{\{\s*capabilities\.([a-zA-Z0-9_-]+)\.cmd\s*\}\}/g;
12651
13399
  }
12652
13400
  });
13401
+ function resultArtifactScope(cwd = process.cwd()) {
13402
+ const base = repoKey(cwd);
13403
+ const key = activeKey(cwd);
13404
+ const composite = key === base ? `${base}::${NO_SESSION}` : key;
13405
+ return createHash("sha256").update(composite, "utf8").digest("hex").slice(0, SCOPE_HEX_LEN);
13406
+ }
13407
+ function resultArtifactPath(sub, cwd = process.cwd()) {
13408
+ checkSafeSegment(sub);
13409
+ return resolve(cwd, ".harnessed", "results", resultArtifactScope(cwd), `${sub}.md`);
13410
+ }
13411
+ var SCOPE_HEX_LEN, NO_SESSION;
13412
+ var init_resultArtifact = __esm({
13413
+ "src/cli/lib/resultArtifact.ts"() {
13414
+ init_workflowStore();
13415
+ init_path_guard();
13416
+ SCOPE_HEX_LEN = 8;
13417
+ NO_SESSION = "nosession";
13418
+ }
13419
+ });
12653
13420
  function userLangPinPath(hostContext) {
12654
13421
  return join(hostContext?.platform.stateRoot ?? detectPlatform().stateRoot, USER_LANG_PIN);
12655
13422
  }
@@ -12814,6 +13581,19 @@ Respond in ${name}.
12814
13581
  ${preserve}
12815
13582
  `;
12816
13583
  }
13584
+ function buildResultDeliverySection(resultFile) {
13585
+ return `
13586
+ ## Result delivery
13587
+ Write your final result to this exact absolute path:
13588
+ ${resultFile}
13589
+
13590
+ Rules:
13591
+ - The file MUST contain your final result AND the verbatim line \`<promise>COMPLETE</promise>\`.
13592
+ - The orchestrator reads THIS FILE as the completion signal. Do NOT rely on your final chat message being delivered \u2014 a background or re-parented agent's message may never arrive.
13593
+ - The file is polled while you write it: create the parent directory if it does not exist, then write the file in one shot (write a temp file next to it, then rename over it) \u2014 a half-written file reads as "not complete yet".
13594
+ - If you cannot write the file, say so explicitly in your final message and name the blocker. Never claim a completion you did not deliver.
13595
+ `;
13596
+ }
12817
13597
  async function resolveMaxIterations2(sub, packageRoot) {
12818
13598
  try {
12819
13599
  const path = resolve(packageRoot, "workflows", "defaults.yaml");
@@ -12852,17 +13632,22 @@ ${opts.task}
12852
13632
  const toolsSection = await buildToolsSection(sub, packageRoot, host);
12853
13633
  const disciplinesSection = await buildDisciplinesSection(sub, packageRoot, locale);
12854
13634
  const languageSection = await buildLanguageSection(packageRoot, host);
13635
+ const resultDeliverySection = opts.resultFile ? buildResultDeliverySection(opts.resultFile) : "";
12855
13636
  return {
12856
13637
  prompt: `${taskSection}${body}
12857
- ${toolsSection}${disciplinesSection}${PROTOCOLS}${languageSection}`,
13638
+ ${toolsSection}${disciplinesSection}${PROTOCOLS}${resultDeliverySection}${languageSection}`,
12858
13639
  model: def.model ?? DEFAULT_MODEL,
12859
- specialist: rolePrompts[sub]?.specialist ?? DEFAULT_SPECIALIST
13640
+ specialist: rolePrompts[sub]?.specialist ?? DEFAULT_SPECIALIST,
13641
+ ...opts.resultFile !== void 0 ? { resultFile: opts.resultFile } : {}
12860
13642
  };
12861
13643
  }
12862
13644
  function registerPrompt(program2) {
12863
13645
  program2.command("prompt").description(
12864
13646
  "Print a spawn-ready prompt for a sub-workflow (role + checklist + protocols, no spawn)."
12865
- ).argument("<sub>", "sub-workflow name (e.g. task-code, verify-paranoid)").option("--task <text>", "task description prepended as a ## Task section").option("--json", "emit JSON {prompt, max_iterations, model, specialist} instead of text").action(async (sub, raw) => {
13647
+ ).argument("<sub>", "sub-workflow name (e.g. task-code, verify-paranoid)").option("--task <text>", "task description prepended as a ## Task section").option(
13648
+ "--json",
13649
+ "emit JSON {prompt, max_iterations, model, specialist, result_file} instead of text"
13650
+ ).action(async (sub, raw) => {
12866
13651
  try {
12867
13652
  checkSafeSegment(sub);
12868
13653
  } catch {
@@ -12871,12 +13656,14 @@ function registerPrompt(program2) {
12871
13656
  return;
12872
13657
  }
12873
13658
  const packageRoot = getAssetsRoot();
13659
+ const resultFile = resultArtifactPath(sub, process.cwd());
12874
13660
  const {
12875
13661
  prompt: fullPrompt,
12876
13662
  model,
12877
13663
  specialist
12878
13664
  } = await buildPromptText(sub, packageRoot, {
12879
- ...typeof raw.task === "string" ? { task: raw.task } : {}
13665
+ ...typeof raw.task === "string" ? { task: raw.task } : {},
13666
+ resultFile
12880
13667
  });
12881
13668
  if (raw.json) {
12882
13669
  const maxIterations = await resolveMaxIterations2(sub, packageRoot);
@@ -12885,7 +13672,8 @@ function registerPrompt(program2) {
12885
13672
  prompt: fullPrompt,
12886
13673
  max_iterations: maxIterations,
12887
13674
  model,
12888
- specialist
13675
+ specialist,
13676
+ result_file: resultFile
12889
13677
  })
12890
13678
  );
12891
13679
  process.exit(0);
@@ -12907,6 +13695,7 @@ var init_prompt = __esm({
12907
13695
  init_run();
12908
13696
  init_capabilityResolver();
12909
13697
  init_hostPrimitives();
13698
+ init_resultArtifact();
12910
13699
  init_rolePromptHostRender();
12911
13700
  init_userLangPin();
12912
13701
  DEFAULT_MAX_ITERATIONS = 20;
@@ -13219,19 +14008,41 @@ async function runGatesPlan(master, raw, deps = defaultRunDeps) {
13219
14008
  clauses.map((c) => c.sub),
13220
14009
  (m) => deps.warn(m)
13221
14010
  );
13222
- let parallelism = { escalate_to_teams: false, reason: null };
14011
+ const teamProbe = await checkAgentTeams();
14012
+ const teamsActive = resolveAgentTeamsStatus({
14013
+ envValue: teamProbe.envValue,
14014
+ settingsValue: teamProbe.settingsValue
14015
+ }).active;
14016
+ const parallelismContract = {
14017
+ teams_active: teamsActive,
14018
+ result_contract: "result-file",
14019
+ bounded_wait: true
14020
+ };
14021
+ const parallelismBlock = (escalate, reason) => ({
14022
+ escalate_to_teams: escalate,
14023
+ reason,
14024
+ ...parallelismContract,
14025
+ transport: escalate ? "teammate" : "subagent"
14026
+ });
14027
+ let parallelism;
13223
14028
  const hl = detectHeadless(process.env, Boolean(process.stdout.isTTY));
13224
14029
  if (hl.headless) {
13225
- parallelism = {
13226
- escalate_to_teams: false,
13227
- reason: "headless mode \u2014 Agent Teams are session-scoped, incompatible with -p (issue #7)"
13228
- };
14030
+ parallelism = parallelismBlock(
14031
+ false,
14032
+ "headless mode \u2014 Agent Teams are session-scoped, incompatible with -p (issue #7)"
14033
+ );
13229
14034
  } else {
13230
14035
  try {
13231
14036
  const escalate = await resolveJudgmentGate(PARALLELISM_GATE, ctx, packageRoot);
13232
- parallelism = escalate ? { escalate_to_teams: true, reason: "agent-teams-upgrade gate fired" } : { escalate_to_teams: false, reason: null };
14037
+ if (!escalate) {
14038
+ parallelism = parallelismBlock(false, null);
14039
+ } else if (!teamsActive) {
14040
+ parallelism = parallelismBlock(false, "agent-teams \u672A\u542F\u7528\uFF0C\u4E0D\u80FD\u6210\u56E2\uFF0C\u6539\u7528 subagent fan-out");
14041
+ } else {
14042
+ parallelism = parallelismBlock(true, "agent-teams-upgrade gate fired");
14043
+ }
13233
14044
  } catch {
13234
- parallelism = { escalate_to_teams: false, reason: null };
14045
+ parallelism = parallelismBlock(false, null);
13235
14046
  }
13236
14047
  }
13237
14048
  const result = { master, fire, skip, parallelism };
@@ -13283,6 +14094,7 @@ var init_gates = __esm({
13283
14094
  init_judgmentResolver();
13284
14095
  init_skipGate();
13285
14096
  init_skipSubs();
14097
+ init_checkAgentTeams();
13286
14098
  init_detectHeadless();
13287
14099
  init_gateContext();
13288
14100
  GATE_MASTERS = ["auto", "discuss", "plan", "task", "verify", "ship"];
@@ -13440,6 +14252,7 @@ async function runScenarioDir(dir, opts) {
13440
14252
  const prevRoot = process.env.HARNESSED_ROOT_OVERRIDE;
13441
14253
  const prevAssets = process.env.HARNESSED_ASSETS_OVERRIDE;
13442
14254
  const prevCeiling = process.env.GIT_CEILING_DIRECTORIES;
14255
+ const prevAgentTeams = process.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS;
13443
14256
  const prevScenarioEnv = /* @__PURE__ */ new Map();
13444
14257
  const steps = [];
13445
14258
  const evaluatedGateRefs = /* @__PURE__ */ new Set();
@@ -13451,6 +14264,7 @@ async function runScenarioDir(dir, opts) {
13451
14264
  process.env[key] = value;
13452
14265
  }
13453
14266
  process.env.GIT_CEILING_DIRECTORIES = tmpdir();
14267
+ process.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = "1";
13454
14268
  process.env.HARNESSED_ROOT_OVERRIDE = stateRoot;
13455
14269
  if (scenario.assets_dir) {
13456
14270
  process.env.HARNESSED_ASSETS_OVERRIDE = isAbsolute(scenario.assets_dir) ? scenario.assets_dir : resolve(dir, scenario.assets_dir);
@@ -13482,6 +14296,8 @@ async function runScenarioDir(dir, opts) {
13482
14296
  else process.env.HARNESSED_ASSETS_OVERRIDE = prevAssets;
13483
14297
  if (prevCeiling === void 0) delete process.env.GIT_CEILING_DIRECTORIES;
13484
14298
  else process.env.GIT_CEILING_DIRECTORIES = prevCeiling;
14299
+ if (prevAgentTeams === void 0) delete process.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS;
14300
+ else process.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = prevAgentTeams;
13485
14301
  for (const [key, prev] of prevScenarioEnv) {
13486
14302
  if (prev === void 0) delete process.env[key];
13487
14303
  else process.env[key] = prev;
@@ -14139,8 +14955,24 @@ async function gcCompiledArtifacts(opts) {
14139
14955
  const dir = dirname(opts.execPath);
14140
14956
  const base = basename(opts.execPath);
14141
14957
  for (const e of await readdir(dir, { withFileTypes: true })) {
14142
- if (!e.isFile() || !e.name.startsWith(`${base}.bak-`)) continue;
14958
+ if (!e.isFile()) continue;
14143
14959
  const p8 = join(dir, e.name);
14960
+ if (e.name.startsWith(`${base}.bak-`)) {
14961
+ removed.push(p8);
14962
+ if (!opts.dryRun) await rm(p8, { force: true });
14963
+ continue;
14964
+ }
14965
+ const fragment = updateFragmentVersion(e.name);
14966
+ if (fragment === null) continue;
14967
+ const relation = compareVersions(fragment, package_default.version);
14968
+ if (relation === "ahead") {
14969
+ kept.push(p8);
14970
+ continue;
14971
+ }
14972
+ if (relation === "unknown") {
14973
+ kept.push(p8);
14974
+ continue;
14975
+ }
14144
14976
  removed.push(p8);
14145
14977
  if (!opts.dryRun) await rm(p8, { force: true });
14146
14978
  }
@@ -14149,6 +14981,10 @@ async function gcCompiledArtifacts(opts) {
14149
14981
  }
14150
14982
  return { removed, kept };
14151
14983
  }
14984
+ function updateFragmentVersion(name) {
14985
+ const match = /^\.harnessed-update-(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?:\.part|\.[A-Za-z0-9]+)?$/.exec(name);
14986
+ return match?.[1] ?? null;
14987
+ }
14152
14988
  function parseDuration(s) {
14153
14989
  const m = DURATION_RE.exec(s);
14154
14990
  if (!m) return null;
@@ -14478,8 +15314,9 @@ function resolveCodexHome(hostContext) {
14478
15314
  return env ? env : detectPlatform().homeDir;
14479
15315
  }
14480
15316
  function reminderStateRoot(hostContext) {
14481
- if (!hostContext)
14482
- return resolve(process.env.HARNESSED_ROOT_OVERRIDE || join(resolveCodexHome(), "harnessed"));
15317
+ const override = process.env.HARNESSED_ROOT_OVERRIDE?.trim();
15318
+ if (override) return resolve(override);
15319
+ if (!hostContext) return canonicalStateRoot("codex");
14483
15320
  const defaultRoot = join(hostContext.platform.homeDir, "harnessed");
14484
15321
  return resolve(
14485
15322
  hostContext.platform.stateRoot !== defaultRoot ? hostContext.platform.stateRoot : join(hostContext.nativeHome, "harnessed")
@@ -15017,6 +15854,7 @@ var init_codexHookAdd = __esm({
15017
15854
  init_assetsRoot();
15018
15855
  init_platform();
15019
15856
  init_runtime();
15857
+ init_stateRoot();
15020
15858
  init_backup();
15021
15859
  init_codexHookPlugin();
15022
15860
  init_codexHookTrust();
@@ -15655,12 +16493,22 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
15655
16493
  } else {
15656
16494
  const expandedCmd = expandTildeForWindows(cmd, ctx.hostContext?.userHome);
15657
16495
  const expandedArgs = args.map((arg) => expandTildeForWindows(arg, ctx.hostContext?.userHome));
15658
- child = spawn("cmd.exe", ["/c", expandedCmd, ...expandedArgs], {
15659
- cwd,
15660
- env,
15661
- windowsHide: true,
15662
- stdio
15663
- });
16496
+ if (expandedArgs.length === 0) {
16497
+ child = spawn("cmd.exe", ["/c", expandedCmd], {
16498
+ cwd,
16499
+ env,
16500
+ windowsHide: true,
16501
+ stdio,
16502
+ windowsVerbatimArguments: true
16503
+ });
16504
+ } else {
16505
+ child = spawn("cmd.exe", ["/c", expandedCmd, ...expandedArgs], {
16506
+ cwd,
16507
+ env,
16508
+ windowsHide: true,
16509
+ stdio
16510
+ });
16511
+ }
15664
16512
  }
15665
16513
  } else {
15666
16514
  child = spawn("/bin/sh", ["-c", joinedCmd], { cwd, env, stdio });
@@ -15673,10 +16521,10 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
15673
16521
  child.stderr?.setEncoding("utf8").on("data", (chunk) => {
15674
16522
  stderr += chunk;
15675
16523
  });
15676
- return await new Promise((resolve40) => {
16524
+ return await new Promise((resolve42) => {
15677
16525
  const timer = setTimeout(() => {
15678
16526
  killProcessTree(child);
15679
- resolve40({
16527
+ resolve42({
15680
16528
  ok: false,
15681
16529
  phase: "spawn",
15682
16530
  error: {
@@ -15697,7 +16545,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
15697
16545
  child.on("error", (err2) => {
15698
16546
  clearTimeout(timer);
15699
16547
  const bashMissing = triedBash && err2.code === "ENOENT";
15700
- resolve40({
16548
+ resolve42({
15701
16549
  ok: false,
15702
16550
  phase: "spawn",
15703
16551
  error: {
@@ -15712,7 +16560,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
15712
16560
  });
15713
16561
  child.on("close", (code2) => {
15714
16562
  clearTimeout(timer);
15715
- resolve40({ ok: true, exitCode: code2 ?? -1, stdout: stdout2, stderr });
16563
+ resolve42({ ok: true, exitCode: code2 ?? -1, stdout: stdout2, stderr });
15716
16564
  });
15717
16565
  });
15718
16566
  }
@@ -16423,7 +17271,7 @@ function touch(binary, lease, source, scratch, context) {
16423
17271
  if (context) env = withHostInstallEnv(env, context);
16424
17272
  env.GSTACK_LEASE_DIR = shellPath(scratch, context);
16425
17273
  env.GSTACK_LEASE_LOCK_TRIES = "1";
16426
- return new Promise((resolve40, reject) => {
17274
+ return new Promise((resolve42, reject) => {
16427
17275
  const child = execFile(
16428
17276
  binary,
16429
17277
  [
@@ -16452,7 +17300,7 @@ function touch(binary, lease, source, scratch, context) {
16452
17300
  `official lease touch exit ${error.code ?? "unknown"}${error.killed ? " (timeout or termination)" : ""}: ${stderr.trim() || error.message}`
16453
17301
  )
16454
17302
  );
16455
- else resolve40();
17303
+ else resolve42();
16456
17304
  }
16457
17305
  );
16458
17306
  child.stdin?.end();
@@ -16992,7 +17840,7 @@ var init_verifyInstalled = __esm({
16992
17840
  }
16993
17841
  });
16994
17842
  function gitRevParseHead(cwd, timeoutMs = 1e4) {
16995
- return new Promise((resolve40) => {
17843
+ return new Promise((resolve42) => {
16996
17844
  const isWin = process.platform === "win32";
16997
17845
  const child = isWin ? spawn("cmd.exe", ["/c", "git", "rev-parse", "HEAD"], { cwd, windowsHide: true }) : spawn("git", ["rev-parse", "HEAD"], { cwd, shell: false });
16998
17846
  let stdout2 = "";
@@ -17001,15 +17849,15 @@ function gitRevParseHead(cwd, timeoutMs = 1e4) {
17001
17849
  });
17002
17850
  const timer = setTimeout(() => {
17003
17851
  killProcessTree(child);
17004
- resolve40({ sha: "", exit: -1 });
17852
+ resolve42({ sha: "", exit: -1 });
17005
17853
  }, timeoutMs);
17006
17854
  child.on("error", () => {
17007
17855
  clearTimeout(timer);
17008
- resolve40({ sha: "", exit: -1 });
17856
+ resolve42({ sha: "", exit: -1 });
17009
17857
  });
17010
17858
  child.on("close", (code2) => {
17011
17859
  clearTimeout(timer);
17012
- resolve40({ sha: stdout2.trim(), exit: code2 ?? -1 });
17860
+ resolve42({ sha: stdout2.trim(), exit: code2 ?? -1 });
17013
17861
  });
17014
17862
  });
17015
17863
  }
@@ -17397,32 +18245,21 @@ var init_componentPlan = __esm({
17397
18245
  init_verificationEnv();
17398
18246
  }
17399
18247
  });
17400
- function isLockContention(error) {
17401
- return error?.code === "ELOCKED";
17402
- }
17403
- function backoffDelay(attempt) {
17404
- return Math.min(
17405
- INSTALL_OWNERSHIP_LOCK_RETRIES.minTimeout * 2 ** attempt,
17406
- INSTALL_OWNERSHIP_LOCK_RETRIES.maxTimeout
17407
- );
18248
+ function lockTarget3(root) {
18249
+ return join(root, ".ownership.lock");
17408
18250
  }
17409
18251
  async function acquireOwnershipLock(root) {
17410
- for (let attempt = 0; ; attempt += 1) {
17411
- try {
17412
- return await lockfile.lock(root, {
17413
- lockfilePath: join(root, ".ownership.lock"),
17414
- realpath: false,
17415
- stale: 10 * 60 * 1e3,
17416
- // One attempt only — the loop below owns the backoff.
17417
- retries: 0
17418
- });
17419
- } catch (error) {
17420
- if (!isLockContention(error) || attempt >= INSTALL_OWNERSHIP_LOCK_RETRIES.retries) {
17421
- throw error;
17422
- }
17423
- await sleep(backoffDelay(attempt));
17424
- }
17425
- }
18252
+ const target = lockTarget3(root);
18253
+ return acquireWithContentionRetry(
18254
+ () => lockfile.lock(target, {
18255
+ lockfilePath: target,
18256
+ realpath: false,
18257
+ stale: 10 * 60 * 1e3,
18258
+ // One attempt only — the retry loop owns the backoff.
18259
+ retries: 0
18260
+ }),
18261
+ INSTALL_OWNERSHIP_LOCK_RETRIES
18262
+ );
17426
18263
  }
17427
18264
  async function withInstallOwnershipLock(context, work) {
17428
18265
  const root = context.platform.stateRoot;
@@ -17431,20 +18268,19 @@ async function withInstallOwnershipLock(context, work) {
17431
18268
  try {
17432
18269
  return await work();
17433
18270
  } finally {
17434
- await release();
18271
+ await releaseLockIdempotently(release);
17435
18272
  }
17436
18273
  }
17437
- var INSTALL_OWNERSHIP_LOCK_RETRIES, sleep;
18274
+ var INSTALL_OWNERSHIP_LOCK_RETRIES;
17438
18275
  var init_installOwnershipLock = __esm({
17439
18276
  "src/installers/lib/installOwnershipLock.ts"() {
18277
+ init_lockContention();
18278
+ init_lockContention();
17440
18279
  INSTALL_OWNERSHIP_LOCK_RETRIES = {
17441
18280
  retries: 30,
17442
18281
  minTimeout: 250,
17443
18282
  maxTimeout: 4e3
17444
18283
  };
17445
- sleep = (ms) => new Promise((resolve40) => {
17446
- setTimeout(resolve40, ms);
17447
- });
17448
18284
  }
17449
18285
  });
17450
18286
  async function mcpReadinessFailure(ctx, allowAbsent = false) {
@@ -18178,11 +19014,11 @@ async function captureSkillOwnershipReceiptParent(receiptPath, options = {}) {
18178
19014
  if (info.isSymbolicLink() || !info.isDirectory()) {
18179
19015
  throw receiptParentFailure("is a symlink, junction, reparse redirect, or non-directory");
18180
19016
  }
18181
- const [canonicalPath2, canonicalStateRoot] = await Promise.all([
19017
+ const [canonicalPath2, canonicalStateRoot2] = await Promise.all([
18182
19018
  realpath(parent),
18183
19019
  realpath(dirname(parent))
18184
19020
  ]);
18185
- if (resolve(canonicalPath2) !== resolve(canonicalStateRoot, basename(parent))) {
19021
+ if (resolve(canonicalPath2) !== resolve(canonicalStateRoot2, basename(parent))) {
18186
19022
  throw receiptParentFailure("canonical path is redirected");
18187
19023
  }
18188
19024
  const canonicalInfo = await lstat(canonicalPath2, { bigint: true });
@@ -20967,8 +21803,8 @@ function preparePackageUpdate(manager, target, context = {}) {
20967
21803
  const prefix = probe(["prefix", "-g"]);
20968
21804
  const modulesRoot = probe(["root", "-g", "--prefix", prefix]);
20969
21805
  const slot = join(modulesRoot, "harnessed");
20970
- const stat18 = lstatSync(slot);
20971
- if (stat18.isSymbolicLink() || !stat18.isDirectory())
21806
+ const stat19 = lstatSync(slot);
21807
+ if (stat19.isSymbolicLink() || !stat19.isDirectory())
20972
21808
  return {
20973
21809
  ok: false,
20974
21810
  reasonCode: "package-layout-unsupported",
@@ -21184,16 +22020,19 @@ async function runBinarySelfUpdate(deps, opts) {
21184
22020
  return { status: "current", version: deps.currentVersion };
21185
22021
  }
21186
22022
  }
22023
+ const partPath = deps.sourceDir ? null : join(execDir, `.harnessed-update-${targetVersion ?? "unknown"}.part`);
22024
+ const verifyPath = partPath ?? tempPath;
22025
+ const stagingPath = deps.sourceDir ? tempPath : join(execDir, `.harnessed-update-${targetVersion ?? "unknown"}${ext}`);
21187
22026
  if (opts.dryRun) {
21188
22027
  const backupDir2 = "bin-backup/<oldver>/ under the harnessed state root";
21189
22028
  const steps = [
21190
- deps.sourceDir ? `copy ${sourceAsset} \u2192 ${tempPath} (local source dir \u2014 rehearsal seam)` : `download ${assetUrl ?? `latest ${asset}`} \u2192 ${tempPath}`,
22029
+ deps.sourceDir ? `copy ${sourceAsset} \u2192 ${stagingPath} (local source dir \u2014 rehearsal seam)` : `download ${assetUrl ?? `latest ${asset}`} \u2192 ${partPath} (resumable fragment)`,
21191
22030
  `verify sha256 against ${deps.sourceDir ? sourceSha : shaUrl ?? `${asset}.sha256`}`,
21192
22031
  ...deps.sourceDir ? [] : ["verify the ed25519 signature (.sha256.sig) against the embedded release public key"],
21193
22032
  ...deps.platform === "win32" ? [] : ["chmod 755 the downloaded binary"],
21194
22033
  "smoke: spawn `--version` on the new binary",
21195
22034
  `rename ${deps.execPath} \u2192 ${bakPath} (same-dir, same-volume)`,
21196
- `rename ${tempPath} \u2192 ${deps.execPath}`,
22035
+ `rename ${stagingPath} \u2192 ${deps.execPath}`,
21197
22036
  `copy the .bak to ${backupDir2} (rollback net)`,
21198
22037
  "delete the .bak (fail-soft \u2014 kept on Windows EPERM or when the backup copy failed)"
21199
22038
  ];
@@ -21202,11 +22041,11 @@ async function runBinarySelfUpdate(deps, opts) {
21202
22041
  try {
21203
22042
  if (deps.sourceDir && sourceAsset) {
21204
22043
  await copyFile(sourceAsset, tempPath);
21205
- } else if (assetUrl) {
21206
- await deps.downloadTo(assetUrl, tempPath, assetFallbackUrl);
22044
+ } else if (assetUrl && partPath) {
22045
+ await deps.downloadTo(assetUrl, partPath, assetFallbackUrl);
21207
22046
  }
21208
22047
  } catch (e) {
21209
- await unlink2(tempPath).catch(() => {
22048
+ if (!partPath) await unlink2(tempPath).catch(() => {
21210
22049
  });
21211
22050
  return { status: "error", message: downloadFailureMessage(e, targetVersion, assetUrl) };
21212
22051
  }
@@ -21214,7 +22053,7 @@ async function runBinarySelfUpdate(deps, opts) {
21214
22053
  const shaText = deps.sourceDir ? await readFile(sourceSha ?? "", "utf8") : await deps.fetchShaText(shaUrl ?? "", shaFallbackUrl);
21215
22054
  const expected = parseShaText(shaText);
21216
22055
  if (!expected) throw new Error(`malformed .sha256 content`);
21217
- const actual = await sha256File(tempPath);
22056
+ const actual = await sha256File(verifyPath);
21218
22057
  if (actual !== expected) {
21219
22058
  throw new Error(
21220
22059
  `sha256 mismatch \u2014 expected ${expected.slice(0, 12)}\u2026, got ${actual.slice(0, 12)}\u2026`
@@ -21231,16 +22070,30 @@ async function runBinarySelfUpdate(deps, opts) {
21231
22070
  }
21232
22071
  }
21233
22072
  } catch (e) {
21234
- await unlink2(tempPath).catch(() => {
22073
+ await unlink2(verifyPath).catch(() => {
21235
22074
  });
21236
22075
  return {
21237
22076
  status: "error",
21238
22077
  message: `integrity verification failed: ${e.message} \u2014 aborted; original binary untouched`
21239
22078
  };
21240
22079
  }
22080
+ if (partPath) {
22081
+ try {
22082
+ await unlink2(stagingPath).catch(() => {
22083
+ });
22084
+ await rename9(partPath, stagingPath);
22085
+ } catch (e) {
22086
+ return {
22087
+ status: "error",
22088
+ message: `could not stage the verified download: ${e.message} \u2014 the download was kept for the next attempt; original binary untouched`
22089
+ };
22090
+ }
22091
+ }
22092
+ let smokeRan = false;
21241
22093
  try {
21242
- if (deps.platform !== "win32") await chmod(tempPath, 493);
21243
- const out = (await deps.smoke(tempPath)).trim();
22094
+ if (deps.platform !== "win32") await chmod(stagingPath, 493);
22095
+ const out = (await deps.smoke(stagingPath)).trim();
22096
+ smokeRan = true;
21244
22097
  const m = /^(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/.exec(out);
21245
22098
  if (!m) throw new Error(`--version smoke returned unexpected output: ${out.slice(0, 80)}`);
21246
22099
  if (targetVersion !== null && out !== targetVersion) {
@@ -21248,8 +22101,13 @@ async function runBinarySelfUpdate(deps, opts) {
21248
22101
  }
21249
22102
  targetVersion = targetVersion ?? m[1] ?? null;
21250
22103
  } catch (e) {
21251
- await unlink2(tempPath).catch(() => {
21252
- });
22104
+ if (partPath && !smokeRan) {
22105
+ await rename9(stagingPath, partPath).catch(() => {
22106
+ });
22107
+ } else {
22108
+ await unlink2(stagingPath).catch(() => {
22109
+ });
22110
+ }
21253
22111
  return {
21254
22112
  status: "error",
21255
22113
  message: `new binary failed the --version smoke: ${e.message} \u2014 aborted; original binary untouched`
@@ -21258,7 +22116,9 @@ async function runBinarySelfUpdate(deps, opts) {
21258
22116
  try {
21259
22117
  await rename9(deps.execPath, bakPath);
21260
22118
  } catch (e) {
21261
- await unlink2(tempPath).catch(() => {
22119
+ if (partPath) await rename9(stagingPath, partPath).catch(() => {
22120
+ });
22121
+ else await unlink2(stagingPath).catch(() => {
21262
22122
  });
21263
22123
  return {
21264
22124
  status: "error",
@@ -21266,17 +22126,24 @@ async function runBinarySelfUpdate(deps, opts) {
21266
22126
  };
21267
22127
  }
21268
22128
  try {
21269
- await rename9(tempPath, deps.execPath);
22129
+ await rename9(stagingPath, deps.execPath);
21270
22130
  } catch (e) {
21271
22131
  try {
21272
22132
  await rename9(bakPath, deps.execPath);
22133
+ if (partPath) await rename9(stagingPath, partPath).catch(() => {
22134
+ });
22135
+ else await unlink2(stagingPath).catch(() => {
22136
+ });
21273
22137
  return {
21274
22138
  status: "error",
21275
22139
  message: `swap failed (${e.message}) \u2014 rolled back to the previous binary`
21276
22140
  };
21277
22141
  } catch (rb) {
22142
+ if (partPath) await rename9(stagingPath, partPath).catch(() => {
22143
+ });
21278
22144
  return {
21279
22145
  status: "error",
22146
+ critical: true,
21280
22147
  message: `CRITICAL: swap failed AND rollback failed (${rb.message}). Restore manually: copy "${bakPath}" "${deps.execPath}"`
21281
22148
  };
21282
22149
  }
@@ -21425,6 +22292,32 @@ async function runBinaryRollback(deps, opts) {
21425
22292
  });
21426
22293
  return { status: "rolled-back", from: deps.currentVersion, to: target, backupUsed: backupBin };
21427
22294
  }
22295
+ function headerOf(res, name) {
22296
+ const headers = res.headers;
22297
+ if (!headers || typeof headers.get !== "function") return null;
22298
+ return headers.get(name);
22299
+ }
22300
+ function parseContentRange(value) {
22301
+ if (!value) return null;
22302
+ const text = value.trim();
22303
+ const unsat = /^bytes\s+\*\/(\d+|\*)$/i.exec(text);
22304
+ if (unsat) return { start: null, total: unsat[1] === "*" ? null : Number(unsat[1]) };
22305
+ const m = /^bytes\s+(\d+)-(\d+)\/(\d+|\*)$/i.exec(text);
22306
+ if (!m) return null;
22307
+ return { start: Number(m[1]), total: m[3] === "*" ? null : Number(m[3]) };
22308
+ }
22309
+ function numberOrUndefined(value) {
22310
+ if (value === null) return void 0;
22311
+ const n = Number(value);
22312
+ return Number.isFinite(n) ? n : void 0;
22313
+ }
22314
+ async function fileSize(p8) {
22315
+ try {
22316
+ return (await stat(p8)).size;
22317
+ } catch {
22318
+ return 0;
22319
+ }
22320
+ }
21428
22321
  async function fetchWithTimeout(url, timeoutMs, net = {}, headers = {}, controller) {
21429
22322
  await ensureProxyDispatcher();
21430
22323
  const doFetch = net.fetchImpl ?? fetch;
@@ -21455,36 +22348,40 @@ function isTransientNetworkError(error) {
21455
22348
  message
21456
22349
  );
21457
22350
  }
21458
- async function fetchAsset(url, fallbackUrl, timeoutMs, net, label, consume) {
21459
- const sleep2 = net.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
22351
+ async function fetchAsset(url, fallbackUrl, timeoutMs, net, label, consume, extra) {
22352
+ const sleep3 = net.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
21460
22353
  const attempts = [];
21461
22354
  let lastError;
21462
22355
  for (const candidate of [url, fallbackUrl].filter((u) => !!u)) {
21463
22356
  for (let attempt = 1; attempt <= DOWNLOAD_ATTEMPTS; attempt++) {
21464
22357
  const ac = new AbortController();
21465
22358
  try {
21466
- const res = await fetchWithTimeout(
21467
- candidate,
21468
- timeoutMs,
21469
- net,
21470
- {
21471
- accept: "application/octet-stream"
21472
- },
21473
- ac
21474
- );
22359
+ const offset = extra?.existingBytes === void 0 ? 0 : await (typeof extra.existingBytes === "function" ? extra.existingBytes() : extra.existingBytes);
22360
+ const headers = {
22361
+ accept: "application/octet-stream",
22362
+ ...extra?.headers
22363
+ };
22364
+ if (offset > 0) headers.range = `bytes=${offset}-`;
22365
+ const res = await fetchWithTimeout(candidate, timeoutMs, net, headers, ac);
21475
22366
  if (!res.ok) {
22367
+ if (res.status === 416) {
22368
+ throw new RangeNotSatisfiableError(
22369
+ parseContentRange(headerOf(res, "content-range"))?.total ?? null
22370
+ );
22371
+ }
21476
22372
  lastError = new Error(`HTTP ${res.status} downloading ${candidate}`);
21477
22373
  if (res.status < 500) break;
21478
22374
  } else {
21479
- return await consume(res, ac);
22375
+ return await consume(res, ac, offset);
21480
22376
  }
21481
22377
  } catch (error) {
21482
- if (error instanceof TransferStalledError) throw error;
22378
+ if (error instanceof RangeNotSatisfiableError) throw error;
21483
22379
  lastError = error;
21484
- if (!isTransientNetworkError(error)) break;
22380
+ const retryable = error instanceof RangeMismatchError || error instanceof TransferStalledError || isTransientNetworkError(error);
22381
+ if (!retryable) break;
21485
22382
  }
21486
22383
  attempts.push(candidate);
21487
- if (attempt < DOWNLOAD_ATTEMPTS) await sleep2(250 * attempt);
22384
+ if (attempt < DOWNLOAD_ATTEMPTS) await sleep3(250 * attempt);
21488
22385
  }
21489
22386
  }
21490
22387
  throw new Error(
@@ -21505,10 +22402,12 @@ function transferStats(received, elapsedMs) {
21505
22402
  const rate = received > 0 ? `, ${formatRate(received, elapsedMs)} average` : "";
21506
22403
  return `${received} bytes received in ${seconds} s${rate}`;
21507
22404
  }
21508
- async function streamAssetToFile(res, dest, ac, stallTimeoutMs, progressIntervalMs, log) {
22405
+ async function streamAssetToFile(res, dest, ac, stallTimeoutMs, progressIntervalMs, log, opts) {
21509
22406
  if (!res.body) throw new Error("the release asset response carried no body");
21510
22407
  const started = Date.now();
21511
- let received = 0;
22408
+ const initialBytes = opts?.initialBytes ?? 0;
22409
+ let received = initialBytes;
22410
+ let attemptBytes = 0;
21512
22411
  let lastProgressAt = started;
21513
22412
  let stalled = false;
21514
22413
  let stallTimer;
@@ -21524,10 +22423,15 @@ async function streamAssetToFile(res, dest, ac, stallTimeoutMs, progressInterval
21524
22423
  const meter = new Transform({
21525
22424
  transform(chunk, _encoding, callback) {
21526
22425
  received += chunk.length;
22426
+ attemptBytes += chunk.length;
21527
22427
  const now = Date.now();
21528
22428
  if (now - lastProgressAt >= progressIntervalMs) {
21529
22429
  lastProgressAt = now;
21530
- log(`downloading ${formatBytes(received)} (${formatRate(received, now - started)})`);
22430
+ const total = opts?.totalBytes;
22431
+ const totalPart = total ? ` / ${formatBytes(total)}` : "";
22432
+ log(
22433
+ `downloading ${formatBytes(received)}${totalPart} (${formatRate(attemptBytes, now - started)})`
22434
+ );
21531
22435
  }
21532
22436
  resetStall();
21533
22437
  callback(null, chunk);
@@ -21540,15 +22444,16 @@ async function streamAssetToFile(res, dest, ac, stallTimeoutMs, progressInterval
21540
22444
  // class is the one Readable.fromWeb accepts.
21541
22445
  Readable.fromWeb(res.body),
21542
22446
  meter,
21543
- // flags 'w' truncates: a retried attempt must not append to the bytes
21544
- // a previous attempt already wrote.
21545
- createWriteStream(dest),
22447
+ // flags 'a' appends (a 206 continues the fragment); 'w' truncates (a
22448
+ // 200 rewrites it — a retried attempt must not append to the bytes a
22449
+ // previous attempt already wrote).
22450
+ createWriteStream(dest, { flags: opts?.append ? "a" : "w" }),
21546
22451
  { signal: ac.signal }
21547
22452
  );
21548
22453
  } catch (e) {
21549
22454
  if (stalled) {
21550
22455
  throw new TransferStalledError(
21551
- `the download stalled \u2014 no data for ${Math.round(stallTimeoutMs / 1e3)} s (${transferStats(received, Date.now() - started)})`
22456
+ `the download stalled \u2014 no data for ${Math.round(stallTimeoutMs / 1e3)} s (${transferStats(attemptBytes, Date.now() - started)})`
21552
22457
  );
21553
22458
  }
21554
22459
  throw e;
@@ -21556,6 +22461,65 @@ async function streamAssetToFile(res, dest, ac, stallTimeoutMs, progressInterval
21556
22461
  if (stallTimer) clearTimeout(stallTimer);
21557
22462
  }
21558
22463
  }
22464
+ async function downloadResumableAsset(url, fallbackUrl, dest, net, log) {
22465
+ const stallTimeoutMs = net.stallTimeoutMs ?? ASSET_STALL_TIMEOUT_MS;
22466
+ const progressIntervalMs = net.progressIntervalMs ?? ASSET_PROGRESS_INTERVAL_MS;
22467
+ let forceFullDownload = false;
22468
+ const offsetOf = async () => {
22469
+ if (forceFullDownload) return 0;
22470
+ return await fileSize(dest);
22471
+ };
22472
+ for (let round = 0; round < 2; round++) {
22473
+ try {
22474
+ await fetchAsset(
22475
+ url,
22476
+ fallbackUrl,
22477
+ ASSET_HEADERS_TIMEOUT_MS,
22478
+ net,
22479
+ "binary",
22480
+ async (res, attempt, requested) => {
22481
+ const range = parseContentRange(headerOf(res, "content-range"));
22482
+ const start = range ? range.start : null;
22483
+ const totalBytes = res.status === 206 ? range?.total ?? void 0 : numberOrUndefined(headerOf(res, "content-length"));
22484
+ if (res.status === 206) {
22485
+ if (start === null || start !== requested) {
22486
+ await unlink(dest).catch(() => {
22487
+ });
22488
+ forceFullDownload = true;
22489
+ throw new RangeMismatchError(
22490
+ `the server answered 206 starting at ${start ?? "?"}, not ${requested}`
22491
+ );
22492
+ }
22493
+ await streamAssetToFile(res, dest, attempt, stallTimeoutMs, progressIntervalMs, log, {
22494
+ append: true,
22495
+ initialBytes: requested,
22496
+ totalBytes
22497
+ });
22498
+ return;
22499
+ }
22500
+ await streamAssetToFile(res, dest, attempt, stallTimeoutMs, progressIntervalMs, log, {
22501
+ append: false,
22502
+ initialBytes: 0,
22503
+ totalBytes
22504
+ });
22505
+ },
22506
+ { existingBytes: offsetOf }
22507
+ );
22508
+ return;
22509
+ } catch (e) {
22510
+ if (e instanceof RangeNotSatisfiableError) {
22511
+ const have = await fileSize(dest);
22512
+ if (e.total !== null && e.total === have) return;
22513
+ await unlink(dest).catch(() => {
22514
+ });
22515
+ forceFullDownload = true;
22516
+ continue;
22517
+ }
22518
+ throw e;
22519
+ }
22520
+ }
22521
+ throw new Error("the release asset could not be downloaded (the server ignored the resume range)");
22522
+ }
21559
22523
  async function resolveLatestRelease(platform = process.platform, arch = process.arch, net = {}) {
21560
22524
  let res;
21561
22525
  try {
@@ -21617,8 +22581,6 @@ async function resolveLatestRelease(platform = process.platform, arch = process.
21617
22581
  }
21618
22582
  function realSelfUpdateDeps(context, net = {}) {
21619
22583
  const log = (line) => console.warn(line);
21620
- const stallTimeoutMs = net.stallTimeoutMs ?? ASSET_STALL_TIMEOUT_MS;
21621
- const progressIntervalMs = net.progressIntervalMs ?? ASSET_PROGRESS_INTERVAL_MS;
21622
22584
  return {
21623
22585
  execPath: process.execPath,
21624
22586
  platform: process.platform,
@@ -21627,14 +22589,7 @@ function realSelfUpdateDeps(context, net = {}) {
21627
22589
  sourceDir: process.env.HARNESSED_UPDATE_SOURCE_DIR?.trim() || null,
21628
22590
  resolveRelease: () => resolveLatestRelease(process.platform, process.arch, net),
21629
22591
  downloadTo: async (url, dest, fallbackUrl) => {
21630
- await fetchAsset(
21631
- url,
21632
- fallbackUrl,
21633
- ASSET_HEADERS_TIMEOUT_MS,
21634
- net,
21635
- "binary",
21636
- (res, attempt) => streamAssetToFile(res, dest, attempt, stallTimeoutMs, progressIntervalMs, log)
21637
- );
22592
+ await downloadResumableAsset(url, fallbackUrl, dest, net, log);
21638
22593
  },
21639
22594
  fetchShaText: async (url, fallbackUrl) => {
21640
22595
  return fetchAsset(url, fallbackUrl, CHECKSUM_TIMEOUT_MS, net, "checksum", (res) => res.text());
@@ -21667,7 +22622,7 @@ async function execDirWritable(execPath) {
21667
22622
  return false;
21668
22623
  }
21669
22624
  }
21670
- var OWNER_REPO, RELEASES_LATEST_URL, RELEASE_METADATA_TIMEOUT_MS, ASSET_HEADERS_TIMEOUT_MS, CHECKSUM_TIMEOUT_MS, ASSET_STALL_TIMEOUT_MS, ASSET_PROGRESS_INTERVAL_MS, RequestTimeoutError, TransferStalledError, DOWNLOAD_ATTEMPTS;
22625
+ var OWNER_REPO, RELEASES_LATEST_URL, RELEASE_METADATA_TIMEOUT_MS, ASSET_HEADERS_TIMEOUT_MS, CHECKSUM_TIMEOUT_MS, ASSET_STALL_TIMEOUT_MS, ASSET_PROGRESS_INTERVAL_MS, RequestTimeoutError, TransferStalledError, RangeMismatchError, RangeNotSatisfiableError, DOWNLOAD_ATTEMPTS;
21671
22626
  var init_selfUpdateBinary = __esm({
21672
22627
  "src/cli/lib/selfUpdateBinary.ts"() {
21673
22628
  init_package();
@@ -21686,6 +22641,15 @@ var init_selfUpdateBinary = __esm({
21686
22641
  };
21687
22642
  TransferStalledError = class extends Error {
21688
22643
  };
22644
+ RangeMismatchError = class extends Error {
22645
+ };
22646
+ RangeNotSatisfiableError = class extends Error {
22647
+ constructor(total) {
22648
+ super("the requested range is not satisfiable");
22649
+ this.total = total;
22650
+ }
22651
+ total;
22652
+ };
21689
22653
  DOWNLOAD_ATTEMPTS = 3;
21690
22654
  }
21691
22655
  });
@@ -22000,7 +22964,7 @@ function decodeUpdateContinuation(encoded) {
22000
22964
  return value;
22001
22965
  }
22002
22966
  async function runContinuationProcess(executablePath, args, options) {
22003
- return new Promise((resolve40, reject) => {
22967
+ return new Promise((resolve42, reject) => {
22004
22968
  const child = spawn(executablePath, args, {
22005
22969
  cwd: options.cwd,
22006
22970
  env: options.env,
@@ -22014,7 +22978,7 @@ async function runContinuationProcess(executablePath, args, options) {
22014
22978
  child.once("error", reject);
22015
22979
  child.once("close", (exitCode, signal) => {
22016
22980
  clearTimeout(timer);
22017
- resolve40({ exitCode, signal });
22981
+ resolve42({ exitCode, signal });
22018
22982
  });
22019
22983
  });
22020
22984
  }
@@ -22202,13 +23166,13 @@ function runWarning(ctx, name, variant) {
22202
23166
  function spawnLoopSteps(indent) {
22203
23167
  const i = indent;
22204
23168
  return [
22205
- `${i}a. Bash: \`harnessed prompt <sub> --task "<spec>" --json\` \u2192 parse \`{prompt, max_iterations, model}\`.`,
22206
- `${i}b. Spawn a {{ host.native }} subagent ({{ host.spawn_subagent }}) with that \`prompt\` and \`model\`, then drive delivery with harnessed's own completion gate:`,
22207
- `${i} - on return, write the subagent's final output to a file and run \`harnessed checkpoint complete <sub> --result-file <path>\` \u2014 it is fail-closed on the declared artifacts, the TDD boundary, and the verbatim \`<promise>COMPLETE</promise>\`.`,
23169
+ `${i}a. Bash: \`harnessed prompt <sub> --task "<spec>" --json\` \u2192 parse \`{prompt, max_iterations, model, result_file}\`.`,
23170
+ `${i}b. Spawn a {{ host.native }} subagent ({{ host.spawn_subagent }}) with that \`prompt\` and \`model\`. The sub writes its own final result into \`result_file\` \u2014 the path that prompt names \u2014 so the FILE is the completion signal: do NOT wait for the sub's chat message, because a background or re-parented agent's message may never arrive. Then drive delivery with harnessed's own completion gate:`,
23171
+ `${i} - the gate is \`harnessed checkpoint complete <sub> --result-file <result_file> --wait 60\` \u2014 one call waits at most 60 seconds, so run the SAME command again when the sub needs longer; it is fail-closed on the declared artifacts, the TDD boundary, and the verbatim \`<promise>COMPLETE</promise>\`.`,
22208
23172
  `${i} - if it blocks, run \`harnessed checkpoint fail <sub> --failing-tests <n>\` to record the attempt; it prints BUDGET-EXHAUSTED / NO-PROGRESS / BREAK-LOOP when a stop condition is reached.`,
22209
23173
  `${i} - respawn ONLY while none of those three has fired. Any one of them means stop: re-scope the subtask, fix the blocker, or escalate to the user. Never respawn past a stop directive.`,
22210
- `${i}c. If the subagent output contains \`STATUS: NEEDS_CLARIFICATION\` + a question list: STOP. Use {{ host.ask_user }} to relay those exact questions to the user. Append the user's answers to the spec, then re-spawn the same sub. (This is the round-trip headless spawn cannot do.)`,
22211
- `${i}d. On \`<promise>COMPLETE</promise>\`: Bash \`harnessed checkpoint complete <sub> --result-file <path> --summary "<one-line>"\`.`
23174
+ `${i}c. If the sub's output contains \`STATUS: NEEDS_CLARIFICATION\` + a question list (read it from \`result_file\` \u2014 the chat message may never arrive): STOP. Use {{ host.ask_user }} to relay those exact questions to the user. Append the user's answers to the spec, then re-spawn the same sub. (This is the round-trip headless spawn cannot do.)`,
23175
+ `${i}d. When \`result_file\` carries the completion marker: Bash \`harnessed checkpoint complete <sub> --result-file <result_file> --wait 60 --summary "<one-line>"\`. A \`result-wait-timeout\` exit means the sub has not signalled YET \u2014 run the same command again; any other non-zero exit means the sub is NOT done.`
22212
23176
  ];
22213
23177
  }
22214
23178
  function buildInteractiveBody(name, prompt) {
@@ -22254,7 +23218,7 @@ function buildOrchestratorBody(name, prompt, ctx) {
22254
23218
  const leafIndent = " ";
22255
23219
  const leafSpawnLoop = [
22256
23220
  ...spawnLoopSteps(leafIndent).slice(0, 6),
22257
- `${leafIndent}d. On \`<promise>COMPLETE</promise>\`: write the subagent's final output to a file, then Bash \`harnessed checkpoint complete <sub> --result-file <path> --summary "<one-line>"\`. The evidence guard runs here (fail-CLOSED) and blocks unless ALL hold: every declared \`artifacts_expected\` file exists, the TDD boundary passes (non-empty evidence / both the red and green sides present / the test file was not deleted), and the result carries a verbatim \`<promise>COMPLETE</promise>\` (or a structured COMPLETE status). \`--result <text>\` is the inline variant; \`--result-file\` wins and is quoting-safe on Windows. If it exits non-zero the sub is NOT done \u2014 re-spawn to fix the gap, or pass \`--force\` only to deliberately override (records \`evidence_status: overridden\` \u2014 an audited override, not a silent pass).`,
23221
+ `${leafIndent}d. When \`result_file\` carries the completion marker: Bash \`harnessed checkpoint complete <sub> --result-file <result_file> --wait 60 --summary "<one-line>"\`. The evidence guard runs here (fail-CLOSED) and blocks unless ALL hold: every declared \`artifacts_expected\` file exists, the TDD boundary passes (non-empty evidence / both the red and green sides present / the test file was not deleted), and the result file carries a verbatim \`<promise>COMPLETE</promise>\` (or a structured COMPLETE status). \`--wait 60\` bounds ONE call to 60 seconds \u2014 run the SAME command again when the sub needs longer, never an unbounded wait. \`--result <text>\` is the inline variant; \`--result-file\` wins and is quoting-safe on Windows. A \`result-wait-timeout\` exit means the sub has not signalled YET \u2014 repeat the same command; any other non-zero exit means the sub is NOT done \u2014 re-spawn to fix the gap, or pass \`--force\` only to deliberately override (records \`evidence_status: overridden\` \u2014 an audited override, not a silent pass).`,
22258
23222
  `${leafIndent}e. If the complete gate blocked: Bash \`harnessed checkpoint fail <sub> --failing-tests <n>\` to record the attempt (omit the flag when the sub has no tests \u2014 the evidence-artifact digest is the fallback progress metric). It prints \`BUDGET-EXHAUSTED\` (attempts spent vs \`workflows/defaults.yaml ralph_max_iterations\`), \`NO-PROGRESS\` (no improvement for N consecutive attempts) or \`BREAK-LOOP\` (this sub failed >= the threshold) when a stop condition is reached. Respawn ONLY while none of those three has fired; any one of them means STOP \u2014 re-scope the subtask, fix the blocker, or escalate to the user, and report it. Never respawn past a stop directive.`
22259
23223
  ];
22260
23224
  return [
@@ -22287,7 +23251,7 @@ function buildOrchestratorBody(name, prompt, ctx) {
22287
23251
  // itself: every judgement-call fact pinned to its firing side and no caller
22288
23252
  // ever passing context, i.e. criteria with zero discriminating power.
22289
23253
  `1b. Bash: \`harnessed facts ${name} --out .harnessed-facts.json\` \u2192 it lists ONLY the facts this stage\u2019s gates actually read: deterministic ones already filled (change size / files touched / stage, from git), judgement calls left \`null\` with a one-line hint of what to judge. Edit the file and replace each \`null\` in \`facts\` with your honest answer from the locked spec \u2014 leave one null only if you genuinely cannot judge it (it then falls back to the built-in default). Do NOT skip this step and do NOT invent facts the command did not ask for.`,
22290
- `2. Bash: \`harnessed gates ${name} --task "<locked spec>" --context-file .harnessed-facts.json --skip-sub discuss\` \u2192 parse the JSON \`{fire: [{sub, order, mode, is_master}], skip: [{sub, reason}], parallelism: {escalate_to_teams}}\`. This is the plan SoT (no spawn). Keep the verbatim JSON for the next step.${name === "auto" ? " For a small self-contained task (single-file / single-page class), the sanctioned lite path is adding `--skip-sub verify --skip-sub retro` (repeatable / comma-separated) \u2014 skipped subs are still recorded in the ledger with reasons; lite \u2260 freestyle (the ledger/evidence IS the difference)." : ""}`,
23254
+ `2. Bash: \`harnessed gates ${name} --task "<locked spec>" --context-file .harnessed-facts.json --skip-sub discuss\` \u2192 parse the JSON \`{fire: [{sub, order, mode, is_master}], skip: [{sub, reason}], parallelism: {escalate_to_teams, teams_active, transport, result_contract, bounded_wait}}\`. \`escalate_to_teams: false\` means the run cannot form a team \u2014 drive the fired subs as a plain subagent fan-out (parallel where \`order\` allows) instead. \`teams_active\` says whether a team is actually running, \`transport\` names the transport this plan uses, \`result_contract\` is \`result-file\` and \`bounded_wait\` is \`true\`: every sub signals completion through its result file, never through a chat message. This is the plan SoT (no spawn). Keep the verbatim JSON for the next step.${name === "auto" ? " For a small self-contained task (single-file / single-page class), the sanctioned lite path is adding `--skip-sub verify --skip-sub retro` (repeatable / comma-separated) \u2014 skipped subs are still recorded in the ledger with reasons; lite \u2260 freestyle (the ledger/evidence IS the difference)." : ""}`,
22291
23255
  `3. Bash: \`harnessed checkpoint start ${name} --plan '<the verbatim gates JSON from step 2>'\` \u2192 seeds the sub-progress ledger in \`current-workflow.json\` (fired subs \u2192 \`pending\`, skipped subs \u2192 \`skipped\` + reason). This makes \`harnessed status --recover\` able to tell you where you are after compaction.`,
22292
23256
  // Phase 65 — this step's text is NOT maintained by hand any more. It is
22293
23257
  // `host.teams_step_note.command` in workflows/host-primitives.yaml; the
@@ -22408,7 +23372,7 @@ function generateCommandArtifact(name, commandsDir, prompt, capabilities, instal
22408
23372
  const filename = `${name}.md`;
22409
23373
  return { ...generated, filename, path: join(commandsDir, filename) };
22410
23374
  }
22411
- async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync28 = (p8) => readFileSync(p8, "utf8"), hostRender) {
23375
+ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync29 = (p8) => readFileSync(p8, "utf8"), hostRender) {
22412
23376
  const results = [];
22413
23377
  const aggregatedWarnings = /* @__PURE__ */ new Set();
22414
23378
  for (const name of slashNames) {
@@ -22427,7 +23391,7 @@ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabiliti
22427
23391
  if (fileExists2(path)) {
22428
23392
  let existing = "";
22429
23393
  try {
22430
- existing = readFileSync28(path);
23394
+ existing = readFileSync29(path);
22431
23395
  } catch {
22432
23396
  existing = "";
22433
23397
  }
@@ -22858,14 +23822,12 @@ async function reminderEnabled(context) {
22858
23822
  const stateRoot = resolve(
22859
23823
  context.platform.stateRoot !== defaultRoot ? context.platform.stateRoot : join(context.nativeHome, "harnessed")
22860
23824
  );
22861
- try {
22862
- const value = JSON.parse(
22863
- await readFile(join(stateRoot, "update-reminder-preferences.json"), "utf8")
22864
- );
22865
- return value.schemaVersion === 1 && value.enabled === true;
22866
- } catch (error) {
22867
- return error.code === "ENOENT";
22868
- }
23825
+ const { preferences, missing, document } = readUpdateReminderPreferencesFile(
23826
+ join(stateRoot, "update-reminder-preferences.json")
23827
+ );
23828
+ if (preferences.unreadable) return false;
23829
+ if (missing) return true;
23830
+ return document?.schemaVersion === 1 && preferences.enabled;
22869
23831
  }
22870
23832
  async function hasFirstPartyRegistration(context, hookEvent, hookCommand) {
22871
23833
  let raw;
@@ -23005,6 +23967,7 @@ var init_refreshOwnedUpdate = __esm({
23005
23967
  init_renderSkillTemplates();
23006
23968
  init_skillBackup();
23007
23969
  init_skillIntegrity();
23970
+ init_updateReminderPreferences();
23008
23971
  init_updateResult();
23009
23972
  init_workflowArtifacts();
23010
23973
  OWNED_HOOKS = [
@@ -24684,87 +25647,6 @@ var init_run2 = __esm({
24684
25647
  _autoChainLoadFailed = false;
24685
25648
  }
24686
25649
  });
24687
- var init_updateReminderCache = __esm({
24688
- "src/cli/lib/updateReminderCache.ts"() {
24689
- }
24690
- });
24691
- var init_updateReminderHookMain = __esm({
24692
- "src/cli/updateReminderHookMain.ts"() {
24693
- init_updateReminderCache();
24694
- }
24695
- });
24696
- function resolveUpdateReminderRuntime(options = {}) {
24697
- const args = [...options.args ?? process.argv.slice(2)];
24698
- if (args[0] === UPDATE_REMINDER_OPERATION || args[0] === UPDATE_REMINDER_WORKER_OPERATION)
24699
- args.shift();
24700
- let host = "claude";
24701
- let explicitStateRoot;
24702
- let platformSpecified = false;
24703
- for (let index = 0; index < args.length; index += 2) {
24704
- const flag = args[index];
24705
- const value = args[index + 1];
24706
- if (!flag || value === void 0 || [flag, value].some(
24707
- (argument) => Array.from(argument).some((character) => character < " " || character === "\x7F")
24708
- ))
24709
- return null;
24710
- if (flag === "--platform") {
24711
- if (platformSpecified || value !== "claude" && value !== "codex") return null;
24712
- platformSpecified = true;
24713
- host = value;
24714
- } else if (flag === "--state-root") {
24715
- if (explicitStateRoot !== void 0 || !isAbsolute(value)) return null;
24716
- explicitStateRoot = resolve(value);
24717
- } else return null;
24718
- }
24719
- const nativeHome = resolve(
24720
- (host === "codex" ? process.env.CODEX_HOME?.trim() : process.env.CLAUDE_CONFIG_DIR) || join(homedir(), host === "codex" ? ".codex" : ".claude")
24721
- );
24722
- const stateRoot = explicitStateRoot ?? resolve(process.env.HARNESSED_ROOT_OVERRIDE || join(nativeHome, "harnessed"));
24723
- const channel = options.compiled ? "binary" : process.versions.bun ? "bun" : "npm";
24724
- const source = channel === "binary" ? BINARY_SOURCE : `${channel}:harnessed`;
24725
- const fingerprint = createHash("sha256").update(
24726
- JSON.stringify([
24727
- host === "codex" ? stateRoot : nativeHome,
24728
- process.execPath,
24729
- package_default.version,
24730
- source
24731
- ])
24732
- ).digest("hex");
24733
- return {
24734
- stateRoot,
24735
- nativeHome,
24736
- cachePath: join(stateRoot, `update-reminder-${host}.json`),
24737
- preferencesPath: join(stateRoot, UPDATE_REMINDER_PREFERENCES_FILE),
24738
- installed: package_default.version,
24739
- identity: {
24740
- host,
24741
- runtime: options.compiled ? "binary" : process.versions.bun ? "bun" : "node",
24742
- channel,
24743
- source,
24744
- fingerprint
24745
- },
24746
- worker: {
24747
- executable: process.execPath,
24748
- args: [
24749
- options.compiled ? UPDATE_REMINDER_WORKER_OPERATION : join(dirname(fileURLToPath(import.meta.url)), "harnessed-update-reminder-worker.mjs"),
24750
- "--platform",
24751
- host,
24752
- ...explicitStateRoot ? ["--state-root", explicitStateRoot] : []
24753
- ]
24754
- }
24755
- };
24756
- }
24757
- var UPDATE_REMINDER_OPERATION, UPDATE_REMINDER_WORKER_OPERATION, UPDATE_REMINDER_PREFERENCES_FILE, BINARY_SOURCE;
24758
- var init_updateReminderEntrypoint = __esm({
24759
- "src/compile/updateReminderEntrypoint.ts"() {
24760
- init_package();
24761
- init_updateReminderHookMain();
24762
- UPDATE_REMINDER_OPERATION = "update-reminder";
24763
- UPDATE_REMINDER_WORKER_OPERATION = "update-reminder-worker";
24764
- UPDATE_REMINDER_PREFERENCES_FILE = "update-reminder-preferences.json";
24765
- BINARY_SOURCE = "https://api.github.com/repos/easyinplay/harnessed/releases/latest";
24766
- }
24767
- });
24768
25650
 
24769
25651
  // src/cli/lib/enableAgentTeamsInSettings.ts
24770
25652
  async function enableAgentTeamsInSettings(hostContext) {
@@ -25827,11 +26709,20 @@ function registerSetup(program2) {
25827
26709
  if (reminder) {
25828
26710
  try {
25829
26711
  await mkdir(reminder.stateRoot, { recursive: true });
25830
- await writeFile(
25831
- reminder.preferencesPath,
25832
- JSON.stringify({ schemaVersion: 1, enabled: raw.updateReminder !== false }),
25833
- { encoding: "utf8", flag: raw.updateReminder === false ? "w" : "wx" }
25834
- );
26712
+ if (raw.updateReminder === false) {
26713
+ const existing = readUpdateReminderPreferencesFile(reminder.preferencesPath);
26714
+ await writeFile(
26715
+ reminder.preferencesPath,
26716
+ JSON.stringify({ ...existing.document ?? { schemaVersion: 1 }, enabled: false }),
26717
+ { encoding: "utf8", flag: "w" }
26718
+ );
26719
+ } else {
26720
+ await writeFile(
26721
+ reminder.preferencesPath,
26722
+ JSON.stringify({ schemaVersion: 1, enabled: true }),
26723
+ { encoding: "utf8", flag: "wx" }
26724
+ );
26725
+ }
25835
26726
  } catch (error) {
25836
26727
  if (raw.updateReminder === false) throw error;
25837
26728
  if (error.code !== "EEXIST")
@@ -26357,6 +27248,7 @@ var init_setup = __esm({
26357
27248
  init_legacyCommandCleanup();
26358
27249
  init_renderSkillTemplates();
26359
27250
  init_setup_helpers();
27251
+ init_updateReminderPreferences();
26360
27252
  init_version_banner();
26361
27253
  KNOWN_PLATFORMS = HOST_IDS;
26362
27254
  }
@@ -26965,7 +27857,7 @@ var init_npmCli3 = __esm({
26965
27857
  cwd: ctx.hostContext.userHome,
26966
27858
  env: withHostInstallEnv(process.env, ctx.hostContext)
26967
27859
  } : {};
26968
- const result = await new Promise((resolve40) => {
27860
+ const result = await new Promise((resolve42) => {
26969
27861
  const child = isWin ? spawn("cmd.exe", ["/c", "npm", "uninstall", "-g", pkg], {
26970
27862
  ...spawnOptions,
26971
27863
  windowsHide: true
@@ -26976,15 +27868,15 @@ var init_npmCli3 = __esm({
26976
27868
  });
26977
27869
  const timer = setTimeout(() => {
26978
27870
  child.kill("SIGKILL");
26979
- resolve40({ exitCode: -1, stderr: `${stderr}[timeout]` });
27871
+ resolve42({ exitCode: -1, stderr: `${stderr}[timeout]` });
26980
27872
  }, 3e4);
26981
27873
  child.on("error", (e) => {
26982
27874
  clearTimeout(timer);
26983
- resolve40({ exitCode: -1, stderr: e.message });
27875
+ resolve42({ exitCode: -1, stderr: e.message });
26984
27876
  });
26985
27877
  child.on("close", (code2) => {
26986
27878
  clearTimeout(timer);
26987
- resolve40({ exitCode: code2 ?? -1, stderr });
27879
+ resolve42({ exitCode: code2 ?? -1, stderr });
26988
27880
  });
26989
27881
  });
26990
27882
  if (result.exitCode !== 0) {
@@ -27582,6 +28474,38 @@ var init_uninstall = __esm({
27582
28474
  }
27583
28475
  });
27584
28476
 
28477
+ // src/cli/lib/changelogSection.ts
28478
+ var changelogSection_exports = {};
28479
+ __export(changelogSection_exports, {
28480
+ changelogSection: () => changelogSection
28481
+ });
28482
+ function escapeRegExp2(value) {
28483
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
28484
+ }
28485
+ function changelogSection(version) {
28486
+ try {
28487
+ const path = join(getAssetsRoot(), "CHANGELOG.md");
28488
+ if (!existsSync(path)) return null;
28489
+ const body = readFileSync(path, "utf8");
28490
+ const heading = version ? new RegExp(`^## \\[${escapeRegExp2(version)}\\]`, "m") : /^## /m;
28491
+ const match = heading.exec(body);
28492
+ if (!match) return null;
28493
+ const rest = body.slice(match.index);
28494
+ const next = rest.slice(1).search(/^## /m);
28495
+ const section = next >= 0 ? rest.slice(0, next + 1) : rest;
28496
+ return section.trim().slice(0, CHANGELOG_EXCERPT_LIMIT);
28497
+ } catch {
28498
+ return null;
28499
+ }
28500
+ }
28501
+ var CHANGELOG_EXCERPT_LIMIT;
28502
+ var init_changelogSection = __esm({
28503
+ "src/cli/lib/changelogSection.ts"() {
28504
+ init_assetsRoot();
28505
+ CHANGELOG_EXCERPT_LIMIT = 1200;
28506
+ }
28507
+ });
28508
+
27585
28509
  // src/cli/lib/ownedRefreshFlag.ts
27586
28510
  var ownedRefreshFlag_exports = {};
27587
28511
  __export(ownedRefreshFlag_exports, {
@@ -27599,7 +28523,8 @@ var ownedRefresh_exports = {};
27599
28523
  __export(ownedRefresh_exports, {
27600
28524
  refreshOwnedState: () => refreshOwnedState,
27601
28525
  runOwnedRefreshEntry: () => runOwnedRefreshEntry,
27602
- spawnOwnedRefresh: () => spawnOwnedRefresh
28526
+ spawnOwnedRefresh: () => spawnOwnedRefresh,
28527
+ writeAutoUpdateNoticeForNewBinary: () => writeAutoUpdateNoticeForNewBinary
27603
28528
  });
27604
28529
  async function refreshOwnedState(context) {
27605
28530
  const { refreshOwnedUpdate: refreshOwnedUpdate2 } = await Promise.resolve().then(() => (init_refreshOwnedUpdate(), refreshOwnedUpdate_exports));
@@ -27614,6 +28539,7 @@ async function runOwnedRefreshEntry() {
27614
28539
  const { captureHostInstallContext: captureHostInstallContext3 } = await Promise.resolve().then(() => (init_hostInstallContext(), hostInstallContext_exports));
27615
28540
  const context = captureHostInstallContext3();
27616
28541
  const outcome = await refreshOwnedState(context);
28542
+ writeAutoUpdateNoticeForNewBinary(context);
27617
28543
  if (outcome.ok) {
27618
28544
  console.log(
27619
28545
  `[harnessed] owned state refreshed (${outcome.updated.length} component(s): ${outcome.updated.join(", ")})`
@@ -27625,9 +28551,28 @@ async function runOwnedRefreshEntry() {
27625
28551
  );
27626
28552
  return 1;
27627
28553
  }
28554
+ async function writeAutoUpdateNoticeForNewBinary(context) {
28555
+ const statusPath = process.env[AUTO_UPDATE_STATUS_PATH_ENV];
28556
+ if (!statusPath) return;
28557
+ try {
28558
+ const [{ readAutoUpdateNotice: readAutoUpdateNotice2, writeAutoUpdateNotice: writeAutoUpdateNotice2 }, { changelogSection: changelogSection2 }] = await Promise.all([Promise.resolve().then(() => (init_autoUpdateNotice(), autoUpdateNotice_exports)), Promise.resolve().then(() => (init_changelogSection(), changelogSection_exports))]);
28559
+ const version = package_default.version;
28560
+ const previous = readAutoUpdateNotice2(statusPath);
28561
+ writeAutoUpdateNotice2(statusPath, {
28562
+ // The `from` version was recorded by the OLD binary before the spawn.
28563
+ from: previous?.from ?? "",
28564
+ to: version,
28565
+ changelog: changelogSection2(version) ?? "",
28566
+ restart: context.hostId === "codex" ? "Codex" : "Claude Code",
28567
+ at: Date.now(),
28568
+ consumedAt: 0
28569
+ });
28570
+ } catch {
28571
+ }
28572
+ }
27628
28573
  async function spawnOwnedRefresh(execPath, context, deps = {}, timeoutMs = OWNED_REFRESH_TIMEOUT_MS) {
27629
28574
  const spawnImpl = deps.spawn ?? spawn;
27630
- return new Promise((resolve40) => {
28575
+ return new Promise((resolve42) => {
27631
28576
  let child;
27632
28577
  try {
27633
28578
  child = spawnImpl(execPath, [OWNED_REFRESH_FLAG], {
@@ -27641,7 +28586,7 @@ async function spawnOwnedRefresh(execPath, context, deps = {}, timeoutMs = OWNED
27641
28586
  shell: false
27642
28587
  });
27643
28588
  } catch (error) {
27644
- resolve40({
28589
+ resolve42({
27645
28590
  ok: false,
27646
28591
  exitCode: null,
27647
28592
  error: error instanceof Error ? error.message : String(error)
@@ -27653,23 +28598,25 @@ async function spawnOwnedRefresh(execPath, context, deps = {}, timeoutMs = OWNED
27653
28598
  killProcessTree(child);
27654
28599
  } catch {
27655
28600
  }
27656
- resolve40({ ok: false, exitCode: null, error: `timed out after ${timeoutMs}ms` });
28601
+ resolve42({ ok: false, exitCode: null, error: `timed out after ${timeoutMs}ms` });
27657
28602
  }, timeoutMs);
27658
28603
  child.on("error", (error) => {
27659
28604
  clearTimeout(timer);
27660
- resolve40({ ok: false, exitCode: null, error: error.message });
28605
+ resolve42({ ok: false, exitCode: null, error: error.message });
27661
28606
  });
27662
28607
  child.on("close", (code2) => {
27663
28608
  clearTimeout(timer);
27664
- resolve40({ ok: code2 === 0, exitCode: code2 });
28609
+ resolve42({ ok: code2 === 0, exitCode: code2 });
27665
28610
  });
27666
28611
  });
27667
28612
  }
27668
28613
  var OWNED_REFRESH_TIMEOUT_MS;
27669
28614
  var init_ownedRefresh = __esm({
27670
28615
  "src/cli/lib/ownedRefresh.ts"() {
28616
+ init_package();
27671
28617
  init_killTree();
27672
28618
  init_runClaudeArgs();
28619
+ init_autoUpdateStatus();
27673
28620
  init_ownedRefreshFlag();
27674
28621
  OWNED_REFRESH_TIMEOUT_MS = 18e4;
27675
28622
  }
@@ -27713,6 +28660,7 @@ var init_migration_report = __esm({
27713
28660
  // src/cli/update.ts
27714
28661
  var update_exports = {};
27715
28662
  __export(update_exports, {
28663
+ changelogTop: () => changelogTop,
27716
28664
  registerUpdate: () => registerUpdate
27717
28665
  });
27718
28666
  function finishLegacyUpdate(code2) {
@@ -27821,20 +28769,6 @@ async function runCompiledFlow(opts, context) {
27821
28769
  return finishLegacyUpdate(1);
27822
28770
  }
27823
28771
  }
27824
- function changelogTop() {
27825
- try {
27826
- const p8 = join(getAssetsRoot(), "CHANGELOG.md");
27827
- if (!existsSync(p8)) return null;
27828
- const body = readFileSync(p8, "utf8");
27829
- const start = body.indexOf("\n## ");
27830
- if (start < 0) return null;
27831
- const rest = body.slice(start + 1);
27832
- const next = rest.indexOf("\n## ", 1);
27833
- return (next > 0 ? rest.slice(0, next) : rest).trim().slice(0, 1200);
27834
- } catch {
27835
- return null;
27836
- }
27837
- }
27838
28772
  function registerUpdate(program2) {
27839
28773
  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").option("--json", "emit one structured update result").option("--platform <host>", "target host: claude | codex").option("--non-interactive", "skip prompts").option("--repair", "request explicitly authorized third-party agent repair").option("--yes", "authorize the listed repair scope in automation").addOption(new Option("--update-continuation <payload>").hideHelp()).addOption(
27840
28774
  new Option(
@@ -27948,7 +28882,7 @@ ${cl}
27948
28882
  });
27949
28883
  });
27950
28884
  }
27951
- var LegacyUpdateExit;
28885
+ var LegacyUpdateExit, changelogTop;
27952
28886
  var init_update = __esm({
27953
28887
  "src/cli/update.ts"() {
27954
28888
  init_package();
@@ -27956,6 +28890,7 @@ var init_update = __esm({
27956
28890
  init_harnessedRoot();
27957
28891
  init_hostInstallContext();
27958
28892
  init_runtime();
28893
+ init_changelogSection();
27959
28894
  init_packageUpdateTarget();
27960
28895
  init_updateCoordinator();
27961
28896
  LegacyUpdateExit = class extends Error {
@@ -27965,6 +28900,7 @@ var init_update = __esm({
27965
28900
  }
27966
28901
  code;
27967
28902
  };
28903
+ changelogTop = changelogSection;
27968
28904
  }
27969
28905
  });
27970
28906
 
@@ -28003,6 +28939,7 @@ var { registerAdvance: registerAdvance2 } = await Promise.resolve().then(() => (
28003
28939
  var { registerAgentsMd: registerAgentsMd2 } = await Promise.resolve().then(() => (init_agents_md(), agents_md_exports));
28004
28940
  var { registerAudit: registerAudit2 } = await Promise.resolve().then(() => (init_audit(), audit_exports));
28005
28941
  var { registerAuditLog: registerAuditLog2 } = await Promise.resolve().then(() => (init_audit_log(), audit_log_exports));
28942
+ var { registerAutoUpdate: registerAutoUpdate2 } = await Promise.resolve().then(() => (init_autoUpdateCmd(), autoUpdateCmd_exports));
28006
28943
  var { registerBackupList: registerBackupList2 } = await Promise.resolve().then(() => (init_backup_list(), backup_list_exports));
28007
28944
  var { registerCheckDocs: registerCheckDocs2 } = await Promise.resolve().then(() => (init_checkDocs(), checkDocs_exports));
28008
28945
  var { registerCheckpoint: registerCheckpoint2 } = await Promise.resolve().then(() => (init_checkpoint(), checkpoint_exports));
@@ -28125,6 +29062,7 @@ registerInjectState2(program);
28125
29062
  registerEval2(program);
28126
29063
  registerCheckDocs2(program);
28127
29064
  registerFacts2(program);
29065
+ registerAutoUpdate2(program);
28128
29066
  var bare = parseBareInvocation2(process.argv.slice(2));
28129
29067
  if (bare.here) {
28130
29068
  void runHere2({ json: bare.json });