harnessed 5.0.12 → 5.0.13

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 +18 -0
  2. package/README-en.md +1 -0
  3. package/README-zh.md +1 -0
  4. package/README.md +1 -0
  5. package/bin/harnessed-check-docs.mjs +15 -0
  6. package/bin/harnessed-update-reminder-worker.mjs +2598 -134
  7. package/bin/harnessed-update-reminder.mjs +636 -61
  8. package/dist/cli.mjs +1524 -589
  9. package/dist/cli.mjs.map +1 -1
  10. package/dist/index.mjs +1 -1
  11. package/dist/index.mjs.map +1 -1
  12. package/messages/en.json +15 -1
  13. package/messages/zh-Hans.json +15 -1
  14. package/package.json +1 -1
  15. package/workflows/auto/SKILL.md +10 -18
  16. package/workflows/auto/SKILL.zh-Hans.md +8 -18
  17. package/workflows/discuss/auto/SKILL.md +4 -7
  18. package/workflows/discuss/auto/SKILL.zh-Hans.md +2 -7
  19. package/workflows/discuss/phase/SKILL.md +4 -7
  20. package/workflows/discuss/phase/SKILL.zh-Hans.md +2 -7
  21. package/workflows/discuss/strategic/SKILL.md +4 -8
  22. package/workflows/discuss/strategic/SKILL.zh-Hans.md +2 -8
  23. package/workflows/discuss/subtask/SKILL.md +4 -7
  24. package/workflows/discuss/subtask/SKILL.zh-Hans.md +2 -7
  25. package/workflows/harnessed-update/SKILL.md +9 -8
  26. package/workflows/harnessed-update/SKILL.zh-Hans.md +7 -8
  27. package/workflows/host-primitives.yaml +8 -8
  28. package/workflows/host-primitives.zh-Hans.yaml +8 -8
  29. package/workflows/plan/ai-integration/SKILL.md +7 -7
  30. package/workflows/plan/ai-integration/SKILL.zh-Hans.md +7 -7
  31. package/workflows/plan/architecture/SKILL.md +7 -13
  32. package/workflows/plan/architecture/SKILL.zh-Hans.md +7 -13
  33. package/workflows/plan/auto/SKILL.md +8 -14
  34. package/workflows/plan/auto/SKILL.zh-Hans.md +8 -14
  35. package/workflows/plan/phase/SKILL.md +7 -13
  36. package/workflows/plan/phase/SKILL.zh-Hans.md +7 -13
  37. package/workflows/plan/secure/SKILL.md +7 -7
  38. package/workflows/plan/secure/SKILL.zh-Hans.md +7 -7
  39. package/workflows/plan/spec/SKILL.md +7 -7
  40. package/workflows/plan/spec/SKILL.zh-Hans.md +7 -7
  41. package/workflows/plan/ui/SKILL.md +7 -7
  42. package/workflows/plan/ui/SKILL.zh-Hans.md +7 -7
  43. package/workflows/research/SKILL.md +7 -7
  44. package/workflows/research/SKILL.zh-Hans.md +7 -7
  45. package/workflows/retro/SKILL.md +8 -15
  46. package/workflows/retro/SKILL.zh-Hans.md +7 -15
  47. package/workflows/ship/auto/SKILL.md +8 -14
  48. package/workflows/ship/auto/SKILL.zh-Hans.md +8 -14
  49. package/workflows/ship/preflight/SKILL.md +7 -9
  50. package/workflows/ship/preflight/SKILL.zh-Hans.md +7 -9
  51. package/workflows/task/auto/SKILL.md +8 -15
  52. package/workflows/task/auto/SKILL.zh-Hans.md +8 -15
  53. package/workflows/task/clarify/SKILL.md +2 -10
  54. package/workflows/task/clarify/SKILL.zh-Hans.md +2 -10
  55. package/workflows/task/code/SKILL.md +7 -15
  56. package/workflows/task/code/SKILL.zh-Hans.md +7 -15
  57. package/workflows/task/deliver/SKILL.md +7 -17
  58. package/workflows/task/deliver/SKILL.zh-Hans.md +7 -17
  59. package/workflows/task/test/SKILL.md +7 -14
  60. package/workflows/task/test/SKILL.zh-Hans.md +7 -14
  61. package/workflows/verify/auto/SKILL.md +9 -14
  62. package/workflows/verify/auto/SKILL.zh-Hans.md +9 -14
  63. package/workflows/verify/code-review/SKILL.md +8 -13
  64. package/workflows/verify/code-review/SKILL.zh-Hans.md +8 -13
  65. package/workflows/verify/design/SKILL.md +8 -12
  66. package/workflows/verify/design/SKILL.zh-Hans.md +7 -12
  67. package/workflows/verify/eval-review/SKILL.md +8 -12
  68. package/workflows/verify/eval-review/SKILL.zh-Hans.md +7 -12
  69. package/workflows/verify/multispec/SKILL.md +8 -15
  70. package/workflows/verify/multispec/SKILL.zh-Hans.md +7 -15
  71. package/workflows/verify/paranoid/SKILL.md +7 -14
  72. package/workflows/verify/paranoid/SKILL.zh-Hans.md +7 -14
  73. package/workflows/verify/progress/SKILL.md +8 -13
  74. package/workflows/verify/progress/SKILL.zh-Hans.md +8 -13
  75. package/workflows/verify/qa/SKILL.md +7 -13
  76. package/workflows/verify/qa/SKILL.zh-Hans.md +7 -13
  77. package/workflows/verify/second-opinion/SKILL.md +8 -12
  78. package/workflows/verify/second-opinion/SKILL.zh-Hans.md +7 -12
  79. package/workflows/verify/security/SKILL.md +8 -12
  80. package/workflows/verify/security/SKILL.zh-Hans.md +7 -12
  81. package/workflows/verify/simplify/SKILL.md +8 -12
  82. package/workflows/verify/simplify/SKILL.zh-Hans.md +7 -12
  83. package/workflows/verify/validate-phase/SKILL.md +8 -12
  84. package/workflows/verify/validate-phase/SKILL.zh-Hans.md +7 -12
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.13",
46
46
  description: "AI coding harness package manager + composition orchestrator",
47
47
  type: "module",
48
48
  license: "Apache-2.0",
@@ -1739,7 +1739,20 @@ var init_en = __esm({
1739
1739
  "manifest_add.gate_passed_wrote": "[manifest-add] EE-5 gate passed; wrote {{path}}",
1740
1740
  "manifest_add.gate_passed_dry_run": "[manifest-add] EE-5 gate passed (dry-run); would write {{path}}",
1741
1741
  "resume.fail": "\u2717 {{error}}",
1742
- "resume.corrupt": "\u2717 {{error}}\n path: {{path}}"
1742
+ "resume.corrupt": "\u2717 {{error}}\n path: {{path}}",
1743
+ "auto_update.consent_on": "[harnessed] auto-update ON",
1744
+ "auto_update.consent_off": "[harnessed] auto-update OFF",
1745
+ "auto_update.preferences_replaced": "[harnessed] the preferences file was unreadable (invalid JSON) \u2014 it has been replaced.",
1746
+ "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.`,
1747
+ "auto_update.path.host": " host: {{host}}",
1748
+ "auto_update.path.preferences": " preferences: {{path}}",
1749
+ "auto_update.path.status": " status: {{path}}",
1750
+ "auto_update.error.unsupported_host": "unsupported host: {{host}} (expected claude or codex)",
1751
+ "auto_update.error.runtime": "could not resolve the {{host}} update-reminder runtime",
1752
+ "auto_update.notice.updated_from": "harnessed updated {{from}} -> {{to}}.",
1753
+ "auto_update.notice.updated_to": "harnessed updated to {{to}}.",
1754
+ "auto_update.notice.restart": "Restart {{host}} so the new version + hooks take effect.",
1755
+ "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
1756
  };
1744
1757
  }
1745
1758
  });
@@ -3448,7 +3461,7 @@ function renderHumanTable(records) {
3448
3461
  }
3449
3462
  }
