harnessed 5.0.15 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/bin/harnessed-update-reminder-worker.mjs +18 -14
  3. package/bin/harnessed-update-reminder.mjs +1 -1
  4. package/dist/cli.mjs +1632 -336
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/index.mjs +1 -1
  7. package/dist/index.mjs.map +1 -1
  8. package/manifests/skill-packs/planning-with-files.yaml +6 -1
  9. package/package.json +1 -1
  10. package/workflows/auto/SKILL.md +1 -1
  11. package/workflows/auto/SKILL.zh-Hans.md +1 -1
  12. package/workflows/discuss/auto/SKILL.md +1 -1
  13. package/workflows/discuss/auto/SKILL.zh-Hans.md +1 -1
  14. package/workflows/discuss/phase/SKILL.md +1 -1
  15. package/workflows/discuss/phase/SKILL.zh-Hans.md +1 -1
  16. package/workflows/discuss/strategic/SKILL.md +1 -1
  17. package/workflows/discuss/strategic/SKILL.zh-Hans.md +1 -1
  18. package/workflows/discuss/subtask/SKILL.md +1 -1
  19. package/workflows/discuss/subtask/SKILL.zh-Hans.md +1 -1
  20. package/workflows/harnessed-update/SKILL.md +1 -1
  21. package/workflows/harnessed-update/SKILL.zh-Hans.md +1 -1
  22. package/workflows/plan/ai-integration/SKILL.md +1 -1
  23. package/workflows/plan/ai-integration/SKILL.zh-Hans.md +1 -1
  24. package/workflows/plan/architecture/SKILL.md +1 -1
  25. package/workflows/plan/architecture/SKILL.zh-Hans.md +1 -1
  26. package/workflows/plan/auto/SKILL.md +1 -1
  27. package/workflows/plan/auto/SKILL.zh-Hans.md +1 -1
  28. package/workflows/plan/phase/SKILL.md +1 -1
  29. package/workflows/plan/phase/SKILL.zh-Hans.md +1 -1
  30. package/workflows/plan/secure/SKILL.md +1 -1
  31. package/workflows/plan/secure/SKILL.zh-Hans.md +1 -1
  32. package/workflows/plan/spec/SKILL.md +1 -1
  33. package/workflows/plan/spec/SKILL.zh-Hans.md +1 -1
  34. package/workflows/plan/ui/SKILL.md +1 -1
  35. package/workflows/plan/ui/SKILL.zh-Hans.md +1 -1
  36. package/workflows/research/SKILL.md +3 -1
  37. package/workflows/research/SKILL.zh-Hans.md +3 -1
  38. package/workflows/retro/SKILL.md +1 -1
  39. package/workflows/retro/SKILL.zh-Hans.md +1 -1
  40. package/workflows/role-prompts.yaml +6 -3
  41. package/workflows/role-prompts.zh-Hans.yaml +6 -3
  42. package/workflows/ship/auto/SKILL.md +1 -1
  43. package/workflows/ship/auto/SKILL.zh-Hans.md +1 -1
  44. package/workflows/ship/preflight/SKILL.md +1 -1
  45. package/workflows/ship/preflight/SKILL.zh-Hans.md +1 -1
  46. package/workflows/task/auto/SKILL.md +1 -1
  47. package/workflows/task/auto/SKILL.zh-Hans.md +1 -1
  48. package/workflows/task/clarify/SKILL.md +1 -1
  49. package/workflows/task/clarify/SKILL.zh-Hans.md +1 -1
  50. package/workflows/task/code/SKILL.md +1 -1
  51. package/workflows/task/code/SKILL.zh-Hans.md +1 -1
  52. package/workflows/task/deliver/SKILL.md +1 -1
  53. package/workflows/task/deliver/SKILL.zh-Hans.md +1 -1
  54. package/workflows/task/test/SKILL.md +1 -1
  55. package/workflows/task/test/SKILL.zh-Hans.md +1 -1
  56. package/workflows/verify/auto/SKILL.md +1 -1
  57. package/workflows/verify/auto/SKILL.zh-Hans.md +1 -1
  58. package/workflows/verify/code-review/SKILL.md +1 -1
  59. package/workflows/verify/code-review/SKILL.zh-Hans.md +1 -1
  60. package/workflows/verify/design/SKILL.md +1 -1
  61. package/workflows/verify/design/SKILL.zh-Hans.md +1 -1
  62. package/workflows/verify/eval-review/SKILL.md +1 -1
  63. package/workflows/verify/eval-review/SKILL.zh-Hans.md +1 -1
  64. package/workflows/verify/multispec/SKILL.md +1 -1
  65. package/workflows/verify/multispec/SKILL.zh-Hans.md +1 -1
  66. package/workflows/verify/paranoid/SKILL.md +1 -1
  67. package/workflows/verify/paranoid/SKILL.zh-Hans.md +1 -1
  68. package/workflows/verify/progress/SKILL.md +1 -1
  69. package/workflows/verify/progress/SKILL.zh-Hans.md +1 -1
  70. package/workflows/verify/qa/SKILL.md +1 -1
  71. package/workflows/verify/qa/SKILL.zh-Hans.md +1 -1
  72. package/workflows/verify/second-opinion/SKILL.md +1 -1
  73. package/workflows/verify/second-opinion/SKILL.zh-Hans.md +1 -1
  74. package/workflows/verify/security/SKILL.md +1 -1
  75. package/workflows/verify/security/SKILL.zh-Hans.md +1 -1
  76. package/workflows/verify/simplify/SKILL.md +1 -1
  77. package/workflows/verify/simplify/SKILL.zh-Hans.md +1 -1
  78. package/workflows/verify/validate-phase/SKILL.md +1 -1
  79. package/workflows/verify/validate-phase/SKILL.zh-Hans.md +1 -1