3450
3463
  function pipeToJq(filterExpr, lines) {
3451
- return new Promise((resolve40, reject) => {
3464
+ return new Promise((resolve42, reject) => {
3452
3465
  const child = spawn("jq", [filterExpr], {
3453
3466
  stdio: ["pipe", "inherit", "inherit"],
3454
3467
  windowsHide: true
@@ -3457,12 +3470,12 @@ function pipeToJq(filterExpr, lines) {
3457
3470
  const e = err2;
3458
3471
  if (e.code === "ENOENT") {
3459
3472
  console.error(t("audit_log.jq_missing"));
3460
- resolve40(1);
3473
+ resolve42(1);
3461
3474
  } else {
3462
3475
  reject(err2);
3463
3476
  }
3464
3477
  });
3465
- child.on("close", (code2) => resolve40(code2 ?? 0));
3478
+ child.on("close", (code2) => resolve42(code2 ?? 0));
3466
3479
  child.stdin.on("error", (err2) => {
3467
3480
  if (err2.code !== "EPIPE") reject(err2);
3468
3481
  });
@@ -3540,6 +3553,550 @@ var init_audit_log = __esm({
3540
3553
  ];
3541
3554
  }
3542
3555
  });
3556
+ function autoUpdateStatusPath(stateRoot) {
3557
+ return join(stateRoot, AUTO_UPDATE_STATUS_FILE);
3558
+ }
3559
+ function isFiniteNumber(value) {
3560
+ return typeof value === "number" && Number.isFinite(value);
3561
+ }
3562
+ function isPlainObject(value) {
3563
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3564
+ }
3565
+ function isValidDateMs(value) {
3566
+ return isFiniteNumber(value) && !Number.isNaN(new Date(value).getTime());
3567
+ }
3568
+ function parseProgress(value) {
3569
+ if (!isPlainObject(value)) return null;
3570
+ const { received, total, updatedAt } = value;
3571
+ if (!isFiniteNumber(received) || received < 0) return null;
3572
+ if (!isFiniteNumber(total) || total < 0) return null;
3573
+ if (!isValidDateMs(updatedAt)) return null;
3574
+ return { received, total, updatedAt };
3575
+ }
3576
+ function parseResult(value) {
3577
+ if (!isPlainObject(value)) return null;
3578
+ const { version, status, reason, message, at } = value;
3579
+ if (typeof version !== "string") return null;
3580
+ if (typeof status !== "string" || !RESULT_STATUSES.includes(status))
3581
+ return null;
3582
+ if (reason !== void 0 && typeof reason !== "string") return null;
3583
+ if (message !== void 0 && typeof message !== "string") return null;
3584
+ if (!isValidDateMs(at)) return null;
3585
+ const result = { version, status, at };
3586
+ if (typeof reason === "string") result.reason = reason;
3587
+ if (typeof message === "string") result.message = message;
3588
+ return result;
3589
+ }
3590
+ function parseNotice(value) {
3591
+ if (!isPlainObject(value)) return null;
3592
+ const { from, to, changelog, restart, at } = value;
3593
+ if (typeof from !== "string" || typeof to !== "string") return null;
3594
+ if (typeof changelog !== "string" || typeof restart !== "string") return null;
3595
+ if (!isValidDateMs(at)) return null;
3596
+ const consumedAt = typeof value.consumedAt === "number" && Number.isFinite(value.consumedAt) && value.consumedAt >= 0 ? value.consumedAt : 0;
3597
+ return { from, to, changelog, restart, at, consumedAt };
3598
+ }
3599
+ function parseStatus(value) {
3600
+ if (!isPlainObject(value)) return null;
3601
+ if (value.schemaVersion !== 1) return null;
3602
+ const consent = value.consent;
3603
+ if (!isPlainObject(consent)) return null;
3604
+ if (typeof consent.autoUpdate !== "boolean" || typeof consent.enabled !== "boolean") return null;
3605
+ if (typeof value.channel !== "string" || !CHANNELS.includes(value.channel))
3606
+ return null;
3607
+ if (typeof value.installed !== "string") return null;
3608
+ if (value.latest !== null && typeof value.latest !== "string") return null;
3609
+ if (typeof value.state !== "string" || !AUTO_UPDATE_STATES.includes(value.state))
3610
+ return null;
3611
+ const progress = parseProgress(value.progress);
3612
+ if (!progress) return null;
3613
+ const lastResult = value.lastResult === null ? null : parseResult(value.lastResult);
3614
+ if (value.lastResult !== null && !lastResult) return null;
3615
+ if (!Array.isArray(value.history)) return null;
3616
+ const history = [];
3617
+ for (const entry of value.history) {
3618
+ const parsed = parseResult(entry);
3619
+ if (!parsed) return null;
3620
+ history.push(parsed);
3621
+ }
3622
+ const notice = value.notice === null ? null : parseNotice(value.notice);
3623
+ if (value.notice !== null && !notice) return null;
3624
+ return {
3625
+ schemaVersion: 1,
3626
+ consent: { autoUpdate: consent.autoUpdate, enabled: consent.enabled },
3627
+ channel: value.channel,
3628
+ installed: value.installed,
3629
+ latest: value.latest,
3630
+ state: value.state,
3631
+ progress,
3632
+ lastResult,
3633
+ history,
3634
+ notice
3635
+ };
3636
+ }
3637
+ function readAutoUpdateStatus(path) {
3638
+ let text;
3639
+ try {
3640
+ text = readFileSync(path, "utf8");
3641
+ } catch {
3642
+ return null;
3643
+ }
3644
+ let parsed;
3645
+ try {
3646
+ parsed = JSON.parse(text);
3647
+ } catch {
3648
+ return null;
3649
+ }
3650
+ return parseStatus(parsed);
3651
+ }
3652
+ function writeAutoUpdateStatus(path, status) {
3653
+ const dir = dirname(path);
3654
+ mkdirSync(dir, { recursive: true });
3655
+ const tmp = `${path}.${process.pid}.${++tmpCounter}.tmp`;
3656
+ try {
3657
+ writeFileSync(tmp, `${JSON.stringify(status, null, 2)}
3658
+ `, "utf8");
3659
+ renameSync(tmp, path);
3660
+ } catch (error) {
3661
+ try {
3662
+ rmSync(tmp, { force: true });
3663
+ } catch {
3664
+ }
3665
+ throw error;
3666
+ }
3667
+ }
3668
+ function formatMegabytes(bytes) {
3669
+ return (bytes / 1024 / 1024).toFixed(1);
3670
+ }
3671
+ function formatTimestamp(at) {
3672
+ return new Date(at).toISOString().replace(/\.000Z$/, "Z");
3673
+ }
3674
+ function formatAutoUpdateStatus(status, now) {
3675
+ if (!status) {
3676
+ return ["auto-update: off", "installed: unknown latest: unknown state: idle"].join("\n");
3677
+ }
3678
+ const lines = [`auto-update: ${status.consent.autoUpdate ? "on" : "off"}`];
3679
+ const latest = status.latest ?? "unknown";
3680
+ let second = `installed: ${status.installed} latest: ${latest} state: ${status.state}`;
3681
+ if (status.progress.total > 0) {
3682
+ second += ` (${formatMegabytes(status.progress.received)} MB / ${formatMegabytes(status.progress.total)} MB)`;
3683
+ }
3684
+ lines.push(second);
3685
+ if (status.lastResult) {
3686
+ const { status: resultStatus, version, reason, at } = status.lastResult;
3687
+ const stamp = Number.isNaN(new Date(at).getTime()) ? now : at;
3688
+ const reasonText = reason ? REASON_TEXT[reason] ?? reason : "ok";
3689
+ lines.push(`last: ${resultStatus} ${version} (${reasonText}) at ${formatTimestamp(stamp)}`);
3690
+ }
3691
+ return lines.join("\n");
3692
+ }
3693
+ var AUTO_UPDATE_STATUS_FILE, AUTO_UPDATE_STATUS_PATH_ENV, AUTO_UPDATE_STATES, CHANNELS, RESULT_STATUSES, tmpCounter, REASON_TEXT;
3694
+ var init_autoUpdateStatus = __esm({
3695
+ "src/cli/lib/autoUpdateStatus.ts"() {
3696
+ AUTO_UPDATE_STATUS_FILE = "auto-update-status.json";
3697
+ AUTO_UPDATE_STATUS_PATH_ENV = "HARNESSED_AUTO_UPDATE_STATUS_PATH";
3698
+ AUTO_UPDATE_STATES = [
3699
+ "idle",
3700
+ "downloading",
3701
+ "verifying",
3702
+ "swapping",
3703
+ "handover",
3704
+ "updated",
3705
+ "failed",
3706
+ "skipped"
3707
+ ];
3708
+ CHANNELS = ["binary", "npm", "bun", "node"];
3709
+ RESULT_STATUSES = ["updated", "failed", "skipped"];
3710
+ tmpCounter = 0;
3711
+ REASON_TEXT = {
3712
+ "npm-channel": "npm channel \u2014 auto-update needs the binary channel"
3713
+ };
3714
+ }
3715
+ });
3716
+ function readRaw(path) {
3717
+ let descriptor;
3718
+ try {
3719
+ descriptor = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
3720
+ const info = fstatSync(descriptor);
3721
+ if (!info.isFile() || info.size > MAX_PREFERENCES_BYTES) return { kind: "unreadable" };
3722
+ const buffer = Buffer.alloc(info.size);
3723
+ const bytes = readSync(descriptor, buffer, 0, buffer.length, 0);
3724
+ return { kind: "parsed", value: JSON.parse(buffer.toString("utf8", 0, bytes)) };
3725
+ } catch (error) {
3726
+ if (error.code === "ENOENT") return { kind: "missing" };
3727
+ return { kind: "unreadable" };
3728
+ } finally {
3729
+ if (descriptor !== void 0) {
3730
+ try {
3731
+ closeSync(descriptor);
3732
+ } catch {
3733
+ }
3734
+ }
3735
+ }
3736
+ }
3737
+ function readUpdateReminderPreferencesFile(path) {
3738
+ const raw = readRaw(path);
3739
+ if (raw.kind === "missing") {
3740
+ return {
3741
+ preferences: { enabled: true, autoUpdate: false, unreadable: false },
3742
+ missing: true,
3743
+ document: null
3744
+ };
3745
+ }
3746
+ if (raw.kind === "unreadable") {
3747
+ return {
3748
+ preferences: { enabled: false, autoUpdate: false, unreadable: true },
3749
+ missing: false,
3750
+ document: null
3751
+ };
3752
+ }
3753
+ const value = raw.value;
3754
+ const record = typeof value === "object" && value !== null ? value : {};
3755
+ return {
3756
+ preferences: {
3757
+ enabled: record.enabled === true,
3758
+ // `autoUpdate` is INDEPENDENT of `enabled` — two separate consents.
3759
+ // Only a strict `true` counts; anything else is off.
3760
+ autoUpdate: record.autoUpdate === true,
3761
+ unreadable: false
3762
+ },
3763
+ missing: false,
3764
+ document: typeof value === "object" && value !== null ? record : null
3765
+ };
3766
+ }
3767
+ var MAX_PREFERENCES_BYTES;
3768
+ var init_updateReminderPreferences = __esm({
3769
+ "src/cli/lib/updateReminderPreferences.ts"() {
3770
+ MAX_PREFERENCES_BYTES = 64 * 1024;
3771
+ }
3772
+ });
3773
+
3774
+ // src/cli/lib/autoUpdateNotice.ts
3775
+ var autoUpdateNotice_exports = {};
3776
+ __export(autoUpdateNotice_exports, {
3777
+ consumeAutoUpdateNotice: () => consumeAutoUpdateNotice,
3778
+ formatAutoUpdateNotice: () => formatAutoUpdateNotice,
3779
+ isPrintableAutoUpdateNotice: () => isPrintableAutoUpdateNotice,
3780
+ readAutoUpdateNotice: () => readAutoUpdateNotice,
3781
+ writeAutoUpdateNotice: () => writeAutoUpdateNotice
3782
+ });
3783
+ function readAutoUpdateNotice(statusPath) {
3784
+ return readAutoUpdateStatus(statusPath)?.notice ?? null;
3785
+ }
3786
+ function isPrintableAutoUpdateNotice(notice) {
3787
+ if (!notice) return false;
3788
+ if (notice.to.trim() === "") return false;
3789
+ return (notice.consumedAt ?? 0) === 0;
3790
+ }
3791
+ function formatAutoUpdateNotice(notice) {
3792
+ const host = notice.restart.trim() || "Claude Code";
3793
+ const from = notice.from.trim();
3794
+ const lines = [];
3795
+ lines.push(
3796
+ from ? t("auto_update.notice.updated_from", { from, to: notice.to }) : t("auto_update.notice.updated_to", { to: notice.to })
3797
+ );
3798
+ const changelog = notice.changelog.trim();
3799
+ if (changelog) lines.push("", changelog);
3800
+ lines.push("", t("auto_update.notice.restart", { host }));
3801
+ if (host === "Codex") {
3802
+ lines.push(t("auto_update.notice.codex_trust"));
3803
+ }
3804
+ return lines.join("\n");
3805
+ }
3806
+ function writeAutoUpdateNotice(statusPath, notice) {
3807
+ const status = readAutoUpdateStatus(statusPath);
3808
+ if (!status) return false;
3809
+ try {
3810
+ writeAutoUpdateStatus(statusPath, { ...status, notice });
3811
+ return true;
3812
+ } catch {
3813
+ return false;
3814
+ }
3815
+ }
3816
+ function consumeAutoUpdateNotice(statusPath, now) {
3817
+ const status = readAutoUpdateStatus(statusPath);
3818
+ const notice = status?.notice;
3819
+ if (!status || !notice) return false;
3820
+ if ((notice.consumedAt ?? 0) !== 0) return false;
3821
+ if (notice.to.trim() === "") return false;
3822
+ try {
3823
+ writeAutoUpdateStatus(statusPath, { ...status, notice: { ...notice, consumedAt: now } });
3824
+ return true;
3825
+ } catch {
3826
+ return false;
3827
+ }
3828
+ }
3829
+ var init_autoUpdateNotice = __esm({
3830
+ "src/cli/lib/autoUpdateNotice.ts"() {
3831
+ init_i18n();
3832
+ init_autoUpdateStatus();
3833
+ }
3834
+ });
3835
+ var init_updateReminderCache = __esm({
3836
+ "src/cli/lib/updateReminderCache.ts"() {
3837
+ }
3838
+ });
3839
+ var init_updateReminderHookMain = __esm({
3840
+ "src/cli/updateReminderHookMain.ts"() {
3841
+ init_autoUpdateNotice();
3842
+ init_autoUpdateStatus();
3843
+ init_updateReminderCache();
3844
+ }
3845
+ });
3846
+ function canonicalStateRoot(hostId) {
3847
+ const override = process.env.HARNESSED_ROOT_OVERRIDE?.trim();
3848
+ if (override) return resolve(override);
3849
+ const nativeHome = hostId === "codex" ? process.env.CODEX_HOME?.trim() || join(homedir(), ".codex") : process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), ".claude");
3850
+ return resolve(join(nativeHome, "harnessed"));
3851
+ }
3852
+ var init_stateRoot = __esm({
3853
+ "src/platform/stateRoot.ts"() {
3854
+ }
3855
+ });
3856
+ function resolveUpdateReminderRuntime(options = {}) {
3857
+ const args = [...options.args ?? process.argv.slice(2)];
3858
+ if (args[0] === UPDATE_REMINDER_OPERATION || args[0] === UPDATE_REMINDER_WORKER_OPERATION)
3859
+ args.shift();
3860
+ let host = "claude";
3861
+ let explicitStateRoot;
3862
+ let platformSpecified = false;
3863
+ for (let index = 0; index < args.length; index += 2) {
3864
+ const flag = args[index];
3865
+ const value = args[index + 1];
3866
+ if (!flag || value === void 0 || [flag, value].some(
3867
+ (argument) => Array.from(argument).some((character) => character < " " || character === "\x7F")
3868
+ ))
3869
+ return null;
3870
+ if (flag === "--platform") {
3871
+ if (platformSpecified || value !== "claude" && value !== "codex") return null;
3872
+ platformSpecified = true;
3873
+ host = value;
3874
+ } else if (flag === "--state-root") {
3875
+ if (explicitStateRoot !== void 0 || !isAbsolute(value)) return null;
3876
+ explicitStateRoot = resolve(value);
3877
+ } else return null;
3878
+ }
3879
+ const nativeHome = resolve(
3880
+ (host === "codex" ? process.env.CODEX_HOME?.trim() : process.env.CLAUDE_CONFIG_DIR) || join(homedir(), host === "codex" ? ".codex" : ".claude")
3881
+ );
3882
+ const stateRoot = explicitStateRoot ?? canonicalStateRoot(host);
3883
+ const channel = options.compiled ? "binary" : process.versions.bun ? "bun" : "npm";
3884
+ const source = channel === "binary" ? BINARY_SOURCE : `${channel}:harnessed`;
3885
+ const fingerprint = createHash("sha256").update(
3886
+ JSON.stringify([
3887
+ host === "codex" ? stateRoot : nativeHome,
3888
+ process.execPath,
3889
+ package_default.version,
3890
+ source
3891
+ ])
3892
+ ).digest("hex");
3893
+ return {
3894
+ stateRoot,
3895
+ nativeHome,
3896
+ cachePath: join(stateRoot, `update-reminder-${host}.json`),
3897
+ preferencesPath: join(stateRoot, UPDATE_REMINDER_PREFERENCES_FILE),
3898
+ // The auto-update status file of THIS host — the hook reads the pending
3899
+ // update notice from it, the worker writes the run state into it.
3900
+ statusPath: autoUpdateStatusPath(stateRoot),
3901
+ installed: package_default.version,
3902
+ identity: {
3903
+ host,
3904
+ runtime: options.compiled ? "binary" : process.versions.bun ? "bun" : "node",
3905
+ channel,
3906
+ source,
3907
+ fingerprint
3908
+ },
3909
+ worker: {
3910
+ executable: process.execPath,
3911
+ args: [
3912
+ options.compiled ? UPDATE_REMINDER_WORKER_OPERATION : join(dirname(fileURLToPath(import.meta.url)), "harnessed-update-reminder-worker.mjs"),
3913
+ "--platform",
3914
+ host,
3915
+ ...explicitStateRoot ? ["--state-root", explicitStateRoot] : []
3916
+ ]
3917
+ }
3918
+ };
3919
+ }
3920
+ var UPDATE_REMINDER_OPERATION, UPDATE_REMINDER_WORKER_OPERATION, UPDATE_REMINDER_PREFERENCES_FILE, BINARY_SOURCE;
3921
+ var init_updateReminderEntrypoint = __esm({
3922
+ "src/compile/updateReminderEntrypoint.ts"() {
3923
+ init_package();
3924
+ init_autoUpdateStatus();
3925
+ init_updateReminderPreferences();
3926
+ init_updateReminderHookMain();
3927
+ init_stateRoot();
3928
+ UPDATE_REMINDER_OPERATION = "update-reminder";
3929
+ UPDATE_REMINDER_WORKER_OPERATION = "update-reminder-worker";
3930
+ UPDATE_REMINDER_PREFERENCES_FILE = "update-reminder-preferences.json";
3931
+ BINARY_SOURCE = "https://api.github.com/repos/easyinplay/harnessed/releases/latest";
3932
+ }
3933
+ });
3934
+
3935
+ // src/cli/autoUpdateCmd.ts
3936
+ var autoUpdateCmd_exports = {};
3937
+ __export(autoUpdateCmd_exports, {
3938
+ mergeAutoUpdateStatus: () => mergeAutoUpdateStatus,
3939
+ registerAutoUpdate: () => registerAutoUpdate,
3940
+ resolveAutoUpdateHostId: () => resolveAutoUpdateHostId,
3941
+ resolveAutoUpdatePaths: () => resolveAutoUpdatePaths,
3942
+ runAutoUpdate: () => runAutoUpdate,
3943
+ setAutoUpdateConsent: () => setAutoUpdateConsent
3944
+ });
3945
+ function resolveAutoUpdateHostId(platform) {
3946
+ if (platform !== void 0) {
3947
+ if (platform !== "claude" && platform !== "codex") {
3948
+ throw new Error(t("auto_update.error.unsupported_host", { host: platform }));
3949
+ }
3950
+ return platform;
3951
+ }
3952
+ const detected = detectPlatform().id;
3953
+ return detected === "codex" ? "codex" : "claude";
3954
+ }
3955
+ function toStatusChannel(channel) {
3956
+ return channel === "binary" || channel === "bun" || channel === "npm" || channel === "node" ? channel : "npm";
3957
+ }
3958
+ function resolveAutoUpdatePaths(platform) {
3959
+ const hostId = resolveAutoUpdateHostId(platform);
3960
+ const runtime = resolveUpdateReminderRuntime({
3961
+ args: ["--platform", hostId],
3962
+ compiled: isCompiledRuntime()
3963
+ });
3964
+ if (!runtime) {
3965
+ throw new Error(t("auto_update.error.runtime", { host: hostId }));
3966
+ }
3967
+ const stateRoot = canonicalStateRoot(hostId);
3968
+ return {
3969
+ hostId,
3970
+ stateRoot,
3971
+ preferencesPath: join(stateRoot, UPDATE_REMINDER_PREFERENCES_FILE),
3972
+ statusPath: autoUpdateStatusPath(stateRoot),
3973
+ channel: toStatusChannel(runtime.identity.channel),
3974
+ installed: runtime.installed
3975
+ };
3976
+ }
3977
+ function writePreferences(path, document) {
3978
+ mkdirSync(dirname(path), { recursive: true });
3979
+ const tmp = `${path}.${process.pid}.tmp`;
3980
+ try {
3981
+ writeFileSync(tmp, `${JSON.stringify(document, null, 2)}
3982
+ `, "utf8");
3983
+ renameSync(tmp, path);
3984
+ } catch (error) {
3985
+ try {
3986
+ rmSync(tmp, { force: true });
3987
+ } catch {
3988
+ }
3989
+ throw error;
3990
+ }
3991
+ }
3992
+ function setAutoUpdateConsent(path, autoUpdate) {
3993
+ const file = readUpdateReminderPreferencesFile(path);
3994
+ const document = file.document && !Array.isArray(file.document) ? file.document : null;
3995
+ const base = document ? { schemaVersion: 1, ...document } : { schemaVersion: 1, enabled: true };
3996
+ writePreferences(path, { ...base, autoUpdate });
3997
+ return {
3998
+ corrupt: file.preferences.unreadable,
3999
+ created: file.missing,
4000
+ enabled: base.enabled === true
4001
+ };
4002
+ }
4003
+ function mergeAutoUpdateStatus(paths, consent, status) {
4004
+ const base = status ?? {
4005
+ schemaVersion: 1,
4006
+ consent: { autoUpdate: consent.autoUpdate, enabled: consent.enabled },
4007
+ channel: paths.channel,
4008
+ installed: paths.installed,
4009
+ latest: null,
4010
+ state: "idle",
4011
+ progress: { received: 0, total: 0, updatedAt: 0 },
4012
+ lastResult: null,
4013
+ history: [],
4014
+ notice: null
4015
+ };
4016
+ return {
4017
+ ...base,
4018
+ consent: { autoUpdate: consent.autoUpdate, enabled: consent.enabled },
4019
+ channel: paths.channel
4020
+ };
4021
+ }
4022
+ function printPaths(paths) {
4023
+ console.log(t("auto_update.path.host", { host: paths.hostId }));
4024
+ console.log(t("auto_update.path.preferences", { path: paths.preferencesPath }));
4025
+ console.log(t("auto_update.path.status", { path: paths.statusPath }));
4026
+ }
4027
+ function setConsent(paths, autoUpdate) {
4028
+ const outcome = setAutoUpdateConsent(paths.preferencesPath, autoUpdate);
4029
+ console.log(t(autoUpdate ? "auto_update.consent_on" : "auto_update.consent_off"));
4030
+ if (outcome.corrupt) {
4031
+ console.log(t("auto_update.preferences_replaced"));
4032
+ }
4033
+ printPaths(paths);
4034
+ if (!outcome.enabled) {
4035
+ console.log(t("auto_update.reminder_off_note"));
4036
+ }
4037
+ }
4038
+ function printStatus(paths, json2) {
4039
+ const preferences = readUpdateReminderPreferencesFile(paths.preferencesPath);
4040
+ const status = readAutoUpdateStatus(paths.statusPath);
4041
+ const merged = mergeAutoUpdateStatus(
4042
+ paths,
4043
+ {
4044
+ autoUpdate: preferences.preferences.autoUpdate,
4045
+ enabled: preferences.preferences.enabled
4046
+ },
4047
+ status
4048
+ );
4049
+ if (json2) {
4050
+ console.log(
4051
+ JSON.stringify(
4052
+ {
4053
+ ...merged,
4054
+ host: paths.hostId,
4055
+ preferencesPath: paths.preferencesPath,
4056
+ statusPath: paths.statusPath
4057
+ },
4058
+ null,
4059
+ 2
4060
+ )
4061
+ );
4062
+ return;
4063
+ }
4064
+ console.log(formatAutoUpdateStatus(merged, Date.now()));
4065
+ printPaths(paths);
4066
+ }
4067
+ async function runAutoUpdate(action, opts) {
4068
+ let paths;
4069
+ try {
4070
+ paths = resolveAutoUpdatePaths(opts.platform);
4071
+ } catch (error) {
4072
+ console.warn(`[harnessed] ${error instanceof Error ? error.message : String(error)}`);
4073
+ process.exitCode = 1;
4074
+ return;
4075
+ }
4076
+ if (action === "status") {
4077
+ printStatus(paths, opts.json === true);
4078
+ return;
4079
+ }
4080
+ setConsent(paths, action === "on");
4081
+ }
4082
+ function registerAutoUpdate(program2) {
4083
+ program2.command("auto-update").description("Turn the background auto-update on or off, or show its consent + last run status").addArgument(
4084
+ new Argument("<action>", "on | off | status").choices(["on", "off", "status"])
4085
+ ).option("--platform <host>", "target host: claude | codex").option("--json", "emit the merged status as one JSON object").action(async (action, opts) => {
4086
+ await runAutoUpdate(action, opts);
4087
+ });
4088
+ }
4089
+ var init_autoUpdateCmd = __esm({
4090
+ "src/cli/autoUpdateCmd.ts"() {
4091
+ init_updateReminderEntrypoint();
4092
+ init_i18n();
4093
+ init_assetsRoot();
4094
+ init_platform();
4095
+ init_stateRoot();
4096
+ init_autoUpdateStatus();
4097
+ init_updateReminderPreferences();
4098
+ }
4099
+ });
3543
4100
  function getBackupRoot(hostContext) {
3544
4101
  return hostContext ? join(hostContext.platform.stateRoot, "backups") : harnessedSubdir("backups");
3545
4102
  }
@@ -3897,69 +4454,191 @@ function registerCheckDocs(program2) {
3897
4454
  "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
4455
  ).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
4456
  }
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
- ];
4457
+ var DEFAULT_MAX_STATE_LINES, KEY_DECISIONS_SECTION_RE, KEY_DECISIONS_SECTION_LIMIT, HISTORICAL_ERRATA_RE, ROADMAP_NARRATIVE_SIGNALS;
4458
+ var init_checkDocs = __esm({
4459
+ "src/cli/checkDocs.ts"() {
4460
+ init_i18n();
4461
+ init_ablation();
4462
+ DEFAULT_MAX_STATE_LINES = 100;
4463
+ KEY_DECISIONS_SECTION_RE = /^##\s+.*关键决议\s*ship\s*总结/gm;
4464
+ KEY_DECISIONS_SECTION_LIMIT = 1;
4465
+ HISTORICAL_ERRATA_RE = /W-[1-9]\s+errata|sister\s+review\s+M[1-9]\s+修正/;
4466
+ ROADMAP_NARRATIVE_SIGNALS = [
4467
+ { id: "commit-hash", test: hasCommitHash },
4468
+ { id: "test-tally", test: (l) => /\b\d{2,}\s*\/\s*0\b/.test(l) },
4469
+ { id: "ci-verdict", test: (l) => /\bCI\s+(green|red|绿|红)/i.test(l) },
4470
+ { id: "lesson", test: (l) => /(教训|lesson\s*[::]|lessons?\s+learned)/i.test(l) }
4471
+ ];
4472
+ }
4473
+ });
4474
+
4475
+ // src/platform/runDeps.ts
4476
+ function captureRunDeps() {
4477
+ const stdout2 = [];
4478
+ const stderr = [];
4479
+ const deps = {
4480
+ exit(code2) {
4481
+ throw new ExitError(code2);
4482
+ },
4483
+ log: (...args) => {
4484
+ stdout2.push(args.map(String).join(" "));
4485
+ },
4486
+ error: (...args) => {
4487
+ stderr.push(args.map(String).join(" "));
4488
+ },
4489
+ warn: (...args) => {
4490
+ stderr.push(args.map(String).join(" "));
4491
+ }
4492
+ };
4493
+ return { deps, stdout: stdout2, stderr };
4494
+ }
4495
+ var ExitError, defaultRunDeps;
4496
+ var init_runDeps = __esm({
4497
+ "src/platform/runDeps.ts"() {
4498
+ ExitError = class extends Error {
4499
+ constructor(code2) {
4500
+ super(`process.exit(${code2})`);
4501
+ this.code = code2;
4502
+ this.name = "ExitError";
4503
+ }
4504
+ code;
4505
+ };
4506
+ defaultRunDeps = {
4507
+ exit(code2) {
4508
+ return process.exit(code2);
4509
+ },
4510
+ log: (...args) => {
4511
+ console.log(...args);
4512
+ },
4513
+ error: (...args) => {
4514
+ console.error(...args);
4515
+ },
4516
+ warn: (...args) => {
4517
+ console.warn(...args);
4518
+ }
4519
+ };
4520
+ }
4521
+ });
4522
+
4523
+ // src/workflow/lib/promiseExtract.ts
4524
+ function extractPromise(text) {
4525
+ const match = text.match(PROMISE_PATTERN);
4526
+ return match ? match[1] : null;
4527
+ }
4528
+ var PROMISE_PATTERN;
4529
+ var init_promiseExtract = __esm({
4530
+ "src/workflow/lib/promiseExtract.ts"() {
4531
+ PROMISE_PATTERN = /<promise>([^<]+)<\/promise>/;
4532
+ }
4533
+ });
4534
+
4535
+ // src/workflow/lib/fallbackHandlers.ts
4536
+ function handleMaxIterationsExceeded(err2, fallback, ctx) {
4537
+ const yamlShort = fallback.message.replace(
4538
+ /\{\{\s*args\.max_iterations\s*\}\}/g,
4539
+ String(ctx.maxIterations)
4540
+ );
4541
+ const truncated = (ctx.lastMessage ?? "<empty>").slice(0, 500);
4542
+ const uxText = `\u274C ralph-loop max-iterations exceeded (${err2.iterations}/${ctx.maxIterations}).
4543
+ Sub-task: ${ctx.subtaskSummary}
4544
+ Workflow: ${ctx.workflowName} / phase ${ctx.phaseId}
4545
+ Last subagent output (truncated): ${truncated}
4546
+ The subagent attempted ${err2.iterations} iterations without emitting verbatim "<promise>COMPLETE</promise>".
4547
+ This indicates one of:
4548
+ 1. Sub-task is genuinely incomplete (escalate to user / re-scope)
4549
+ 2. Subagent is stuck in a loop (review prompt / system instructions)
4550
+ 3. max-iterations too low (override via --max-iterations <N>, hard upper limit 100)
4551
+ Manual options:
4552
+ A) Continue with current state: \`harnessed workflow resume --skip-completion-gate\`
4553
+ B) Re-run from last checkpoint: \`harnessed workflow resume --from-checkpoint\`
4554
+ C) Abort cleanly: exit 1
4555
+ Exit code: ${fallback.exit_code}
4556
+ ${yamlShort}`;
4557
+ console.error(uxText);
4558
+ throw new WorkflowHaltError(
4559
+ `ralph-loop max-iterations exceeded (${err2.iterations}/${ctx.maxIterations}) for ${ctx.workflowName} / phase ${ctx.phaseId}`,
4560
+ fallback.exit_code
4561
+ );
4562
+ }
4563
+ var WorkflowHaltError;
4564
+ var init_fallbackHandlers = __esm({
4565
+ "src/workflow/lib/fallbackHandlers.ts"() {
4566
+ WorkflowHaltError = class extends Error {
4567
+ constructor(message, exitCode) {
4568
+ super(message);
4569
+ this.exitCode = exitCode;
4570
+ this.name = "WorkflowHaltError";
4571
+ }
4572
+ exitCode;
4573
+ };
4574
+ }
4575
+ });
4576
+
4577
+ // src/workflow/lib/ralphLoop.ts
4578
+ function isComplete(output) {
4579
+ let env;
4580
+ try {
4581
+ env = JSON.parse(output);
4582
+ } catch {
4583
+ return extractPromise(output) === "COMPLETE";
4584
+ }
4585
+ const succeeded = env.subtype === "success";
4586
+ const status = env.structured_output?.status;
4587
+ if (status === "COMPLETE") return succeeded;
4588
+ if (status === "PARTIAL" || status === "BLOCKED") return false;
4589
+ if (succeeded) return true;
4590
+ return extractPromise(env.text ?? env.result ?? "") === "COMPLETE";
4591
+ }
4592
+ async function ralphLoopWrap(spawn10, maxIter) {
4593
+ let last = "";
4594
+ let sessionId;
4595
+ for (let i = 0; i < maxIter; i++) {
4596
+ last = await spawn10(sessionId, (id) => {
4597
+ sessionId = id;
4598
+ });
4599
+ if (isComplete(last)) return last;
4600
+ }
4601
+ throw new MaxIterationsExceededError(maxIter);
4602
+ }
4603
+ var MaxIterationsExceededError;
4604
+ var init_ralphLoop = __esm({
4605
+ "src/workflow/lib/ralphLoop.ts"() {
4606
+ init_promiseExtract();
4607
+ init_fallbackHandlers();
4608
+ MaxIterationsExceededError = class extends Error {
4609
+ constructor(iterations) {
4610
+ super(`ralph-loop max-iterations exceeded after ${iterations} attempts`);
4611
+ this.iterations = iterations;
4612
+ this.name = "MaxIterationsExceededError";
4613
+ }
4614
+ iterations;
4615
+ };
3915
4616
  }
3916
4617
  });
3917
4618
 
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(" "));
4619
+ // src/checkpoint/completionClaim.ts
4620
+ var completionClaim_exports = {};
4621
+ __export(completionClaim_exports, {
4622
+ verifyCompletionClaim: () => verifyCompletionClaim
4623
+ });
4624
+ async function verifyCompletionClaim(input) {
4625
+ if (input.resultFile) {
4626
+ let text;
4627
+ try {
4628
+ text = await readFile(input.resultFile, "utf8");
4629
+ } catch {
4630
+ return { verdict: "incomplete", source: input.resultFile };
3934
4631
  }
3935
- };
3936
- return { deps, stdout: stdout2, stderr };
4632
+ return { verdict: isComplete(text) ? "complete" : "incomplete", source: input.resultFile };
4633
+ }
4634
+ if (typeof input.result === "string" && input.result.trim() !== "") {
4635
+ return { verdict: isComplete(input.result) ? "complete" : "incomplete", source: "--result" };
4636
+ }
4637
+ return { verdict: "not_provided", source: null };
3937
4638
  }
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
- };
4639
+ var init_completionClaim = __esm({
4640
+ "src/checkpoint/completionClaim.ts"() {
4641
+ init_ralphLoop();
3963
4642
  }
3964
4643
  });
3965
4644
 