package/dist/cli.mjs CHANGED
@@ -1,19 +1,19 @@
1
1
  #!/usr/bin/env node
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';
2
+ import { readFileSync, existsSync, mkdirSync, readdirSync, writeFileSync, appendFileSync, accessSync, constants, statSync, unlinkSync, realpathSync, renameSync, rmSync, openSync, closeSync, fsyncSync, lstatSync, fstatSync, readSync, mkdtempSync, createWriteStream, 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';
6
- import { readFile, mkdir, writeFile, readdir, stat, appendFile, rename, mkdtemp, rm, access, realpath, copyFile, unlink, chmod, cp, lstat, symlink } from 'fs/promises';
6
+ import { realpath, readFile, mkdir, writeFile, readdir, stat, appendFile, rename, mkdtemp, rm, access, copyFile, unlink, chmod, cp, lstat, symlink } from 'fs/promises';
7
+ import { randomUUID, createHash, randomBytes, timingSafeEqual, verify, createPublicKey } from 'crypto';
8
+ import { AsyncLocalStorage } from 'async_hooks';
7
9
  import { Value } from '@sinclair/typebox/value';
8
10
  import lockfile from 'proper-lockfile';
9
- import { createHash, randomBytes, timingSafeEqual, verify, createPublicKey, randomUUID } from 'crypto';
10
11
  import { pathToFileURL, fileURLToPath } from 'url';
11
12
  import { LineCounter, parseDocument, parse, isSeq, isAlias, isScalar, stringify, isMap } from 'yaml';
12
13
  import { Ajv } from 'ajv';
13
14
  import * as ajvFormatsNs from 'ajv-formats';
14
15
  import { spawnSync, execFileSync, spawn, execFile, exec } from 'child_process';
15
16
  import { Argument, InvalidArgumentError, Option } from 'commander';
16
- import { AsyncLocalStorage } from 'async_hooks';
17
17
  import { promisify, isDeepStrictEqual } from 'util';
18
18
  import { Parser } from 'expr-eval';
19
19
  import * as p from '@clack/prompts';
@@ -42,7 +42,7 @@ var init_package = __esm({
42
42
  "package.json"() {
43
43
  package_default = {
44
44
  name: "harnessed",
45
- version: "5.0.15",
45
+ version: "5.1.0",
46
46
  description: "AI coding harness package manager + composition orchestrator",
47
47
  type: "module",
48
48
  license: "Apache-2.0",
@@ -401,6 +401,17 @@ var init_hostInstallContext = __esm({
401
401
  init_platform();
402
402
  }
403
403
  });
404
+ function shareVolume(a, b) {
405
+ try {
406
+ return statSync(a).dev === statSync(b).dev;
407
+ } catch {
408
+ return true;
409
+ }
410
+ }
411
+ var init_volumeIdentity = __esm({
412
+ "src/platform/volumeIdentity.ts"() {
413
+ }
414
+ });
404
415
 
405
416
  // src/platform/harnessedRoot.ts
406
417
  var harnessedRoot_exports = {};
@@ -408,6 +419,7 @@ __export(harnessedRoot_exports, {
408
419
  getHarnessedRoot: () => getHarnessedRoot,
409
420
  harnessedFile: () => harnessedFile,
410
421
  harnessedSubdir: () => harnessedSubdir,
422
+ legacyMigrationRoot: () => legacyMigrationRoot,
411
423
  migrateLegacyHarnessedRoot: () => migrateLegacyHarnessedRoot
412
424
  });
413
425
  function getHarnessedRoot() {
@@ -431,8 +443,13 @@ function renameLegacyRoot(source, target) {
431
443
  return false;
432
444
  }
433
445
  }
434
- function migrateLegacyHarnessedRoot(context = captureHostInstallContext()) {
435
- const legacyRoot = join(context.userHome, ".harnessed");
446
+ function legacyMigrationRoot(context) {
447
+ if (process.env.HARNESSED_ROOT_OVERRIDE) return void 0;
448
+ return join(context.userHome, ".harnessed");
449
+ }
450
+ function migrateLegacyHarnessedRoot(context = captureHostInstallContext(), missingTargetOnly = false) {
451
+ const legacyRoot = legacyMigrationRoot(context);
452
+ if (!legacyRoot) return;
436
453
  const newRoot = context.platform.stateRoot;
437
454
  const targetParent = dirname(newRoot);
438
455
  if (!existsSync(legacyRoot)) return;
@@ -444,6 +461,13 @@ function migrateLegacyHarnessedRoot(context = captureHostInstallContext()) {
444
461
  );
445
462
  return;
446
463
  }
464
+ if (missingTargetOnly) return;
465
+ if (!shareVolume(legacyRoot, newRoot)) {
466
+ console.error(
467
+ `[harnessed] WARN: legacy state directory ${legacyRoot} is on a different volume than ${newRoot} and cannot be imported by rename; leaving legacy data in place \u2014 copy it manually if you need it`
468
+ );
469
+ return;
470
+ }
447
471
  const safetyBak = join(context.userHome, ".harnessed.legacy-bak");
448
472
  if (existsSync(safetyBak)) {
449
473
  console.error(
@@ -460,6 +484,7 @@ var init_harnessedRoot = __esm({
460
484
  "src/platform/harnessedRoot.ts"() {
461
485
  init_hostInstallContext();
462
486
  init_platform();
487
+ init_volumeIdentity();
463
488
  }
464
489
  });
465
490
  function branchOnSchemaVersion(v, handlers) {
@@ -625,7 +650,7 @@ var init_spawnFailure = __esm({
625
650
  };
626
651
  }
627
652
  });
628
- var WorkflowStatus, EvidenceRef, SubProgressEntry, CurrentWorkflowV1;
653
+ var WorkflowStatus, EvidenceRef, SubProgressEntry, HANDOFF_UUID_PATTERN, HandoffHost, HANDOFF_SESSION_ID_PATTERN, CurrentWorkflowV1;
629
654
  var init_currentWorkflow_v1 = __esm({
630
655
  "src/checkpoint/schema/currentWorkflow.v1.ts"() {
631
656
  init_schemaVersion();
@@ -668,6 +693,27 @@ var init_currentWorkflow_v1 = __esm({
668
693
  // G6 — failure counter; incremented only on each ->failed transition (drives
669
694
  // breakLoop detection). 'rejected' is terminal and does NOT increment it.
670
695
  fail_count: Type.Optional(Type.Integer({ minimum: 0 })),
696
+ // Absent: legacy/manual; null: invalidated, awaiting a new dispatch.
697
+ // The containing workflow and entry identify the run and sub.
698
+ result_attempt: Type.Optional(
699
+ Type.Union([
700
+ Type.Null(),
701
+ Type.Object(
702
+ {
703
+ id: Type.String({ pattern: "^[0-9a-f-]{36}$" }),
704
+ owner: Type.String({ minLength: 1 }),
705
+ number: Type.Integer({ minimum: 0 }),
706
+ result_file: Type.String({ minLength: 1 }),
707
+ git_head: Type.Union([
708
+ Type.String({ pattern: "^[0-9a-f]{40}([0-9a-f]{24})?$" }),
709
+ Type.Null()
710
+ ]),
711
+ accepted_digest: Type.Optional(Type.String({ pattern: "^[0-9a-f]{64}$" }))
712
+ },
713
+ { additionalProperties: false }
714
+ )
715
+ ])
716
+ ),
671
717
  // 4.26.0 (A3 serial-order guard) — seeding-time serial/parallel semantics
672
718
  // carried over from the gates plan (fire[].mode/order). Optional: pre-4.26.0
673
719
  // envelopes lack them, and the guard no-ops on entries without `mode`
@@ -738,6 +784,9 @@ var init_currentWorkflow_v1 = __esm({
738
784
  },
739
785
  { additionalProperties: false }
740
786
  );
787
+ HANDOFF_UUID_PATTERN = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}(?![\\s\\S])";
788
+ HandoffHost = Type.Union([Type.Literal("claude"), Type.Literal("codex")]);
789
+ HANDOFF_SESSION_ID_PATTERN = "^(?!(?:displaced|premigrate)-)[a-zA-Z0-9_-]+(?![\\s\\S])";
741
790
  CurrentWorkflowV1 = Type.Object(
742
791
  {
743
792
  schemaVersion: Type.Literal(SCHEMA_VERSIONS.currentWorkflow),
@@ -752,6 +801,29 @@ var init_currentWorkflow_v1 = __esm({
752
801
  // checkpoint envelope does NOT carry a copy). Old files without this field
753
802
  // still `Value.Check`-pass → no schema version bump; readers use `?? []`.
754
803
  sub_progress: Type.Optional(Type.Array(SubProgressEntry)),
804
+ // Present from the first publication of an explicitly enrolled run.
805
+ handoff_authority: Type.Optional(
806
+ Type.Object(
807
+ {
808
+ run_id: Type.String({ pattern: HANDOFF_UUID_PATTERN }),
809
+ host: HandoffHost,
810
+ session_id: Type.String({ pattern: HANDOFF_SESSION_ID_PATTERN }),
811
+ frozen: Type.Optional(
812
+ Type.Object(
813
+ {
814
+ transfer_id: Type.String({ pattern: HANDOFF_UUID_PATTERN }),
815
+ source_root: Type.String({ minLength: 1 }),
816
+ target_host: HandoffHost,
817
+ target_root: Type.String({ minLength: 1 }),
818
+ repo_key: Type.String({ minLength: 1 })
819
+ },
820
+ { additionalProperties: false }
821
+ )
822
+ )
823
+ },
824
+ { additionalProperties: false }
825
+ )
826
+ ),
755
827
  // G1 — verification depth used during the verify phase ('light' | 'full').
756
828
  verify_mode: Type.Optional(Type.Union([Type.Literal("light"), Type.Literal("full")])),
757
829
  // G2 — when true the next-step contract reports NEXT:auto (skill auto-advances);
@@ -795,6 +867,18 @@ var init_currentWorkflow_v1 = __esm({
795
867
  );
796
868
  }
797
869
  });
870
+ function ownerHash(ownerKey = activeKey()) {
871
+ return createHash("sha256").update(ownerKey).digest("hex").slice(0, 16);
872
+ }
873
+ function ownerPath(area, segments, ownerKey = activeKey()) {
874
+ return join(harnessedSubdir(area), ownerHash(ownerKey), ...segments);
875
+ }
876
+ var init_ownerPath = __esm({
877
+ "src/checkpoint/ownerPath.ts"() {
878
+ init_harnessedRoot();
879
+ init_workflowStore();
880
+ }
881
+ });
798
882
  var CheckpointStatus, CheckpointV1;
799
883
  var init_checkpoint_v1 = __esm({
800
884
  "src/checkpoint/schema/checkpoint.v1.ts"() {
@@ -842,12 +926,16 @@ __export(state_exports, {
842
926
  LockHeldError: () => LockHeldError,
843
927
  WorkflowStateError: () => WorkflowStateError,
844
928
  activate: () => activate,
929
+ claimHandoff: () => claimHandoff,
845
930
  complete: () => complete,
931
+ enrollHandoffRun: () => enrollHandoffRun,
932
+ freezeHandoffSource: () => freezeHandoffSource,
846
933
  mutateStore: () => mutateStore,
847
934
  mutateSubProgress: () => mutateSubProgress,
848
935
  mutateWorkflow: () => mutateWorkflow,
849
936
  pause: () => pause,
850
937
  readCurrentWorkflow: () => readCurrentWorkflow,
938
+ withWorkflowEffects: () => withWorkflowEffects,
851
939
  writeCurrentWorkflow: () => writeCurrentWorkflow
852
940
  });
853
941
  function statePath() {
@@ -863,9 +951,9 @@ function lockOpts() {
863
951
  lockfilePath: harnessedFile(".lock")
864
952
  };
865
953
  }
866
- async function withLock(fn) {
954
+ async function withLock(fn, existingRootOnly = false) {
867
955
  const target = lockTarget();
868
- await mkdir(target, { recursive: true });
956
+ if (!existingRootOnly) await mkdir(target, { recursive: true });
869
957
  let release;
870
958
  try {
871
959
  release = await lockfile.lock(target, lockOpts());
@@ -873,25 +961,64 @@ async function withLock(fn) {
873
961
  if (e.code === "ELOCKED") throw new LockHeldError();
874
962
  throw e;
875
963
  }
964
+ const scope = { root: target, held: true };
876
965
  try {
877
- return await fn();
966
+ return await lockScope.run(scope, fn);
878
967
  } finally {
968
+ scope.held = false;
879
969
  await release?.();
880
970
  }
881
971
  }
882
- async function readCurrentWorkflow() {
883
- const store = await readStoreRaw();
972
+ async function withLocalLock(fn) {
973
+ const scope = lockScope.getStore();
974
+ return scope?.held && scope.root === lockTarget() ? fn() : withLock(fn);
975
+ }
976
+ async function withWorkflowEffects(fn) {
977
+ return withLocalLock(async () => fn(await readCurrentWorkflow(true)));
978
+ }
979
+ async function readCurrentWorkflow(forMutation = false, recovery = false) {
980
+ if (forMutation) return writableWorkflow(await readStoreAt(getHarnessedRoot(), true));
981
+ const store = recovery ? await readRecoveryStore() : await readStoreRaw();
884
982
  return store.workflows[activeKey()] ?? store.workflows[repoKey()] ?? null;
885
983
  }
984
+ function writableWorkflow(store) {
985
+ const base = repoKey();
986
+ const key = activeKey();
987
+ const slot = store.workflows[key] ?? store.workflows[base] ?? null;
988
+ if (slot?.handoff_authority?.frozen) {
989
+ throw new WorkflowStateError("workflow source is frozen for handoff");
990
+ }
991
+ if (slot?.handoff_authority && (key !== `${base}::${slot.handoff_authority.session_id}` || slot !== store.workflows[key] || resolveHostWithReason().descriptor.id !== slot.handoff_authority.host)) {
992
+ throw new WorkflowStateError("handoff workflow requires its exact session slot");
993
+ }
994
+ if (!store.workflows[key] && Object.values(store.handoff_claims ?? {}).some(
995
+ (claim) => claim.repo_key === base && (key === `${base}::${claim.target_session_id}` || key === base)
996
+ )) {
997
+ throw new WorkflowStateError("cannot recreate a pruned handoff claim");
998
+ }
999
+ if (!slot && key === base && Object.entries(store.workflows).some(
1000
+ ([k, wf]) => k.startsWith(`${base}::`) && wf.handoff_authority
1001
+ )) {
1002
+ throw new WorkflowStateError("handoff workflow requires its exact session slot");
1003
+ }
1004
+ return slot;
1005
+ }
886
1006
  async function writeCurrentWorkflowUnlocked(input) {
887
1007
  const s = { ...input, updated_at: (/* @__PURE__ */ new Date()).toISOString() };
888
1008
  if (!Value.Check(CurrentWorkflowV1, s)) {
889
1009
  const errs = [...Value.Errors(CurrentWorkflowV1, s)].map((e) => e.message).join("; ");
890
1010
  throw new WorkflowStateError(`current-workflow schema validation failed: ${errs}`);
891
1011
  }
892
- const store = await readStoreRaw();
893
- store.workflows[activeKey()] = s;
1012
+ const store = await readStoreAt(getHarnessedRoot(), true);
1013
+ writableWorkflow(store);
1014
+ const key = activeKey();
1015
+ const authority = store.workflows[key]?.handoff_authority;
1016
+ if (authority && s.handoff_authority?.run_id !== authority.run_id) {
1017
+ throw new WorkflowStateError("cannot replace a --handoff-ready workflow run");
1018
+ }
1019
+ store.workflows[key] = s;
894
1020
  await writeStoreRaw(store);
1021
+ if (s.handoff_authority) return;
895
1022
  await writeFileAtomic(statePath(), JSON.stringify(s, null, 2));
896
1023
  }
897
1024
  async function writeCurrentWorkflow(s) {
@@ -899,25 +1026,313 @@ async function writeCurrentWorkflow(s) {
899
1026
  }
900
1027
  async function mutateSubProgress(fn) {
901
1028
  await withLock(async () => {
902
- const s = await readCurrentWorkflow();
1029
+ const s = await readCurrentWorkflow(true);
903
1030
  if (!s) return;
904
1031
  const next = fn(s.sub_progress ?? []);
905
1032
  await writeCurrentWorkflowUnlocked({ ...s, sub_progress: next });
906
1033
  });
907
1034
  }
908
- async function mutateWorkflow(fn) {
1035
+ async function mutateWorkflow(fn, onMissing) {
909
1036
  await withLock(async () => {
910
- const s = await readCurrentWorkflow();
911
- if (!s) return;
912
- await writeCurrentWorkflowUnlocked(fn(s));
1037
+ const s = await readCurrentWorkflow(true);
1038
+ if (!s) {
1039
+ await onMissing?.();
1040
+ return;
1041
+ }
1042
+ const next = await fn(s);
1043
+ if (next !== s) await writeCurrentWorkflowUnlocked(next);
913
1044
  });
914
1045
  }
915
1046
  async function mutateStore(fn) {
1047
+ await withLocalLock(async () => {
1048
+ const store = await readStoreAt(getHarnessedRoot(), true);
1049
+ writableWorkflow(store);
1050
+ const frozen = Object.entries(store.workflows).filter(([, slot]) => slot.handoff_authority?.frozen).map(([key, slot]) => [key, JSON.stringify(slot)]);
1051
+ const next = fn(store);
1052
+ if (frozen.some(([key, slot]) => JSON.stringify(next.workflows[key]) !== slot)) {
1053
+ throw new WorkflowStateError("cannot change a frozen handoff source slot");
1054
+ }
1055
+ if (next !== store) await writeStoreRaw(next);
1056
+ });
1057
+ }
1058
+ async function enrollHandoffRun(phase, entries) {
1059
+ const { descriptor, reason } = resolveHostWithReason();
1060
+ const { id: host, sessionIdEnv } = descriptor;
1061
+ const sid = sessionIdEnv ? process.env[sessionIdEnv] : void 0;
1062
+ if (!isHostId(host) || !sid || !new RegExp(HANDOFF_SESSION_ID_PATTERN).test(sid) || reason.kind !== "host-session-env" && reason.kind !== "env-platform" || process.env.HARNESSED_HEADLESS === "1") {
1063
+ throw new WorkflowStateError(
1064
+ "--handoff-ready requires an exact live session on the active host"
1065
+ );
1066
+ }
1067
+ const base = repoKey();
1068
+ if (base.includes("::"))
1069
+ throw new WorkflowStateError("ambiguous repository key for --handoff-ready");
1070
+ const key = `${base}::${sid}`;
1071
+ const checkpointPath = ownerPath("checkpoints", [`${phase}.json`], key);
1072
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1073
+ const slot = {
1074
+ schemaVersion: SCHEMA_VERSIONS.currentWorkflow,
1075
+ phase,
1076
+ status: "active",
1077
+ last_checkpoint_path: checkpointPath,
1078
+ started_at: now,
1079
+ updated_at: now,
1080
+ sub_progress: entries,
1081
+ handoff_authority: { run_id: randomUUID(), host, session_id: sid }
1082
+ };
1083
+ if (!Value.Check(CurrentWorkflowV1, slot)) {
1084
+ throw new WorkflowStateError("--handoff-ready requires a valid --plan ledger");
1085
+ }
916
1086
  await withLock(async () => {
917
- const store = await readStoreRaw();
918
- await writeStoreRaw(fn(store));
1087
+ const store = await readStoreAt(getHarnessedRoot(), true);
1088
+ const occupied = Object.keys(store.workflows).some((existing) => {
1089
+ const separator = existing.indexOf("::");
1090
+ const canonical = separator < 0 ? normalizeRepoKey(existing) : normalizeRepoKey(existing.slice(0, separator)) + existing.slice(separator);
1091
+ return canonical === key || canonical === base;
1092
+ });
1093
+ if (occupied || Object.values(store.handoff_claims ?? {}).some(
1094
+ (claim) => claim.repo_key === base && claim.target_session_id === sid
1095
+ )) {
1096
+ throw new WorkflowStateError("an exact or bare workflow slot already exists or was claimed");
1097
+ }
1098
+ store.workflows[key] = slot;
1099
+ if (store.intents) {
1100
+ delete store.intents[key];
1101
+ delete store.intents[base];
1102
+ }
1103
+ await writeStoreRaw(store);
1104
+ });
1105
+ return checkpointPath;
1106
+ }
1107
+ async function canonicalHandoffRoot(path, allowMissing = false) {
1108
+ if (!isAbsolute(path) || resolve(path) !== path || path.includes("\0") || process.platform === "win32" && path.startsWith("\\\\")) {
1109
+ throw new WorkflowStateError("malformed handoff root");
1110
+ }
1111
+ let entry;
1112
+ try {
1113
+ entry = await lstat(path);
1114
+ } catch (error) {
1115
+ if (!allowMissing || error.code !== "ENOENT") throw error;
1116
+ const parent = dirname(path);
1117
+ if (parent === path) throw error;
1118
+ return join(await canonicalHandoffRoot(parent, true), basename(path));
1119
+ }
1120
+ const canonical = await realpath(path);
1121
+ if (!entry.isDirectory() || normalizeRepoKey(path) !== normalizeRepoKey(canonical)) {
1122
+ throw new WorkflowStateError("handoff root is not a canonical directory");
1123
+ }
1124
+ return canonical;
1125
+ }
1126
+ async function assertHandoffLedgerFile(root) {
1127
+ const file = await lstat(join(root, "workflows.json")).catch((error) => {
1128
+ if (error.code === "ENOENT") return void 0;
1129
+ throw error;
1130
+ });
1131
+ if (file && (!file.isFile() || file.nlink !== 1)) {
1132
+ throw new WorkflowStateError("handoff ledger must be a regular, unaliased file");
1133
+ }
1134
+ }
1135
+ function distinctHandoffRoots(source, target) {
1136
+ const a = normalizeRepoKey(source);
1137
+ const b = normalizeRepoKey(target);
1138
+ return a !== b && !a.startsWith(b + sep) && !b.startsWith(a + sep);
1139
+ }
1140
+ async function checkHandoffClaimRoots(source, target, configured) {
1141
+ const src = await canonicalHandoffRoot(source, true);
1142
+ const dest = await canonicalHandoffRoot(target, true);
1143
+ if (!distinctHandoffRoots(src, dest)) {
1144
+ throw new WorkflowStateError("handoff requires separate host roots");
1145
+ }
1146
+ if (normalizeRepoKey(dest) !== normalizeRepoKey(await canonicalHandoffRoot(configured, true))) {
1147
+ throw new WorkflowStateError("active root is not the configured handoff target root");
1148
+ }
1149
+ return { src, dest };
1150
+ }
1151
+ async function assertHandoffLockPath(root) {
1152
+ const lock2 = await lstat(join(root, ".lock")).catch((error) => {
1153
+ if (error.code === "ENOENT") return void 0;
1154
+ throw error;
1155
+ });
1156
+ if (lock2 && !lock2.isDirectory()) throw new WorkflowStateError("invalid handoff destination lock");
1157
+ }
1158
+ async function hasHandoffConflict(store, base, session, runId, allowed) {
1159
+ for (const [key, slot] of Object.entries(store.workflows)) {
1160
+ if (key === allowed) continue;
1161
+ if (slot.handoff_authority?.run_id === runId) return true;
1162
+ const [repo, sid, archive] = key.split("::");
1163
+ if (!repo || sid && (sid !== session || archive)) continue;
1164
+ if (normalizeRepoKey(repo) === base) return true;
1165
+ if (!isAbsolute(repo) || process.platform === "win32" && repo.startsWith("\\\\")) continue;
1166
+ try {
1167
+ if (normalizeRepoKey(await realpath(repo)) === base) return true;
1168
+ } catch (error) {
1169
+ const code2 = error.code;
1170
+ if (code2 !== "ENOENT" && code2 !== "ENOTDIR") throw error;
1171
+ }
1172
+ }
1173
+ return false;
1174
+ }
1175
+ function pendingHandoffAttempt(slot) {
1176
+ return slot.sub_progress?.some(
1177
+ (e) => e.result_attempt && !(e.status === "done" && e.result_attempt.accepted_digest)
1178
+ ) ?? false;
1179
+ }
1180
+ async function claimHandoff(from, transferId) {
1181
+ const { descriptor, reason } = resolveHostWithReason();
1182
+ const { id: host, sessionIdEnv } = descriptor;
1183
+ const sid = sessionIdEnv ? process.env[sessionIdEnv] : void 0;
1184
+ if (!isHostId(host) || !sid || !new RegExp(HANDOFF_SESSION_ID_PATTERN).test(sid) || reason.kind !== "host-session-env" && reason.kind !== "env-platform" || process.env.HARNESSED_HEADLESS === "1") {
1185
+ throw new WorkflowStateError("handoff claim requires an exact live destination session");
1186
+ }
1187
+ if (!isHostId(from) || from === host || !new RegExp(HANDOFF_UUID_PATTERN).test(transferId)) {
1188
+ throw new WorkflowStateError(
1189
+ "handoff claim requires --from <opposite host> and a valid transfer ID"
1190
+ );
1191
+ }
1192
+ const base = repoKey();
1193
+ if (base.includes("::") || normalizeRepoKey(await realpath(base)) !== base) {
1194
+ throw new WorkflowStateError("handoff requires a canonical repository key");
1195
+ }
1196
+ const key = `${base}::${sid}`;
1197
+ const source = descriptorForConfiguredHome(from);
1198
+ const target = getHarnessedRoot();
1199
+ const roots = () => checkHandoffClaimRoots(source.stateRoot, target, descriptor.stateRoot);
1200
+ await canonicalHandoffRoot(source.homeDir, true);
1201
+ await canonicalHandoffRoot(descriptor.homeDir, true);
1202
+ await roots();
1203
+ await assertHandoffLedgerFile(target);
1204
+ await assertHandoffLockPath(target);
1205
+ return withLock(async () => {
1206
+ const { src, dest } = await roots();
1207
+ await assertHandoffLedgerFile(dest);
1208
+ const store = await readStoreAt(dest, true);
1209
+ const receipt = store.handoff_claims?.[transferId];
1210
+ if (receipt) {
1211
+ if (receipt.repo_key !== base || receipt.target_session_id !== sid || receipt.source_host !== from || receipt.target_host !== host || normalizeRepoKey(receipt.source_root) !== normalizeRepoKey(src) || normalizeRepoKey(receipt.target_root) !== normalizeRepoKey(dest)) {
1212
+ throw new WorkflowStateError(
1213
+ "handoff transfer already claimed by another destination identity"
1214
+ );
1215
+ }
1216
+ return receipt;
1217
+ }
1218
+ await assertHandoffLedgerFile(src);
1219
+ const sourceStore = await readStoreAt(src, true);
1220
+ const candidates = Object.entries(sourceStore.workflows).filter(
1221
+ ([, slot2]) => slot2.handoff_authority?.frozen?.transfer_id === transferId
1222
+ );
1223
+ const [sourceKey, slot] = candidates[0] ?? [];
1224
+ const authority = slot?.handoff_authority;
1225
+ const frozen = authority?.frozen;
1226
+ if (candidates.length !== 1 || !slot || !authority || !frozen || sourceKey !== `${base}::${authority.session_id}` || authority.host !== from || frozen.repo_key !== base || frozen.target_host !== host || normalizeRepoKey(frozen.source_root) !== normalizeRepoKey(src) || normalizeRepoKey(frozen.target_root) !== normalizeRepoKey(dest) || slot.status !== "active" || !slot.sub_progress?.length || pendingHandoffAttempt(slot)) {
1227
+ throw new WorkflowStateError(
1228
+ "no matching prepared handoff for this host, root and repository"
1229
+ );
1230
+ }
1231
+ if (await hasHandoffConflict(sourceStore, base, authority.session_id, authority.run_id, sourceKey)) {
1232
+ throw new WorkflowStateError("conflicting source workflow slot");
1233
+ }
1234
+ if (await hasHandoffConflict(store, base, sid, authority.run_id) || Object.values(store.handoff_claims ?? {}).some(
1235
+ (claim2) => claim2.run_id === authority.run_id || claim2.repo_key === base && claim2.target_session_id === sid
1236
+ )) {
1237
+ throw new WorkflowStateError("destination workflow slot is occupied or already claimed");
1238
+ }
1239
+ const claimedAt = (/* @__PURE__ */ new Date()).toISOString();
1240
+ const claim = {
1241
+ run_id: authority.run_id,
1242
+ repo_key: base,
1243
+ source_host: from,
1244
+ source_root: src,
1245
+ target_host: host,
1246
+ target_root: dest,
1247
+ target_session_id: sid,
1248
+ claimed_at: claimedAt
1249
+ };
1250
+ store.workflows[key] = {
1251
+ ...slot,
1252
+ updated_at: claimedAt,
1253
+ handoff_authority: { host, session_id: sid, run_id: authority.run_id },
1254
+ sub_progress: slot.sub_progress.map(
1255
+ (entry) => entry.result_attempt ? { ...entry, result_attempt: null } : entry
1256
+ )
1257
+ };
1258
+ store.handoff_claims = { ...store.handoff_claims, [transferId]: claim };
1259
+ await writeStoreRaw(store);
1260
+ return claim;
919
1261
  });
920
1262
  }
1263
+ async function freezeHandoffSource(to) {
1264
+ const { descriptor, reason } = resolveHostWithReason();
1265
+ const { id: host, sessionIdEnv } = descriptor;
1266
+ const sid = sessionIdEnv ? process.env[sessionIdEnv] : void 0;
1267
+ if (!isHostId(host) || !sid || !new RegExp(HANDOFF_SESSION_ID_PATTERN).test(sid) || reason.kind !== "host-session-env" && reason.kind !== "env-platform" || process.env.HARNESSED_HEADLESS === "1") {
1268
+ throw new WorkflowStateError("handoff requires an exact live source session");
1269
+ }
1270
+ if (!isHostId(to) || to === host)
1271
+ throw new WorkflowStateError("handoff requires the opposite host");
1272
+ const target = descriptorForConfiguredHome(to);
1273
+ const requestedRoot = getHarnessedRoot();
1274
+ await canonicalHandoffRoot(requestedRoot);
1275
+ const base = repoKey();
1276
+ if (base.includes("::") || normalizeRepoKey(await realpath(base)) !== base) {
1277
+ throw new WorkflowStateError("handoff requires a canonical repository key");
1278
+ }
1279
+ const key = `${base}::${sid}`;
1280
+ return withLock(async () => {
1281
+ const sourceRoot = await canonicalHandoffRoot(requestedRoot);
1282
+ await canonicalHandoffRoot(target.homeDir, true);
1283
+ const targetRoot = await canonicalHandoffRoot(target.stateRoot, true);
1284
+ const source = normalizeRepoKey(sourceRoot);
1285
+ const dest = normalizeRepoKey(targetRoot);
1286
+ if (source === dest || source.startsWith(dest + sep) || dest.startsWith(source + sep)) {
1287
+ throw new WorkflowStateError("handoff requires separate host roots");
1288
+ }
1289
+ const configuredSource = await canonicalHandoffRoot(
1290
+ descriptorForConfiguredHome(host).stateRoot,
1291
+ true
1292
+ );
1293
+ if (normalizeRepoKey(configuredSource) !== source) {
1294
+ throw new WorkflowStateError("active root is not the configured handoff source root");
1295
+ }
1296
+ const store = await readStoreAt(sourceRoot, true);
1297
+ const slot = store.workflows[key];
1298
+ const authority = slot?.handoff_authority;
1299
+ if (!slot || authority?.host !== host || authority.session_id !== sid) {
1300
+ throw new WorkflowStateError("handoff requires the exact enrolled source slot");
1301
+ }
1302
+ const frozen = authority.frozen;
1303
+ if (frozen) {
1304
+ if (frozen.target_host === to && frozen.repo_key === base && normalizeRepoKey(frozen.source_root) === source && normalizeRepoKey(frozen.target_root) === dest)
1305
+ return frozen.transfer_id;
1306
+ throw new WorkflowStateError("source already frozen; cannot retarget handoff");
1307
+ }
1308
+ if (Object.values(store.handoff_claims ?? {}).some((claim) => claim.run_id === authority.run_id)) {
1309
+ throw new WorkflowStateError("a claimed handoff cannot be handed off again");
1310
+ }
1311
+ if (slot.status !== "active") throw new WorkflowStateError("handoff source is not active");
1312
+ if (await hasHandoffConflict(store, base, sid, authority.run_id, key)) {
1313
+ throw new WorkflowStateError("conflicting source workflow slot");
1314
+ }
1315
+ if (pendingHandoffAttempt(slot)) {
1316
+ throw new WorkflowStateError("handoff source has an unsettled managed attempt");
1317
+ }
1318
+ const transferId = randomUUID();
1319
+ store.workflows[key] = {
1320
+ ...slot,
1321
+ handoff_authority: {
1322
+ ...authority,
1323
+ frozen: {
1324
+ transfer_id: transferId,
1325
+ source_root: sourceRoot,
1326
+ target_host: to,
1327
+ target_root: targetRoot,
1328
+ repo_key: base
1329
+ }
1330
+ }
1331
+ };
1332
+ await writeStoreRaw(store);
1333
+ return transferId;
1334
+ }, true);
1335
+ }
921
1336
  async function activate(phase, checkpointPath = null) {
922
1337
  await writeCurrentWorkflow({
923
1338
  schemaVersion: SCHEMA_VERSIONS.currentWorkflow,
@@ -927,22 +1342,27 @@ async function activate(phase, checkpointPath = null) {
927
1342
  started_at: (/* @__PURE__ */ new Date()).toISOString()
928
1343
  });
929
1344
  }
930
- async function pause() {
931
- await mutateWorkflow((s) => ({ ...s, status: "paused", paused_at: (/* @__PURE__ */ new Date()).toISOString() }));
1345
+ async function pause(publish) {
1346
+ await mutateWorkflow((s) => {
1347
+ publish?.();
1348
+ return { ...s, status: "paused", paused_at: (/* @__PURE__ */ new Date()).toISOString() };
1349
+ }, publish);
932
1350
  }
933
- async function complete() {
934
- await mutateWorkflow((s) => ({
935
- ...s,
936
- status: "complete",
937
- completed_at: (/* @__PURE__ */ new Date()).toISOString()
938
- }));
1351
+ async function complete(publish) {
1352
+ await mutateWorkflow((s) => {
1353
+ publish?.();
1354
+ return { ...s, status: "complete", completed_at: (/* @__PURE__ */ new Date()).toISOString() };
1355
+ }, publish);
939
1356
  }
940
- var WorkflowStateError, LockHeldError;
1357
+ var WorkflowStateError, LockHeldError, lockScope;
941
1358
  var init_state = __esm({
942
1359
  "src/checkpoint/state.ts"() {
943
1360
  init_harnessedRoot();
1361
+ init_platform();
944
1362
  init_schemaVersion();
945
1363
  init_atomicWrite();
1364
+ init_ownerPath();
1365
+ init_currentWorkflow_v1();
946
1366
  init_schema();
947
1367
  init_workflowStore();
948
1368
  WorkflowStateError = class extends Error {
@@ -960,6 +1380,7 @@ var init_state = __esm({
960
1380
  Object.setPrototypeOf(this, _LockHeldError.prototype);
961
1381
  }
962
1382
  };
1383
+ lockScope = new AsyncLocalStorage();
963
1384
  }
964
1385
  });
965
1386
 
@@ -972,13 +1393,34 @@ __export(workflowStore_exports, {
972
1393
  activeKey: () => activeKey,
973
1394
  listWorkflows: () => listWorkflows,
974
1395
  migrateRepoKeyCase: () => migrateRepoKeyCase,
1396
+ needsRepoKeyFold: () => needsRepoKeyFold,
975
1397
  normalizeRepoKey: () => normalizeRepoKey,
976
1398
  readIntent: () => readIntent,
1399
+ readLocalHandoff: () => readLocalHandoff,
1400
+ readRecoveryStore: () => readRecoveryStore,
977
1401
  readStoreAt: () => readStoreAt,
978
1402
  readStoreRaw: () => readStoreRaw,
979
1403
  repoKey: () => repoKey,
980
1404
  writeStoreRaw: () => writeStoreRaw
981
1405
  });
1406
+ async function readLocalHandoff() {
1407
+ const root = getHarnessedRoot();
1408
+ const store = await readStoreAt(root, true);
1409
+ const base = repoKey();
1410
+ const key = activeKey();
1411
+ const host = detectPlatform().id;
1412
+ const slot = store.workflows[key];
1413
+ const authority = slot?.handoff_authority;
1414
+ if (authority?.frozen && authority.host === host && key === `${base}::${authority.session_id}` && authority.frozen.repo_key === base && normalizeRepoKey(authority.frozen.source_root) === normalizeRepoKey(root)) {
1415
+ return { kind: "frozen", authority, frozen: authority.frozen };
1416
+ }
1417
+ for (const [id, claim] of Object.entries(store.handoff_claims ?? {})) {
1418
+ if (claim.target_host === host && claim.repo_key === base && key === `${base}::${claim.target_session_id}` && normalizeRepoKey(claim.target_root) === normalizeRepoKey(root)) {
1419
+ return { kind: "claimed", id, claim, slot };
1420
+ }
1421
+ }
1422
+ return null;
1423
+ }
982
1424
  function storePath() {
983
1425
  return harnessedFile("workflows.json");
984
1426
  }
@@ -1007,12 +1449,15 @@ function activeKey(cwd = process.cwd()) {
1007
1449
  async function readStoreRaw() {
1008
1450
  return readStoreAt(getHarnessedRoot());
1009
1451
  }
1010
- async function readStoreAt(root) {
1452
+ async function readStoreAt(root, strict = false) {
1453
+ const path = join(root, "workflows.json");
1011
1454
  try {
1012
- const parsed = JSON.parse(await readFile(join(root, "workflows.json"), "utf8"));
1455
+ const parsed = JSON.parse(await readFile(path, "utf8"));
1013
1456
  if (Value.Check(WorkflowStoreV1, parsed)) return parsed;
1014
- } catch {
1457
+ } catch (error) {
1458
+ if (error.code === "ENOENT") return emptyStore();
1015
1459
  }
1460
+ if (strict) throw new Error(`workflow ledger is unreadable: ${path}`);
1016
1461
  return emptyStore();
1017
1462
  }
1018
1463
  async function writeStoreRaw(store) {
@@ -1024,8 +1469,8 @@ async function writeStoreRaw(store) {
1024
1469
  await mkdir(dirname(p8), { recursive: true });
1025
1470
  await writeFileAtomic(p8, JSON.stringify(store, null, 2));
1026
1471
  }
1027
- async function readIntent(cwd = process.cwd()) {
1028
- const store = await readStoreRaw();
1472
+ async function readIntent(cwd = process.cwd(), recovery = false) {
1473
+ const store = recovery ? await readRecoveryStore() : await readStoreRaw();
1029
1474
  return store.intents?.[activeKey(cwd)] ?? store.intents?.[repoKey(cwd)] ?? null;
1030
1475
  }
1031
1476
  async function listWorkflows() {
@@ -1050,6 +1495,9 @@ function needsFold(store, platform) {
1050
1495
  }
1051
1496
  return false;
1052
1497
  }
1498
+ function needsRepoKeyFold(store) {
1499
+ return process.platform === "win32" && needsFold(store, process.platform);
1500
+ }
1053
1501
  function foldMap(map, newer, platform) {
1054
1502
  const groups = /* @__PURE__ */ new Map();
1055
1503
  let folded = 0;
@@ -1074,6 +1522,47 @@ function foldMap(map, newer, platform) {
1074
1522
  }
1075
1523
  return { next, folded, archived };
1076
1524
  }
1525
+ function foldStore(store, platform) {
1526
+ const w = foldMap(
1527
+ store.workflows,
1528
+ (a, b) => (a.updated_at ?? "") > (b.updated_at ?? ""),
1529
+ platform
1530
+ );
1531
+ const r = store.retro_meta ? foldMap(
1532
+ store.retro_meta,
1533
+ (a, b) => a.phases_since_retro !== b.phases_since_retro ? a.phases_since_retro > b.phases_since_retro : (a.last_retro_at ?? "") > (b.last_retro_at ?? ""),
1534
+ platform
1535
+ ) : void 0;
1536
+ const i = store.intents ? foldMap(store.intents, (a, b) => a.ts > b.ts, platform) : void 0;
1537
+ const next = { ...store, workflows: w.next };
1538
+ if (r) next.retro_meta = r.next;
1539
+ if (i) next.intents = i.next;
1540
+ return {
1541
+ next,
1542
+ folded: w.folded + (r?.folded ?? 0) + (i?.folded ?? 0),
1543
+ archived: w.archived + (r?.archived ?? 0) + (i?.archived ?? 0)
1544
+ };
1545
+ }
1546
+ async function readRecoveryStore() {
1547
+ const root = getHarnessedRoot();
1548
+ const legacy = existsSync(root) ? void 0 : legacyMigrationRoot(captureHostInstallContext());
1549
+ const store = await readStoreAt(legacy ?? root);
1550
+ const ordinary = {
1551
+ ...store,
1552
+ workflows: Object.fromEntries(
1553
+ Object.entries(store.workflows).filter(([, slot]) => !slot.handoff_authority)
1554
+ )
1555
+ };
1556
+ const projected = needsRepoKeyFold(ordinary) ? foldStore(ordinary, process.platform).next : ordinary;
1557
+ if (!legacy) {
1558
+ for (const [key, slot] of Object.entries(store.workflows)) {
1559
+ if (slot.handoff_authority && foldStoreKey(key, process.platform) === key) {
1560
+ projected.workflows[key] = slot;
1561
+ }
1562
+ }
1563
+ }
1564
+ return projected;
1565
+ }
1077
1566
  async function migrateRepoKeyCase(platform = process.platform) {
1078
1567
  const noop = { folded: 0, archived: 0 };
1079
1568
  if (platform !== "win32") return noop;
@@ -1081,24 +1570,9 @@ async function migrateRepoKeyCase(platform = process.platform) {
1081
1570
  let result = noop;
1082
1571
  const { mutateStore: mutateStore2 } = await Promise.resolve().then(() => (init_state(), state_exports));
1083
1572
  await mutateStore2((store) => {
1084
- const w = foldMap(
1085
- store.workflows,
1086
- (a, b) => (a.updated_at ?? "") > (b.updated_at ?? ""),
1087
- platform
1088
- );
1089
- const r = store.retro_meta ? foldMap(
1090
- store.retro_meta,
1091
- (a, b) => a.phases_since_retro !== b.phases_since_retro ? a.phases_since_retro > b.phases_since_retro : (a.last_retro_at ?? "") > (b.last_retro_at ?? ""),
1092
- platform
1093
- ) : void 0;
1094
- const i = store.intents ? foldMap(store.intents, (a, b) => a.ts > b.ts, platform) : void 0;
1095
- result = {
1096
- folded: w.folded + (r?.folded ?? 0) + (i?.folded ?? 0),
1097
- archived: w.archived + (r?.archived ?? 0) + (i?.archived ?? 0)
1098
- };
1099
- const next = { ...store, workflows: w.next };
1100
- if (r) next.retro_meta = r.next;
1101
- if (i) next.intents = i.next;
1573
+ if (!needsFold(store, platform)) return store;
1574
+ const { next, folded, archived } = foldStore(store, platform);
1575
+ result = { folded, archived };
1102
1576
  return next;
1103
1577
  });
1104
1578
  if (result.folded > 0 || result.archived > 0) {
@@ -1108,10 +1582,11 @@ async function migrateRepoKeyCase(platform = process.platform) {
1108
1582
  }
1109
1583
  return result;
1110
1584
  }
1111
- var RetroMetaEntry, IntentEntry, WorkflowStoreV1, PREMIGRATE;
1585
+ var RetroMetaEntry, IntentEntry, HandoffClaim, WorkflowStoreV1, PREMIGRATE;
1112
1586
  var init_workflowStore = __esm({
1113
1587
  "src/checkpoint/workflowStore.ts"() {
1114
1588
  init_harnessedRoot();
1589
+ init_hostInstallContext();
1115
1590
  init_platform();
1116
1591
  init_schemaVersion();
1117
1592
  init_atomicWrite();
@@ -1137,6 +1612,19 @@ var init_workflowStore = __esm({
1137
1612
  },
1138
1613
  { additionalProperties: false }
1139
1614
  );
1615
+ HandoffClaim = Type.Object(
1616
+ {
1617
+ run_id: Type.String({ pattern: HANDOFF_UUID_PATTERN }),
1618
+ repo_key: Type.String({ minLength: 1 }),
1619
+ source_host: HandoffHost,
1620
+ source_root: Type.String({ minLength: 1 }),
1621
+ target_host: HandoffHost,
1622
+ target_root: Type.String({ minLength: 1 }),
1623
+ target_session_id: Type.String({ pattern: HANDOFF_SESSION_ID_PATTERN }),
1624
+ claimed_at: Type.String({ minLength: 1 })
1625
+ },
1626
+ { additionalProperties: false }
1627
+ );
1140
1628
  WorkflowStoreV1 = Type.Object(
1141
1629
  {
1142
1630
  schemaVersion: Type.Literal(SCHEMA_VERSIONS.workflowStore),
@@ -1144,7 +1632,12 @@ var init_workflowStore = __esm({
1144
1632
  // Additive-optional (no schemaVersion bump — old stores Value.Check-pass).
1145
1633
  retro_meta: Type.Optional(Type.Record(Type.String(), RetroMetaEntry)),
1146
1634
  // 4.22.0 — additive-optional, same rationale.
1147
- intents: Type.Optional(Type.Record(Type.String(), IntentEntry))
1635
+ intents: Type.Optional(Type.Record(Type.String(), IntentEntry)),
1636
+ handoff_claims: Type.Optional(
1637
+ Type.Record(Type.String({ pattern: HANDOFF_UUID_PATTERN }), HandoffClaim, {
1638
+ additionalProperties: false
1639
+ })
1640
+ )
1148
1641
  },
1149
1642
  { additionalProperties: false }
1150
1643
  );
@@ -1372,7 +1865,10 @@ function markSub(entries, sub, status, opts) {
1372
1865
  }
1373
1866
  const current = entries[idx];
1374
1867
  const updated = { ...current, status };
1375
- if (status === "failed") updated.fail_count = (current.fail_count ?? 0) + 1;
1868
+ if (status === "failed") {
1869
+ updated.fail_count = (current.fail_count ?? 0) + 1;
1870
+ if (current.result_attempt !== void 0) updated.result_attempt = null;
1871
+ }
1376
1872
  if (opts?.evidence !== void 0) updated.evidence = opts.evidence;
1377
1873
  if (opts?.evidence_status !== void 0) updated.evidence_status = opts.evidence_status;
1378
1874
  if (opts?.completion_claim !== void 0) updated.completion_claim = opts.completion_claim;
@@ -1406,6 +1902,7 @@ function reopenSub(entries, sub, reason) {
1406
1902
  next[idx] = {
1407
1903
  ...rest,
1408
1904
  status: "pending",
1905
+ result_attempt: null,
1409
1906
  fail_count: (current.fail_count ?? 0) + 1,
1410
1907
  reason
1411
1908
  };
@@ -2247,8 +2744,8 @@ function stripAgentsMdSection(body) {
2247
2744
  function insertAgentsMdSection(body, section) {
2248
2745
  const base = stripAgentsMdSection(body);
2249
2746
  if (section === "") return base;
2250
- const sep6 = base === "" || base.endsWith("\n\n") ? "" : base.endsWith("\n") ? "\n" : "\n\n";
2251
- return `${base}${sep6}${section}`;
2747
+ const sep7 = base === "" || base.endsWith("\n\n") ? "" : base.endsWith("\n") ? "\n" : "\n\n";
2748
+ return `${base}${sep7}${section}`;
2252
2749
  }
2253
2750
  async function resolveCommandNames(workflowsDir) {
2254
2751
  const { readdir: readdir28 } = await import('fs/promises');
@@ -3451,9 +3948,9 @@ function redactRecord(r) {
3451
3948
  }
3452
3949
  function renderHumanTable(records) {
3453
3950
  const header = `${"ts".padEnd(19)} | ${"phase".padEnd(6)} | ${"category".padEnd(11)} | ${"matched_rule_id".padEnd(20)} | outcome`;
3454
- const sep6 = `${"-".repeat(19)}-+-${"-".repeat(6)}-+-${"-".repeat(11)}-+-${"-".repeat(20)}-+--------`;
3951
+ const sep7 = `${"-".repeat(19)}-+-${"-".repeat(6)}-+-${"-".repeat(11)}-+-${"-".repeat(20)}-+--------`;
3455
3952
  console.log(header);
3456
- console.log(sep6);
3953
+ console.log(sep7);
3457
3954
  for (const r of records) {
3458
3955
  const ts = r.ts.slice(0, 19);
3459
3956
  const phase = r.phase.padEnd(6);
@@ -3463,7 +3960,7 @@ function renderHumanTable(records) {
3463
3960
  }
3464
3961
  }
3465
3962
  function pipeToJq(filterExpr, lines) {
3466
- return new Promise((resolve42, reject) => {
3963
+ return new Promise((resolve44, reject) => {
3467
3964
  const child = spawn("jq", [filterExpr], {
3468
3965
  stdio: ["pipe", "inherit", "inherit"],
3469
3966
  windowsHide: true
@@ -3472,12 +3969,12 @@ function pipeToJq(filterExpr, lines) {
3472
3969
  const e = err2;
3473
3970
  if (e.code === "ENOENT") {
3474
3971
  console.error(t("audit_log.jq_missing"));
3475
- resolve42(1);
3972
+ resolve44(1);
3476
3973
  } else {
3477
3974
  reject(err2);
3478
3975
  }
3479
3976
  });
3480
- child.on("close", (code2) => resolve42(code2 ?? 0));
3977
+ child.on("close", (code2) => resolve44(code2 ?? 0));
3481
3978
  child.stdin.on("error", (err2) => {
3482
3979
  if (err2.code !== "EPIPE") reject(err2);
3483
3980
  });
@@ -4099,6 +4596,149 @@ var init_autoUpdateCmd = __esm({
4099
4596
  init_updateReminderPreferences();
4100
4597
  }
4101
4598
  });
4599
+
4600
+ // src/installers/lib/jsonSubtree.ts
4601
+ function isJsonObject(v) {
4602
+ return typeof v === "object" && v !== null && !Array.isArray(v);
4603
+ }
4604
+ function tryParseJsonObject(text) {
4605
+ try {
4606
+ const v = JSON.parse(text);
4607
+ return isJsonObject(v) ? v : null;
4608
+ } catch {
4609
+ return null;
4610
+ }
4611
+ }
4612
+ function hasOwn(obj, key) {
4613
+ return Object.hasOwn(obj, key);
4614
+ }
4615
+ function setOwn(obj, key, value) {
4616
+ Object.defineProperty(obj, key, {
4617
+ value,
4618
+ writable: true,
4619
+ enumerable: true,
4620
+ configurable: true
4621
+ });
4622
+ }
4623
+ function deepEqualJson(a, b) {
4624
+ if (a === b) return true;
4625
+ if (Array.isArray(a) && Array.isArray(b)) {
4626
+ return a.length === b.length && a.every((v, i) => deepEqualJson(v, b[i]));
4627
+ }
4628
+ if (isJsonObject(a) && isJsonObject(b)) {
4629
+ const aKeys = Object.keys(a);
4630
+ const bKeys = Object.keys(b);
4631
+ return aKeys.length === bKeys.length && aKeys.every((k) => hasOwn(b, k) && deepEqualJson(a[k], b[k]));
4632
+ }
4633
+ return false;
4634
+ }
4635
+ function diffJsonObjects(oldObj, newObj) {
4636
+ const changes = [];
4637
+ const walk = (o, n, base) => {
4638
+ for (const key of Object.keys(o)) {
4639
+ const path = [...base, key];
4640
+ if (!hasOwn(n, key)) {
4641
+ changes.push({ path, existed: true, value: o[key] });
4642
+ } else {
4643
+ compare(o[key], n[key], path);
4644
+ }
4645
+ }
4646
+ for (const key of Object.keys(n)) {
4647
+ if (!hasOwn(o, key)) changes.push({ path: [...base, key], existed: false });
4648
+ }
4649
+ };
4650
+ const compare = (a, b, path) => {
4651
+ if (isJsonObject(a) && isJsonObject(b)) {
4652
+ walk(a, b, path);
4653
+ } else if (!deepEqualJson(a, b)) {
4654
+ changes.push({ path, existed: true, value: a });
4655
+ }
4656
+ };
4657
+ walk(oldObj, newObj, []);
4658
+ return changes;
4659
+ }
4660
+ function containsUnsafeJsonNumber(value) {
4661
+ if (typeof value === "number") {
4662
+ return !Number.isFinite(value) || Number.isInteger(value) && !Number.isSafeInteger(value);
4663
+ }
4664
+ if (Array.isArray(value)) return value.some(containsUnsafeJsonNumber);
4665
+ if (isJsonObject(value)) {
4666
+ return Object.keys(value).some((k) => containsUnsafeJsonNumber(value[k]));
4667
+ }
4668
+ return false;
4669
+ }
4670
+ function pathsOverlap(a, b) {
4671
+ const n = Math.min(a.length, b.length);
4672
+ return a.slice(0, n).every((seg, i) => seg === b[i]);
4673
+ }
4674
+ function validateSubtreePayload(parsed) {
4675
+ if (!isJsonObject(parsed)) return { ok: false, reason: "payload is not a JSON object" };
4676
+ if (parsed.version !== SUBTREE_PAYLOAD_VERSION) {
4677
+ return { ok: false, reason: `unsupported payload version ${String(parsed.version)}` };
4678
+ }
4679
+ const raw = parsed.changes;
4680
+ if (!Array.isArray(raw)) return { ok: false, reason: "changes is not an array" };
4681
+ const changes = [];
4682
+ for (const item of raw) {
4683
+ if (!isJsonObject(item)) return { ok: false, reason: "change entry is not an object" };
4684
+ const { path, existed } = item;
4685
+ if (!Array.isArray(path) || path.length === 0 || !path.every((seg) => typeof seg === "string")) {
4686
+ return { ok: false, reason: "change path must be a non-empty string array" };
4687
+ }
4688
+ if (typeof existed !== "boolean") {
4689
+ return { ok: false, reason: "change existed must be boolean" };
4690
+ }
4691
+ const hasValue = hasOwn(item, "value");
4692
+ if (existed && !hasValue) {
4693
+ return { ok: false, reason: "existed change missing old value" };
4694
+ }
4695
+ if (!existed && hasValue) {
4696
+ return { ok: false, reason: "added-path change must not carry a value" };
4697
+ }
4698
+ const p8 = path;
4699
+ for (const prev of changes) {
4700
+ if (pathsOverlap(prev.path, p8)) {
4701
+ return {
4702
+ ok: false,
4703
+ reason: `duplicate or overlapping change path ${JSON.stringify(p8)}`
4704
+ };
4705
+ }
4706
+ }
4707
+ const change = { path: p8, existed };
4708
+ if (hasValue) change.value = item.value;
4709
+ changes.push(change);
4710
+ }
4711
+ return { ok: true, changes };
4712
+ }
4713
+ function applySubtreeChanges(current, changes) {
4714
+ for (const change of changes) {
4715
+ let node = current;
4716
+ for (const seg of change.path.slice(0, -1)) {
4717
+ const next = hasOwn(node, seg) ? node[seg] : void 0;
4718
+ if (!isJsonObject(next)) {
4719
+ return {
4720
+ ok: false,
4721
+ reason: `conflict at ${JSON.stringify(change.path)}: parent ${JSON.stringify(seg)} is missing or not an object`
4722
+ };
4723
+ }
4724
+ node = next;
4725
+ }
4726
+ const leaf = change.path[change.path.length - 1];
4727
+ if (change.existed) {
4728
+ setOwn(node, leaf, change.value);
4729
+ } else if (hasOwn(node, leaf)) {
4730
+ delete node[leaf];
4731
+ }
4732
+ }
4733
+ return { ok: true };
4734
+ }
4735
+ var SUBTREE_PAYLOAD_VERSION, SUBTREE_ENTRY_SHA1;
4736
+ var init_jsonSubtree = __esm({
4737
+ "src/installers/lib/jsonSubtree.ts"() {
4738
+ SUBTREE_PAYLOAD_VERSION = 1;
4739
+ SUBTREE_ENTRY_SHA1 = "json-subtree-v1";
4740
+ }
4741
+ });
4102
4742
  function getBackupRoot(hostContext) {
4103
4743
  return hostContext ? join(hostContext.platform.stateRoot, "backups") : harnessedSubdir("backups");
4104
4744
  }
@@ -4174,12 +4814,56 @@ async function backup(plan, ctx) {
4174
4814
  }
4175
4815
  };
4176
4816
  }
4177
- const sha1 = createHash("sha1").update(buf).digest("hex");
4178
4817
  const eol = detectEol(buf);
4179
4818
  const dest = mirrorPath(file.target, file.scope, backupDir, ctx.hostContext);
4819
+ const entry = {
4820
+ target: file.target,
4821
+ backup: dest,
4822
+ sha1: createHash("sha1").update(buf).digest("hex"),
4823
+ eol
4824
+ };
4825
+ let stored = buf;
4826
+ const oldJson = tryParseJsonObject(file.oldText);
4827
+ const newJson = tryParseJsonObject(file.newText);
4828
+ if (oldJson !== null && newJson !== null) {
4829
+ if (buf.toString("utf8") !== file.oldText) {
4830
+ return {
4831
+ ok: false,
4832
+ error: {
4833
+ file: filename,
4834
+ path: file.target,
4835
+ message: "on-disk content differs from plan oldText (stale plan); re-run the install to regenerate the plan",
4836
+ line: null,
4837
+ column: null,
4838
+ keyword: "backup-stale-plan"
4839
+ }
4840
+ };
4841
+ }
4842
+ if (containsUnsafeJsonNumber(oldJson) || containsUnsafeJsonNumber(newJson)) {
4843
+ return {
4844
+ ok: false,
4845
+ error: {
4846
+ file: filename,
4847
+ path: file.target,
4848
+ message: "JSON contains a number that cannot round-trip through JSON.stringify (non-finite or unsafe integer); scoped backup refused \u2014 edit the file manually",
4849
+ line: null,
4850
+ column: null,
4851
+ keyword: "backup-json-unsafe-number"
4852
+ }
4853
+ };
4854
+ }
4855
+ stored = Buffer.from(
4856
+ `${JSON.stringify({ version: 1, changes: diffJsonObjects(oldJson, newJson) }, null, 2)}
4857
+ `,
4858
+ "utf8"
4859
+ );
4860
+ entry.kind = "json-subtree";
4861
+ entry.sha1 = SUBTREE_ENTRY_SHA1;
4862
+ entry.payloadSha1 = createHash("sha1").update(stored).digest("hex");
4863
+ }
4180
4864
  try {
4181
4865
  await mkdir(dirname(dest), { recursive: true });
4182
- await writeFile(dest, buf);
4866
+ await writeFile(dest, stored);
4183
4867
  } catch (err2) {
4184
4868
  return {
4185
4869
  ok: false,
@@ -4193,7 +4877,7 @@ async function backup(plan, ctx) {
4193
4877
  }
4194
4878
  };
4195
4879
  }
4196
- entries.push({ target: file.target, backup: dest, sha1, eol });
4880
+ entries.push(entry);
4197
4881
  }
4198
4882
  const metadata = {
4199
4883
  installer: filename,
@@ -4224,6 +4908,7 @@ var HOME_DIR;
4224
4908
  var init_backup = __esm({
4225
4909
  "src/installers/lib/backup.ts"() {
4226
4910
  init_harnessedRoot();
4911
+ init_jsonSubtree();
4227
4912
  HOME_DIR = process.env.HOME ?? process.env.USERPROFILE ?? "";
4228
4913
  }
4229
4914
  });
@@ -4474,54 +5159,6 @@ var init_checkDocs = __esm({
4474
5159
  }
4475
5160
  });
4476
5161
 
4477
- // src/platform/runDeps.ts
4478
- function captureRunDeps() {
4479
- const stdout2 = [];
4480
- const stderr = [];
4481
- const deps = {
4482
- exit(code2) {
4483
- throw new ExitError(code2);
4484
- },
4485
- log: (...args) => {
4486
- stdout2.push(args.map(String).join(" "));
4487
- },
4488
- error: (...args) => {
4489
- stderr.push(args.map(String).join(" "));
4490
- },
4491
- warn: (...args) => {
4492
- stderr.push(args.map(String).join(" "));
4493
- }
4494
- };
4495
- return { deps, stdout: stdout2, stderr };
4496
- }
4497
- var ExitError, defaultRunDeps;
4498
- var init_runDeps = __esm({
4499
- "src/platform/runDeps.ts"() {
4500
- ExitError = class extends Error {
4501
- constructor(code2) {
4502
- super(`process.exit(${code2})`);
4503
- this.code = code2;
4504
- this.name = "ExitError";
4505
- }
4506
- code;
4507
- };
4508
- defaultRunDeps = {
4509
- exit(code2) {
4510
- return process.exit(code2);
4511
- },
4512
- log: (...args) => {
4513
- console.log(...args);
4514
- },
4515
- error: (...args) => {
4516
- console.error(...args);
4517
- },
4518
- warn: (...args) => {
4519
- console.warn(...args);
4520
- }
4521
- };
4522
- }
4523
- });
4524
-
4525
5162
  // src/workflow/lib/promiseExtract.ts
4526
5163
  function extractPromise(text) {
4527
5164
  const match = text.match(PROMISE_PATTERN);
@@ -4617,30 +5254,149 @@ var init_ralphLoop = __esm({
4617
5254
  };
4618
5255
  }
4619
5256
  });
4620
-
4621
- // src/checkpoint/completionClaim.ts
4622
- var completionClaim_exports = {};
4623
- __export(completionClaim_exports, {
4624
- verifyCompletionClaim: () => verifyCompletionClaim
4625
- });
5257
+ function resultAttemptLine(id) {
5258
+ return `${ATTEMPT_PREFIX}${id}`;
5259
+ }
4626
5260
  async function verifyCompletionClaim(input) {
4627
5261
  if (input.resultFile) {
4628
- let text;
5262
+ let bytes;
4629
5263
  try {
4630
- text = await readFile(input.resultFile, "utf8");
5264
+ bytes = await readFile(input.resultFile);
4631
5265
  } catch {
4632
5266
  return { verdict: "incomplete", source: input.resultFile };
4633
5267
  }
4634
- return { verdict: isComplete(text) ? "complete" : "incomplete", source: input.resultFile };
5268
+ const text = bytes.toString("utf8");
5269
+ const lines = text.split(/\r?\n/).filter((line) => line.startsWith(ATTEMPT_PREFIX));
5270
+ return {
5271
+ verdict: isComplete(text) ? "complete" : "incomplete",
5272
+ source: input.resultFile,
5273
+ ...lines.length > 0 && { hasAttemptLine: true },
5274
+ ...input.attemptId && lines.length === 1 && lines[0] === resultAttemptLine(input.attemptId) && {
5275
+ attemptDigest: createHash("sha256").update(bytes).digest("hex")
5276
+ }
5277
+ };
4635
5278
  }
4636
5279
  if (typeof input.result === "string" && input.result.trim() !== "") {
4637
- return { verdict: isComplete(input.result) ? "complete" : "incomplete", source: "--result" };
5280
+ return {
5281
+ verdict: isComplete(input.result) ? "complete" : "incomplete",
5282
+ source: "--result",
5283
+ ...input.result.split(/\r?\n/).some((line) => line.startsWith(ATTEMPT_PREFIX)) && {
5284
+ hasAttemptLine: true
5285
+ }
5286
+ };
4638
5287
  }
4639
5288
  return { verdict: "not_provided", source: null };
4640
5289
  }
5290
+ var ATTEMPT_PREFIX;
4641
5291
  var init_completionClaim = __esm({
4642
5292
  "src/checkpoint/completionClaim.ts"() {
4643
5293
  init_ralphLoop();
5294
+ ATTEMPT_PREFIX = "Checkpoint-Attempt: ";
5295
+ }
5296
+ });
5297
+
5298
+ // src/platform/runDeps.ts
5299
+ function captureRunDeps() {
5300
+ const stdout2 = [];
5301
+ const stderr = [];
5302
+ const deps = {
5303
+ exit(code2) {
5304
+ throw new ExitError(code2);
5305
+ },
5306
+ log: (...args) => {
5307
+ stdout2.push(args.map(String).join(" "));
5308
+ },
5309
+ error: (...args) => {
5310
+ stderr.push(args.map(String).join(" "));
5311
+ },
5312
+ warn: (...args) => {
5313
+ stderr.push(args.map(String).join(" "));
5314
+ }
5315
+ };
5316
+ return { deps, stdout: stdout2, stderr };
5317
+ }
5318
+ var ExitError, defaultRunDeps;
5319
+ var init_runDeps = __esm({
5320
+ "src/platform/runDeps.ts"() {
5321
+ ExitError = class extends Error {
5322
+ constructor(code2) {
5323
+ super(`process.exit(${code2})`);
5324
+ this.code = code2;
5325
+ this.name = "ExitError";
5326
+ }
5327
+ code;
5328
+ };
5329
+ defaultRunDeps = {
5330
+ exit(code2) {
5331
+ return process.exit(code2);
5332
+ },
5333
+ log: (...args) => {
5334
+ console.log(...args);
5335
+ },
5336
+ error: (...args) => {
5337
+ console.error(...args);
5338
+ },
5339
+ warn: (...args) => {
5340
+ console.warn(...args);
5341
+ }
5342
+ };
5343
+ }
5344
+ });
5345
+ function resultAttemptOwner() {
5346
+ return `${detectPlatform().id}:${activeKey()}`;
5347
+ }
5348
+ function gitOutput(cwd, args) {
5349
+ try {
5350
+ return execFileSync("git", args, {
5351
+ cwd,
5352
+ encoding: "utf8",
5353
+ stdio: ["ignore", "pipe", "pipe"],
5354
+ timeout: 5e3
5355
+ }).trim();
5356
+ } catch {
5357
+ return null;
5358
+ }
5359
+ }
5360
+ function newResultAttempt(sub, number) {
5361
+ const cwd = process.cwd();
5362
+ const id = randomUUID();
5363
+ const head = gitOutput(cwd, ["rev-parse", "--verify", "HEAD^{commit}"]);
5364
+ return {
5365
+ id,
5366
+ owner: resultAttemptOwner(),
5367
+ number,
5368
+ result_file: resultArtifactPath(sub, cwd, id),
5369
+ git_head: head && /^[0-9a-f]{40}([0-9a-f]{24})?$/.test(head) ? head : null
5370
+ };
5371
+ }
5372
+ function matchesResultBaseline(attempt) {
5373
+ return attempt.git_head === null || gitOutput(process.cwd(), ["merge-base", "--is-ancestor", attempt.git_head, "HEAD"]) !== null;
5374
+ }
5375
+ function isManagedResultPath(path) {
5376
+ return MANAGED_FILENAME.test(basename(path));
5377
+ }
5378
+ function resultArtifactScope(cwd = process.cwd()) {
5379
+ const base = repoKey(cwd);
5380
+ const key = activeKey(cwd);
5381
+ const composite = key === base ? `${base}::${NO_SESSION}` : key;
5382
+ return createHash("sha256").update(composite, "utf8").digest("hex").slice(0, SCOPE_HEX_LEN);
5383
+ }
5384
+ function resultArtifactPath(sub, cwd = process.cwd(), attemptId) {
5385
+ checkSafeSegment(sub);
5386
+ if (attemptId !== void 0) checkSafeSegment(attemptId);
5387
+ const name = attemptId === void 0 ? `${sub}.md` : `${sub}.attempt-${attemptId}.md`;
5388
+ return resolve(cwd, ".harnessed", "results", resultArtifactScope(cwd), name);
5389
+ }
5390
+ var ATTEMPT_ID, MANAGED_FILENAME, SCOPE_HEX_LEN, NO_SESSION;
5391
+ var init_resultArtifact = __esm({
5392
+ "src/cli/lib/resultArtifact.ts"() {
5393
+ init_workflowStore();
5394
+ init_path_guard();
5395
+ init_platform();
5396
+ ATTEMPT_ID = "[0-9a-f-]{36}";
5397
+ MANAGED_FILENAME = new RegExp(`\\.attempt-${ATTEMPT_ID}\\.md$`, "i");
5398
+ SCOPE_HEX_LEN = 8;
5399
+ NO_SESSION = "nosession";
4644
5400
  }
4645
5401
  });
4646
5402
 
@@ -4657,18 +5413,6 @@ var init_failure = __esm({
4657
5413
  LEGACY_FAILED_PREFIX = "FAILED:";
4658
5414
  }
4659
5415
  });
4660
- function ownerHash(ownerKey = activeKey()) {
4661
- return createHash("sha256").update(ownerKey).digest("hex").slice(0, 16);
4662
- }
4663
- function ownerPath(area, segments, ownerKey = activeKey()) {
4664
- return join(harnessedSubdir(area), ownerHash(ownerKey), ...segments);
4665
- }
4666
- var init_ownerPath = __esm({
4667
- "src/checkpoint/ownerPath.ts"() {
4668
- init_harnessedRoot();
4669
- init_workflowStore();
4670
- }
4671
- });
4672
5416
  function estimateTokens(s) {
4673
5417
  return Math.ceil(Buffer.byteLength(s, "utf8") / 4);
4674
5418
  }
@@ -4731,6 +5475,11 @@ async function activatePhase(phaseId) {
4731
5475
  return { checkpointPath };
4732
5476
  }
4733
5477
  async function completePhase(ctx) {
5478
+ const publish = () => publishPhaseCheckpoint(ctx);
5479
+ if (ctx.transitionWorkflowComplete === false) await withWorkflowEffects(publish);
5480
+ else await complete(publish);
5481
+ }
5482
+ function publishPhaseCheckpoint(ctx) {
4734
5483
  if (ctx.phaseId === "unknown") {
4735
5484
  console.error(
4736
5485
  `[harnessed] WARN engineHook: phaseId="unknown" \u2014 checkpoint paths fall back to ${ownerPath("checkpoints", ["unknown.json"])} (Karpathy fail-loud non-blocking; W-04 mitigation)`
@@ -4748,9 +5497,6 @@ async function completePhase(ctx) {
4748
5497
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
4749
5498
  archive_path: `${ownerPath("archive", [`phase-${ctx.phaseId}`])}/`
4750
5499
  });
4751
- if (ctx.transitionWorkflowComplete !== false) {
4752
- await complete();
4753
- }
4754
5500
  }
4755
5501
  var init_engineHook = __esm({
4756
5502
  "src/checkpoint/engineHook.ts"() {
@@ -4824,7 +5570,7 @@ function resolveWindowsBin(bin, env = process.env, isFile = (p8) => existsSync(p
4824
5570
  const candidates = extname(bin) ? [""] : exts;
4825
5571
  for (const dir of dirs) {
4826
5572
  for (const ext of candidates) {
4827
- const p8 = join21(dir, `${bin}${ext}`);
5573
+ const p8 = join22(dir, `${bin}${ext}`);
4828
5574
  if (isFile(p8)) return p8;
4829
5575
  }
4830
5576
  }
@@ -4839,10 +5585,10 @@ function planWindowsSpawn(bin, args, resolved) {
4839
5585
  const line = [escapeCommand(resolved), ...args.map((a) => escapeArgument(a))].join(" ");
4840
5586
  return { command: "cmd.exe", args: ["/d", "/s", "/c", `"${line}"`], verbatim: true };
4841
5587
  }
4842
- var extname, join21, META;
5588
+ var extname, join22, META;
4843
5589
  var init_winSpawn = __esm({
4844
5590
  "src/installers/lib/winSpawn.ts"() {
4845
- ({ extname, join: join21 } = win32);
5591
+ ({ extname, join: join22 } = win32);
4846
5592
  META = /([()\][%!^"`<>&|;, *?])/g;
4847
5593
  }
4848
5594
  });
@@ -4865,7 +5611,7 @@ function withHostInstallEnv(env, hostContext) {
4865
5611
  return { ...result, ...pins };
4866
5612
  }
4867
5613
  function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3, hostContext) {
4868
- return new Promise((resolve42) => {
5614
+ return new Promise((resolve44) => {
4869
5615
  const isWin = (hostContext?.os ?? process.platform) === "win32";
4870
5616
  const envOpts = hostContext ? { env: withHostInstallEnv(process.env, hostContext) } : {};
4871
5617
  const stdio = ["ignore", "pipe", "pipe"];
@@ -4893,17 +5639,17 @@ function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3, hostContext) {
4893
5639
  });
4894
5640
  const timer = setTimeout(() => {
4895
5641
  killProcessTree(child);
4896
- resolve42({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
5642
+ resolve44({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
4897
5643
  }, timeoutMs);
4898
5644
  child.on("error", (e) => {
4899
5645
  clearTimeout(timer);
4900
5646
  const enoent = e.code === "ENOENT";
4901
5647
  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;
4902
- resolve42({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
5648
+ resolve44({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
4903
5649
  });
4904
5650
  child.on("close", (code2) => {
4905
5651
  clearTimeout(timer);
4906
- resolve42({ exitCode: code2 ?? -1, stdout: stdout2, stderr });
5652
+ resolve44({ exitCode: code2 ?? -1, stdout: stdout2, stderr });
4907
5653
  });
4908
5654
  });
4909
5655
  }
@@ -5217,8 +5963,8 @@ async function releaseLockIdempotently(release) {
5217
5963
  var sleep;
5218
5964
  var init_lockContention = __esm({
5219
5965
  "src/platform/lockContention.ts"() {
5220
- sleep = (ms) => new Promise((resolve42) => {
5221
- setTimeout(resolve42, ms);
5966
+ sleep = (ms) => new Promise((resolve44) => {
5967
+ setTimeout(resolve44, ms);
5222
5968
  });
5223
5969
  }
5224
5970
  });
@@ -6519,7 +7265,7 @@ function estTokens(x) {
6519
7265
  return Math.ceil(Buffer.byteLength(JSON.stringify(x) ?? "", "utf8") / 4);
6520
7266
  }
6521
7267
  function isEvictable(e) {
6522
- if ((e.fail_count ?? 0) > 0) return false;
7268
+ if ((e.fail_count ?? 0) > 0 || e.result_attempt !== void 0) return false;
6523
7269
  return e.status === "done" || e.status === "skipped" || e.status === "rejected";
6524
7270
  }
6525
7271
  function compactLedger(entries) {
@@ -6547,8 +7293,8 @@ function mergeCounts(prev, next) {
6547
7293
  for (const [k, v] of Object.entries(next)) out[k] = (out[k] ?? 0) + v;
6548
7294
  return out;
6549
7295
  }
6550
- async function compactWorkflow() {
6551
- const wf = await readCurrentWorkflow();
7296
+ async function compactWorkflow(condition) {
7297
+ const wf = await readCurrentWorkflow(true);
6552
7298
  if (!wf) {
6553
7299
  return {
6554
7300
  kept: [],
@@ -6563,8 +7309,9 @@ async function compactWorkflow() {
6563
7309
  }
6564
7310
  const probe = compactLedger(wf.sub_progress ?? []);
6565
7311
  if (probe.evicted === 0) return { ...probe, phase: wf.phase };
6566
- let result = { ...probe, phase: wf.phase };
7312
+ let result = { ...probe, evicted: 0, phase: wf.phase };
6567
7313
  await mutateWorkflow((cur) => {
7314
+ if (condition && !condition(cur)) return cur;
6568
7315
  const r = compactLedger(cur.sub_progress ?? []);
6569
7316
  result = { ...r, phase: cur.phase };
6570
7317
  if (r.evicted === 0) return cur;
@@ -7025,11 +7772,17 @@ async function adoptSlot(options = {}) {
7025
7772
  }
7026
7773
  const sourceKey = candidates[0];
7027
7774
  const slot = source.workflows[sourceKey];
7775
+ if (slot.handoff_authority) return refuse({ kind: "source-enrolled", sourceKey });
7028
7776
  const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
7029
7777
  let archivedKey;
7030
7778
  let retroMeta;
7031
7779
  try {
7032
7780
  await mutateStore((store) => {
7781
+ if (Object.entries(store.workflows).some(
7782
+ ([k, wf]) => wf.handoff_authority && normalizeRepoKey(k.split("::", 1)[0] ?? "") === key
7783
+ ) || Object.values(store.handoff_claims ?? {}).some((claim) => claim.repo_key === key)) {
7784
+ throw new AdoptRefused({ kind: "dest-handoff-protected" });
7785
+ }
7033
7786
  const occupant = store.workflows[key];
7034
7787
  if (occupant?.status === "active") {
7035
7788
  throw new AdoptRefused({
@@ -7044,7 +7797,15 @@ async function adoptSlot(options = {}) {
7044
7797
  archivedKey = `${key}${DISPLACED}${updatedAt}`;
7045
7798
  workflows[archivedKey] = occupant;
7046
7799
  }
7047
- workflows[key] = { ...slot, updated_at: updatedAt };
7800
+ workflows[key] = {
7801
+ ...slot,
7802
+ updated_at: updatedAt,
7803
+ ...slot.sub_progress && {
7804
+ sub_progress: slot.sub_progress.map(
7805
+ (entry) => entry.result_attempt ? { ...entry, result_attempt: null } : entry
7806
+ )
7807
+ }
7808
+ };
7048
7809
  const next = { ...store, workflows };
7049
7810
  const srcRetro = source.retro_meta?.[key];
7050
7811
  if (srcRetro) {
@@ -7180,15 +7941,8 @@ async function absorbIntentFor(sub) {
7180
7941
  } catch {
7181
7942
  }
7182
7943
  }
7183
- async function readLedgerSafe(deps = defaultRunDeps) {
7184
- try {
7185
- const { readCurrentWorkflow: readCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
7186
- const wf = await readCurrentWorkflow2();
7187
- return wf?.sub_progress ?? [];
7188
- } catch (e) {
7189
- deps.warn(`[harnessed] ledger read skipped (fail-soft): ${e.message}`);
7190
- return [];
7191
- }
7944
+ function sameWorkflowRun(before, current) {
7945
+ return before !== null && before.started_at === current.started_at && before.phase === current.phase;
7192
7946
  }
7193
7947
  function enforceSerialOrder(action, sub, blockers, force, deps = defaultRunDeps) {
7194
7948
  if (blockers.length === 0) return true;
@@ -7214,20 +7968,51 @@ function parseWaitSeconds(raw) {
7214
7968
  return seconds;
7215
7969
  }
7216
7970
  function sleep2(ms) {
7217
- return new Promise((resolve42) => setTimeout(resolve42, ms));
7971
+ return new Promise((resolve44) => setTimeout(resolve44, ms));
7218
7972
  }
7219
- async function waitForResultClaim(resultFile, seconds, pollMs) {
7220
- const { verifyCompletionClaim: verifyCompletionClaim2 } = await Promise.resolve().then(() => (init_completionClaim(), completionClaim_exports));
7973
+ async function waitForResultClaim(input, seconds, pollMs) {
7221
7974
  const deadline = Date.now() + seconds * 1e3;
7222
7975
  for (; ; ) {
7223
- const claim = await verifyCompletionClaim2({ resultFile });
7224
- if (claim.verdict === "complete") return true;
7976
+ const claim = await verifyCompletionClaim(input);
7977
+ const ready = claim.verdict === "complete" && (!input.attemptId || !!claim.attemptDigest);
7225
7978
  const remaining = deadline - Date.now();
7226
- if (remaining <= 0) return false;
7979
+ if (ready || remaining <= 0) return { claim, ready };
7227
7980
  await sleep2(Math.min(pollMs, remaining));
7228
7981
  }
7229
- }
7230
- async function runCheckpointStart(sub, opts, deps = defaultRunDeps) {
7982
+ }
7983
+ async function runCheckpointStart(sub, opts, deps = defaultRunDeps) {
7984
+ if (opts.handoffReady) {
7985
+ try {
7986
+ checkSafeSegment(sub);
7987
+ const { seedLedger: seedLedger2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
7988
+ const plan2 = await parsePlan(opts.plan).catch(() => null);
7989
+ if (!plan2 || plan2.master !== void 0 && plan2.master !== sub) {
7990
+ throw new Error("--handoff-ready requires a valid --plan for this master");
7991
+ }
7992
+ let ledger;
7993
+ try {
7994
+ ledger = seedLedger2(plan2);
7995
+ for (const entry of ledger) checkSafeSegment(entry.sub);
7996
+ } catch {
7997
+ throw new Error("--handoff-ready requires a valid --plan ledger");
7998
+ }
7999
+ const { enrollHandoffRun: enrollHandoffRun2 } = await Promise.resolve().then(() => (init_state(), state_exports));
8000
+ const path = await enrollHandoffRun2(sub, ledger);
8001
+ deps.log(`[harnessed] checkpoint started: ${sub} \u2192 ${path}`);
8002
+ } catch (error) {
8003
+ deps.error(
8004
+ `[harnessed] checkpoint start refused: ${error instanceof Error ? error.message : String(error)}`
8005
+ );
8006
+ deps.exit(1);
8007
+ return;
8008
+ }
8009
+ deps.exit(0);
8010
+ return;
8011
+ }
8012
+ const { readCurrentWorkflow: readCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
8013
+ if ((await readCurrentWorkflow2(true))?.handoff_authority) {
8014
+ throw new Error("cannot replace a --handoff-ready workflow run");
8015
+ }
7231
8016
  const { activatePhase: activatePhase2 } = await Promise.resolve().then(() => (init_engineHook(), engineHook_exports));
7232
8017
  try {
7233
8018
  const { stat: statFs } = await import('fs/promises');
@@ -7254,10 +8039,11 @@ async function runCheckpointStart(sub, opts, deps = defaultRunDeps) {
7254
8039
  if (det.active) {
7255
8040
  const ge = await Promise.resolve().then(() => (init_guard_exemption(), guard_exemption_exports));
7256
8041
  const isTty = process.stdin.isTTY === true && process.stdout.isTTY === true;
8042
+ const { withWorkflowEffects: withWorkflowEffects2 } = await Promise.resolve().then(() => (init_state(), state_exports));
7257
8043
  const flowResult = await ge.runExemptionFlow({
7258
8044
  probe: () => ge.probeExemptCapability(),
7259
8045
  readEnvValue: () => ge.readCurrentEnvValue(),
7260
- merge: (value) => ge.applyEnvExemption(value),
8046
+ merge: (value) => withWorkflowEffects2(() => ge.applyEnvExemption(value)),
7261
8047
  print: (line) => deps.error(line),
7262
8048
  ...isTty ? {
7263
8049
  confirm: async () => {
@@ -7321,39 +8107,75 @@ async function runCheckpointStart(sub, opts, deps = defaultRunDeps) {
7321
8107
  }
7322
8108
  async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
7323
8109
  const { completePhase: completePhase2 } = await Promise.resolve().then(() => (init_engineHook(), engineHook_exports));
7324
- const preLedger = await readLedgerSafe(deps);
7325
- if (!enforceSerialOrder("complete", sub, findSerialBlockers(preLedger, sub), opts.force, deps)) {
8110
+ const { readCurrentWorkflow: readCurrentWorkflow2, mutateWorkflow: mutateWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
8111
+ let before;
8112
+ try {
8113
+ before = await readCurrentWorkflow2(true);
8114
+ } catch (e) {
8115
+ deps.error(
8116
+ `[harnessed] checkpoint complete BLOCKED: could not read ledger: ${e.message}`
8117
+ );
7326
8118
  deps.exit(1);
7327
8119
  return;
7328
8120
  }
8121
+ const preLedger = before?.sub_progress ?? [];
8122
+ const entry = preLedger.find((e) => e.sub === sub);
8123
+ const attempt = entry?.result_attempt;
8124
+ const rejectResult = (reason) => {
8125
+ deps.error(`[harnessed] checkpoint complete BLOCKED: ${sub}: ${reason}`);
8126
+ deps.exit(1);
8127
+ };
7329
8128
  const waitSeconds = opts.wait ?? 0;
8129
+ if (waitSeconds > 0 && !opts.resultFile) {
8130
+ deps.error("[harnessed] checkpoint complete: --wait \u5FC5\u987B\u642D\u914D --result-file");
8131
+ deps.exit(2);
8132
+ return;
8133
+ }
8134
+ if (attempt === null || before?.handoff_authority && !attempt || !attempt && ((entry?.fail_count ?? 0) > 0 || opts.resultFile && isManagedResultPath(opts.resultFile)) || attempt && (attempt.owner !== resultAttemptOwner() || attempt.number !== (entry?.fail_count ?? 0) || !opts.resultFile || resolve(opts.resultFile) !== attempt.result_file)) {
8135
+ rejectResult(
8136
+ entry?.status === "done" ? "subtask is already complete; reopen it before dispatching new work" : "result does not belong to the current dispatch; rerun harnessed prompt and use its --result-file"
8137
+ );
8138
+ return;
8139
+ }
8140
+ if (!enforceSerialOrder("complete", sub, findSerialBlockers(preLedger, sub), opts.force, deps)) {
8141
+ deps.exit(1);
8142
+ return;
8143
+ }
8144
+ const claimInput = {
8145
+ ...opts.result !== void 0 ? { result: opts.result } : {},
8146
+ ...opts.resultFile !== void 0 ? { resultFile: opts.resultFile } : {},
8147
+ ...attempt ? { attemptId: attempt.id } : {}
8148
+ };
7330
8149
  let waitTimeoutMessage;
7331
- if (waitSeconds > 0) {
8150
+ let claim;
8151
+ if (waitSeconds > 0 && opts.resultFile) {
7332
8152
  const resultFile = opts.resultFile;
7333
- if (!resultFile) {
7334
- deps.error(
7335
- "[harnessed] checkpoint complete: --wait \u5FC5\u987B\u642D\u914D --result-file \u2014\u2014 \u6CA1\u6709\u53EF\u7B49\u5F85\u7684\u7ED3\u679C\u6587\u4EF6"
7336
- );
7337
- deps.exit(2);
7338
- return;
7339
- }
7340
8153
  const pollMs = opts.waitPollMs ?? RESULT_WAIT_POLL_MS;
7341
8154
  deps.log(
7342
8155
  `[harnessed] \u7B49\u5F85 ${waitSeconds}s \u5185 ${resultFile} \u643A\u5E26\u5B8C\u6210\u6807\u8BB0\uFF08\u6BCF ${pollMs}ms \u8F6E\u8BE2\u4E00\u6B21\uFF09`
7343
8156
  );
7344
- const ready = await waitForResultClaim(resultFile, waitSeconds, pollMs);
7345
- if (ready) {
8157
+ const waited = await waitForResultClaim(claimInput, waitSeconds, pollMs);
8158
+ claim = waited.claim;
8159
+ if (waited.ready) {
7346
8160
  deps.log(`[harnessed] \u7ED3\u679C\u6587\u4EF6\u5DF2\u5C31\u7EEA: ${resultFile}`);
7347
8161
  } else {
7348
8162
  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`;
7349
8163
  }
8164
+ } else {
8165
+ claim = await verifyCompletionClaim(claimInput);
8166
+ }
8167
+ if (attempt ? !claim.attemptDigest : claim.hasAttemptLine) {
8168
+ rejectResult(
8169
+ waitTimeoutMessage ?? "result is missing the current dispatch identity or belongs to a different dispatch"
8170
+ );
8171
+ return;
7350
8172
  }
7351
8173
  const { checkArtifacts: checkArtifacts2 } = await Promise.resolve().then(() => (init_evidence(), evidence_exports));
7352
- const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
7353
8174
  const { getAssetsRoot: getAssetsRoot3 } = await Promise.resolve().then(() => (init_assetsRoot(), assetsRoot_exports));
7354
8175
  const result = await checkArtifacts2(sub, getAssetsRoot3());
7355
8176
  const { checkPlanningSync: checkPlanningSync2 } = await Promise.resolve().then(() => (init_evidence(), evidence_exports));
7356
8177
  const syncResult = await checkPlanningSync2(process.cwd(), null);
8178
+ const syncMissing = sub === "research" && before === null ? [] : syncResult.missing;
7357
8179
  const boundaryBlocks = [];
7358
8180
  try {
7359
8181
  const { checkTddBoundary: checkTddBoundary2, isTddEvidencePath: isTddEvidencePath2 } = await Promise.resolve().then(() => (init_tddBoundary(), tddBoundary_exports));
@@ -7366,11 +8188,6 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
7366
8188
  }
7367
8189
  } catch {
7368
8190
  }
7369
- const { verifyCompletionClaim: verifyCompletionClaim2 } = await Promise.resolve().then(() => (init_completionClaim(), completionClaim_exports));
7370
- const claim = await verifyCompletionClaim2({
7371
- ...opts.result !== void 0 ? { result: opts.result } : {},
7372
- ...opts.resultFile !== void 0 ? { resultFile: opts.resultFile } : {}
7373
- });
7374
8191
  const claimBlocks = claim.verdict === "incomplete" ? [
7375
8192
  `completion promise not met (${claim.source}): the subagent output carries no verbatim <promise>COMPLETE</promise> and no structured COMPLETE status on a successful run`
7376
8193
  ] : [];
@@ -7382,7 +8199,7 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
7382
8199
  const waitBlocks = waitTimeoutMessage !== void 0 ? [waitTimeoutMessage] : [];
7383
8200
  const allMissing = [
7384
8201
  ...result.missing,
7385
- ...syncResult.missing,
8202
+ ...syncMissing,
7386
8203
  ...boundaryBlocks,
7387
8204
  ...claimBlocks,
7388
8205
  ...waitBlocks
@@ -7392,7 +8209,7 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
7392
8209
  `[harnessed] checkpoint complete ${waitTimeoutMessage}\uFF08--force: \u5DF2\u8BB0\u4E3A audited override\uFF09`
7393
8210
  );
7394
8211
  }
7395
- if (allMissing.length > 0 && !opts.force) {
8212
+ if (allMissing.length > 0 && !opts.force && !(attempt && entry?.status === "done")) {
7396
8213
  deps.error(
7397
8214
  `[harnessed] checkpoint complete BLOCKED: ${sub} \u2014 ${allMissing.length} item(s) missing (evidence guard + .planning/ sync, fail-closed):`
7398
8215
  );
@@ -7410,25 +8227,78 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
7410
8227
  evidence_status: evidenceStatus,
7411
8228
  completion_claim: claim.verdict
7412
8229
  };
7413
- await mutateSubProgress2((e) => markIfSeeded(e, sub, "done", markOpts));
7414
- await absorbIntentFor(sub);
7415
8230
  const { collectScaleMetrics: collectScaleMetrics2, assessScale: assessScale2 } = await Promise.resolve().then(() => (init_scale(), scale_exports));
7416
- const { readCurrentWorkflow: readCurrentWorkflow2, mutateWorkflow: mutateWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
7417
- const afterMark = await readCurrentWorkflow2();
7418
- if (afterMark) {
7419
- const metrics = await collectScaleMetrics2(process.cwd(), afterMark.sub_progress ?? []);
7420
- const verifyMode = assessScale2(metrics);
7421
- await mutateWorkflow2((s) => ({ ...s, verify_mode: verifyMode }));
7422
- }
7423
8231
  const { nextPending: nextPending2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
7424
- const allResolved = nextPending2(afterMark?.sub_progress ?? []) === null;
7425
- await completePhase2({
8232
+ const verifyMode = before ? assessScale2(await collectScaleMetrics2(process.cwd(), markIfSeeded(preLedger, sub, "done"))) : void 0;
8233
+ const publish = () => completePhase2({
7426
8234
  phaseId: sub,
7427
8235
  status: "complete",
7428
8236
  lastTask: opts.summary ?? `phase ${sub} complete`,
7429
- transitionWorkflowComplete: allResolved
8237
+ // The callback owns the workflow lock. Do not re-enter it through the engine hook.
8238
+ transitionWorkflowComplete: false
7430
8239
  });
7431
- if (allResolved && afterMark?.phase === "task") {
8240
+ const sameRun = (s) => sameWorkflowRun(before, s);
8241
+ let afterMark;
8242
+ let allResolved = false;
8243
+ let accepted = false;
8244
+ let rejection = "dispatch or ledger state changed; no checkpoint was written";
8245
+ const baselineMatches = !attempt || entry?.status === "done" || matchesResultBaseline(attempt);
8246
+ await mutateWorkflow2(
8247
+ async (s) => {
8248
+ const entries = s.sub_progress ?? [];
8249
+ const current = entries.find((e) => e.sub === sub);
8250
+ const binding = current?.result_attempt;
8251
+ if (!sameRun(s) || (current?.fail_count ?? 0) !== (entry?.fail_count ?? 0) || binding?.id !== attempt?.id || binding === null || attempt && (binding?.owner !== resultAttemptOwner() || binding.number !== attempt.number || binding.result_file !== attempt.result_file || binding.git_head !== attempt.git_head))
8252
+ return s;
8253
+ if (attempt && current?.status === "done") {
8254
+ accepted = binding?.accepted_digest === claim.attemptDigest;
8255
+ rejection = "result bytes differ from the accepted dispatch receipt";
8256
+ return s;
8257
+ }
8258
+ if (current?.status !== entry?.status || attempt && current?.status !== "pending") return s;
8259
+ if (!baselineMatches) {
8260
+ rejection = "Git HEAD is not the dispatch baseline or its descendant; no checkpoint was written";
8261
+ return s;
8262
+ }
8263
+ if (!opts.force && findSerialBlockers(entries, sub).length > 0) return s;
8264
+ let marked = markIfSeeded(entries, sub, "done", markOpts);
8265
+ if (attempt && claim.attemptDigest) {
8266
+ const acceptedAttempt = { ...attempt, accepted_digest: claim.attemptDigest };
8267
+ marked = marked.map((e) => e.sub === sub ? { ...e, result_attempt: acceptedAttempt } : e);
8268
+ }
8269
+ allResolved = nextPending2(marked) === null;
8270
+ await publish();
8271
+ afterMark = {
8272
+ ...s,
8273
+ sub_progress: marked,
8274
+ ...verifyMode && { verify_mode: verifyMode },
8275
+ ...allResolved && { status: "complete", completed_at: (/* @__PURE__ */ new Date()).toISOString() }
8276
+ };
8277
+ accepted = true;
8278
+ return afterMark;
8279
+ },
8280
+ async () => {
8281
+ if (before) return;
8282
+ await publish();
8283
+ accepted = true;
8284
+ }
8285
+ );
8286
+ if (!accepted) {
8287
+ rejectResult(rejection);
8288
+ return;
8289
+ }
8290
+ if (attempt && !afterMark) {
8291
+ deps.log(`[harnessed] checkpoint already complete: ${sub}`);
8292
+ deps.exit(0);
8293
+ return;
8294
+ }
8295
+ await absorbIntentFor(sub);
8296
+ const stillCommitted = (s) => {
8297
+ if (!sameRun(s)) return false;
8298
+ const current = s.sub_progress?.find((e) => e.sub === sub);
8299
+ return (entry ? current?.status === "done" : !current) && (current?.fail_count ?? 0) === (entry?.fail_count ?? 0) && current?.result_attempt?.id === attempt?.id;
8300
+ };
8301
+ if (allResolved && afterMark?.phase === "task" && !afterMark.handoff_authority) {
7432
8302
  try {
7433
8303
  const { maybeInitCodeGraph: maybeInitCodeGraph2 } = await Promise.resolve().then(() => (init_codegraphInit(), codegraphInit_exports));
7434
8304
  maybeInitCodeGraph2({ note: (m) => deps.error(m) });
@@ -7437,14 +8307,16 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
7437
8307
  }
7438
8308
  if (allResolved && afterMark) {
7439
8309
  const { captureWorkflowLearnings: captureWorkflowLearnings2 } = await Promise.resolve().then(() => (init_learnings(), learnings_exports));
7440
- const captured = await captureWorkflowLearnings2(afterMark.sub_progress ?? [], sub);
8310
+ const entries = afterMark.sub_progress ?? [];
8311
+ const capture = () => captureWorkflowLearnings2(entries, sub);
8312
+ const captured = afterMark.handoff_authority ? await (await Promise.resolve().then(() => (init_state(), state_exports))).withWorkflowEffects(capture) : await capture();
7441
8313
  if (captured > 0) {
7442
8314
  deps.log(`[harnessed] captured ${captured} learning(s) \u2192 .planning/LEARNINGS.md`);
7443
8315
  }
7444
8316
  }
7445
8317
  const { shouldAutoCompact: shouldAutoCompact2, compactWorkflow: compactWorkflow2 } = await Promise.resolve().then(() => (init_compact(), compact_exports));
7446
8318
  if (shouldAutoCompact2(opts.tokens != null ? Number(opts.tokens) : void 0)) {
7447
- const c = await compactWorkflow2();
8319
+ const c = await compactWorkflow2(stillCommitted);
7448
8320
  if (c.evicted > 0) {
7449
8321
  deps.log(
7450
8322
  `[harnessed] auto-compact: evicted ${c.evicted} resolved entries (-${c.pct_saved}% tokens)`
@@ -7456,24 +8328,24 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
7456
8328
  const { defaultShipReady: defaultShipReady2 } = await Promise.resolve().then(() => (init_shipReady(), shipReady_exports));
7457
8329
  const { incrementPhases: incrementPhases2, isRetroDue: isRetroDue2, retroThreshold: retroThreshold2 } = await Promise.resolve().then(() => (init_retroMeta(), retroMeta_exports));
7458
8330
  const { mutateStore: mutateStore2, mutateWorkflow: mutateWorkflow3 } = await Promise.resolve().then(() => (init_state(), state_exports));
7459
- const { repoKey: repoKey2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
8331
+ const { activeKey: activeKey2, repoKey: repoKey2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
7460
8332
  const ship = defaultShipReady2(process.cwd());
7461
8333
  const key = repoKey2();
7462
8334
  const threshold = retroThreshold2(process.env);
7463
8335
  let retroDue = false;
7464
8336
  await mutateStore2((store) => {
8337
+ const current = store.workflows[activeKey2()] ?? store.workflows[key];
8338
+ if (!current || current.status !== "complete" || !sameRun(current) || attempt && !stillCommitted(current))
8339
+ return store;
7465
8340
  const meta = { ...store.retro_meta ?? {} };
7466
8341
  const next = incrementPhases2(meta[key]);
7467
8342
  meta[key] = next;
7468
8343
  retroDue = isRetroDue2(next.phases_since_retro, threshold);
7469
8344
  return { ...store, retro_meta: meta };
7470
8345
  });
7471
- await mutateWorkflow3((s) => ({
7472
- ...s,
7473
- ship_ready: ship.ready,
7474
- ship_commits: ship.commits,
7475
- retro_due: retroDue
7476
- }));
8346
+ await mutateWorkflow3(
8347
+ (s) => s.status === "complete" && sameRun(s) && (!attempt || stillCommitted(s)) ? { ...s, ship_ready: ship.ready, ship_commits: ship.commits, retro_due: retroDue } : s
8348
+ );
7477
8349
  } catch {
7478
8350
  }
7479
8351
  }
@@ -7492,7 +8364,15 @@ async function runCheckpointFail(sub, opts, deps = defaultRunDeps) {
7492
8364
  return;
7493
8365
  }
7494
8366
  const spawnFailure = isSpawnFailure2(opts.failure) ? opts.failure : void 0;
7495
- const preLedger = await readLedgerSafe(deps);
8367
+ const { readCurrentWorkflow: readCurrentWorkflow2, mutateWorkflow: mutateWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
8368
+ const before = await readCurrentWorkflow2(true);
8369
+ const preLedger = before?.sub_progress ?? [];
8370
+ const entry = preLedger.find((e) => e.sub === sub);
8371
+ if (before?.handoff_authority && !(entry?.status === "pending" && entry.result_attempt)) {
8372
+ deps.error(`[harnessed] checkpoint fail BLOCKED: ${sub}: dispatch with harnessed prompt first`);
8373
+ deps.exit(1);
8374
+ return;
8375
+ }
7496
8376
  if (!enforceSerialOrder("fail", sub, findSerialBlockers(preLedger, sub), opts.force, deps)) {
7497
8377
  deps.exit(1);
7498
8378
  return;
@@ -7514,26 +8394,47 @@ async function runCheckpointFail(sub, opts, deps = defaultRunDeps) {
7514
8394
  });
7515
8395
  const { resolveAttemptBudget: resolveAttemptBudget2, isBudgetExhausted: isBudgetExhausted2 } = await Promise.resolve().then(() => (init_budget(), budget_exports));
7516
8396
  const budget = await resolveAttemptBudget2(sub, assetsRoot);
7517
- const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
7518
- await mutateSubProgress2(
7519
- (e) => markIfSeeded(e, sub, "failed", {
7520
- attempt_budget: budget,
7521
- ...nextProgress ? { progress: nextProgress } : {},
7522
- // T4 — omitted when absent so an untagged failure leaves NO key on the entry
7523
- // (13 eval goldens compare the serialized ledger verbatim).
7524
- ...spawnFailure ? { spawn_failure: spawnFailure } : {}
7525
- })
7526
- );
7527
- await absorbIntentFor(sub);
7528
- await completePhase2({
8397
+ const publish = () => completePhase2({
7529
8398
  phaseId: sub,
7530
8399
  status: "failed",
7531
8400
  lastTask: `FAILED: ${opts.summary ?? ""}`,
7532
8401
  transitionWorkflowComplete: false
7533
8402
  });
7534
- const { readCurrentWorkflow: readCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
8403
+ let latest;
8404
+ let recorded = false;
8405
+ await mutateWorkflow2(
8406
+ async (s) => {
8407
+ const entries = s.sub_progress ?? [];
8408
+ const current = entries.find((e) => e.sub === sub);
8409
+ if (!sameWorkflowRun(before, s) || current?.status !== entry?.status || current?.fail_count !== entry?.fail_count || current?.result_attempt?.id !== entry?.result_attempt?.id || !opts.force && findSerialBlockers(entries, sub).length > 0)
8410
+ return s;
8411
+ latest = {
8412
+ ...s,
8413
+ sub_progress: markIfSeeded(entries, sub, "failed", {
8414
+ attempt_budget: budget,
8415
+ ...nextProgress ? { progress: nextProgress } : {},
8416
+ // T4 — omitted when absent so an untagged failure leaves NO key on the entry
8417
+ // (13 eval goldens compare the serialized ledger verbatim).
8418
+ ...spawnFailure ? { spawn_failure: spawnFailure } : {}
8419
+ })
8420
+ };
8421
+ await publish();
8422
+ recorded = true;
8423
+ return latest;
8424
+ },
8425
+ async () => {
8426
+ if (before) return;
8427
+ await publish();
8428
+ recorded = true;
8429
+ }
8430
+ );
8431
+ if (!recorded) {
8432
+ deps.error(`[harnessed] checkpoint fail BLOCKED: ${sub}: dispatch or ledger state changed`);
8433
+ deps.exit(1);
8434
+ return;
8435
+ }
8436
+ await absorbIntentFor(sub);
7535
8437
  const { detectLoop: detectLoop2, LOOP_THRESHOLD: LOOP_THRESHOLD2 } = await Promise.resolve().then(() => (init_breakLoop(), breakLoop_exports));
7536
- const latest = await readCurrentWorkflow2();
7537
8438
  const loops = detectLoop2(latest?.sub_progress ?? []);
7538
8439
  const looped = loops.find((l) => l.sub === sub);
7539
8440
  if (looped) {
@@ -7568,7 +8469,7 @@ async function runCheckpointReopen(sub, opts, deps = defaultRunDeps) {
7568
8469
  return;
7569
8470
  }
7570
8471
  const { readCurrentWorkflow: readCurrentWorkflow2, mutateWorkflow: mutateWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
7571
- const wf = await readCurrentWorkflow2();
8472
+ const wf = await readCurrentWorkflow2(true);
7572
8473
  if (!wf) {
7573
8474
  deps.error("[harnessed] checkpoint reopen: no active workflow \u2014 nothing to send back.");
7574
8475
  deps.exit(1);
@@ -7696,6 +8597,12 @@ function renderAdoptRefusal(r) {
7696
8597
  lines.push(" \u5728\u6E90\u5BBF\u4E3B\u4FA7\u628A\u591A\u4F59\u7684 complete / pause \u6389\u3001\u53EA\u7559\u4E00\u4E2A,\u518D adopt\u3002");
7697
8598
  return lines;
7698
8599
  }
8600
+ case "source-enrolled":
8601
+ return [`refused: \u6E90\u69FD\u4F4D ${r.sourceKey} \u5DF2\u901A\u8FC7 --handoff-ready \u767B\u8BB0\uFF0C\u4E0D\u80FD\u7528\u666E\u901A adopt \u590D\u5236\u3002`];
8602
+ case "dest-handoff-protected":
8603
+ return [
8604
+ "refused: destination has a protected handoff run; ordinary adopt cannot add a bare copy."
8605
+ ];
7699
8606
  case "dest-occupied": {
7700
8607
  const subs = r.mine.total > 0 ? `, ${r.mine.done}/${r.mine.total} subs done` : "";
7701
8608
  return [
@@ -7731,6 +8638,24 @@ function renderAdoptSuccess(r) {
7731
8638
  return lines;
7732
8639
  }
7733
8640
  async function runCheckpointAdopt(opts, deps = defaultRunDeps) {
8641
+ if (opts.transferId !== void 0) {
8642
+ if (opts.from === void 0) {
8643
+ deps.error("expected checkpoint adopt --from <host> --transfer-id <id>");
8644
+ deps.exit(1);
8645
+ return;
8646
+ }
8647
+ const { claimHandoff: claimHandoff2 } = await Promise.resolve().then(() => (init_state(), state_exports));
8648
+ try {
8649
+ const claim = await claimHandoff2(opts.from, opts.transferId);
8650
+ deps.log(`handoff claimed: ${opts.transferId} at ${claim.claimed_at}`);
8651
+ } catch (error) {
8652
+ deps.error(`handoff claim refused: ${error instanceof Error ? error.message : String(error)}`);
8653
+ deps.exit(1);
8654
+ return;
8655
+ }
8656
+ deps.exit(0);
8657
+ return;
8658
+ }
7734
8659
  const { adoptSlot: adoptSlot2 } = await Promise.resolve().then(() => (init_adoptSlot(), adoptSlot_exports));
7735
8660
  const outcome = await adoptSlot2({ ...opts.from !== void 0 ? { from: opts.from } : {} });
7736
8661
  if (!outcome.ok) {
@@ -7745,6 +8670,9 @@ function registerCheckpoint(program2) {
7745
8670
  program2.command("checkpoint <action> [sub]").description(
7746
8671
  "Record workflow progress: intent | start | complete | fail | reopen <sub-workflow>, or adopt (cross-host relay) (writes under the active host state root)"
7747
8672
  ).option("--summary <text>", "short summary stored as the checkpoint lastTask").option("--plan <json>", "gates plan JSON (start only) \u2014 seeds the sub-progress ledger").option(
8673
+ "--handoff-ready",
8674
+ "start only \u2014 enroll a new exact-session run; disables ordinary adopt"
8675
+ ).option(
7748
8676
  "--force",
7749
8677
  "complete/fail \u2014 override a fail-closed guard: the missing-artifact evidence block (complete; records overridden) or the serial-order guard"
7750
8678
  ).option(
@@ -7771,7 +8699,7 @@ function registerCheckpoint(program2) {
7771
8699
  ).option(
7772
8700
  "--from <host>",
7773
8701
  `adopt only \u2014 which host's ledger to copy this repo's slot FROM: ${HOST_IDS.join(" | ")} (omitted \u2192 the other host)`
7774
- ).action(
8702
+ ).option("--to <host>", `handoff only \u2014 freeze for the opposite host: ${HOST_IDS.join(" | ")}`).option("--transfer-id <id>", "adopt only \u2014 claim a prepared handoff; requires explicit --from").action(
7775
8703
  async (action, sub, opts) => {
7776
8704
  if (!isAction(action)) {
7777
8705
  console.error(
@@ -7787,6 +8715,31 @@ function registerCheckpoint(program2) {
7787
8715
  process.exit(2);
7788
8716
  return;
7789
8717
  }
8718
+ if (opts.handoffReady && action !== "start") {
8719
+ console.error("[harnessed] --handoff-ready is only valid with checkpoint start");
8720
+ process.exit(1);
8721
+ return;
8722
+ }
8723
+ if (opts.transferId !== void 0 && (action !== "adopt" || sub !== void 0 || opts.force)) {
8724
+ console.error("[harnessed] expected checkpoint adopt --from <host> --transfer-id <id>");
8725
+ process.exit(1);
8726
+ return;
8727
+ }
8728
+ if (action === "handoff") {
8729
+ if (sub !== void 0 || !opts.to || opts.from !== void 0 || opts.force) {
8730
+ console.error("[harnessed] expected checkpoint handoff --to <host>");
8731
+ process.exit(1);
8732
+ return;
8733
+ }
8734
+ const { freezeHandoffSource: freezeHandoffSource2 } = await Promise.resolve().then(() => (init_state(), state_exports));
8735
+ console.log(await freezeHandoffSource2(opts.to));
8736
+ return;
8737
+ }
8738
+ if (opts.to !== void 0) {
8739
+ console.error("[harnessed] --to is only valid with checkpoint handoff");
8740
+ process.exit(1);
8741
+ return;
8742
+ }
7790
8743
  if (action === "adopt") {
7791
8744
  await runCheckpointAdopt(opts);
7792
8745
  return;
@@ -7874,11 +8827,13 @@ function registerCheckpoint(program2) {
7874
8827
  var ACTIONS, RESULT_WAIT_MAX_SECONDS, RESULT_WAIT_POLL_MS;
7875
8828
  var init_checkpoint = __esm({
7876
8829
  "src/cli/checkpoint.ts"() {
8830
+ init_completionClaim();
7877
8831
  init_path_guard();
7878
8832
  init_platform();
7879
8833
  init_runDeps();
8834
+ init_resultArtifact();
7880
8835
  init_ledger();
7881
- ACTIONS = ["start", "complete", "fail", "reopen", "intent", "adopt"];
8836
+ ACTIONS = ["start", "complete", "fail", "reopen", "intent", "adopt", "handoff"];
7882
8837
  RESULT_WAIT_MAX_SECONDS = 600;
7883
8838
  RESULT_WAIT_POLL_MS = 2e3;
7884
8839
  }
@@ -8024,8 +8979,8 @@ function compute(d) {
8024
8979
  }
8025
8980
  const gitFirst = d.where("git")[0];
8026
8981
  if (gitFirst && /git\.exe$/i.test(gitFirst)) {
8027
- const root = dirname15(dirname15(gitFirst));
8028
- for (const cand of [join34(root, "bin", "bash.exe"), join34(root, "usr", "bin", "bash.exe")]) {
8982
+ const root = dirname16(dirname16(gitFirst));
8983
+ for (const cand of [join35(root, "bin", "bash.exe"), join35(root, "usr", "bin", "bash.exe")]) {
8029
8984
  if (d.exists(cand) && usable(cand)) return { path: cand, source: "git-derived", wslOnPath };
8030
8985
  }
8031
8986
  }
@@ -8033,13 +8988,13 @@ function compute(d) {
8033
8988
  d.env.ProgramFiles,
8034
8989
  d.env.ProgramW6432,
8035
8990
  d.env["ProgramFiles(x86)"],
8036
- d.env.LOCALAPPDATA ? join34(d.env.LOCALAPPDATA, "Programs") : void 0
8991
+ d.env.LOCALAPPDATA ? join35(d.env.LOCALAPPDATA, "Programs") : void 0
8037
8992
  ];
8038
8993
  for (const base of bases) {
8039
8994
  if (!base) continue;
8040
8995
  for (const cand of [
8041
- join34(base, "Git", "bin", "bash.exe"),
8042
- join34(base, "Git", "usr", "bin", "bash.exe")
8996
+ join35(base, "Git", "bin", "bash.exe"),
8997
+ join35(base, "Git", "usr", "bin", "bash.exe")
8043
8998
  ]) {
8044
8999
  if (d.exists(cand) && usable(cand))
8045
9000
  return { path: cand, source: "standard-location", wslOnPath };
@@ -8052,10 +9007,10 @@ function compute(d) {
8052
9007
  }
8053
9008
  return { path: "bash", source: "path-fallback" };
8054
9009
  }
8055
- var dirname15, join34, WSL_STUB_RE, cache4;
9010
+ var dirname16, join35, WSL_STUB_RE, cache4;
8056
9011
  var init_resolveBash = __esm({
8057
9012
  "src/installers/lib/resolveBash.ts"() {
8058
- ({ dirname: dirname15, join: join34 } = win32);
9013
+ ({ dirname: dirname16, join: join35 } = win32);
8059
9014
  WSL_STUB_RE = /[\\/](windows[\\/](system32|sysnative|syswow64)|microsoft[\\/]windowsapps)[\\/]bash\.exe$/i;
8060
9015
  cache4 = null;
8061
9016
  }
@@ -10512,7 +11467,7 @@ async function withAppServer(deps, body) {
10512
11467
  const call = (method, params) => {
10513
11468
  if (closed) return Promise.reject(closed);
10514
11469
  const id = nextId++;
10515
- return new Promise((resolve42, reject) => {
11470
+ return new Promise((resolve44, reject) => {
10516
11471
  const timer = setTimeout(() => {
10517
11472
  pending.delete(id);
10518
11473
  reject(new RpcError("timeout", `${method} timed out after ${timeoutMs}ms`));
@@ -10520,7 +11475,7 @@ async function withAppServer(deps, body) {
10520
11475
  pending.set(id, {
10521
11476
  resolve: (v) => {
10522
11477
  clearTimeout(timer);
10523
- resolve42(v);
11478
+ resolve44(v);
10524
11479
  },
10525
11480
  reject: (e) => {
10526
11481
  clearTimeout(timer);
@@ -11446,25 +12401,25 @@ var init_discipline = __esm({
11446
12401
  );
11447
12402
  }
11448
12403
  });
11449
- async function loadDiscipline(basename10, packageRoot) {
11450
- const cached = _cache.get(basename10);
12404
+ async function loadDiscipline(basename12, packageRoot) {
12405
+ const cached = _cache.get(basename12);
11451
12406
  if (cached) return cached;
11452
- const yamlPath = resolve(packageRoot, "workflows", "disciplines", `${basename10}.yaml`);
12407
+ const yamlPath = resolve(packageRoot, "workflows", "disciplines", `${basename12}.yaml`);
11453
12408
  const raw = await readFile(yamlPath, "utf8");
11454
12409
  const parsedRaw = parse(raw);
11455
12410
  if (!Value.Check(Discipline, parsedRaw)) {
11456
12411
  const errors = [...Value.Errors(Discipline, parsedRaw)].slice(0, 3).map((e) => `${e.path} ${e.message}`).join("; ");
11457
- throw new Error(`Invalid discipline file ${basename10}.yaml: ${errors}`);
12412
+ throw new Error(`Invalid discipline file ${basename12}.yaml: ${errors}`);
11458
12413
  }
11459
12414
  const parsed = parsedRaw;
11460
- _cache.set(basename10, parsed);
12415
+ _cache.set(basename12, parsed);
11461
12416
  return parsed;
11462
12417
  }
11463
12418
  async function loadAllApplied(disciplines_applied, packageRoot) {
11464
12419
  const applied = disciplines_applied && disciplines_applied.length > 0 ? disciplines_applied : DEFAULT_APPLIED;
11465
12420
  const out = /* @__PURE__ */ new Map();
11466
- for (const basename10 of applied) {
11467
- out.set(basename10, await loadDiscipline(basename10, packageRoot));
12421
+ for (const basename12 of applied) {
12422
+ out.set(basename12, await loadDiscipline(basename12, packageRoot));
11468
12423
  }
11469
12424
  return out;
11470
12425
  }
@@ -11986,7 +12941,7 @@ function realSpawn(req) {
11986
12941
  };
11987
12942
  }
11988
12943
  function runOnce(req, spawnFn, timeoutMs, onThreadId) {
11989
- return new Promise((resolve42, reject) => {
12944
+ return new Promise((resolve44, reject) => {
11990
12945
  const events = [];
11991
12946
  let garbageLines = 0;
11992
12947
  let stderr = "";
@@ -12007,7 +12962,7 @@ function runOnce(req, spawnFn, timeoutMs, onThreadId) {
12007
12962
  if (settled || !exited || openStreams > 0) return;
12008
12963
  settled = true;
12009
12964
  clearTimeout(timer);
12010
- resolve42({ exitCode: exited.code, signal: exited.signal, events, garbageLines, stderr });
12965
+ resolve44({ exitCode: exited.code, signal: exited.signal, events, garbageLines, stderr });
12011
12966
  };
12012
12967
  const fail2 = (err2) => {
12013
12968
  if (settled) return;
@@ -12982,6 +13937,9 @@ function loadMaxIterTable(packageRoot) {
12982
13937
  }
12983
13938
  }
12984
13939
  async function runWorkflow(yamlPath, vars, opts = {}) {
13940
+ if ((await readCurrentWorkflow(true))?.handoff_authority) {
13941
+ throw new Error("headless execution is not supported for a handoff-ready run");
13942
+ }
12985
13943
  const parsed = loadPhases(yamlPath, vars);
12986
13944
  const yamlDir = dirname(resolve(yamlPath));
12987
13945
  const inferredRoot = resolve(yamlDir, "..", "..");
@@ -13401,25 +14359,6 @@ var init_capabilityResolver = __esm({
13401
14359
  CAPABILITY_CMD_TEMPLATE = /\{\{\s*capabilities\.([a-zA-Z0-9_-]+)\.cmd\s*\}\}/g;
13402
14360
  }
13403
14361
  });
13404
- function resultArtifactScope(cwd = process.cwd()) {
13405
- const base = repoKey(cwd);
13406
- const key = activeKey(cwd);
13407
- const composite = key === base ? `${base}::${NO_SESSION}` : key;
13408
- return createHash("sha256").update(composite, "utf8").digest("hex").slice(0, SCOPE_HEX_LEN);
13409
- }
13410
- function resultArtifactPath(sub, cwd = process.cwd()) {
13411
- checkSafeSegment(sub);
13412
- return resolve(cwd, ".harnessed", "results", resultArtifactScope(cwd), `${sub}.md`);
13413
- }
13414
- var SCOPE_HEX_LEN, NO_SESSION;
13415
- var init_resultArtifact = __esm({
13416
- "src/cli/lib/resultArtifact.ts"() {
13417
- init_workflowStore();
13418
- init_path_guard();
13419
- SCOPE_HEX_LEN = 8;
13420
- NO_SESSION = "nosession";
13421
- }
13422
- });
13423
14362
  function userLangPinPath(hostContext) {
13424
14363
  return join(hostContext?.platform.stateRoot ?? detectPlatform().stateRoot, USER_LANG_PIN);
13425
14364
  }
@@ -13584,14 +14523,16 @@ Respond in ${name}.
13584
14523
  ${preserve}
13585
14524
  `;
13586
14525
  }
13587
- function buildResultDeliverySection(resultFile) {
14526
+ function buildResultDeliverySection(resultFile, attemptId) {
14527
+ const attemptRule = attemptId ? `
14528
+ - Include this exact standalone line: \`${resultAttemptLine(attemptId)}\`. Use \`--result-file\` with the path above for every \`checkpoint complete\` call.` : "";
13588
14529
  return `
13589
14530
  ## Result delivery
13590
14531
  Write your final result to this exact absolute path:
13591
14532
  ${resultFile}
13592
14533
 
13593
14534
  Rules:
13594
- - The file MUST contain your final result AND the verbatim line \`<promise>COMPLETE</promise>\`.
14535
+ - The file MUST contain your final result AND the verbatim line \`<promise>COMPLETE</promise>\`.${attemptRule}
13595
14536
  - 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.
13596
14537
  - 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".
13597
14538
  - 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.
@@ -13635,7 +14576,7 @@ ${opts.task}
13635
14576
  const toolsSection = await buildToolsSection(sub, packageRoot, host);
13636
14577
  const disciplinesSection = await buildDisciplinesSection(sub, packageRoot, locale);
13637
14578
  const languageSection = await buildLanguageSection(packageRoot, host);
13638
- const resultDeliverySection = opts.resultFile ? buildResultDeliverySection(opts.resultFile) : "";
14579
+ const resultDeliverySection = opts.resultFile ? buildResultDeliverySection(opts.resultFile, opts.resultAttemptId) : "";
13639
14580
  return {
13640
14581
  prompt: `${taskSection}${body}
13641
14582
  ${toolsSection}${disciplinesSection}${PROTOCOLS}${resultDeliverySection}${languageSection}`,
@@ -13658,36 +14599,77 @@ function registerPrompt(program2) {
13658
14599
  process.exit(2);
13659
14600
  return;
13660
14601
  }
14602
+ const { mutateWorkflow: mutateWorkflow2, readCurrentWorkflow: readCurrentWorkflow2, withWorkflowEffects: withWorkflowEffects2 } = await Promise.resolve().then(() => (init_state(), state_exports));
14603
+ const workflow = await readCurrentWorkflow2(true);
14604
+ const sameRun = (current) => current !== null && current.started_at === workflow?.started_at && current.phase === workflow.phase && current.handoff_authority?.run_id === workflow.handoff_authority?.run_id;
14605
+ const dispatchChanged = () => new Error(`checkpoint dispatch changed for ${sub}; rerun harnessed prompt`);
13661
14606
  const packageRoot = getAssetsRoot();
13662
- const resultFile = resultArtifactPath(sub, process.cwd());
14607
+ let dispatch;
14608
+ const candidate = workflow?.sub_progress?.find((e) => e.sub === sub);
14609
+ if (workflow?.handoff_authority && candidate?.status !== "pending" && candidate?.status !== "failed")
14610
+ throw new Error("handoff-ready workflow requires a managed dispatch");
14611
+ if (candidate?.status === "pending" || candidate?.status === "failed") {
14612
+ const prepared = newResultAttempt(sub, candidate.fail_count ?? 0);
14613
+ await mutateWorkflow2((workflow2) => {
14614
+ if (!sameRun(workflow2)) throw dispatchChanged();
14615
+ const entries = workflow2.sub_progress ?? [];
14616
+ const entry = entries.find((e) => e.sub === sub);
14617
+ if (!entry || entry.status !== "pending" && entry.status !== "failed") return workflow2;
14618
+ const owner = resultAttemptOwner();
14619
+ const number = entry.fail_count ?? 0;
14620
+ const current = entry.result_attempt;
14621
+ if (entry.status === "pending" && current?.owner === owner && current.number === number) {
14622
+ dispatch = current;
14623
+ return workflow2;
14624
+ }
14625
+ const attempt = { ...prepared, number };
14626
+ dispatch = attempt;
14627
+ return {
14628
+ ...workflow2,
14629
+ status: workflow2.status === "complete" ? "active" : workflow2.status,
14630
+ sub_progress: entries.map(
14631
+ (e) => e === entry ? { ...e, status: "pending", result_attempt: attempt } : e
14632
+ )
14633
+ };
14634
+ });
14635
+ if (!dispatch) throw dispatchChanged();
14636
+ }
14637
+ const resultFile = dispatch?.result_file ?? resultArtifactPath(sub);
13663
14638
  const {
13664
14639
  prompt: fullPrompt,
13665
14640
  model,
13666
14641
  specialist
13667
14642
  } = await buildPromptText(sub, packageRoot, {
13668
14643
  ...typeof raw.task === "string" ? { task: raw.task } : {},
13669
- resultFile
14644
+ resultFile,
14645
+ ...dispatch && { resultAttemptId: dispatch.id }
13670
14646
  });
13671
- if (raw.json) {
13672
- const maxIterations = await resolveMaxIterations2(sub, packageRoot);
13673
- console.log(
13674
- JSON.stringify({
13675
- prompt: fullPrompt,
13676
- max_iterations: maxIterations,
13677
- model,
13678
- specialist,
13679
- result_file: resultFile
13680
- })
13681
- );
13682
- process.exit(0);
14647
+ const output = raw.json ? JSON.stringify({
14648
+ prompt: fullPrompt,
14649
+ max_iterations: await resolveMaxIterations2(sub, packageRoot),
14650
+ model,
14651
+ specialist,
14652
+ result_file: resultFile
14653
+ }) : fullPrompt;
14654
+ const issued = dispatch;
14655
+ if (issued) {
14656
+ await withWorkflowEffects2((current) => {
14657
+ const entry = current?.sub_progress?.find((e) => e.sub === sub);
14658
+ const attempt = entry?.result_attempt;
14659
+ if (!sameRun(current) || entry?.status !== "pending" || attempt?.id !== issued.id || attempt.owner !== issued.owner || attempt.number !== issued.number || attempt.result_file !== issued.result_file || attempt.git_head !== issued.git_head)
14660
+ throw dispatchChanged();
14661
+ console.log(output);
14662
+ });
14663
+ } else {
14664
+ console.log(output);
13683
14665
  }
13684
- console.log(fullPrompt);
13685
14666
  process.exit(0);
13686
14667
  });
13687
14668
  }
13688
14669
  var DEFAULT_MAX_ITERATIONS, DEFAULT_MODEL, DEFAULT_SPECIALIST, LANG_NAMES, CHAT_TRIGGER_RE, CHAT_SCOPE_NOTE, PRESERVE_FALLBACK, PROTOCOLS;
13689
14670
  var init_prompt = __esm({
13690
14671
  "src/cli/prompt.ts"() {
14672
+ init_completionClaim();
13691
14673
  init_i18n();
13692
14674
  init_localeYaml();
13693
14675
  init_path_guard();
@@ -16524,10 +17506,10 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
16524
17506
  child.stderr?.setEncoding("utf8").on("data", (chunk) => {
16525
17507
  stderr += chunk;
16526
17508
  });
16527
- return await new Promise((resolve42) => {
17509
+ return await new Promise((resolve44) => {
16528
17510
  const timer = setTimeout(() => {
16529
17511
  killProcessTree(child);
16530
- resolve42({
17512
+ resolve44({
16531
17513
  ok: false,
16532
17514
  phase: "spawn",
16533
17515
  error: {
@@ -16548,7 +17530,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
16548
17530
  child.on("error", (err2) => {
16549
17531
  clearTimeout(timer);
16550
17532
  const bashMissing = triedBash && err2.code === "ENOENT";
16551
- resolve42({
17533
+ resolve44({
16552
17534
  ok: false,
16553
17535
  phase: "spawn",
16554
17536
  error: {
@@ -16563,7 +17545,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
16563
17545
  });
16564
17546
  child.on("close", (code2) => {
16565
17547
  clearTimeout(timer);
16566
- resolve42({ ok: true, exitCode: code2 ?? -1, stdout: stdout2, stderr });
17548
+ resolve44({ ok: true, exitCode: code2 ?? -1, stdout: stdout2, stderr });
16567
17549
  });
16568
17550
  });
16569
17551
  }
@@ -17277,7 +18259,7 @@ function touch(binary, lease, source, scratch, context) {
17277
18259
  if (context) env = withHostInstallEnv(env, context);
17278
18260
  env.GSTACK_LEASE_DIR = shellPath(scratch, context);
17279
18261
  env.GSTACK_LEASE_LOCK_TRIES = "1";
17280
- return new Promise((resolve42, reject) => {
18262
+ return new Promise((resolve44, reject) => {
17281
18263
  const child = execFile(
17282
18264
  binary,
17283
18265
  [
@@ -17306,7 +18288,7 @@ function touch(binary, lease, source, scratch, context) {
17306
18288
  `official lease touch exit ${error.code ?? "unknown"}${error.killed ? " (timeout or termination)" : ""}: ${stderr.trim() || error.message}`
17307
18289
  )
17308
18290
  );
17309
- else resolve42();
18291
+ else resolve44();
17310
18292
  }
17311
18293
  );
17312
18294
  child.stdin?.end();
@@ -17846,7 +18828,7 @@ var init_verifyInstalled = __esm({
17846
18828
  }
17847
18829
  });
17848
18830
  function gitRevParseHead(cwd, timeoutMs = 1e4) {
17849
- return new Promise((resolve42) => {
18831
+ return new Promise((resolve44) => {
17850
18832
  const isWin = process.platform === "win32";
17851
18833
  const child = isWin ? spawn("cmd.exe", ["/c", "git", "rev-parse", "HEAD"], { cwd, windowsHide: true }) : spawn("git", ["rev-parse", "HEAD"], { cwd, shell: false });
17852
18834
  let stdout2 = "";
@@ -17855,15 +18837,15 @@ function gitRevParseHead(cwd, timeoutMs = 1e4) {
17855
18837
  });
17856
18838
  const timer = setTimeout(() => {
17857
18839
  killProcessTree(child);
17858
- resolve42({ sha: "", exit: -1 });
18840
+ resolve44({ sha: "", exit: -1 });
17859
18841
  }, timeoutMs);
17860
18842
  child.on("error", () => {
17861
18843
  clearTimeout(timer);
17862
- resolve42({ sha: "", exit: -1 });
18844
+ resolve44({ sha: "", exit: -1 });
17863
18845
  });
17864
18846
  child.on("close", (code2) => {
17865
18847
  clearTimeout(timer);
17866
- resolve42({ sha: stdout2.trim(), exit: code2 ?? -1 });
18848
+ resolve44({ sha: stdout2.trim(), exit: code2 ?? -1 });
17867
18849
  });
17868
18850
  });
17869
18851
  }
@@ -20853,14 +21835,36 @@ async function buildRecoverLines(workflow, ledger, intent) {
20853
21835
  function registerStatus(program2) {
20854
21836
  program2.command("status").description("Show installed upstreams (from <harnessed-root>/state.json)").option("--recover", "structured recovery view of the active workflow ledger (v5.0 Spec 1 B)").action(async (opts) => {
20855
21837
  if (opts.recover) {
20856
- const wf = await readCurrentWorkflow();
21838
+ const { readLocalHandoff: readLocalHandoff2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
21839
+ const handoff = await readLocalHandoff2();
21840
+ if (handoff?.kind === "frozen") {
21841
+ const { authority, frozen } = handoff;
21842
+ console.log(
21843
+ `handoff frozen locally: ${frozen.transfer_id}; destination claim status unknown`
21844
+ );
21845
+ console.log(
21846
+ `In the exact ${frozen.target_host} destination session, retry the same ID: harnessed checkpoint adopt --from ${authority.host} --transfer-id ${frozen.transfer_id}`
21847
+ );
21848
+ return;
21849
+ }
21850
+ if (handoff?.kind === "claimed") {
21851
+ console.log(`handoff claimed locally: ${handoff.id} at ${handoff.claim.claimed_at}`);
21852
+ console.log(
21853
+ `To recover a lost acknowledgement in this session: harnessed checkpoint adopt --from ${handoff.claim.source_host} --transfer-id ${handoff.id}`
21854
+ );
21855
+ if (!handoff.slot) {
21856
+ console.log("The workflow slot was pruned; the receipt does not recreate it.");
21857
+ return;
21858
+ }
21859
+ }
21860
+ const wf = handoff?.slot ?? await readCurrentWorkflow(false, true);
20857
21861
  const ledger = wf?.sub_progress ?? [];
20858
21862
  let intent = null;
20859
21863
  if (ledger.length === 0) {
20860
21864
  try {
20861
21865
  const { readIntent: readIntent2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
20862
21866
  const { INTENT_TTL_MS: INTENT_TTL_MS2 } = await Promise.resolve().then(() => (init_injectState(), injectState_exports));
20863
- const raw = await readIntent2();
21867
+ const raw = await readIntent2(void 0, true);
20864
21868
  if (raw) {
20865
21869
  const age = Date.now() - Date.parse(raw.ts);
20866
21870
  if (!Number.isNaN(age) && age >= 0 && age <= INTENT_TTL_MS2) {
@@ -22245,7 +23249,7 @@ async function runBinarySelfUpdate(deps, opts) {
22245
23249
  try {
22246
23250
  const dir = join(deps.stateRoot(), "bin-backup", deps.currentVersion);
22247
23251
  await mkdir(dir, { recursive: true });
22248
- await copyFile$1(bakPath, join(dir, execBase));
23252
+ await copyFile$1(bakPath, join(dir, asset));
22249
23253
  backupDir = dir;
22250
23254
  copied = true;
22251
23255
  } catch (e) {
@@ -22290,20 +23294,26 @@ async function runBinaryRollback(deps, opts) {
22290
23294
  }
22291
23295
  const asset = assetNameFor(deps.platform, deps.arch);
22292
23296
  const backupsRoot = join(deps.stateRoot(), "bin-backup");
22293
- let versions = [];
23297
+ const execBase = basename(deps.execPath);
23298
+ const banked = /* @__PURE__ */ new Map();
22294
23299
  try {
22295
23300
  const entries = await readdir(backupsRoot, { withFileTypes: true });
22296
23301
  for (const e of entries) {
22297
23302
  if (!e.isDirectory()) continue;
22298
- const has = await access(join(backupsRoot, e.name, asset)).then(
22299
- () => true,
22300
- () => false
22301
- );
22302
- if (has) versions.push(e.name);
23303
+ for (const name of asset === execBase ? [asset] : [asset, execBase]) {
23304
+ const has = await access(join(backupsRoot, e.name, name)).then(
23305
+ () => true,
23306
+ () => false
23307
+ );
23308
+ if (has) {
23309
+ banked.set(e.name, name);
23310
+ break;
23311
+ }
23312
+ }
22303
23313
  }
22304
23314
  } catch {
22305
- versions = [];
22306
23315
  }
23316
+ const versions = [...banked.keys()];
22307
23317
  if (versions.length === 0) {
22308
23318
  return {
22309
23319
  status: "error",
@@ -22322,9 +23332,8 @@ async function runBinaryRollback(deps, opts) {
22322
23332
  } else {
22323
23333
  target = versions.reduce((a, b) => compareVersions(a, b) === "behind" ? b : a);
22324
23334
  }
22325
- const backupBin = join(backupsRoot, target, asset);
23335
+ const backupBin = join(backupsRoot, target, banked.get(target) ?? asset);
22326
23336
  const execDir = dirname(deps.execPath);
22327
- const execBase = basename(deps.execPath);
22328
23337
  const ext = deps.platform === "win32" ? ".exe" : "";
22329
23338
  const tempPath = join(execDir, `.harnessed-rollback-${deps.pid}${ext}`);
22330
23339
  const bakPath = join(execDir, `${execBase}.bak-${deps.currentVersion}`);
@@ -22373,7 +23382,7 @@ async function runBinaryRollback(deps, opts) {
22373
23382
  try {
22374
23383
  const dir = join(backupsRoot, deps.currentVersion);
22375
23384
  await mkdir(dir, { recursive: true });
22376
- await copyFile$1(bakPath, join(dir, execBase));
23385
+ await copyFile$1(bakPath, join(dir, asset));
22377
23386
  copied = true;
22378
23387
  } catch (e) {
22379
23388
  deps.log(
@@ -23056,7 +24065,7 @@ function decodeUpdateContinuation(encoded) {
23056
24065
  return value;
23057
24066
  }
23058
24067
  async function runContinuationProcess(executablePath, args, options) {
23059
- return new Promise((resolve42, reject) => {
24068
+ return new Promise((resolve44, reject) => {
23060
24069
  const child = spawn(executablePath, args, {
23061
24070
  cwd: options.cwd,
23062
24071
  env: options.env,
@@ -23070,7 +24079,7 @@ async function runContinuationProcess(executablePath, args, options) {
23070
24079
  child.once("error", reject);
23071
24080
  child.once("close", (exitCode, signal) => {
23072
24081
  clearTimeout(timer);
23073
- resolve42({ exitCode, signal });
24082
+ resolve44({ exitCode, signal });
23074
24083
  });
23075
24084
  });
23076
24085
  }
@@ -23405,6 +24414,18 @@ function buildExecutionBody(name, prompt, ctx) {
23405
24414
  ...spawnLoopSteps("").map(
23406
24415
  (s) => s.replace("<sub>", name).replace('--task "<spec>"', '--task "$ARGUMENTS"')
23407
24416
  ),
24417
+ // Phase 91 — research-only persistence contract (sister of the step-6 text
24418
+ // in scripts/rewrite-skill-invoke-sections.mjs executionEn/Zh, which is the
24419
+ // bilingual canonical pair; this surface is English-only by design). The
24420
+ // standalone `/research` trap: the main session improvised a localized PWF
24421
+ // variant's init-session triple at the project root and the sub wrote
24422
+ // .planning/phases/.../findings.md, tripping the planning-sync gate. The
24423
+ // trailing `` keeps exactly one blank line before the run warning in both
24424
+ // the research and non-research layouts.
24425
+ ...name === "research" ? [
24426
+ ``,
24427
+ `Persistence \u2014 the \`result_file\` IS the research report: the sub writes its full findings there and you read them back from that file. Do NOT create a planning-with-files triple (\`task_plan.md\` / \`progress.md\` / \`findings.md\`) or a GSD skeleton (\`.planning/STATE.md\` / \`ROADMAP.md\` / \`REQUIREMENTS.md\`) around a standalone research run, and do not invoke \`planning-with-files\` or any localized variant of it (e.g. \`planning-with-files-de\`): the canonical skill belongs to managed phase workflows whose caller explicitly asks for planning-doc persistence, and a localized variant is never a substitute for it. If you explicitly direct the report into an existing phase dir or a dedicated report path, \`result_file\` still carries the link + one-paragraph summary + completion marker.`
24428
+ ] : [],
23408
24429
  ``,
23409
24430
  runWarning(ctx, name, "command_execution"),
23410
24431
  ``,
@@ -24725,14 +25746,14 @@ var manifest_add_exports = {};
24725
25746
  __export(manifest_add_exports, {
24726
25747
  registerManifestAdd: () => registerManifestAdd
24727
25748
  });
24728
- function basename8(upstream) {
25749
+ function basename10(upstream) {
24729
25750
  return (upstream.split("/").pop() ?? upstream).replace(/\.git$/, "");
24730
25751
  }
24731
25752
  function registerManifestAdd(program2) {
24732
25753
  program2.command("manifest-add <upstream>").description(
24733
25754
  "Add a new upstream adapter (EE-5 5-question merge gate; immediate by default \u2014 use --dry-run for preview)"
24734
25755
  ).option("--category <cat>", "manifest category (skill-packs | tools)", "skill-packs").option("--name <name>", "short adapter name (defaults to <upstream> basename)").option("--dry-run", "preview only \u2014 do not write JSON (opt-in for advanced users)").option("--non-interactive", "CI/scripts \u2014 WARN-only dry-run").action(async (upstream, raw) => {
24735
- const name = raw.name ?? basename8(upstream);
25756
+ const name = raw.name ?? basename10(upstream);
24736
25757
  const category = raw.category ?? "skill-packs";
24737
25758
  try {
24738
25759
  checkSafeSegment(category);
@@ -25383,9 +26404,49 @@ ${t("rollback.metadata_unreadable.fix")}`
25383
26404
  process.exit(1);
25384
26405
  return;
25385
26406
  }
26407
+ {
26408
+ const counts = /* @__PURE__ */ new Map();
26409
+ for (const entry of meta.files) {
26410
+ counts.set(entry.target, (counts.get(entry.target) ?? 0) + 1);
26411
+ }
26412
+ const dupInvolvingSubtree = meta.files.some(
26413
+ (entry) => entry.kind === "json-subtree" && (counts.get(entry.target) ?? 0) > 1
26414
+ );
26415
+ if (dupInvolvingSubtree) {
26416
+ console.error(
26417
+ "error: backup metadata has duplicate entries for a json-subtree target; refusing to guess composition order"
26418
+ );
26419
+ process.exit(1);
26420
+ return;
26421
+ }
26422
+ }
25386
26423
  const ordered = [...meta.files].reverse();
25387
26424
  const planned = [];
25388
26425
  for (const entry of ordered) {
26426
+ if (entry.kind === "json-subtree") {
26427
+ if (entry.sha1 !== SUBTREE_ENTRY_SHA1 || typeof entry.payloadSha1 !== "string" || !/^[a-f0-9]{40}$/.test(entry.payloadSha1) || entry.backup === "" || entry.sentinel !== void 0) {
26428
+ console.error(
26429
+ `error: malformed json-subtree backup entry for ${entry.target}; scoped snapshots require a compatible harnessed reader \u2014 restore manually`
26430
+ );
26431
+ process.exit(1);
26432
+ return;
26433
+ }
26434
+ } else {
26435
+ if (entry.kind !== void 0 && entry.kind !== "bytes") {
26436
+ console.error(
26437
+ `error: backup entry for ${entry.target} has unknown kind ${String(entry.kind)}; upgrade harnessed or restore manually`
26438
+ );
26439
+ process.exit(1);
26440
+ return;
26441
+ }
26442
+ if (entry.payloadSha1 !== void 0) {
26443
+ console.error(
26444
+ `error: backup entry for ${entry.target} carries payloadSha1 without json-subtree kind; refusing to guess its format`
26445
+ );
26446
+ process.exit(1);
26447
+ return;
26448
+ }
26449
+ }
25389
26450
  if (entry.backup === "") {
25390
26451
  if (entry.sentinel === "created") {
25391
26452
  planned.push({ target: entry.target, action: "remove-created" });
@@ -25419,13 +26480,81 @@ ${t("rollback.metadata_unreadable.fix")}`
25419
26480
  process.exit(1);
25420
26481
  return;
25421
26482
  }
25422
- const sha1 = createHash("sha1").update(buf).digest("hex");
25423
- if (sha1 !== entry.sha1) {
26483
+ const digest = createHash("sha1").update(buf).digest("hex");
26484
+ if (entry.kind === "json-subtree") {
26485
+ if (digest !== entry.payloadSha1) {
26486
+ console.error(
26487
+ t("rollback.checksum_mismatch", {
26488
+ target: entry.target,
26489
+ expected: (entry.payloadSha1 ?? "").slice(0, 12),
26490
+ actual: digest.slice(0, 12)
26491
+ })
26492
+ );
26493
+ process.exit(1);
26494
+ return;
26495
+ }
26496
+ let parsedPayload;
26497
+ try {
26498
+ parsedPayload = JSON.parse(buf.toString("utf8"));
26499
+ } catch {
26500
+ console.error(`error: backup payload for ${entry.target} is not valid JSON`);
26501
+ process.exit(1);
26502
+ return;
26503
+ }
26504
+ const payload = validateSubtreePayload(parsedPayload);
26505
+ if (!payload.ok) {
26506
+ console.error(
26507
+ `error: invalid json-subtree payload for ${entry.target}: ${payload.reason}`
26508
+ );
26509
+ process.exit(1);
26510
+ return;
26511
+ }
26512
+ const currentText = await (async () => {
26513
+ try {
26514
+ return await readFile(entry.target, "utf8");
26515
+ } catch {
26516
+ return null;
26517
+ }
26518
+ })();
26519
+ const current = currentText === null ? null : tryParseJsonObject(currentText);
26520
+ if (current === null) {
26521
+ console.error(
26522
+ `error: cannot restore ${entry.target}: current content is not a readable JSON object (refusing to overwrite user edits)`
26523
+ );
26524
+ process.exit(1);
26525
+ return;
26526
+ }
26527
+ const unsafe = containsUnsafeJsonNumber(current) || payload.changes.some((c) => c.existed && containsUnsafeJsonNumber(c.value));
26528
+ if (unsafe) {
26529
+ console.error(
26530
+ `error: cannot restore ${entry.target}: JSON contains a number that cannot round-trip through JSON.stringify (non-finite or unsafe integer) \u2014 restore manually`
26531
+ );
26532
+ process.exit(1);
26533
+ return;
26534
+ }
26535
+ const applied = applySubtreeChanges(current, payload.changes);
26536
+ if (!applied.ok) {
26537
+ console.error(`error: cannot restore ${entry.target}: ${applied.reason}`);
26538
+ process.exit(1);
26539
+ return;
26540
+ }
26541
+ planned.push({
26542
+ target: entry.target,
26543
+ action: "write",
26544
+ data: normalizeEol(
26545
+ Buffer.from(`${JSON.stringify(current, null, 2)}
26546
+ `, "utf8"),
26547
+ entry.eol
26548
+ )
26549
+ });
26550
+ continue;
26551
+ }
26552
+ if (digest !== entry.sha1) {
25424
26553
  console.error(
25425
26554
  t("rollback.checksum_mismatch", {
25426
26555
  target: entry.target,
25427
26556
  expected: entry.sha1.slice(0, 12),
25428
- actual: sha1.slice(0, 12)
26557
+ actual: digest.slice(0, 12)
25429
26558
  })
25430
26559
  );
25431
26560
  process.exit(1);
@@ -25464,6 +26593,7 @@ var init_rollback = __esm({
25464
26593
  "src/cli/rollback.ts"() {
25465
26594
  init_i18n();
25466
26595
  init_backup();
26596
+ init_jsonSubtree();
25467
26597
  init_path_guard();
25468
26598
  }
25469
26599
  });
@@ -25557,6 +26687,10 @@ function registerRun(program2) {
25557
26687
  process.exit(2);
25558
26688
  return;
25559
26689
  }
26690
+ const { readCurrentWorkflow: readCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
26691
+ if ((await readCurrentWorkflow2(true))?.handoff_authority) {
26692
+ throw new Error("headless execution is not supported for a handoff-ready run");
26693
+ }
25560
26694
  let task = "";
25561
26695
  if (typeof raw.task === "string") {
25562
26696
  task = raw.task;
@@ -27992,7 +29126,7 @@ var init_npmCli3 = __esm({
27992
29126
  cwd: ctx.hostContext.userHome,
27993
29127
  env: withHostInstallEnv(process.env, ctx.hostContext)
27994
29128
  } : {};
27995
- const result = await new Promise((resolve42) => {
29129
+ const result = await new Promise((resolve44) => {
27996
29130
  const child = isWin ? spawn("cmd.exe", ["/c", "npm", "uninstall", "-g", pkg], {
27997
29131
  ...spawnOptions,
27998
29132
  windowsHide: true
@@ -28003,15 +29137,15 @@ var init_npmCli3 = __esm({
28003
29137
  });
28004
29138
  const timer = setTimeout(() => {
28005
29139
  child.kill("SIGKILL");
28006
- resolve42({ exitCode: -1, stderr: `${stderr}[timeout]` });
29140
+ resolve44({ exitCode: -1, stderr: `${stderr}[timeout]` });
28007
29141
  }, 3e4);
28008
29142
  child.on("error", (e) => {
28009
29143
  clearTimeout(timer);
28010
- resolve42({ exitCode: -1, stderr: e.message });
29144
+ resolve44({ exitCode: -1, stderr: e.message });
28011
29145
  });
28012
29146
  child.on("close", (code2) => {
28013
29147
  clearTimeout(timer);
28014
- resolve42({ exitCode: code2 ?? -1, stderr });
29148
+ resolve44({ exitCode: code2 ?? -1, stderr });
28015
29149
  });
28016
29150
  });
28017
29151
  if (result.exitCode !== 0) {
@@ -28674,7 +29808,7 @@ async function runOwnedRefreshEntry() {
28674
29808
  const { captureHostInstallContext: captureHostInstallContext3 } = await Promise.resolve().then(() => (init_hostInstallContext(), hostInstallContext_exports));
28675
29809
  const context = captureHostInstallContext3();
28676
29810
  const outcome = await refreshOwnedState(context);
28677
- writeAutoUpdateNoticeForNewBinary(context);
29811
+ await writeAutoUpdateNoticeForNewBinary(context);
28678
29812
  if (outcome.ok) {
28679
29813
  console.log(
28680
29814
  `[harnessed] owned state refreshed (${outcome.updated.length} component(s): ${outcome.updated.join(", ")})`
@@ -28707,7 +29841,7 @@ async function writeAutoUpdateNoticeForNewBinary(context) {
28707
29841
  }
28708
29842
  async function spawnOwnedRefresh(execPath, context, deps = {}, timeoutMs = OWNED_REFRESH_TIMEOUT_MS) {
28709
29843
  const spawnImpl = deps.spawn ?? spawn;
28710
- return new Promise((resolve42) => {
29844
+ return new Promise((resolve44) => {
28711
29845
  let child;
28712
29846
  try {
28713
29847
  child = spawnImpl(execPath, [OWNED_REFRESH_FLAG], {
@@ -28721,7 +29855,7 @@ async function spawnOwnedRefresh(execPath, context, deps = {}, timeoutMs = OWNED
28721
29855
  shell: false
28722
29856
  });
28723
29857
  } catch (error) {
28724
- resolve42({
29858
+ resolve44({
28725
29859
  ok: false,
28726
29860
  exitCode: null,
28727
29861
  error: error instanceof Error ? error.message : String(error)
@@ -28733,15 +29867,15 @@ async function spawnOwnedRefresh(execPath, context, deps = {}, timeoutMs = OWNED
28733
29867
  killProcessTree(child);
28734
29868
  } catch {
28735
29869
  }
28736
- resolve42({ ok: false, exitCode: null, error: `timed out after ${timeoutMs}ms` });
29870
+ resolve44({ ok: false, exitCode: null, error: `timed out after ${timeoutMs}ms` });
28737
29871
  }, timeoutMs);
28738
29872
  child.on("error", (error) => {
28739
29873
  clearTimeout(timer);
28740
- resolve42({ ok: false, exitCode: null, error: error.message });
29874
+ resolve44({ ok: false, exitCode: null, error: error.message });
28741
29875
  });
28742
29876
  child.on("close", (code2) => {
28743
29877
  clearTimeout(timer);
28744
- resolve42({ ok: code2 === 0, exitCode: code2 });
29878
+ resolve44({ ok: code2 === 0, exitCode: code2 });
28745
29879
  });
28746
29880
  });
28747
29881
  }
@@ -29060,8 +30194,163 @@ var init_workflows = __esm({
29060
30194
  }
29061
30195
  });
29062
30196
 
30197
+ // src/cli/lib/workflowStartup.ts
30198
+ var workflowStartup_exports = {};
30199
+ __export(workflowStartup_exports, {
30200
+ prepareWorkflowStartup: () => prepareWorkflowStartup
30201
+ });
30202
+ function pathInfo(path) {
30203
+ try {
30204
+ return lstatSync(path);
30205
+ } catch (error) {
30206
+ if (error.code !== "ENOENT") throw error;
30207
+ }
30208
+ }
30209
+ async function prepareWorkflowStartup(unpack) {
30210
+ const context = captureHostInstallContext();
30211
+ let root = getHarnessedRoot();
30212
+ const legacy = legacyMigrationRoot(context);
30213
+ const legacyInfo = legacy ? pathInfo(legacy) : void 0;
30214
+ if (legacyInfo && context.platform.stateRoot !== root) {
30215
+ throw new WorkflowStateError("legacy migration destination differs from the active state root");
30216
+ }
30217
+ let legacyImportRefused = false;
30218
+ if (legacy && legacyInfo && !pathInfo(root)) {
30219
+ if (!legacyInfo.isDirectory()) throw new WorkflowStateError("legacy state is not a directory");
30220
+ const old = await readStoreAt(legacy, true);
30221
+ if (old.handoff_claims || Object.values(old.workflows).some((slot) => slot.handoff_authority)) {
30222
+ throw new WorkflowStateError("legacy state contains handoff authority; cannot import it");
30223
+ }
30224
+ migrateLegacyHarnessedRoot(context, true);
30225
+ if (!pathInfo(root)) {
30226
+ if (!pathInfo(legacy)) throw new WorkflowStateError("legacy state was not imported");
30227
+ legacyImportRefused = true;
30228
+ }
30229
+ root = getHarnessedRoot();
30230
+ }
30231
+ const store = process.platform === "win32" ? await readStoreAt(root, true) : void 0;
30232
+ if (!unpack && !(legacy && pathInfo(legacy)) && !(store && needsRepoKeyFold(store))) return;
30233
+ await readCurrentWorkflow(true);
30234
+ await withWorkflowEffects(async () => {
30235
+ if (legacy && !legacyImportRefused && context.platform.stateRoot === root)
30236
+ migrateLegacyHarnessedRoot(context);
30237
+ await migrateRepoKeyCase();
30238
+ unpack?.();
30239
+ });
30240
+ }
30241
+ var init_workflowStartup = __esm({
30242
+ "src/cli/lib/workflowStartup.ts"() {
30243
+ init_state();
30244
+ init_workflowStore();
30245
+ init_harnessedRoot();
30246
+ init_hostInstallContext();
30247
+ }
30248
+ });
30249
+
29063
30250
  // src/cli.ts
29064
30251
  init_package();
30252
+
30253
+ // src/cli/lib/entryCommand.ts
30254
+ function entryCommandIndex(args) {
30255
+ let index = 0;
30256
+ while (index < args.length) {
30257
+ const arg = args[index];
30258
+ if (arg === "--lang") index += 2;
30259
+ else if (arg?.startsWith("--lang=")) index++;
30260
+ else break;
30261
+ }
30262
+ return args[index] === "--" ? index + 1 : index;
30263
+ }
30264
+ function isWorkflowWriter(args) {
30265
+ const command = args[entryCommandIndex(args)];
30266
+ return ["checkpoint", "prompt", "run", "compact", "reject", "retro", "gc"].some(
30267
+ (writer) => writer === command
30268
+ );
30269
+ }
30270
+ var GLOBAL_VALUE_OPTIONS = ["--lang"];
30271
+ var CHECKPOINT_VALUE_OPTIONS = /* @__PURE__ */ new Set([
30272
+ ...GLOBAL_VALUE_OPTIONS,
30273
+ "--summary",
30274
+ "--plan",
30275
+ "--tokens",
30276
+ "--result",
30277
+ "--result-file",
30278
+ "--wait",
30279
+ "--reason",
30280
+ "--failing-tests",
30281
+ "--failure",
30282
+ "--from",
30283
+ "--to",
30284
+ "--transfer-id"
30285
+ ]);
30286
+ var RUN_VALUE_OPTIONS = /* @__PURE__ */ new Set([
30287
+ ...GLOBAL_VALUE_OPTIONS,
30288
+ "--task",
30289
+ "--max-iterations",
30290
+ "--model",
30291
+ "--skip-sub"
30292
+ ]);
30293
+ var STATUS_VALUE_OPTIONS = /* @__PURE__ */ new Set([...GLOBAL_VALUE_OPTIONS]);
30294
+ var HELP_SCAN_VALUE_OPTIONS = /* @__PURE__ */ new Set([
30295
+ ...CHECKPOINT_VALUE_OPTIONS,
30296
+ ...RUN_VALUE_OPTIONS,
30297
+ "--older-than",
30298
+ "--keep-last"
30299
+ ]);
30300
+ function scanCommandTokens(args, index, valueOptions) {
30301
+ const positionals = [];
30302
+ const options = /* @__PURE__ */ new Set();
30303
+ let positionalOnly = false;
30304
+ let i = index + 1;
30305
+ while (i < args.length) {
30306
+ const arg = args[i];
30307
+ if (!positionalOnly && arg === "--") {
30308
+ positionalOnly = true;
30309
+ i += 1;
30310
+ continue;
30311
+ }
30312
+ if (!positionalOnly && arg !== void 0 && arg.length > 1 && arg.startsWith("-")) {
30313
+ const eq = arg.indexOf("=");
30314
+ const name = eq === -1 ? arg : arg.slice(0, eq);
30315
+ options.add(name);
30316
+ if (eq === -1 && valueOptions.has(name)) i += 2;
30317
+ else i += 1;
30318
+ continue;
30319
+ }
30320
+ if (arg !== void 0) positionals.push(arg);
30321
+ i += 1;
30322
+ }
30323
+ return { positionals, options };
30324
+ }
30325
+ function isHandoffEnrollment(args) {
30326
+ const index = entryCommandIndex(args);
30327
+ if (args[index] !== "checkpoint") return false;
30328
+ return scanCommandTokens(args, index, CHECKPOINT_VALUE_OPTIONS).options.has("--handoff-ready");
30329
+ }
30330
+ function isRecoveryInvocation(args) {
30331
+ const index = entryCommandIndex(args);
30332
+ if (args[index] !== "status") return false;
30333
+ return scanCommandTokens(args, index, STATUS_VALUE_OPTIONS).options.has("--recover");
30334
+ }
30335
+ function isHandoffInvocation(args) {
30336
+ const index = entryCommandIndex(args);
30337
+ if (args[index] !== "checkpoint") return false;
30338
+ const { positionals, options } = scanCommandTokens(args, index, CHECKPOINT_VALUE_OPTIONS);
30339
+ const action = positionals[0];
30340
+ if (action === "handoff") return true;
30341
+ return action === "adopt" && options.has("--transfer-id");
30342
+ }
30343
+ function isRunListInvocation(args) {
30344
+ const index = entryCommandIndex(args);
30345
+ if (args[index] !== "run") return false;
30346
+ return scanCommandTokens(args, index, RUN_VALUE_OPTIONS).options.has("--list");
30347
+ }
30348
+ function hasHelpFlag(args) {
30349
+ const { options } = scanCommandTokens(args, -1, HELP_SCAN_VALUE_OPTIONS);
30350
+ return options.has("--help") || options.has("-h");
30351
+ }
30352
+
30353
+ // src/cli.ts
29065
30354
  var entryArgs = process.argv.slice(2);
29066
30355
  if (entryArgs.length === 1 && entryArgs[0] === "--internal-update-identity") {
29067
30356
  process.stdout.write(`${package_default.version}
@@ -29112,7 +30401,7 @@ var { getAssetsRoot: getAssetsRoot2 } = await Promise.resolve().then(() => (init
29112
30401
  var { captureHostInstallContext: captureHostInstallContext2 } = await Promise.resolve().then(() => (init_hostInstallContext(), hostInstallContext_exports));
29113
30402
  var { migrateLegacyHarnessedRoot: migrateLegacyHarnessedRoot2 } = await Promise.resolve().then(() => (init_harnessedRoot(), harnessedRoot_exports));
29114
30403
  wireMessagesDir2(() => join(getAssetsRoot2(), "messages"));
29115
- var updateInvocation = entryArgs.includes("update");
30404
+ var updateInvocation = entryArgs[entryCommandIndex(entryArgs)] === "update";
29116
30405
  function explicitPlatform(args) {
29117
30406
  for (let index = 0; index < args.length; index++) {
29118
30407
  const arg = args[index];
@@ -29147,14 +30436,21 @@ process.on("unhandledRejection", (reason) => {
29147
30436
  process.on("uncaughtException", (err2) => {
29148
30437
  fatal(err2 instanceof Error ? err2.message : String(err2));
29149
30438
  });
29150
- if (!updateInvocation) {
29151
- const hostId = explicitPlatform(entryArgs);
29152
- migrateLegacyHarnessedRoot2(captureHostInstallContext2(hostId === void 0 ? {} : { hostId }));
29153
- await migrateRepoKeyCase2().catch((e) => {
29154
- console.error(
29155
- `[harnessed] WARN: repo-key case migration deferred: ${e instanceof Error ? e.message : String(e)}`
29156
- );
29157
- });
30439
+ if (!updateInvocation && !isHandoffInvocation(entryArgs) && !isHandoffEnrollment(entryArgs) && !isRecoveryInvocation(entryArgs) && !isRunListInvocation(entryArgs)) {
30440
+ if (isWorkflowWriter(entryArgs)) {
30441
+ if (!hasHelpFlag(entryArgs)) {
30442
+ const { prepareWorkflowStartup: prepareWorkflowStartup2 } = await Promise.resolve().then(() => (init_workflowStartup(), workflowStartup_exports));
30443
+ await prepareWorkflowStartup2();
30444
+ }
30445
+ } else {
30446
+ const hostId = explicitPlatform(entryArgs);
30447
+ migrateLegacyHarnessedRoot2(captureHostInstallContext2(hostId === void 0 ? {} : { hostId }));
30448
+ await migrateRepoKeyCase2().catch((e) => {
30449
+ console.error(
30450
+ `[harnessed] WARN: repo-key case migration deferred: ${e instanceof Error ? e.message : String(e)}`
30451
+ );
30452
+ });
30453
+ }
29158
30454
  }
29159
30455
  var { OWNED_REFRESH_FLAG: OWNED_REFRESH_FLAG2 } = await Promise.resolve().then(() => (init_ownedRefreshFlag(), ownedRefreshFlag_exports));
29160
30456
  if (entryArgs.length === 1 && entryArgs[0] === OWNED_REFRESH_FLAG2) {