@@ -4143,7 +4822,7 @@ function resolveWindowsBin(bin, env = process.env, isFile = (p8) => existsSync(p
4143
4822
  const candidates = extname(bin) ? [""] : exts;
4144
4823
  for (const dir of dirs) {
4145
4824
  for (const ext of candidates) {
4146
- const p8 = join17(dir, `${bin}${ext}`);
4825
+ const p8 = join21(dir, `${bin}${ext}`);
4147
4826
  if (isFile(p8)) return p8;
4148
4827
  }
4149
4828
  }
@@ -4158,10 +4837,10 @@ function planWindowsSpawn(bin, args, resolved) {
4158
4837
  const line = [escapeCommand(resolved), ...args.map((a) => escapeArgument(a))].join(" ");
4159
4838
  return { command: "cmd.exe", args: ["/d", "/s", "/c", `"${line}"`], verbatim: true };
4160
4839
  }
4161
- var extname, join17, META;
4840
+ var extname, join21, META;
4162
4841
  var init_winSpawn = __esm({
4163
4842
  "src/installers/lib/winSpawn.ts"() {
4164
- ({ extname, join: join17 } = win32);
4843
+ ({ extname, join: join21 } = win32);
4165
4844
  META = /([()\][%!^"`<>&|;, *?])/g;
4166
4845
  }
4167
4846
  });
@@ -4184,7 +4863,7 @@ function withHostInstallEnv(env, hostContext) {
4184
4863
  return { ...result, ...pins };
4185
4864
  }
4186
4865
  function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3, hostContext) {
4187
- return new Promise((resolve40) => {
4866
+ return new Promise((resolve42) => {
4188
4867
  const isWin = (hostContext?.os ?? process.platform) === "win32";
4189
4868
  const envOpts = hostContext ? { env: withHostInstallEnv(process.env, hostContext) } : {};
4190
4869
  const stdio = ["ignore", "pipe", "pipe"];
@@ -4212,17 +4891,17 @@ function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3, hostContext) {
4212
4891
  });
4213
4892
  const timer = setTimeout(() => {
4214
4893
  killProcessTree(child);
4215
- resolve40({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
4894
+ resolve42({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
4216
4895
  }, timeoutMs);
4217
4896
  child.on("error", (e) => {
4218
4897
  clearTimeout(timer);
4219
4898
  const enoent = e.code === "ENOENT";
4220
4899
  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}` });
4900
+ resolve42({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
4222
4901
  });
4223
4902
  child.on("close", (code2) => {
4224
4903
  clearTimeout(timer);
4225
- resolve40({ exitCode: code2 ?? -1, stdout: stdout2, stderr });
4904
+ resolve42({ exitCode: code2 ?? -1, stdout: stdout2, stderr });
4226
4905
  });
4227
4906
  });
4228
4907
  }
@@ -4504,9 +5183,62 @@ var init_readClaudeConfig = __esm({
4504
5183
  init_codexPlugins();
4505
5184
  }
4506
5185
  });
5186
+
5187
+ // src/platform/lockContention.ts
5188
+ function isLockContention(error) {
5189
+ return error?.code === "ELOCKED";
5190
+ }
5191
+ function isLockNotHeld(error) {
5192
+ const code2 = error?.code;
5193
+ return code2 === "ERELEASED" || code2 === "ENOTACQUIRED";
5194
+ }
5195
+ function lockBackoffDelay(attempt, budget) {
5196
+ return Math.min(budget.minTimeout * 2 ** attempt, budget.maxTimeout);
5197
+ }
5198
+ async function acquireWithContentionRetry(acquire, budget) {
5199
+ for (let attempt = 0; ; attempt += 1) {
5200
+ try {
5201
+ return await acquire();
5202
+ } catch (error) {
5203
+ if (!isLockContention(error) || attempt >= budget.retries) throw error;
5204
+ await sleep(lockBackoffDelay(attempt, budget));
5205
+ }
5206
+ }
5207
+ }
5208
+ async function releaseLockIdempotently(release) {
5209
+ try {
5210
+ await release();
5211
+ } catch (error) {
5212
+ if (!isLockNotHeld(error)) throw error;
5213
+ }
5214
+ }
5215
+ var sleep;
5216
+ var init_lockContention = __esm({
5217
+ "src/platform/lockContention.ts"() {
5218
+ sleep = (ms) => new Promise((resolve42) => {
5219
+ setTimeout(resolve42, ms);
5220
+ });
5221
+ }
5222
+ });
4507
5223
  function lockRoots(hostContext) {
4508
5224
  return [join(hostContext?.nativeHome ?? detectPlatform().homeDir, "harnessed")];
4509
5225
  }
5226
+ function lockTarget2(root) {
5227
+ return join(root, ".settings-transaction.lock");
5228
+ }
5229
+ async function acquireSettingsLock(root) {
5230
+ const target = lockTarget2(root);
5231
+ return acquireWithContentionRetry(
5232
+ () => lockfile.lock(target, {
5233
+ stale: 6e4,
5234
+ // One attempt only — the retry loop owns the backoff.
5235
+ retries: 0,
5236
+ lockfilePath: target,
5237
+ realpath: false
5238
+ }),
5239
+ SETTINGS_TRANSACTION_LOCK_RETRIES
5240
+ );
5241
+ }
4510
5242
  async function withSettingsTransactionLock(hostContext, work) {
4511
5243
  const active = heldLocks.getStore();
4512
5244
  const roots = lockRoots(hostContext);
@@ -4517,31 +5249,25 @@ async function withSettingsTransactionLock(hostContext, work) {
4517
5249
  for (const root of roots) {
4518
5250
  if (next.has(root)) continue;
4519
5251
  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
- );
5252
+ releases.push(await acquireSettingsLock(root));
4533
5253
  next.add(root);
4534
5254
  }
4535
5255
  return await heldLocks.run(next, work);
4536
5256
  } finally {
4537
- for (const release of releases.reverse()) await release();
5257
+ for (const release of releases.reverse()) await releaseLockIdempotently(release);
4538
5258
  }
4539
5259
  }
4540
- var heldLocks;
5260
+ var heldLocks, SETTINGS_TRANSACTION_LOCK_RETRIES;
4541
5261
  var init_settingsTransactionLock = __esm({
4542
5262
  "src/cli/lib/settingsTransactionLock.ts"() {
5263
+ init_lockContention();
4543
5264
  init_platform();
4544
5265
  heldLocks = new AsyncLocalStorage();
5266
+ SETTINGS_TRANSACTION_LOCK_RETRIES = {
5267
+ retries: 30,
5268
+ minTimeout: 250,
5269
+ maxTimeout: 4e3
5270
+ };
4545
5271
  }
4546
5272
  });
4547
5273
  function settingsOwnershipReceiptPath(hostContext) {
@@ -5293,135 +6019,13 @@ function assertionDelta(diff) {
5293
6019
  var execFileP, TDD_EVIDENCE_ARTIFACT, RED_MARKER, GREEN_MARKER, SKIP_DECLARATION, SCOPE, ASSERTION_TOKEN;
5294
6020
  var init_tddBoundary = __esm({
5295
6021
  "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();
6022
+ execFileP = promisify(execFile);
6023
+ TDD_EVIDENCE_ARTIFACT = "tdd-evidence.md";
6024
+ RED_MARKER = /\b(red|fail(?:s|ed|ing|ure)?)\b/i;
6025
+ GREEN_MARKER = /\b(green|pass(?:es|ed|ing)?)\b/i;
6026
+ SKIP_DECLARATION = /\bSKIPPED\b\s*[—–:-]\s*\S+/i;
6027
+ SCOPE = ["--", "."];
6028
+ ASSERTION_TOKEN = /\b(expect|assert\w*|should|toBe\w*|toEqual|toThrow|toMatch)\b|\.to\./;
5425
6029
  }
5426
6030
  });
5427
6031
 
@@ -6513,6 +7117,8 @@ var init_intentKind = __esm({
6513
7117
  // src/cli/checkpoint.ts
6514
7118
  var checkpoint_exports = {};
6515
7119
  __export(checkpoint_exports, {
7120
+ parsePlan: () => parsePlan,
7121
+ parseWaitSeconds: () => parseWaitSeconds,
6516
7122
  registerCheckpoint: () => registerCheckpoint,
6517
7123
  runCheckpointAdopt: () => runCheckpointAdopt,
6518
7124
  runCheckpointComplete: () => runCheckpointComplete,
@@ -6542,7 +7148,18 @@ async function parsePlan(raw) {
6542
7148
  };
6543
7149
  if (typeof p8.master === "string") plan.master = p8.master;
6544
7150
  if (p8.parallelism && typeof p8.parallelism === "object" && !Array.isArray(p8.parallelism)) {
6545
- plan.parallelism = p8.parallelism;
7151
+ const par = p8.parallelism;
7152
+ const parallelism = {
7153
+ escalate_to_teams: typeof par.escalate_to_teams === "boolean" ? par.escalate_to_teams : false,
7154
+ reason: typeof par.reason === "string" ? par.reason : null
7155
+ };
7156
+ if (typeof par.teams_active === "boolean") parallelism.teams_active = par.teams_active;
7157
+ if (par.transport === "subagent" || par.transport === "teammate") {
7158
+ parallelism.transport = par.transport;
7159
+ }
7160
+ if (par.result_contract === "result-file") parallelism.result_contract = par.result_contract;
7161
+ if (typeof par.bounded_wait === "boolean") parallelism.bounded_wait = par.bounded_wait;
7162
+ plan.parallelism = parallelism;
6546
7163
  }
6547
7164
  return plan;
6548
7165
  }
@@ -6586,6 +7203,28 @@ function enforceSerialOrder(action, sub, blockers, force, deps = defaultRunDeps)
6586
7203
  );
6587
7204
  return true;
6588
7205
  }
7206
+ function parseWaitSeconds(raw) {
7207
+ if (raw === void 0) return null;
7208
+ const trimmed = raw.trim();
7209
+ if (!/^\d+$/.test(trimmed)) return null;
7210
+ const seconds = Number(trimmed);
7211
+ if (!Number.isInteger(seconds) || seconds < 0 || seconds > RESULT_WAIT_MAX_SECONDS) return null;
7212
+ return seconds;
7213
+ }
7214
+ function sleep2(ms) {
7215
+ return new Promise((resolve42) => setTimeout(resolve42, ms));
7216
+ }
7217
+ async function waitForResultClaim(resultFile, seconds, pollMs) {
7218
+ const { verifyCompletionClaim: verifyCompletionClaim2 } = await Promise.resolve().then(() => (init_completionClaim(), completionClaim_exports));
7219
+ const deadline = Date.now() + seconds * 1e3;
7220
+ for (; ; ) {
7221
+ const claim = await verifyCompletionClaim2({ resultFile });
7222
+ if (claim.verdict === "complete") return true;
7223
+ const remaining = deadline - Date.now();
7224
+ if (remaining <= 0) return false;
7225
+ await sleep2(Math.min(pollMs, remaining));
7226
+ }
7227
+ }
6589
7228
  async function runCheckpointStart(sub, opts, deps = defaultRunDeps) {
6590
7229
  const { activatePhase: activatePhase2 } = await Promise.resolve().then(() => (init_engineHook(), engineHook_exports));
6591
7230
  try {
@@ -6685,6 +7324,28 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
6685
7324
  deps.exit(1);
6686
7325
  return;
6687
7326
  }
7327
+ const waitSeconds = opts.wait ?? 0;
7328
+ let waitTimeoutMessage;
7329
+ if (waitSeconds > 0) {
7330
+ const resultFile = opts.resultFile;
7331
+ if (!resultFile) {
7332
+ deps.error(
7333
+ "[harnessed] checkpoint complete: --wait \u5FC5\u987B\u642D\u914D --result-file \u2014\u2014 \u6CA1\u6709\u53EF\u7B49\u5F85\u7684\u7ED3\u679C\u6587\u4EF6"
7334
+ );
7335
+ deps.exit(2);
7336
+ return;
7337
+ }
7338
+ const pollMs = opts.waitPollMs ?? RESULT_WAIT_POLL_MS;
7339
+ deps.log(
7340
+ `[harnessed] \u7B49\u5F85 ${waitSeconds}s \u5185 ${resultFile} \u643A\u5E26\u5B8C\u6210\u6807\u8BB0\uFF08\u6BCF ${pollMs}ms \u8F6E\u8BE2\u4E00\u6B21\uFF09`
7341
+ );
7342
+ const ready = await waitForResultClaim(resultFile, waitSeconds, pollMs);
7343
+ if (ready) {
7344
+ deps.log(`[harnessed] \u7ED3\u679C\u6587\u4EF6\u5DF2\u5C31\u7EEA: ${resultFile}`);
7345
+ } else {
7346
+ 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`;
7347
+ }
7348
+ }
6688
7349
  const { checkArtifacts: checkArtifacts2 } = await Promise.resolve().then(() => (init_evidence(), evidence_exports));
6689
7350
  const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
6690
7351
  const { getAssetsRoot: getAssetsRoot3 } = await Promise.resolve().then(() => (init_assetsRoot(), assetsRoot_exports));
@@ -6716,7 +7377,19 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
6716
7377
  `\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
7378
  );
6718
7379
  }
6719
- const allMissing = [...result.missing, ...syncResult.missing, ...boundaryBlocks, ...claimBlocks];
7380
+ const waitBlocks = waitTimeoutMessage !== void 0 ? [waitTimeoutMessage] : [];
7381
+ const allMissing = [
7382
+ ...result.missing,
7383
+ ...syncResult.missing,
7384
+ ...boundaryBlocks,
7385
+ ...claimBlocks,
7386
+ ...waitBlocks
7387
+ ];
7388
+ if (waitTimeoutMessage !== void 0 && opts.force) {
7389
+ deps.warn(
7390
+ `[harnessed] checkpoint complete ${waitTimeoutMessage}\uFF08--force: \u5DF2\u8BB0\u4E3A audited override\uFF09`
7391
+ );
7392
+ }
6720
7393
  if (allMissing.length > 0 && !opts.force) {
6721
7394
  deps.error(
6722
7395
  `[harnessed] checkpoint complete BLOCKED: ${sub} \u2014 ${allMissing.length} item(s) missing (evidence guard + .planning/ sync, fail-closed):`
@@ -7081,6 +7754,9 @@ function registerCheckpoint(program2) {
7081
7754
  ).option(
7082
7755
  "--result-file <path>",
7083
7756
  "complete only \u2014 same as --result but read from a file (quoting-safe on Windows); wins over --result"
7757
+ ).option(
7758
+ "--wait <seconds>",
7759
+ `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
7760
  ).option(
7085
7761
  "--reason <text>",
7086
7762
  "reopen only \u2014 why the sub is coming back (required); recorded on the ledger entry and surfaced by the per-turn injector"
@@ -7102,6 +7778,13 @@ function registerCheckpoint(program2) {
7102
7778
  process.exit(1);
7103
7779
  return;
7104
7780
  }
7781
+ if (opts.wait !== void 0 && action !== "complete") {
7782
+ console.error(
7783
+ `[harnessed] checkpoint ${action}: --wait \u53EA\u5BF9 \`checkpoint complete\` \u6709\u6548`
7784
+ );
7785
+ process.exit(2);
7786
+ return;
7787
+ }
7105
7788
  if (action === "adopt") {
7106
7789
  await runCheckpointAdopt(opts);
7107
7790
  return;
@@ -7149,7 +7832,33 @@ function registerCheckpoint(program2) {
7149
7832
  return;
7150
7833
  }
7151
7834
  if (action === "complete") {
7152
- await runCheckpointComplete(sub, opts);
7835
+ let waitSeconds;
7836
+ if (opts.wait !== void 0) {
7837
+ const parsed = parseWaitSeconds(opts.wait);
7838
+ if (parsed === null) {
7839
+ console.error(
7840
+ `[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`
7841
+ );
7842
+ process.exit(2);
7843
+ return;
7844
+ }
7845
+ if (!opts.resultFile) {
7846
+ console.error(
7847
+ "[harnessed] checkpoint complete: --wait \u5FC5\u987B\u642D\u914D --result-file \u2014\u2014 \u6CA1\u6709\u53EF\u7B49\u5F85\u7684\u7ED3\u679C\u6587\u4EF6"
7848
+ );
7849
+ process.exit(2);
7850
+ return;
7851
+ }
7852
+ waitSeconds = parsed;
7853
+ }
7854
+ await runCheckpointComplete(sub, {
7855
+ ...opts.summary !== void 0 ? { summary: opts.summary } : {},
7856
+ ...opts.force !== void 0 ? { force: opts.force } : {},
7857
+ ...opts.tokens !== void 0 ? { tokens: opts.tokens } : {},
7858
+ ...opts.result !== void 0 ? { result: opts.result } : {},
7859
+ ...opts.resultFile !== void 0 ? { resultFile: opts.resultFile } : {},
7860
+ ...waitSeconds !== void 0 ? { wait: waitSeconds } : {}
7861
+ });
7153
7862
  return;
7154
7863
  }
7155
7864
  if (action === "reopen") {
@@ -7160,7 +7869,7 @@ function registerCheckpoint(program2) {
7160
7869
  }
7161
7870
  );
7162
7871
  }
7163
- var ACTIONS;
7872
+ var ACTIONS, RESULT_WAIT_MAX_SECONDS, RESULT_WAIT_POLL_MS;
7164
7873
  var init_checkpoint = __esm({
7165
7874
  "src/cli/checkpoint.ts"() {
7166
7875
  init_path_guard();
@@ -7168,6 +7877,8 @@ var init_checkpoint = __esm({
7168
7877
  init_runDeps();
7169
7878
  init_ledger();
7170
7879
  ACTIONS = ["start", "complete", "fail", "reopen", "intent", "adopt"];
7880
+ RESULT_WAIT_MAX_SECONDS = 600;
7881
+ RESULT_WAIT_POLL_MS = 2e3;
7171
7882
  }
7172
7883
  });
7173
7884
 
@@ -7311,8 +8022,8 @@ function compute(d) {
7311
8022
  }
7312
8023
  const gitFirst = d.where("git")[0];
7313
8024
  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")]) {
8025
+ const root = dirname15(dirname15(gitFirst));
8026
+ for (const cand of [join34(root, "bin", "bash.exe"), join34(root, "usr", "bin", "bash.exe")]) {
7316
8027
  if (d.exists(cand) && usable(cand)) return { path: cand, source: "git-derived", wslOnPath };
7317
8028
  }
7318
8029
  }
@@ -7320,13 +8031,13 @@ function compute(d) {
7320
8031
  d.env.ProgramFiles,
7321
8032
  d.env.ProgramW6432,
7322
8033
  d.env["ProgramFiles(x86)"],
7323
- d.env.LOCALAPPDATA ? join30(d.env.LOCALAPPDATA, "Programs") : void 0
8034
+ d.env.LOCALAPPDATA ? join34(d.env.LOCALAPPDATA, "Programs") : void 0
7324
8035
  ];
7325
8036
  for (const base of bases) {
7326
8037
  if (!base) continue;
7327
8038
  for (const cand of [
7328
- join30(base, "Git", "bin", "bash.exe"),
7329
- join30(base, "Git", "usr", "bin", "bash.exe")
8039
+ join34(base, "Git", "bin", "bash.exe"),
8040
+ join34(base, "Git", "usr", "bin", "bash.exe")
7330
8041
  ]) {
7331
8042
  if (d.exists(cand) && usable(cand))
7332
8043
  return { path: cand, source: "standard-location", wslOnPath };
@@ -7339,10 +8050,10 @@ function compute(d) {
7339
8050
  }
7340
8051
  return { path: "bash", source: "path-fallback" };
7341
8052
  }
7342
- var dirname12, join30, WSL_STUB_RE, cache4;
8053
+ var dirname15, join34, WSL_STUB_RE, cache4;
7343
8054
  var init_resolveBash = __esm({
7344
8055
  "src/installers/lib/resolveBash.ts"() {
7345
- ({ dirname: dirname12, join: join30 } = win32);
8056
+ ({ dirname: dirname15, join: join34 } = win32);
7346
8057
  WSL_STUB_RE = /[\\/](windows[\\/](system32|sysnative|syswow64)|microsoft[\\/]windowsapps)[\\/]bash\.exe$/i;
7347
8058
  cache4 = null;
7348
8059
  }
@@ -7724,21 +8435,39 @@ var init_check_token_budget = __esm({
7724
8435
  PER_SKILL_THRESHOLD = 5e3;
7725
8436
  }
7726
8437
  });
8438
+ function isEnabledValue(value) {
8439
+ if (typeof value !== "string") return false;
8440
+ const normalized2 = value.trim().toLowerCase();
8441
+ return normalized2 === "1" || normalized2 === "true";
8442
+ }
8443
+ function resolveAgentTeamsStatus(input) {
8444
+ const { envValue, settingsValue } = input;
8445
+ const envOn = isEnabledValue(envValue);
8446
+ const settingsOn = isEnabledValue(settingsValue);
8447
+ const status = {
8448
+ active: envOn || settingsOn,
8449
+ source: envOn ? "env" : settingsOn ? "settings" : "none"
8450
+ };
8451
+ if (envValue !== void 0) status.envValue = envValue;
8452
+ if (settingsValue !== void 0) status.settingsValue = settingsValue;
8453
+ return status;
8454
+ }
7727
8455
  async function checkAgentTeams() {
7728
8456
  const envValue = process.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS;
7729
- const envOn = envValue === "1";
7730
8457
  let settingsValue;
7731
- let settingsOn = false;
7732
8458
  try {
7733
8459
  const path = getSettingsPath();
7734
8460
  const raw = path === null ? "{}" : await readFile(path, "utf8");
7735
8461
  const data = JSON.parse(raw);
7736
8462
  settingsValue = data.env?.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS;
7737
- settingsOn = settingsValue === "1";
7738
8463
  } catch {
7739
8464
  }
7740
- const detected = { env: envOn, settingsJson: settingsOn };
7741
- if (envOn || settingsOn) {
8465
+ const detected = {
8466
+ env: isEnabledValue(envValue),
8467
+ settingsJson: isEnabledValue(settingsValue)
8468
+ };
8469
+ const status = resolveAgentTeamsStatus({ envValue, settingsValue });
8470
+ if (status.active) {
7742
8471
  return { status: "pass", detected, envValue, settingsValue };
7743
8472
  }
7744
8473
  return {
@@ -7791,6 +8520,123 @@ var init_check_agent_teams_doctor = __esm({
7791
8520
  }
7792
8521
  });
7793
8522
 
8523
+ // src/platform/runtime.ts
8524
+ function isBunRuntime(versions = process.versions, compiled) {
8525
+ return typeof versions.bun === "string" && versions.bun.trim().length > 0 && !(compiled ?? isCompiledRuntime());
8526
+ }
8527
+ function bunExecutable() {
8528
+ return isBunRuntime() ? process.execPath : process.platform === "win32" ? "bun.exe" : "bun";
8529
+ }
8530
+ var init_runtime = __esm({
8531
+ "src/platform/runtime.ts"() {
8532
+ init_assetsRoot();
8533
+ }
8534
+ });
8535
+
8536
+ // src/cli/lib/version-check.ts
8537
+ var version_check_exports = {};
8538
+ __export(version_check_exports, {
8539
+ compareVersionNames: () => compareVersionNames,
8540
+ compareVersions: () => compareVersions,
8541
+ fetchLatestBunVersion: () => fetchLatestBunVersion,
8542
+ fetchLatestNpmVersion: () => fetchLatestNpmVersion,
8543
+ fetchLatestVersion: () => fetchLatestVersion
8544
+ });
8545
+ function parse3(v) {
8546
+ const m = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(v.trim());
8547
+ if (!m) return null;
8548
+ return { nums: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] ?? null };
8549
+ }
8550
+ function compareVersions(installed2, latest) {
8551
+ const a = parse3(installed2);
8552
+ const b = parse3(latest);
8553
+ if (!a || !b) return "unknown";
8554
+ for (let i = 0; i < 3; i++) {
8555
+ const ai = a.nums[i] ?? 0;
8556
+ const bi = b.nums[i] ?? 0;
8557
+ if (ai < bi) return "behind";
8558
+ if (ai > bi) return "ahead";
8559
+ }
8560
+ if (a.pre && !b.pre) return "behind";
8561
+ if (!a.pre && b.pre) return "ahead";
8562
+ if (a.pre && b.pre && a.pre !== b.pre) return a.pre < b.pre ? "behind" : "ahead";
8563
+ return "current";
8564
+ }
8565
+ function compareVersionNames(a, b) {
8566
+ const relation = compareVersions(a, b);
8567
+ if (relation === "ahead") return 1;
8568
+ if (relation === "behind") return -1;
8569
+ if (relation === "current") return 0;
8570
+ const segments = (v) => v.split(".").map((part) => {
8571
+ const n = Number.parseInt(part, 10);
8572
+ return Number.isNaN(n) ? 0 : n;
8573
+ });
8574
+ const as = segments(a);
8575
+ const bs = segments(b);
8576
+ for (let i = 0; i < Math.max(as.length, bs.length); i++) {
8577
+ const diff = (as[i] ?? 0) - (bs[i] ?? 0);
8578
+ if (diff !== 0) return diff;
8579
+ }
8580
+ return 0;
8581
+ }
8582
+ function npmExecutable() {
8583
+ return process.platform === "win32" ? "npm.cmd" : "npm";
8584
+ }
8585
+ async function defaultRunner() {
8586
+ if (process.platform === "win32") {
8587
+ const { stdout: stdout3 } = await execAsync("npm view harnessed version", {
8588
+ timeout: 8e3,
8589
+ windowsHide: true
8590
+ });
8591
+ return stdout3;
8592
+ }
8593
+ const { stdout: stdout2 } = await execFileAsync(npmExecutable(), ["view", "harnessed", "version"], {
8594
+ timeout: 8e3,
8595
+ windowsHide: true
8596
+ });
8597
+ return stdout2;
8598
+ }
8599
+ async function fetchLatestVersion(runner) {
8600
+ try {
8601
+ if (runner !== void 0) return await fetchLatestNpmVersion(runner);
8602
+ return isBunRuntime() ? await fetchLatestBunVersion() : await fetchLatestNpmVersion();
8603
+ } catch {
8604
+ return null;
8605
+ }
8606
+ }
8607
+ async function fetchLatestNpmVersion(runner = defaultRunner) {
8608
+ try {
8609
+ const out = (await runner()).trim();
8610
+ return /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(out) ? out : null;
8611
+ } catch {
8612
+ return null;
8613
+ }
8614
+ }
8615
+ async function defaultBunRunner() {
8616
+ const { stdout: stdout2 } = await execFileAsync(
8617
+ bunExecutable(),
8618
+ ["info", "harnessed@latest", "version", "--json"],
8619
+ { timeout: 8e3, windowsHide: true, shell: false }
8620
+ );
8621
+ return stdout2;
8622
+ }
8623
+ async function fetchLatestBunVersion(runner = defaultBunRunner) {
8624
+ try {
8625
+ const version = JSON.parse(await runner());
8626
+ return typeof version === "string" && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version) ? version : null;
8627
+ } catch {
8628
+ return null;
8629
+ }
8630
+ }
8631
+ var execFileAsync, execAsync;
8632
+ var init_version_check = __esm({
8633
+ "src/cli/lib/version-check.ts"() {
8634
+ init_runtime();
8635
+ execFileAsync = promisify(execFile);
8636
+ execAsync = promisify(exec);
8637
+ }
8638
+ });
8639
+
7794
8640
  // src/cli/lib/check-planning-with-files.ts
7795
8641
  var check_planning_with_files_exports = {};
7796
8642
  __export(check_planning_with_files_exports, {
@@ -7833,15 +8679,15 @@ async function checkPlanningWithFiles() {
7833
8679
  );
7834
8680
  try {
7835
8681
  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);
8682
+ const versions = entries.filter((entry) => entry.isDirectory() && /^\d+\.\d+/.test(entry.name)).map((entry) => entry.name).sort((a, b) => compareVersionNames(b, a));
8683
+ for (const version of versions) {
8684
+ const versionRoot = join(root, version);
7839
8685
  for (const candidate of [join(versionRoot, "skills", "planning-with-files"), versionRoot]) {
7840
8686
  if (await hasPlanningContent(candidate)) {
7841
8687
  return {
7842
8688
  name: "planning-with-files plugin",
7843
8689
  status: "pass",
7844
- message: `local planning-with-files content detected (version ${version.name}; SKILL.md, scripts and templates); runtime execution not verified`
8690
+ message: `local planning-with-files content detected (version ${version}; SKILL.md, scripts and templates); runtime execution not verified`
7845
8691
  };
7846
8692
  }
7847
8693
  }
@@ -7867,6 +8713,7 @@ var REMEDIATION, INSTALL_COMMANDS;
7867
8713
  var init_check_planning_with_files = __esm({
7868
8714
  "src/cli/lib/check-planning-with-files.ts"() {
7869
8715
  init_platform();
8716
+ init_version_check();
7870
8717
  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
8718
  INSTALL_COMMANDS = [
7872
8719
  "claude plugin marketplace add OthmanAdi/planning-with-files",
@@ -7918,9 +8765,9 @@ async function checkMattpocockSkills() {
7918
8765
  if (getPluginsRegistry() !== null) {
7919
8766
  try {
7920
8767
  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");
8768
+ const versions = entries.filter((entry) => entry.isDirectory() && /^\d+\.\d+/.test(entry.name)).map((entry) => entry.name).sort((a, b) => compareVersionNames(b, a));
8769
+ for (const version of versions) {
8770
+ const root = join(pluginRoot, version, "skills");
7924
8771
  const indicator = await findIndicator(root);
7925
8772
  if (indicator) return contentDetected(indicator, root);
7926
8773
  }
@@ -7949,6 +8796,7 @@ var REMEDIATION2, INDICATORS;
7949
8796
  var init_check_mattpocock_skills = __esm({
7950
8797
  "src/cli/lib/check-mattpocock-skills.ts"() {
7951
8798
  init_platform();
8799
+ init_version_check();
7952
8800
  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
8801
  INDICATORS = ["tdd", "diagnosing-bugs", "grill-with-docs", "diagnose"];
7954
8802
  }
@@ -8384,112 +9232,13 @@ async function checkSkillIntegrity() {
8384
9232
  } catch {
8385
9233
  return { name, status: "pass", message: "skipped (environment not auditable)" };
8386
9234
  }
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);
9235
+ }
9236
+ var init_check_skill_integrity = __esm({
9237
+ "src/cli/lib/check-skill-integrity.ts"() {
9238
+ init_assetsRoot();
9239
+ init_platform();
9240
+ init_scan_nested();
9241
+ init_skillIntegrity();
8493
9242
  }
8494
9243
  });
8495
9244
 
@@ -9761,7 +10510,7 @@ async function withAppServer(deps, body) {
9761
10510
  const call = (method, params) => {
9762
10511
  if (closed) return Promise.reject(closed);
9763
10512
  const id = nextId++;
9764
- return new Promise((resolve40, reject) => {
10513
+ return new Promise((resolve42, reject) => {
9765
10514
  const timer = setTimeout(() => {
9766
10515
  pending.delete(id);
9767
10516
  reject(new RpcError("timeout", `${method} timed out after ${timeoutMs}ms`));
@@ -9769,7 +10518,7 @@ async function withAppServer(deps, body) {
9769
10518
  pending.set(id, {
9770
10519
  resolve: (v) => {
9771
10520
  clearTimeout(timer);
9772
- resolve40(v);
10521
+ resolve42(v);
9773
10522
  },
9774
10523
  reject: (e) => {
9775
10524
  clearTimeout(timer);
@@ -11235,7 +11984,7 @@ function realSpawn(req) {
11235
11984
  };
11236
11985
  }
11237
11986
  function runOnce(req, spawnFn, timeoutMs, onThreadId) {
11238
- return new Promise((resolve40, reject) => {
11987
+ return new Promise((resolve42, reject) => {
11239
11988
  const events = [];
11240
11989
  let garbageLines = 0;
11241
11990
  let stderr = "";
@@ -11256,7 +12005,7 @@ function runOnce(req, spawnFn, timeoutMs, onThreadId) {
11256
12005
  if (settled || !exited || openStreams > 0) return;
11257
12006
  settled = true;
11258
12007
  clearTimeout(timer);
11259
- resolve40({ exitCode: exited.code, signal: exited.signal, events, garbageLines, stderr });
12008
+ resolve42({ exitCode: exited.code, signal: exited.signal, events, garbageLines, stderr });
11260
12009
  };
11261
12010
  const fail2 = (err2) => {
11262
12011
  if (settled) return;
@@ -12650,6 +13399,25 @@ var init_capabilityResolver = __esm({
12650
13399
  CAPABILITY_CMD_TEMPLATE = /\{\{\s*capabilities\.([a-zA-Z0-9_-]+)\.cmd\s*\}\}/g;
12651
13400
  }
12652
13401
  });
13402
+ function resultArtifactScope(cwd = process.cwd()) {
13403
+ const base = repoKey(cwd);
13404
+ const key = activeKey(cwd);
13405
+ const composite = key === base ? `${base}::${NO_SESSION}` : key;
13406
+ return createHash("sha256").update(composite, "utf8").digest("hex").slice(0, SCOPE_HEX_LEN);
13407
+ }
13408
+ function resultArtifactPath(sub, cwd = process.cwd()) {
13409
+ checkSafeSegment(sub);
13410
+ return resolve(cwd, ".harnessed", "results", resultArtifactScope(cwd), `${sub}.md`);
13411
+ }
13412
+ var SCOPE_HEX_LEN, NO_SESSION;
13413
+ var init_resultArtifact = __esm({
13414
+ "src/cli/lib/resultArtifact.ts"() {
13415
+ init_workflowStore();
13416
+ init_path_guard();
13417
+ SCOPE_HEX_LEN = 8;
13418
+ NO_SESSION = "nosession";
13419
+ }
13420
+ });
12653
13421
  function userLangPinPath(hostContext) {
12654
13422
  return join(hostContext?.platform.stateRoot ?? detectPlatform().stateRoot, USER_LANG_PIN);
12655
13423
  }
@@ -12814,6 +13582,19 @@ Respond in ${name}.
12814
13582
  ${preserve}
12815
13583
  `;
12816
13584
  }
13585
+ function buildResultDeliverySection(resultFile) {
13586
+ return `
13587
+ ## Result delivery
13588
+ Write your final result to this exact absolute path:
13589
+ ${resultFile}
13590
+
13591
+ Rules:
13592
+ - The file MUST contain your final result AND the verbatim line \`<promise>COMPLETE</promise>\`.
13593
+ - 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.
13594
+ - 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".
13595
+ - 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.
13596
+ `;
13597
+ }
12817
13598
  async function resolveMaxIterations2(sub, packageRoot) {
12818
13599
  try {
12819
13600
  const path = resolve(packageRoot, "workflows", "defaults.yaml");
@@ -12852,17 +13633,22 @@ ${opts.task}
12852
13633
  const toolsSection = await buildToolsSection(sub, packageRoot, host);
12853
13634
  const disciplinesSection = await buildDisciplinesSection(sub, packageRoot, locale);
12854
13635
  const languageSection = await buildLanguageSection(packageRoot, host);
13636
+ const resultDeliverySection = opts.resultFile ? buildResultDeliverySection(opts.resultFile) : "";
12855
13637
  return {
12856
13638
  prompt: `${taskSection}${body}
12857
- ${toolsSection}${disciplinesSection}${PROTOCOLS}${languageSection}`,
13639
+ ${toolsSection}${disciplinesSection}${PROTOCOLS}${resultDeliverySection}${languageSection}`,
12858
13640
  model: def.model ?? DEFAULT_MODEL,
12859
- specialist: rolePrompts[sub]?.specialist ?? DEFAULT_SPECIALIST
13641
+ specialist: rolePrompts[sub]?.specialist ?? DEFAULT_SPECIALIST,
13642
+ ...opts.resultFile !== void 0 ? { resultFile: opts.resultFile } : {}
12860
13643
  };
12861
13644
  }
12862
13645
  function registerPrompt(program2) {
12863
13646
  program2.command("prompt").description(
12864
13647
  "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) => {
13648
+ ).argument("<sub>", "sub-workflow name (e.g. task-code, verify-paranoid)").option("--task <text>", "task description prepended as a ## Task section").option(
13649
+ "--json",
13650
+ "emit JSON {prompt, max_iterations, model, specialist, result_file} instead of text"
13651
+ ).action(async (sub, raw) => {
12866
13652
  try {
12867
13653
  checkSafeSegment(sub);
12868
13654
  } catch {
@@ -12871,12 +13657,14 @@ function registerPrompt(program2) {
12871
13657
  return;
12872
13658
  }
12873
13659
  const packageRoot = getAssetsRoot();
13660
+ const resultFile = resultArtifactPath(sub, process.cwd());
12874
13661
  const {
12875
13662
  prompt: fullPrompt,
12876
13663
  model,
12877
13664
  specialist
12878
13665
  } = await buildPromptText(sub, packageRoot, {
12879
- ...typeof raw.task === "string" ? { task: raw.task } : {}
13666
+ ...typeof raw.task === "string" ? { task: raw.task } : {},
13667
+ resultFile
12880
13668
  });
12881
13669
  if (raw.json) {
12882
13670
  const maxIterations = await resolveMaxIterations2(sub, packageRoot);
@@ -12885,7 +13673,8 @@ function registerPrompt(program2) {
12885
13673
  prompt: fullPrompt,
12886
13674
  max_iterations: maxIterations,
12887
13675
  model,
12888
- specialist
13676
+ specialist,
13677
+ result_file: resultFile
12889
13678
  })
12890
13679
  );
12891
13680
  process.exit(0);
@@ -12907,6 +13696,7 @@ var init_prompt = __esm({
12907
13696
  init_run();
12908
13697
  init_capabilityResolver();
12909
13698
  init_hostPrimitives();
13699
+ init_resultArtifact();
12910
13700
  init_rolePromptHostRender();
12911
13701
  init_userLangPin();
12912
13702
  DEFAULT_MAX_ITERATIONS = 20;
@@ -13219,19 +14009,41 @@ async function runGatesPlan(master, raw, deps = defaultRunDeps) {
13219
14009
  clauses.map((c) => c.sub),
13220
14010
  (m) => deps.warn(m)
13221
14011
  );
13222
- let parallelism = { escalate_to_teams: false, reason: null };
14012
+ const teamProbe = await checkAgentTeams();
14013
+ const teamsActive = resolveAgentTeamsStatus({
14014
+ envValue: teamProbe.envValue,
14015
+ settingsValue: teamProbe.settingsValue
14016
+ }).active;
14017
+ const parallelismContract = {
14018
+ teams_active: teamsActive,
14019
+ result_contract: "result-file",
14020
+ bounded_wait: true
14021
+ };
14022
+ const parallelismBlock = (escalate, reason) => ({
14023
+ escalate_to_teams: escalate,
14024
+ reason,
14025
+ ...parallelismContract,
14026
+ transport: escalate ? "teammate" : "subagent"
14027
+ });
14028
+ let parallelism;
13223
14029
  const hl = detectHeadless(process.env, Boolean(process.stdout.isTTY));
13224
14030
  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
- };
14031
+ parallelism = parallelismBlock(
14032
+ false,
14033
+ "headless mode \u2014 Agent Teams are session-scoped, incompatible with -p (issue #7)"
14034
+ );
13229
14035
  } else {
13230
14036
  try {
13231
14037
  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 };
14038
+ if (!escalate) {
14039
+ parallelism = parallelismBlock(false, null);
14040
+ } else if (!teamsActive) {
14041
+ parallelism = parallelismBlock(false, "agent-teams \u672A\u542F\u7528\uFF0C\u4E0D\u80FD\u6210\u56E2\uFF0C\u6539\u7528 subagent fan-out");
14042
+ } else {
14043
+ parallelism = parallelismBlock(true, "agent-teams-upgrade gate fired");
14044
+ }
13233
14045
  } catch {
13234
- parallelism = { escalate_to_teams: false, reason: null };
14046
+ parallelism = parallelismBlock(false, null);
13235
14047
  }
13236
14048
  }
13237
14049
  const result = { master, fire, skip, parallelism };
@@ -13283,6 +14095,7 @@ var init_gates = __esm({
13283
14095
  init_judgmentResolver();
13284
14096
  init_skipGate();
13285
14097
  init_skipSubs();
14098
+ init_checkAgentTeams();
13286
14099
  init_detectHeadless();
13287
14100
  init_gateContext();
13288
14101
  GATE_MASTERS = ["auto", "discuss", "plan", "task", "verify", "ship"];
@@ -14139,8 +14952,24 @@ async function gcCompiledArtifacts(opts) {
14139
14952
  const dir = dirname(opts.execPath);
14140
14953
  const base = basename(opts.execPath);
14141
14954
  for (const e of await readdir(dir, { withFileTypes: true })) {
14142
- if (!e.isFile() || !e.name.startsWith(`${base}.bak-`)) continue;
14955
+ if (!e.isFile()) continue;
14143
14956
  const p8 = join(dir, e.name);
14957
+ if (e.name.startsWith(`${base}.bak-`)) {
14958
+ removed.push(p8);
14959
+ if (!opts.dryRun) await rm(p8, { force: true });
14960
+ continue;
14961
+ }
14962
+ const fragment = updateFragmentVersion(e.name);
14963
+ if (fragment === null) continue;
14964
+ const relation = compareVersions(fragment, package_default.version);
14965
+ if (relation === "ahead") {
14966
+ kept.push(p8);
14967
+ continue;
14968
+ }
14969
+ if (relation === "unknown") {
14970
+ kept.push(p8);
14971
+ continue;
14972
+ }
14144
14973
  removed.push(p8);
14145
14974
  if (!opts.dryRun) await rm(p8, { force: true });
14146
14975
  }
@@ -14149,6 +14978,10 @@ async function gcCompiledArtifacts(opts) {
14149
14978
  }
14150
14979
  return { removed, kept };
14151
14980
  }
14981
+ function updateFragmentVersion(name) {
14982
+ const match = /^\.harnessed-update-(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?:\.part|\.[A-Za-z0-9]+)?$/.exec(name);
14983
+ return match?.[1] ?? null;
14984
+ }
14152
14985
  function parseDuration(s) {
14153
14986
  const m = DURATION_RE.exec(s);
14154
14987
  if (!m) return null;
@@ -14478,8 +15311,9 @@ function resolveCodexHome(hostContext) {
14478
15311
  return env ? env : detectPlatform().homeDir;
14479
15312
  }
14480
15313
  function reminderStateRoot(hostContext) {
14481
- if (!hostContext)
14482
- return resolve(process.env.HARNESSED_ROOT_OVERRIDE || join(resolveCodexHome(), "harnessed"));
15314
+ const override = process.env.HARNESSED_ROOT_OVERRIDE?.trim();
15315
+ if (override) return resolve(override);
15316
+ if (!hostContext) return canonicalStateRoot("codex");
14483
15317
  const defaultRoot = join(hostContext.platform.homeDir, "harnessed");
14484
15318
  return resolve(
14485
15319
  hostContext.platform.stateRoot !== defaultRoot ? hostContext.platform.stateRoot : join(hostContext.nativeHome, "harnessed")
@@ -15017,6 +15851,7 @@ var init_codexHookAdd = __esm({
15017
15851
  init_assetsRoot();
15018
15852
  init_platform();
15019
15853
  init_runtime();
15854
+ init_stateRoot();
15020
15855
  init_backup();
15021
15856
  init_codexHookPlugin();
15022
15857
  init_codexHookTrust();
@@ -15655,12 +16490,22 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
15655
16490
  } else {
15656
16491
  const expandedCmd = expandTildeForWindows(cmd, ctx.hostContext?.userHome);
15657
16492
  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
- });
16493
+ if (expandedArgs.length === 0) {
16494
+ child = spawn("cmd.exe", ["/c", expandedCmd], {
16495
+ cwd,
16496
+ env,
16497
+ windowsHide: true,
16498
+ stdio,
16499
+ windowsVerbatimArguments: true
16500
+ });
16501
+ } else {
16502
+ child = spawn("cmd.exe", ["/c", expandedCmd, ...expandedArgs], {
16503
+ cwd,
16504
+ env,
16505
+ windowsHide: true,
16506
+ stdio
16507
+ });
16508
+ }
15664
16509
  }
15665
16510
  } else {
15666
16511
  child = spawn("/bin/sh", ["-c", joinedCmd], { cwd, env, stdio });
@@ -15673,10 +16518,10 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
15673
16518
  child.stderr?.setEncoding("utf8").on("data", (chunk) => {
15674
16519
  stderr += chunk;
15675
16520
  });
15676
- return await new Promise((resolve40) => {
16521
+ return await new Promise((resolve42) => {
15677
16522
  const timer = setTimeout(() => {
15678
16523
  killProcessTree(child);
15679
- resolve40({
16524
+ resolve42({
15680
16525
  ok: false,
15681
16526
  phase: "spawn",
15682
16527
  error: {
@@ -15697,7 +16542,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
15697
16542
  child.on("error", (err2) => {
15698
16543
  clearTimeout(timer);
15699
16544
  const bashMissing = triedBash && err2.code === "ENOENT";
15700
- resolve40({
16545
+ resolve42({
15701
16546
  ok: false,
15702
16547
  phase: "spawn",
15703
16548
  error: {
@@ -15712,7 +16557,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
15712
16557
  });
15713
16558
  child.on("close", (code2) => {
15714
16559
  clearTimeout(timer);
15715
- resolve40({ ok: true, exitCode: code2 ?? -1, stdout: stdout2, stderr });
16560
+ resolve42({ ok: true, exitCode: code2 ?? -1, stdout: stdout2, stderr });
15716
16561
  });
15717
16562
  });
15718
16563
  }
@@ -16423,7 +17268,7 @@ function touch(binary, lease, source, scratch, context) {
16423
17268
  if (context) env = withHostInstallEnv(env, context);
16424
17269
  env.GSTACK_LEASE_DIR = shellPath(scratch, context);
16425
17270
  env.GSTACK_LEASE_LOCK_TRIES = "1";
16426
- return new Promise((resolve40, reject) => {
17271
+ return new Promise((resolve42, reject) => {
16427
17272
  const child = execFile(
16428
17273
  binary,
16429
17274
  [
@@ -16452,7 +17297,7 @@ function touch(binary, lease, source, scratch, context) {
16452
17297
  `official lease touch exit ${error.code ?? "unknown"}${error.killed ? " (timeout or termination)" : ""}: ${stderr.trim() || error.message}`
16453
17298
  )
16454
17299
  );
16455
- else resolve40();
17300
+ else resolve42();
16456
17301
  }
16457
17302
  );
16458
17303
  child.stdin?.end();
@@ -16992,7 +17837,7 @@ var init_verifyInstalled = __esm({
16992
17837
  }
16993
17838
  });
16994
17839
  function gitRevParseHead(cwd, timeoutMs = 1e4) {
16995
- return new Promise((resolve40) => {
17840
+ return new Promise((resolve42) => {
16996
17841
  const isWin = process.platform === "win32";
16997
17842
  const child = isWin ? spawn("cmd.exe", ["/c", "git", "rev-parse", "HEAD"], { cwd, windowsHide: true }) : spawn("git", ["rev-parse", "HEAD"], { cwd, shell: false });
16998
17843
  let stdout2 = "";
@@ -17001,15 +17846,15 @@ function gitRevParseHead(cwd, timeoutMs = 1e4) {
17001
17846
  });
17002
17847
  const timer = setTimeout(() => {
17003
17848
  killProcessTree(child);
17004
- resolve40({ sha: "", exit: -1 });
17849
+ resolve42({ sha: "", exit: -1 });
17005
17850
  }, timeoutMs);
17006
17851
  child.on("error", () => {
17007
17852
  clearTimeout(timer);
17008
- resolve40({ sha: "", exit: -1 });
17853
+ resolve42({ sha: "", exit: -1 });
17009
17854
  });
17010
17855
  child.on("close", (code2) => {
17011
17856
  clearTimeout(timer);
17012
- resolve40({ sha: stdout2.trim(), exit: code2 ?? -1 });
17857
+ resolve42({ sha: stdout2.trim(), exit: code2 ?? -1 });
17013
17858
  });
17014
17859
  });
17015
17860
  }
@@ -17397,32 +18242,21 @@ var init_componentPlan = __esm({
17397
18242
  init_verificationEnv();
17398
18243
  }
17399
18244
  });
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
- );
18245
+ function lockTarget3(root) {
18246
+ return join(root, ".ownership.lock");
17408
18247
  }
17409
18248
  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
- }
18249
+ const target = lockTarget3(root);
18250
+ return acquireWithContentionRetry(
18251
+ () => lockfile.lock(target, {
18252
+ lockfilePath: target,
18253
+ realpath: false,
18254
+ stale: 10 * 60 * 1e3,
18255
+ // One attempt only — the retry loop owns the backoff.
18256
+ retries: 0
18257
+ }),
18258
+ INSTALL_OWNERSHIP_LOCK_RETRIES
18259
+ );
17426
18260
  }
17427
18261
  async function withInstallOwnershipLock(context, work) {
17428
18262
  const root = context.platform.stateRoot;
@@ -17431,20 +18265,19 @@ async function withInstallOwnershipLock(context, work) {
17431
18265
  try {
17432
18266
  return await work();
17433
18267
  } finally {
17434
- await release();
18268
+ await releaseLockIdempotently(release);
17435
18269
  }
17436
18270
  }
17437
- var INSTALL_OWNERSHIP_LOCK_RETRIES, sleep;
18271
+ var INSTALL_OWNERSHIP_LOCK_RETRIES;
17438
18272
  var init_installOwnershipLock = __esm({
17439
18273
  "src/installers/lib/installOwnershipLock.ts"() {
18274
+ init_lockContention();
18275
+ init_lockContention();
17440
18276
  INSTALL_OWNERSHIP_LOCK_RETRIES = {
17441
18277
  retries: 30,
17442
18278
  minTimeout: 250,
17443
18279
  maxTimeout: 4e3
17444
18280
  };
17445
- sleep = (ms) => new Promise((resolve40) => {
17446
- setTimeout(resolve40, ms);
17447
- });
17448
18281
  }
17449
18282
  });
17450
18283
  async function mcpReadinessFailure(ctx, allowAbsent = false) {
@@ -18178,11 +19011,11 @@ async function captureSkillOwnershipReceiptParent(receiptPath, options = {}) {
18178
19011
  if (info.isSymbolicLink() || !info.isDirectory()) {
18179
19012
  throw receiptParentFailure("is a symlink, junction, reparse redirect, or non-directory");
18180
19013
  }
18181
- const [canonicalPath2, canonicalStateRoot] = await Promise.all([
19014
+ const [canonicalPath2, canonicalStateRoot2] = await Promise.all([
18182
19015
  realpath(parent),
18183
19016
  realpath(dirname(parent))
18184
19017
  ]);
18185
- if (resolve(canonicalPath2) !== resolve(canonicalStateRoot, basename(parent))) {
19018
+ if (resolve(canonicalPath2) !== resolve(canonicalStateRoot2, basename(parent))) {
18186
19019
  throw receiptParentFailure("canonical path is redirected");
18187
19020
  }
18188
19021
  const canonicalInfo = await lstat(canonicalPath2, { bigint: true });
@@ -20967,8 +21800,8 @@ function preparePackageUpdate(manager, target, context = {}) {
20967
21800
  const prefix = probe(["prefix", "-g"]);
20968
21801
  const modulesRoot = probe(["root", "-g", "--prefix", prefix]);
20969
21802
  const slot = join(modulesRoot, "harnessed");
20970
- const stat18 = lstatSync(slot);
20971
- if (stat18.isSymbolicLink() || !stat18.isDirectory())
21803
+ const stat19 = lstatSync(slot);
21804
+ if (stat19.isSymbolicLink() || !stat19.isDirectory())
20972
21805
  return {
20973
21806
  ok: false,
20974
21807
  reasonCode: "package-layout-unsupported",
@@ -21184,16 +22017,19 @@ async function runBinarySelfUpdate(deps, opts) {
21184
22017
  return { status: "current", version: deps.currentVersion };
21185
22018
  }
21186
22019
  }
22020
+ const partPath = deps.sourceDir ? null : join(execDir, `.harnessed-update-${targetVersion ?? "unknown"}.part`);
22021
+ const verifyPath = partPath ?? tempPath;
22022
+ const stagingPath = deps.sourceDir ? tempPath : join(execDir, `.harnessed-update-${targetVersion ?? "unknown"}${ext}`);
21187
22023
  if (opts.dryRun) {
21188
22024
  const backupDir2 = "bin-backup/<oldver>/ under the harnessed state root";
21189
22025
  const steps = [
21190
- deps.sourceDir ? `copy ${sourceAsset} \u2192 ${tempPath} (local source dir \u2014 rehearsal seam)` : `download ${assetUrl ?? `latest ${asset}`} \u2192 ${tempPath}`,
22026
+ deps.sourceDir ? `copy ${sourceAsset} \u2192 ${stagingPath} (local source dir \u2014 rehearsal seam)` : `download ${assetUrl ?? `latest ${asset}`} \u2192 ${partPath} (resumable fragment)`,
21191
22027
  `verify sha256 against ${deps.sourceDir ? sourceSha : shaUrl ?? `${asset}.sha256`}`,
21192
22028
  ...deps.sourceDir ? [] : ["verify the ed25519 signature (.sha256.sig) against the embedded release public key"],
21193
22029
  ...deps.platform === "win32" ? [] : ["chmod 755 the downloaded binary"],
21194
22030
  "smoke: spawn `--version` on the new binary",
21195
22031
  `rename ${deps.execPath} \u2192 ${bakPath} (same-dir, same-volume)`,
21196
- `rename ${tempPath} \u2192 ${deps.execPath}`,
22032
+ `rename ${stagingPath} \u2192 ${deps.execPath}`,
21197
22033
  `copy the .bak to ${backupDir2} (rollback net)`,
21198
22034
  "delete the .bak (fail-soft \u2014 kept on Windows EPERM or when the backup copy failed)"
21199
22035
  ];
@@ -21202,11 +22038,11 @@ async function runBinarySelfUpdate(deps, opts) {
21202
22038
  try {
21203
22039
  if (deps.sourceDir && sourceAsset) {
21204
22040
  await copyFile(sourceAsset, tempPath);
21205
- } else if (assetUrl) {
21206
- await deps.downloadTo(assetUrl, tempPath, assetFallbackUrl);
22041
+ } else if (assetUrl && partPath) {
22042
+ await deps.downloadTo(assetUrl, partPath, assetFallbackUrl);
21207
22043
  }
21208
22044
  } catch (e) {
21209
- await unlink2(tempPath).catch(() => {
22045
+ if (!partPath) await unlink2(tempPath).catch(() => {
21210
22046
  });
21211
22047
  return { status: "error", message: downloadFailureMessage(e, targetVersion, assetUrl) };
21212
22048
  }
@@ -21214,7 +22050,7 @@ async function runBinarySelfUpdate(deps, opts) {
21214
22050
  const shaText = deps.sourceDir ? await readFile(sourceSha ?? "", "utf8") : await deps.fetchShaText(shaUrl ?? "", shaFallbackUrl);
21215
22051
  const expected = parseShaText(shaText);
21216
22052
  if (!expected) throw new Error(`malformed .sha256 content`);
21217
- const actual = await sha256File(tempPath);
22053
+ const actual = await sha256File(verifyPath);
21218
22054
  if (actual !== expected) {
21219
22055
  throw new Error(
21220
22056
  `sha256 mismatch \u2014 expected ${expected.slice(0, 12)}\u2026, got ${actual.slice(0, 12)}\u2026`
@@ -21231,16 +22067,30 @@ async function runBinarySelfUpdate(deps, opts) {
21231
22067
  }
21232
22068
  }
21233
22069
  } catch (e) {
21234
- await unlink2(tempPath).catch(() => {
22070
+ await unlink2(verifyPath).catch(() => {
21235
22071
  });
21236
22072
  return {
21237
22073
  status: "error",
21238
22074
  message: `integrity verification failed: ${e.message} \u2014 aborted; original binary untouched`
21239
22075
  };
21240
22076
  }
22077
+ if (partPath) {
22078
+ try {
22079
+ await unlink2(stagingPath).catch(() => {
22080
+ });
22081
+ await rename9(partPath, stagingPath);
22082
+ } catch (e) {
22083
+ return {
22084
+ status: "error",
22085
+ message: `could not stage the verified download: ${e.message} \u2014 the download was kept for the next attempt; original binary untouched`
22086
+ };
22087
+ }
22088
+ }
22089
+ let smokeRan = false;
21241
22090
  try {
21242
- if (deps.platform !== "win32") await chmod(tempPath, 493);
21243
- const out = (await deps.smoke(tempPath)).trim();
22091
+ if (deps.platform !== "win32") await chmod(stagingPath, 493);
22092
+ const out = (await deps.smoke(stagingPath)).trim();
22093
+ smokeRan = true;
21244
22094
  const m = /^(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/.exec(out);
21245
22095
  if (!m) throw new Error(`--version smoke returned unexpected output: ${out.slice(0, 80)}`);
21246
22096
  if (targetVersion !== null && out !== targetVersion) {
@@ -21248,8 +22098,13 @@ async function runBinarySelfUpdate(deps, opts) {
21248
22098
  }
21249
22099
  targetVersion = targetVersion ?? m[1] ?? null;
21250
22100
  } catch (e) {
21251
- await unlink2(tempPath).catch(() => {
21252
- });
22101
+ if (partPath && !smokeRan) {
22102
+ await rename9(stagingPath, partPath).catch(() => {
22103
+ });
22104
+ } else {
22105
+ await unlink2(stagingPath).catch(() => {
22106
+ });
22107
+ }
21253
22108
  return {
21254
22109
  status: "error",
21255
22110
  message: `new binary failed the --version smoke: ${e.message} \u2014 aborted; original binary untouched`
@@ -21258,7 +22113,9 @@ async function runBinarySelfUpdate(deps, opts) {
21258
22113
  try {
21259
22114
  await rename9(deps.execPath, bakPath);
21260
22115
  } catch (e) {
21261
- await unlink2(tempPath).catch(() => {
22116
+ if (partPath) await rename9(stagingPath, partPath).catch(() => {
22117
+ });
22118
+ else await unlink2(stagingPath).catch(() => {
21262
22119
  });
21263
22120
  return {
21264
22121
  status: "error",
@@ -21266,17 +22123,24 @@ async function runBinarySelfUpdate(deps, opts) {
21266
22123
  };
21267
22124
  }
21268
22125
  try {
21269
- await rename9(tempPath, deps.execPath);
22126
+ await rename9(stagingPath, deps.execPath);
21270
22127
  } catch (e) {
21271
22128
  try {
21272
22129
  await rename9(bakPath, deps.execPath);
22130
+ if (partPath) await rename9(stagingPath, partPath).catch(() => {
22131
+ });
22132
+ else await unlink2(stagingPath).catch(() => {
22133
+ });
21273
22134
  return {
21274
22135
  status: "error",
21275
22136
  message: `swap failed (${e.message}) \u2014 rolled back to the previous binary`
21276
22137
  };
21277
22138
  } catch (rb) {
22139
+ if (partPath) await rename9(stagingPath, partPath).catch(() => {
22140
+ });
21278
22141
  return {
21279
22142
  status: "error",
22143
+ critical: true,
21280
22144
  message: `CRITICAL: swap failed AND rollback failed (${rb.message}). Restore manually: copy "${bakPath}" "${deps.execPath}"`
21281
22145
  };
21282
22146
  }
@@ -21425,6 +22289,32 @@ async function runBinaryRollback(deps, opts) {
21425
22289
  });
21426
22290
  return { status: "rolled-back", from: deps.currentVersion, to: target, backupUsed: backupBin };
21427
22291
  }
22292
+ function headerOf(res, name) {
22293
+ const headers = res.headers;
22294
+ if (!headers || typeof headers.get !== "function") return null;
22295
+ return headers.get(name);
22296
+ }
22297
+ function parseContentRange(value) {
22298
+ if (!value) return null;
22299
+ const text = value.trim();
22300
+ const unsat = /^bytes\s+\*\/(\d+|\*)$/i.exec(text);
22301
+ if (unsat) return { start: null, total: unsat[1] === "*" ? null : Number(unsat[1]) };
22302
+ const m = /^bytes\s+(\d+)-(\d+)\/(\d+|\*)$/i.exec(text);
22303
+ if (!m) return null;
22304
+ return { start: Number(m[1]), total: m[3] === "*" ? null : Number(m[3]) };
22305
+ }
22306
+ function numberOrUndefined(value) {
22307
+ if (value === null) return void 0;
22308
+ const n = Number(value);
22309
+ return Number.isFinite(n) ? n : void 0;
22310
+ }
22311
+ async function fileSize(p8) {
22312
+ try {
22313
+ return (await stat(p8)).size;
22314
+ } catch {
22315
+ return 0;
22316
+ }
22317
+ }
21428
22318
  async function fetchWithTimeout(url, timeoutMs, net = {}, headers = {}, controller) {
21429
22319
  await ensureProxyDispatcher();
21430
22320
  const doFetch = net.fetchImpl ?? fetch;
@@ -21455,36 +22345,40 @@ function isTransientNetworkError(error) {
21455
22345
  message
21456
22346
  );
21457
22347
  }
21458
- async function fetchAsset(url, fallbackUrl, timeoutMs, net, label, consume) {
21459
- const sleep2 = net.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
22348
+ async function fetchAsset(url, fallbackUrl, timeoutMs, net, label, consume, extra) {
22349
+ const sleep3 = net.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
21460
22350
  const attempts = [];
21461
22351
  let lastError;
21462
22352
  for (const candidate of [url, fallbackUrl].filter((u) => !!u)) {
21463
22353
  for (let attempt = 1; attempt <= DOWNLOAD_ATTEMPTS; attempt++) {
21464
22354
  const ac = new AbortController();
21465
22355
  try {
21466
- const res = await fetchWithTimeout(
21467
- candidate,
21468
- timeoutMs,
21469
- net,
21470
- {
21471
- accept: "application/octet-stream"
21472
- },
21473
- ac
21474
- );
22356
+ const offset = extra?.existingBytes === void 0 ? 0 : await (typeof extra.existingBytes === "function" ? extra.existingBytes() : extra.existingBytes);
22357
+ const headers = {
22358
+ accept: "application/octet-stream",
22359
+ ...extra?.headers
22360
+ };
22361
+ if (offset > 0) headers.range = `bytes=${offset}-`;
22362
+ const res = await fetchWithTimeout(candidate, timeoutMs, net, headers, ac);
21475
22363
  if (!res.ok) {
22364
+ if (res.status === 416) {
22365
+ throw new RangeNotSatisfiableError(
22366
+ parseContentRange(headerOf(res, "content-range"))?.total ?? null
22367
+ );
22368
+ }
21476
22369
  lastError = new Error(`HTTP ${res.status} downloading ${candidate}`);
21477
22370
  if (res.status < 500) break;
21478
22371
  } else {
21479
- return await consume(res, ac);
22372
+ return await consume(res, ac, offset);
21480
22373
  }
21481
22374
  } catch (error) {
21482
- if (error instanceof TransferStalledError) throw error;
22375
+ if (error instanceof RangeNotSatisfiableError) throw error;
21483
22376
  lastError = error;
21484
- if (!isTransientNetworkError(error)) break;
22377
+ const retryable = error instanceof RangeMismatchError || error instanceof TransferStalledError || isTransientNetworkError(error);
22378
+ if (!retryable) break;
21485
22379
  }
21486
22380
  attempts.push(candidate);
21487
- if (attempt < DOWNLOAD_ATTEMPTS) await sleep2(250 * attempt);
22381
+ if (attempt < DOWNLOAD_ATTEMPTS) await sleep3(250 * attempt);
21488
22382
  }
21489
22383
  }
21490
22384
  throw new Error(
@@ -21505,10 +22399,12 @@ function transferStats(received, elapsedMs) {
21505
22399
  const rate = received > 0 ? `, ${formatRate(received, elapsedMs)} average` : "";
21506
22400
  return `${received} bytes received in ${seconds} s${rate}`;
21507
22401
  }
21508
- async function streamAssetToFile(res, dest, ac, stallTimeoutMs, progressIntervalMs, log) {
22402
+ async function streamAssetToFile(res, dest, ac, stallTimeoutMs, progressIntervalMs, log, opts) {
21509
22403
  if (!res.body) throw new Error("the release asset response carried no body");
21510
22404
  const started = Date.now();
21511
- let received = 0;
22405
+ const initialBytes = opts?.initialBytes ?? 0;
22406
+ let received = initialBytes;
22407
+ let attemptBytes = 0;
21512
22408
  let lastProgressAt = started;
21513
22409
  let stalled = false;
21514
22410
  let stallTimer;
@@ -21524,10 +22420,15 @@ async function streamAssetToFile(res, dest, ac, stallTimeoutMs, progressInterval
21524
22420
  const meter = new Transform({
21525
22421
  transform(chunk, _encoding, callback) {
21526
22422
  received += chunk.length;
22423
+ attemptBytes += chunk.length;
21527
22424
  const now = Date.now();
21528
22425
  if (now - lastProgressAt >= progressIntervalMs) {
21529
22426
  lastProgressAt = now;
21530
- log(`downloading ${formatBytes(received)} (${formatRate(received, now - started)})`);
22427
+ const total = opts?.totalBytes;
22428
+ const totalPart = total ? ` / ${formatBytes(total)}` : "";
22429
+ log(
22430
+ `downloading ${formatBytes(received)}${totalPart} (${formatRate(attemptBytes, now - started)})`
22431
+ );
21531
22432
  }
21532
22433
  resetStall();
21533
22434
  callback(null, chunk);
@@ -21540,15 +22441,16 @@ async function streamAssetToFile(res, dest, ac, stallTimeoutMs, progressInterval
21540
22441
  // class is the one Readable.fromWeb accepts.
21541
22442
  Readable.fromWeb(res.body),
21542
22443
  meter,
21543
- // flags 'w' truncates: a retried attempt must not append to the bytes
21544
- // a previous attempt already wrote.
21545
- createWriteStream(dest),
22444
+ // flags 'a' appends (a 206 continues the fragment); 'w' truncates (a
22445
+ // 200 rewrites it — a retried attempt must not append to the bytes a
22446
+ // previous attempt already wrote).
22447
+ createWriteStream(dest, { flags: opts?.append ? "a" : "w" }),
21546
22448
  { signal: ac.signal }
21547
22449
  );
21548
22450
  } catch (e) {
21549
22451
  if (stalled) {
21550
22452
  throw new TransferStalledError(
21551
- `the download stalled \u2014 no data for ${Math.round(stallTimeoutMs / 1e3)} s (${transferStats(received, Date.now() - started)})`
22453
+ `the download stalled \u2014 no data for ${Math.round(stallTimeoutMs / 1e3)} s (${transferStats(attemptBytes, Date.now() - started)})`
21552
22454
  );
21553
22455
  }
21554
22456
  throw e;
@@ -21556,6 +22458,65 @@ async function streamAssetToFile(res, dest, ac, stallTimeoutMs, progressInterval
21556
22458
  if (stallTimer) clearTimeout(stallTimer);
21557
22459
  }
21558
22460
  }
22461
+ async function downloadResumableAsset(url, fallbackUrl, dest, net, log) {
22462
+ const stallTimeoutMs = net.stallTimeoutMs ?? ASSET_STALL_TIMEOUT_MS;
22463
+ const progressIntervalMs = net.progressIntervalMs ?? ASSET_PROGRESS_INTERVAL_MS;
22464
+ let forceFullDownload = false;
22465
+ const offsetOf = async () => {
22466
+ if (forceFullDownload) return 0;
22467
+ return await fileSize(dest);
22468
+ };
22469
+ for (let round = 0; round < 2; round++) {
22470
+ try {
22471
+ await fetchAsset(
22472
+ url,
22473
+ fallbackUrl,
22474
+ ASSET_HEADERS_TIMEOUT_MS,
22475
+ net,
22476
+ "binary",
22477
+ async (res, attempt, requested) => {
22478
+ const range = parseContentRange(headerOf(res, "content-range"));
22479
+ const start = range ? range.start : null;
22480
+ const totalBytes = res.status === 206 ? range?.total ?? void 0 : numberOrUndefined(headerOf(res, "content-length"));
22481
+ if (res.status === 206) {
22482
+ if (start === null || start !== requested) {
22483
+ await unlink(dest).catch(() => {
22484
+ });
22485
+ forceFullDownload = true;
22486
+ throw new RangeMismatchError(
22487
+ `the server answered 206 starting at ${start ?? "?"}, not ${requested}`
22488
+ );
22489
+ }
22490
+ await streamAssetToFile(res, dest, attempt, stallTimeoutMs, progressIntervalMs, log, {
22491
+ append: true,
22492
+ initialBytes: requested,
22493
+ totalBytes
22494
+ });
22495
+ return;
22496
+ }
22497
+ await streamAssetToFile(res, dest, attempt, stallTimeoutMs, progressIntervalMs, log, {
22498
+ append: false,
22499
+ initialBytes: 0,
22500
+ totalBytes
22501
+ });
22502
+ },
22503
+ { existingBytes: offsetOf }
22504
+ );
22505
+ return;
22506
+ } catch (e) {
22507
+ if (e instanceof RangeNotSatisfiableError) {
22508
+ const have = await fileSize(dest);
22509
+ if (e.total !== null && e.total === have) return;
22510
+ await unlink(dest).catch(() => {
22511
+ });
22512
+ forceFullDownload = true;
22513
+ continue;
22514
+ }
22515
+ throw e;
22516
+ }
22517
+ }
22518
+ throw new Error("the release asset could not be downloaded (the server ignored the resume range)");
22519
+ }
21559
22520
  async function resolveLatestRelease(platform = process.platform, arch = process.arch, net = {}) {
21560
22521
  let res;
21561
22522
  try {
@@ -21617,8 +22578,6 @@ async function resolveLatestRelease(platform = process.platform, arch = process.
21617
22578
  }
21618
22579
  function realSelfUpdateDeps(context, net = {}) {
21619
22580
  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
22581
  return {
21623
22582
  execPath: process.execPath,
21624
22583
  platform: process.platform,
@@ -21627,14 +22586,7 @@ function realSelfUpdateDeps(context, net = {}) {
21627
22586
  sourceDir: process.env.HARNESSED_UPDATE_SOURCE_DIR?.trim() || null,
21628
22587
  resolveRelease: () => resolveLatestRelease(process.platform, process.arch, net),
21629
22588
  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
- );
22589
+ await downloadResumableAsset(url, fallbackUrl, dest, net, log);
21638
22590
  },
21639
22591
  fetchShaText: async (url, fallbackUrl) => {
21640
22592
  return fetchAsset(url, fallbackUrl, CHECKSUM_TIMEOUT_MS, net, "checksum", (res) => res.text());
@@ -21667,7 +22619,7 @@ async function execDirWritable(execPath) {
21667
22619
  return false;
21668
22620
  }
21669
22621
  }
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;
22622
+ 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
22623
  var init_selfUpdateBinary = __esm({
21672
22624
  "src/cli/lib/selfUpdateBinary.ts"() {
21673
22625
  init_package();
@@ -21686,6 +22638,15 @@ var init_selfUpdateBinary = __esm({
21686
22638
  };
21687
22639
  TransferStalledError = class extends Error {
21688
22640
  };
22641
+ RangeMismatchError = class extends Error {
22642
+ };
22643
+ RangeNotSatisfiableError = class extends Error {
22644
+ constructor(total) {
22645
+ super("the requested range is not satisfiable");
22646
+ this.total = total;
22647
+ }
22648
+ total;
22649
+ };
21689
22650
  DOWNLOAD_ATTEMPTS = 3;
21690
22651
  }
21691
22652
  });
@@ -22000,7 +22961,7 @@ function decodeUpdateContinuation(encoded) {
22000
22961
  return value;
22001
22962
  }
22002
22963
  async function runContinuationProcess(executablePath, args, options) {
22003
- return new Promise((resolve40, reject) => {
22964
+ return new Promise((resolve42, reject) => {
22004
22965
  const child = spawn(executablePath, args, {
22005
22966
  cwd: options.cwd,
22006
22967
  env: options.env,
@@ -22014,7 +22975,7 @@ async function runContinuationProcess(executablePath, args, options) {
22014
22975
  child.once("error", reject);
22015
22976
  child.once("close", (exitCode, signal) => {
22016
22977
  clearTimeout(timer);
22017
- resolve40({ exitCode, signal });
22978
+ resolve42({ exitCode, signal });
22018
22979
  });
22019
22980
  });
22020
22981
  }
@@ -22202,13 +23163,13 @@ function runWarning(ctx, name, variant) {
22202
23163
  function spawnLoopSteps(indent) {
22203
23164
  const i = indent;
22204
23165
  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>\`.`,
23166
+ `${i}a. Bash: \`harnessed prompt <sub> --task "<spec>" --json\` \u2192 parse \`{prompt, max_iterations, model, result_file}\`.`,
23167
+ `${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:`,
23168
+ `${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
23169
  `${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
23170
  `${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>"\`.`
23171
+ `${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.)`,
23172
+ `${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
23173
  ];
22213
23174
  }
22214
23175
  function buildInteractiveBody(name, prompt) {
@@ -22254,7 +23215,7 @@ function buildOrchestratorBody(name, prompt, ctx) {
22254
23215
  const leafIndent = " ";
22255
23216
  const leafSpawnLoop = [
22256
23217
  ...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).`,
23218
+ `${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
23219
  `${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
23220
  ];
22260
23221
  return [
@@ -22287,7 +23248,7 @@ function buildOrchestratorBody(name, prompt, ctx) {
22287
23248
  // itself: every judgement-call fact pinned to its firing side and no caller
22288
23249
  // ever passing context, i.e. criteria with zero discriminating power.
22289
23250
  `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)." : ""}`,
23251
+ `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
23252
  `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
23253
  // Phase 65 — this step's text is NOT maintained by hand any more. It is
22293
23254
  // `host.teams_step_note.command` in workflows/host-primitives.yaml; the
@@ -22408,7 +23369,7 @@ function generateCommandArtifact(name, commandsDir, prompt, capabilities, instal
22408
23369
  const filename = `${name}.md`;
22409
23370
  return { ...generated, filename, path: join(commandsDir, filename) };
22410
23371
  }
22411
- async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync28 = (p8) => readFileSync(p8, "utf8"), hostRender) {
23372
+ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync29 = (p8) => readFileSync(p8, "utf8"), hostRender) {
22412
23373
  const results = [];
22413
23374
  const aggregatedWarnings = /* @__PURE__ */ new Set();
22414
23375
  for (const name of slashNames) {
@@ -22427,7 +23388,7 @@ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabiliti
22427
23388
  if (fileExists2(path)) {
22428
23389
  let existing = "";
22429
23390
  try {
22430
- existing = readFileSync28(path);
23391
+ existing = readFileSync29(path);
22431
23392
  } catch {
22432
23393
  existing = "";
22433
23394
  }
@@ -22858,14 +23819,12 @@ async function reminderEnabled(context) {
22858
23819
  const stateRoot = resolve(
22859
23820
  context.platform.stateRoot !== defaultRoot ? context.platform.stateRoot : join(context.nativeHome, "harnessed")
22860
23821
  );
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
- }
23822
+ const { preferences, missing, document } = readUpdateReminderPreferencesFile(
23823
+ join(stateRoot, "update-reminder-preferences.json")
23824
+ );
23825
+ if (preferences.unreadable) return false;
23826
+ if (missing) return true;
23827
+ return document?.schemaVersion === 1 && preferences.enabled;
22869
23828
  }
22870
23829
  async function hasFirstPartyRegistration(context, hookEvent, hookCommand) {
22871
23830
  let raw;
@@ -23005,6 +23964,7 @@ var init_refreshOwnedUpdate = __esm({
23005
23964
  init_renderSkillTemplates();
23006
23965
  init_skillBackup();
23007
23966
  init_skillIntegrity();
23967
+ init_updateReminderPreferences();
23008
23968
  init_updateResult();
23009
23969
  init_workflowArtifacts();
23010
23970
  OWNED_HOOKS = [
@@ -24684,87 +25644,6 @@ var init_run2 = __esm({
24684
25644
  _autoChainLoadFailed = false;
24685
25645
  }
24686
25646
  });
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
25647
 
24769
25648
  // src/cli/lib/enableAgentTeamsInSettings.ts
24770
25649
  async function enableAgentTeamsInSettings(hostContext) {
@@ -25827,11 +26706,20 @@ function registerSetup(program2) {
25827
26706
  if (reminder) {
25828
26707
  try {
25829
26708
  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
- );
26709
+ if (raw.updateReminder === false) {
26710
+ const existing = readUpdateReminderPreferencesFile(reminder.preferencesPath);
26711
+ await writeFile(
26712
+ reminder.preferencesPath,
26713
+ JSON.stringify({ ...existing.document ?? { schemaVersion: 1 }, enabled: false }),
26714
+ { encoding: "utf8", flag: "w" }
26715
+ );
26716
+ } else {
26717
+ await writeFile(
26718
+ reminder.preferencesPath,
26719
+ JSON.stringify({ schemaVersion: 1, enabled: true }),
26720
+ { encoding: "utf8", flag: "wx" }
26721
+ );
26722
+ }
25835
26723
  } catch (error) {
25836
26724
  if (raw.updateReminder === false) throw error;
25837
26725
  if (error.code !== "EEXIST")
@@ -26357,6 +27245,7 @@ var init_setup = __esm({
26357
27245
  init_legacyCommandCleanup();
26358
27246
  init_renderSkillTemplates();
26359
27247
  init_setup_helpers();
27248
+ init_updateReminderPreferences();
26360
27249
  init_version_banner();
26361
27250
  KNOWN_PLATFORMS = HOST_IDS;
26362
27251
  }
@@ -26965,7 +27854,7 @@ var init_npmCli3 = __esm({
26965
27854
  cwd: ctx.hostContext.userHome,
26966
27855
  env: withHostInstallEnv(process.env, ctx.hostContext)
26967
27856
  } : {};
26968
- const result = await new Promise((resolve40) => {
27857
+ const result = await new Promise((resolve42) => {
26969
27858
  const child = isWin ? spawn("cmd.exe", ["/c", "npm", "uninstall", "-g", pkg], {
26970
27859
  ...spawnOptions,
26971
27860
  windowsHide: true
@@ -26976,15 +27865,15 @@ var init_npmCli3 = __esm({
26976
27865
  });
26977
27866
  const timer = setTimeout(() => {
26978
27867
  child.kill("SIGKILL");
26979
- resolve40({ exitCode: -1, stderr: `${stderr}[timeout]` });
27868
+ resolve42({ exitCode: -1, stderr: `${stderr}[timeout]` });
26980
27869
  }, 3e4);
26981
27870
  child.on("error", (e) => {
26982
27871
  clearTimeout(timer);
26983
- resolve40({ exitCode: -1, stderr: e.message });
27872
+ resolve42({ exitCode: -1, stderr: e.message });
26984
27873
  });
26985
27874
  child.on("close", (code2) => {
26986
27875
  clearTimeout(timer);
26987
- resolve40({ exitCode: code2 ?? -1, stderr });
27876
+ resolve42({ exitCode: code2 ?? -1, stderr });
26988
27877
  });
26989
27878
  });
26990
27879
  if (result.exitCode !== 0) {
@@ -27582,6 +28471,38 @@ var init_uninstall = __esm({
27582
28471
  }
27583
28472
  });
27584
28473
 
28474
+ // src/cli/lib/changelogSection.ts
28475
+ var changelogSection_exports = {};
28476
+ __export(changelogSection_exports, {
28477
+ changelogSection: () => changelogSection
28478
+ });
28479
+ function escapeRegExp2(value) {
28480
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
28481
+ }
28482
+ function changelogSection(version) {
28483
+ try {
28484
+ const path = join(getAssetsRoot(), "CHANGELOG.md");
28485
+ if (!existsSync(path)) return null;
28486
+ const body = readFileSync(path, "utf8");
28487
+ const heading = version ? new RegExp(`^## \\[${escapeRegExp2(version)}\\]`, "m") : /^## /m;
28488
+ const match = heading.exec(body);
28489
+ if (!match) return null;
28490
+ const rest = body.slice(match.index);
28491
+ const next = rest.slice(1).search(/^## /m);
28492
+ const section = next >= 0 ? rest.slice(0, next + 1) : rest;
28493
+ return section.trim().slice(0, CHANGELOG_EXCERPT_LIMIT);
28494
+ } catch {
28495
+ return null;
28496
+ }
28497
+ }
28498
+ var CHANGELOG_EXCERPT_LIMIT;
28499
+ var init_changelogSection = __esm({
28500
+ "src/cli/lib/changelogSection.ts"() {
28501
+ init_assetsRoot();
28502
+ CHANGELOG_EXCERPT_LIMIT = 1200;
28503
+ }
28504
+ });
28505
+
27585
28506
  // src/cli/lib/ownedRefreshFlag.ts
27586
28507
  var ownedRefreshFlag_exports = {};
27587
28508
  __export(ownedRefreshFlag_exports, {
@@ -27599,7 +28520,8 @@ var ownedRefresh_exports = {};
27599
28520
  __export(ownedRefresh_exports, {
27600
28521
  refreshOwnedState: () => refreshOwnedState,
27601
28522
  runOwnedRefreshEntry: () => runOwnedRefreshEntry,
27602
- spawnOwnedRefresh: () => spawnOwnedRefresh
28523
+ spawnOwnedRefresh: () => spawnOwnedRefresh,
28524
+ writeAutoUpdateNoticeForNewBinary: () => writeAutoUpdateNoticeForNewBinary
27603
28525
  });
27604
28526
  async function refreshOwnedState(context) {
27605
28527
  const { refreshOwnedUpdate: refreshOwnedUpdate2 } = await Promise.resolve().then(() => (init_refreshOwnedUpdate(), refreshOwnedUpdate_exports));
@@ -27614,6 +28536,7 @@ async function runOwnedRefreshEntry() {
27614
28536
  const { captureHostInstallContext: captureHostInstallContext3 } = await Promise.resolve().then(() => (init_hostInstallContext(), hostInstallContext_exports));
27615
28537
  const context = captureHostInstallContext3();
27616
28538
  const outcome = await refreshOwnedState(context);
28539
+ writeAutoUpdateNoticeForNewBinary(context);
27617
28540
  if (outcome.ok) {
27618
28541
  console.log(
27619
28542
  `[harnessed] owned state refreshed (${outcome.updated.length} component(s): ${outcome.updated.join(", ")})`
@@ -27625,9 +28548,28 @@ async function runOwnedRefreshEntry() {
27625
28548
  );
27626
28549
  return 1;
27627
28550
  }
28551
+ async function writeAutoUpdateNoticeForNewBinary(context) {
28552
+ const statusPath = process.env[AUTO_UPDATE_STATUS_PATH_ENV];
28553
+ if (!statusPath) return;
28554
+ try {
28555
+ const [{ readAutoUpdateNotice: readAutoUpdateNotice2, writeAutoUpdateNotice: writeAutoUpdateNotice2 }, { changelogSection: changelogSection2 }] = await Promise.all([Promise.resolve().then(() => (init_autoUpdateNotice(), autoUpdateNotice_exports)), Promise.resolve().then(() => (init_changelogSection(), changelogSection_exports))]);
28556
+ const version = package_default.version;
28557
+ const previous = readAutoUpdateNotice2(statusPath);
28558
+ writeAutoUpdateNotice2(statusPath, {
28559
+ // The `from` version was recorded by the OLD binary before the spawn.
28560
+ from: previous?.from ?? "",
28561
+ to: version,
28562
+ changelog: changelogSection2(version) ?? "",
28563
+ restart: context.hostId === "codex" ? "Codex" : "Claude Code",
28564
+ at: Date.now(),
28565
+ consumedAt: 0
28566
+ });
28567
+ } catch {
28568
+ }
28569
+ }
27628
28570
  async function spawnOwnedRefresh(execPath, context, deps = {}, timeoutMs = OWNED_REFRESH_TIMEOUT_MS) {
27629
28571
  const spawnImpl = deps.spawn ?? spawn;
27630
- return new Promise((resolve40) => {
28572
+ return new Promise((resolve42) => {
27631
28573
  let child;
27632
28574
  try {
27633
28575
  child = spawnImpl(execPath, [OWNED_REFRESH_FLAG], {
@@ -27641,7 +28583,7 @@ async function spawnOwnedRefresh(execPath, context, deps = {}, timeoutMs = OWNED
27641
28583
  shell: false
27642
28584
  });
27643
28585
  } catch (error) {
27644
- resolve40({
28586
+ resolve42({
27645
28587
  ok: false,
27646
28588
  exitCode: null,
27647
28589
  error: error instanceof Error ? error.message : String(error)
@@ -27653,23 +28595,25 @@ async function spawnOwnedRefresh(execPath, context, deps = {}, timeoutMs = OWNED
27653
28595
  killProcessTree(child);
27654
28596
  } catch {
27655
28597
  }
27656
- resolve40({ ok: false, exitCode: null, error: `timed out after ${timeoutMs}ms` });
28598
+ resolve42({ ok: false, exitCode: null, error: `timed out after ${timeoutMs}ms` });
27657
28599
  }, timeoutMs);
27658
28600
  child.on("error", (error) => {
27659
28601
  clearTimeout(timer);
27660
- resolve40({ ok: false, exitCode: null, error: error.message });
28602
+ resolve42({ ok: false, exitCode: null, error: error.message });
27661
28603
  });
27662
28604
  child.on("close", (code2) => {
27663
28605
  clearTimeout(timer);
27664
- resolve40({ ok: code2 === 0, exitCode: code2 });
28606
+ resolve42({ ok: code2 === 0, exitCode: code2 });
27665
28607
  });
27666
28608
  });
27667
28609
  }
27668
28610
  var OWNED_REFRESH_TIMEOUT_MS;
27669
28611
  var init_ownedRefresh = __esm({
27670
28612
  "src/cli/lib/ownedRefresh.ts"() {
28613
+ init_package();
27671
28614
  init_killTree();
27672
28615
  init_runClaudeArgs();
28616
+ init_autoUpdateStatus();
27673
28617
  init_ownedRefreshFlag();
27674
28618
  OWNED_REFRESH_TIMEOUT_MS = 18e4;
27675
28619
  }
@@ -27713,6 +28657,7 @@ var init_migration_report = __esm({
27713
28657
  // src/cli/update.ts
27714
28658
  var update_exports = {};
27715
28659
  __export(update_exports, {
28660
+ changelogTop: () => changelogTop,
27716
28661
  registerUpdate: () => registerUpdate
27717
28662
  });
27718
28663
  function finishLegacyUpdate(code2) {
@@ -27821,20 +28766,6 @@ async function runCompiledFlow(opts, context) {
27821
28766
  return finishLegacyUpdate(1);
27822
28767
  }
27823
28768
  }
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
28769
  function registerUpdate(program2) {
27839
28770
  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
28771
  new Option(
@@ -27948,7 +28879,7 @@ ${cl}
27948
28879
  });
27949
28880
  });
27950
28881
  }
27951
- var LegacyUpdateExit;
28882
+ var LegacyUpdateExit, changelogTop;
27952
28883
  var init_update = __esm({
27953
28884
  "src/cli/update.ts"() {
27954
28885
  init_package();
@@ -27956,6 +28887,7 @@ var init_update = __esm({
27956
28887
  init_harnessedRoot();
27957
28888
  init_hostInstallContext();
27958
28889
  init_runtime();
28890
+ init_changelogSection();
27959
28891
  init_packageUpdateTarget();
27960
28892
  init_updateCoordinator();
27961
28893
  LegacyUpdateExit = class extends Error {
@@ -27965,6 +28897,7 @@ var init_update = __esm({
27965
28897
  }
27966
28898
  code;
27967
28899
  };
28900
+ changelogTop = changelogSection;
27968
28901
  }
27969
28902
  });
27970
28903
 
@@ -28003,6 +28936,7 @@ var { registerAdvance: registerAdvance2 } = await Promise.resolve().then(() => (
28003
28936
  var { registerAgentsMd: registerAgentsMd2 } = await Promise.resolve().then(() => (init_agents_md(), agents_md_exports));
28004
28937
  var { registerAudit: registerAudit2 } = await Promise.resolve().then(() => (init_audit(), audit_exports));
28005
28938
  var { registerAuditLog: registerAuditLog2 } = await Promise.resolve().then(() => (init_audit_log(), audit_log_exports));
28939
+ var { registerAutoUpdate: registerAutoUpdate2 } = await Promise.resolve().then(() => (init_autoUpdateCmd(), autoUpdateCmd_exports));
28006
28940
  var { registerBackupList: registerBackupList2 } = await Promise.resolve().then(() => (init_backup_list(), backup_list_exports));
28007
28941
  var { registerCheckDocs: registerCheckDocs2 } = await Promise.resolve().then(() => (init_checkDocs(), checkDocs_exports));
28008
28942
  var { registerCheckpoint: registerCheckpoint2 } = await Promise.resolve().then(() => (init_checkpoint(), checkpoint_exports));
@@ -28125,6 +29059,7 @@ registerInjectState2(program);
28125
29059
  registerEval2(program);
28126
29060
  registerCheckDocs2(program);
28127
29061
  registerFacts2(program);
29062
+ registerAutoUpdate2(program);
28128
29063
  var bare = parseBareInvocation2(process.argv.slice(2));
28129
29064
  if (bare.here) {
28130
29065
  void runHere2({ json: bare.json });