harnessed 5.0.16 → 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 +15 -0
  2. package/bin/harnessed-update-reminder-worker.mjs +1 -1
  3. package/bin/harnessed-update-reminder.mjs +1 -1
  4. package/dist/cli.mjs +1314 -322
  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.16",
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,10 +443,13 @@ function renameLegacyRoot(source, target) {
431
443
  return false;
432
444
  }
433
445
  }
434
- function migrateLegacyHarnessedRoot(context = captureHostInstallContext()) {
435
- const override = process.env.HARNESSED_ROOT_OVERRIDE;
436
- if (override !== void 0 && override !== "") return;
437
- 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;
438
453
  const newRoot = context.platform.stateRoot;
439
454
  const targetParent = dirname(newRoot);
440
455
  if (!existsSync(legacyRoot)) return;
@@ -446,6 +461,13 @@ function migrateLegacyHarnessedRoot(context = captureHostInstallContext()) {
446
461
  );
447
462
  return;
448
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
+ }
449
471
  const safetyBak = join(context.userHome, ".harnessed.legacy-bak");
450
472
  if (existsSync(safetyBak)) {
451
473
  console.error(
@@ -462,6 +484,7 @@ var init_harnessedRoot = __esm({
462
484
  "src/platform/harnessedRoot.ts"() {
463
485
  init_hostInstallContext();
464
486
  init_platform();
487
+ init_volumeIdentity();
465
488
  }
466
489
  });
467
490
  function branchOnSchemaVersion(v, handlers) {
@@ -627,7 +650,7 @@ var init_spawnFailure = __esm({
627
650
  };
628
651
  }
629
652
  });
630
- var WorkflowStatus, EvidenceRef, SubProgressEntry, CurrentWorkflowV1;
653
+ var WorkflowStatus, EvidenceRef, SubProgressEntry, HANDOFF_UUID_PATTERN, HandoffHost, HANDOFF_SESSION_ID_PATTERN, CurrentWorkflowV1;
631
654
  var init_currentWorkflow_v1 = __esm({
632
655
  "src/checkpoint/schema/currentWorkflow.v1.ts"() {
633
656
  init_schemaVersion();
@@ -670,6 +693,27 @@ var init_currentWorkflow_v1 = __esm({
670
693
  // G6 — failure counter; incremented only on each ->failed transition (drives
671
694
  // breakLoop detection). 'rejected' is terminal and does NOT increment it.
672
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
+ ),
673
717
  // 4.26.0 (A3 serial-order guard) — seeding-time serial/parallel semantics
674
718
  // carried over from the gates plan (fire[].mode/order). Optional: pre-4.26.0
675
719
  // envelopes lack them, and the guard no-ops on entries without `mode`
@@ -740,6 +784,9 @@ var init_currentWorkflow_v1 = __esm({
740
784
  },
741
785
  { additionalProperties: false }
742
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])";
743
790
  CurrentWorkflowV1 = Type.Object(
744
791
  {
745
792
  schemaVersion: Type.Literal(SCHEMA_VERSIONS.currentWorkflow),
@@ -754,6 +801,29 @@ var init_currentWorkflow_v1 = __esm({
754
801
  // checkpoint envelope does NOT carry a copy). Old files without this field
755
802
  // still `Value.Check`-pass → no schema version bump; readers use `?? []`.
756
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
+ ),
757
827
  // G1 — verification depth used during the verify phase ('light' | 'full').
758
828
  verify_mode: Type.Optional(Type.Union([Type.Literal("light"), Type.Literal("full")])),
759
829
  // G2 — when true the next-step contract reports NEXT:auto (skill auto-advances);
@@ -797,6 +867,18 @@ var init_currentWorkflow_v1 = __esm({
797
867
  );
798
868
  }
799
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
+ });
800
882
  var CheckpointStatus, CheckpointV1;
801
883
  var init_checkpoint_v1 = __esm({
802
884
  "src/checkpoint/schema/checkpoint.v1.ts"() {
@@ -844,12 +926,16 @@ __export(state_exports, {
844
926
  LockHeldError: () => LockHeldError,
845
927
  WorkflowStateError: () => WorkflowStateError,
846
928
  activate: () => activate,
929
+ claimHandoff: () => claimHandoff,
847
930
  complete: () => complete,
931
+ enrollHandoffRun: () => enrollHandoffRun,
932
+ freezeHandoffSource: () => freezeHandoffSource,
848
933
  mutateStore: () => mutateStore,
849
934
  mutateSubProgress: () => mutateSubProgress,
850
935
  mutateWorkflow: () => mutateWorkflow,
851
936
  pause: () => pause,
852
937
  readCurrentWorkflow: () => readCurrentWorkflow,
938
+ withWorkflowEffects: () => withWorkflowEffects,
853
939
  writeCurrentWorkflow: () => writeCurrentWorkflow
854
940
  });
855
941
  function statePath() {
@@ -865,9 +951,9 @@ function lockOpts() {
865
951
  lockfilePath: harnessedFile(".lock")
866
952
  };
867
953
  }
868
- async function withLock(fn) {
954
+ async function withLock(fn, existingRootOnly = false) {
869
955
  const target = lockTarget();
870
- await mkdir(target, { recursive: true });
956
+ if (!existingRootOnly) await mkdir(target, { recursive: true });
871
957
  let release;
872
958
  try {
873
959
  release = await lockfile.lock(target, lockOpts());
@@ -875,25 +961,64 @@ async function withLock(fn) {
875
961
  if (e.code === "ELOCKED") throw new LockHeldError();
876
962
  throw e;
877
963
  }
964
+ const scope = { root: target, held: true };
878
965
  try {
879
- return await fn();
966
+ return await lockScope.run(scope, fn);
880
967
  } finally {
968
+ scope.held = false;
881
969
  await release?.();
882
970
  }
883
971
  }
884
- async function readCurrentWorkflow() {
885
- 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();
886
982
  return store.workflows[activeKey()] ?? store.workflows[repoKey()] ?? null;
887
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
+ }
888
1006
  async function writeCurrentWorkflowUnlocked(input) {
889
1007
  const s = { ...input, updated_at: (/* @__PURE__ */ new Date()).toISOString() };
890
1008
  if (!Value.Check(CurrentWorkflowV1, s)) {
891
1009
  const errs = [...Value.Errors(CurrentWorkflowV1, s)].map((e) => e.message).join("; ");
892
1010
  throw new WorkflowStateError(`current-workflow schema validation failed: ${errs}`);
893
1011
  }
894
- const store = await readStoreRaw();
895
- 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;
896
1020
  await writeStoreRaw(store);
1021
+ if (s.handoff_authority) return;
897
1022
  await writeFileAtomic(statePath(), JSON.stringify(s, null, 2));
898
1023
  }
899
1024
  async function writeCurrentWorkflow(s) {
@@ -901,25 +1026,313 @@ async function writeCurrentWorkflow(s) {
901
1026
  }
902
1027
  async function mutateSubProgress(fn) {
903
1028
  await withLock(async () => {
904
- const s = await readCurrentWorkflow();
1029
+ const s = await readCurrentWorkflow(true);
905
1030
  if (!s) return;
906
1031
  const next = fn(s.sub_progress ?? []);
907
1032
  await writeCurrentWorkflowUnlocked({ ...s, sub_progress: next });
908
1033
  });
909
1034
  }
910
- async function mutateWorkflow(fn) {
1035
+ async function mutateWorkflow(fn, onMissing) {
911
1036
  await withLock(async () => {
912
- const s = await readCurrentWorkflow();
913
- if (!s) return;
914
- 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);
915
1044
  });
916
1045
  }
917
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
+ }
918
1086
  await withLock(async () => {
919
- const store = await readStoreRaw();
920
- 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;
921
1261
  });
922
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
+ }
923
1336
  async function activate(phase, checkpointPath = null) {
924
1337
  await writeCurrentWorkflow({
925
1338
  schemaVersion: SCHEMA_VERSIONS.currentWorkflow,
@@ -929,22 +1342,27 @@ async function activate(phase, checkpointPath = null) {
929
1342
  started_at: (/* @__PURE__ */ new Date()).toISOString()
930
1343
  });
931
1344
  }
932
- async function pause() {
933
- 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);
934
1350
  }
935
- async function complete() {
936
- await mutateWorkflow((s) => ({
937
- ...s,
938
- status: "complete",
939
- completed_at: (/* @__PURE__ */ new Date()).toISOString()
940
- }));
1351
+ async function complete(publish) {
1352
+ await mutateWorkflow((s) => {
1353
+ publish?.();
1354
+ return { ...s, status: "complete", completed_at: (/* @__PURE__ */ new Date()).toISOString() };
1355
+ }, publish);
941
1356
  }
942
- var WorkflowStateError, LockHeldError;
1357
+ var WorkflowStateError, LockHeldError, lockScope;
943
1358
  var init_state = __esm({
944
1359
  "src/checkpoint/state.ts"() {
945
1360
  init_harnessedRoot();
1361
+ init_platform();
946
1362
  init_schemaVersion();
947
1363
  init_atomicWrite();
1364
+ init_ownerPath();
1365
+ init_currentWorkflow_v1();
948
1366
  init_schema();
949
1367
  init_workflowStore();
950
1368
  WorkflowStateError = class extends Error {
@@ -962,6 +1380,7 @@ var init_state = __esm({
962
1380
  Object.setPrototypeOf(this, _LockHeldError.prototype);
963
1381
  }
964
1382
  };
1383
+ lockScope = new AsyncLocalStorage();
965
1384
  }
966
1385
  });
967
1386
 
@@ -974,13 +1393,34 @@ __export(workflowStore_exports, {
974
1393
  activeKey: () => activeKey,
975
1394
  listWorkflows: () => listWorkflows,
976
1395
  migrateRepoKeyCase: () => migrateRepoKeyCase,
1396
+ needsRepoKeyFold: () => needsRepoKeyFold,
977
1397
  normalizeRepoKey: () => normalizeRepoKey,
978
1398
  readIntent: () => readIntent,
1399
+ readLocalHandoff: () => readLocalHandoff,
1400
+ readRecoveryStore: () => readRecoveryStore,
979
1401
  readStoreAt: () => readStoreAt,
980
1402
  readStoreRaw: () => readStoreRaw,
981
1403
  repoKey: () => repoKey,
982
1404
  writeStoreRaw: () => writeStoreRaw
983
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
+ }
984
1424
  function storePath() {
985
1425
  return harnessedFile("workflows.json");
986
1426
  }
@@ -1009,12 +1449,15 @@ function activeKey(cwd = process.cwd()) {
1009
1449
  async function readStoreRaw() {
1010
1450
  return readStoreAt(getHarnessedRoot());
1011
1451
  }
1012
- async function readStoreAt(root) {
1452
+ async function readStoreAt(root, strict = false) {
1453
+ const path = join(root, "workflows.json");
1013
1454
  try {
1014
- const parsed = JSON.parse(await readFile(join(root, "workflows.json"), "utf8"));
1455
+ const parsed = JSON.parse(await readFile(path, "utf8"));
1015
1456
  if (Value.Check(WorkflowStoreV1, parsed)) return parsed;
1016
- } catch {
1457
+ } catch (error) {
1458
+ if (error.code === "ENOENT") return emptyStore();
1017
1459
  }
1460
+ if (strict) throw new Error(`workflow ledger is unreadable: ${path}`);
1018
1461
  return emptyStore();
1019
1462
  }
1020
1463
  async function writeStoreRaw(store) {
@@ -1026,8 +1469,8 @@ async function writeStoreRaw(store) {
1026
1469
  await mkdir(dirname(p8), { recursive: true });
1027
1470
  await writeFileAtomic(p8, JSON.stringify(store, null, 2));
1028
1471
  }
1029
- async function readIntent(cwd = process.cwd()) {
1030
- const store = await readStoreRaw();
1472
+ async function readIntent(cwd = process.cwd(), recovery = false) {
1473
+ const store = recovery ? await readRecoveryStore() : await readStoreRaw();
1031
1474
  return store.intents?.[activeKey(cwd)] ?? store.intents?.[repoKey(cwd)] ?? null;
1032
1475
  }
1033
1476
  async function listWorkflows() {
@@ -1052,6 +1495,9 @@ function needsFold(store, platform) {
1052
1495
  }
1053
1496
  return false;
1054
1497
  }
1498
+ function needsRepoKeyFold(store) {
1499
+ return process.platform === "win32" && needsFold(store, process.platform);
1500
+ }
1055
1501
  function foldMap(map, newer, platform) {
1056
1502
  const groups = /* @__PURE__ */ new Map();
1057
1503
  let folded = 0;
@@ -1076,6 +1522,47 @@ function foldMap(map, newer, platform) {
1076
1522
  }
1077
1523
  return { next, folded, archived };
1078
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
+ }
1079
1566
  async function migrateRepoKeyCase(platform = process.platform) {
1080
1567
  const noop = { folded: 0, archived: 0 };
1081
1568
  if (platform !== "win32") return noop;
@@ -1083,24 +1570,9 @@ async function migrateRepoKeyCase(platform = process.platform) {
1083
1570
  let result = noop;
1084
1571
  const { mutateStore: mutateStore2 } = await Promise.resolve().then(() => (init_state(), state_exports));
1085
1572
  await mutateStore2((store) => {
1086
- const w = foldMap(
1087
- store.workflows,
1088
- (a, b) => (a.updated_at ?? "") > (b.updated_at ?? ""),
1089
- platform
1090
- );
1091
- const r = store.retro_meta ? foldMap(
1092
- store.retro_meta,
1093
- (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 ?? ""),
1094
- platform
1095
- ) : void 0;
1096
- const i = store.intents ? foldMap(store.intents, (a, b) => a.ts > b.ts, platform) : void 0;
1097
- result = {
1098
- folded: w.folded + (r?.folded ?? 0) + (i?.folded ?? 0),
1099
- archived: w.archived + (r?.archived ?? 0) + (i?.archived ?? 0)
1100
- };
1101
- const next = { ...store, workflows: w.next };
1102
- if (r) next.retro_meta = r.next;
1103
- 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 };
1104
1576
  return next;
1105
1577
  });
1106
1578
  if (result.folded > 0 || result.archived > 0) {
@@ -1110,10 +1582,11 @@ async function migrateRepoKeyCase(platform = process.platform) {
1110
1582
  }
1111
1583
  return result;
1112
1584
  }
1113
- var RetroMetaEntry, IntentEntry, WorkflowStoreV1, PREMIGRATE;
1585
+ var RetroMetaEntry, IntentEntry, HandoffClaim, WorkflowStoreV1, PREMIGRATE;
1114
1586
  var init_workflowStore = __esm({
1115
1587
  "src/checkpoint/workflowStore.ts"() {
1116
1588
  init_harnessedRoot();
1589
+ init_hostInstallContext();
1117
1590
  init_platform();
1118
1591
  init_schemaVersion();
1119
1592
  init_atomicWrite();
@@ -1139,6 +1612,19 @@ var init_workflowStore = __esm({
1139
1612
  },
1140
1613
  { additionalProperties: false }
1141
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
+ );
1142
1628
  WorkflowStoreV1 = Type.Object(
1143
1629
  {
1144
1630
  schemaVersion: Type.Literal(SCHEMA_VERSIONS.workflowStore),
@@ -1146,7 +1632,12 @@ var init_workflowStore = __esm({
1146
1632
  // Additive-optional (no schemaVersion bump — old stores Value.Check-pass).
1147
1633
  retro_meta: Type.Optional(Type.Record(Type.String(), RetroMetaEntry)),
1148
1634
  // 4.22.0 — additive-optional, same rationale.
1149
- 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
+ )
1150
1641
  },
1151
1642
  { additionalProperties: false }
1152
1643
  );
@@ -1374,7 +1865,10 @@ function markSub(entries, sub, status, opts) {
1374
1865
  }
1375
1866
  const current = entries[idx];
1376
1867
  const updated = { ...current, status };
1377
- 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
+ }
1378
1872
  if (opts?.evidence !== void 0) updated.evidence = opts.evidence;
1379
1873
  if (opts?.evidence_status !== void 0) updated.evidence_status = opts.evidence_status;
1380
1874
  if (opts?.completion_claim !== void 0) updated.completion_claim = opts.completion_claim;
@@ -1408,6 +1902,7 @@ function reopenSub(entries, sub, reason) {
1408
1902
  next[idx] = {
1409
1903
  ...rest,
1410
1904
  status: "pending",
1905
+ result_attempt: null,
1411
1906
  fail_count: (current.fail_count ?? 0) + 1,
1412
1907
  reason
1413
1908
  };
@@ -2249,8 +2744,8 @@ function stripAgentsMdSection(body) {
2249
2744
  function insertAgentsMdSection(body, section) {
2250
2745
  const base = stripAgentsMdSection(body);
2251
2746
  if (section === "") return base;
2252
- const sep6 = base === "" || base.endsWith("\n\n") ? "" : base.endsWith("\n") ? "\n" : "\n\n";
2253
- return `${base}${sep6}${section}`;
2747
+ const sep7 = base === "" || base.endsWith("\n\n") ? "" : base.endsWith("\n") ? "\n" : "\n\n";
2748
+ return `${base}${sep7}${section}`;
2254
2749
  }
2255
2750
  async function resolveCommandNames(workflowsDir) {
2256
2751
  const { readdir: readdir28 } = await import('fs/promises');
@@ -3453,9 +3948,9 @@ function redactRecord(r) {
3453
3948
  }
3454
3949
  function renderHumanTable(records) {
3455
3950
  const header = `${"ts".padEnd(19)} | ${"phase".padEnd(6)} | ${"category".padEnd(11)} | ${"matched_rule_id".padEnd(20)} | outcome`;
3456
- const sep6 = `${"-".repeat(19)}-+-${"-".repeat(6)}-+-${"-".repeat(11)}-+-${"-".repeat(20)}-+--------`;
3951
+ const sep7 = `${"-".repeat(19)}-+-${"-".repeat(6)}-+-${"-".repeat(11)}-+-${"-".repeat(20)}-+--------`;
3457
3952
  console.log(header);
3458
- console.log(sep6);
3953
+ console.log(sep7);
3459
3954
  for (const r of records) {
3460
3955
  const ts = r.ts.slice(0, 19);
3461
3956
  const phase = r.phase.padEnd(6);
@@ -3465,7 +3960,7 @@ function renderHumanTable(records) {
3465
3960
  }
3466
3961
  }
3467
3962
  function pipeToJq(filterExpr, lines) {
3468
- return new Promise((resolve42, reject) => {
3963
+ return new Promise((resolve44, reject) => {
3469
3964
  const child = spawn("jq", [filterExpr], {
3470
3965
  stdio: ["pipe", "inherit", "inherit"],
3471
3966
  windowsHide: true
@@ -3474,12 +3969,12 @@ function pipeToJq(filterExpr, lines) {
3474
3969
  const e = err2;
3475
3970
  if (e.code === "ENOENT") {
3476
3971
  console.error(t("audit_log.jq_missing"));
3477
- resolve42(1);
3972
+ resolve44(1);
3478
3973
  } else {
3479
3974
  reject(err2);
3480
3975
  }
3481
3976
  });
3482
- child.on("close", (code2) => resolve42(code2 ?? 0));
3977
+ child.on("close", (code2) => resolve44(code2 ?? 0));
3483
3978
  child.stdin.on("error", (err2) => {
3484
3979
  if (err2.code !== "EPIPE") reject(err2);
3485
3980
  });
@@ -4664,54 +5159,6 @@ var init_checkDocs = __esm({
4664
5159
  }
4665
5160
  });
4666
5161
 
4667
- // src/platform/runDeps.ts
4668
- function captureRunDeps() {
4669
- const stdout2 = [];
4670
- const stderr = [];
4671
- const deps = {
4672
- exit(code2) {
4673
- throw new ExitError(code2);
4674
- },
4675
- log: (...args) => {
4676
- stdout2.push(args.map(String).join(" "));
4677
- },
4678
- error: (...args) => {
4679
- stderr.push(args.map(String).join(" "));
4680
- },
4681
- warn: (...args) => {
4682
- stderr.push(args.map(String).join(" "));
4683
- }
4684
- };
4685
- return { deps, stdout: stdout2, stderr };
4686
- }
4687
- var ExitError, defaultRunDeps;
4688
- var init_runDeps = __esm({
4689
- "src/platform/runDeps.ts"() {
4690
- ExitError = class extends Error {
4691
- constructor(code2) {
4692
- super(`process.exit(${code2})`);
4693
- this.code = code2;
4694
- this.name = "ExitError";
4695
- }
4696
- code;
4697
- };
4698
- defaultRunDeps = {
4699
- exit(code2) {
4700
- return process.exit(code2);
4701
- },
4702
- log: (...args) => {
4703
- console.log(...args);
4704
- },
4705
- error: (...args) => {
4706
- console.error(...args);
4707
- },
4708
- warn: (...args) => {
4709
- console.warn(...args);
4710
- }
4711
- };
4712
- }
4713
- });
4714
-
4715
5162
  // src/workflow/lib/promiseExtract.ts
4716
5163
  function extractPromise(text) {
4717
5164
  const match = text.match(PROMISE_PATTERN);
@@ -4807,30 +5254,149 @@ var init_ralphLoop = __esm({
4807
5254
  };
4808
5255
  }
4809
5256
  });
4810
-
4811
- // src/checkpoint/completionClaim.ts
4812
- var completionClaim_exports = {};
4813
- __export(completionClaim_exports, {
4814
- verifyCompletionClaim: () => verifyCompletionClaim
4815
- });
5257
+ function resultAttemptLine(id) {
5258
+ return `${ATTEMPT_PREFIX}${id}`;
5259
+ }
4816
5260
  async function verifyCompletionClaim(input) {
4817
5261
  if (input.resultFile) {
4818
- let text;
5262
+ let bytes;
4819
5263
  try {
4820
- text = await readFile(input.resultFile, "utf8");
5264
+ bytes = await readFile(input.resultFile);
4821
5265
  } catch {
4822
5266
  return { verdict: "incomplete", source: input.resultFile };
4823
5267
  }
4824
- 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
+ };
4825
5278
  }
4826
5279
  if (typeof input.result === "string" && input.result.trim() !== "") {
4827
- 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
+ };
5287
+ }
5288
+ return { verdict: "not_provided", source: null };
5289
+ }
5290
+ var ATTEMPT_PREFIX;
5291
+ var init_completionClaim = __esm({
5292
+ "src/checkpoint/completionClaim.ts"() {
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;
4828
5358
  }
4829
- return { verdict: "not_provided", source: null };
4830
5359
  }
4831
- var init_completionClaim = __esm({
4832
- "src/checkpoint/completionClaim.ts"() {
4833
- init_ralphLoop();
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";
4834
5400
  }
4835
5401
  });
4836
5402
 
@@ -4847,18 +5413,6 @@ var init_failure = __esm({
4847
5413
  LEGACY_FAILED_PREFIX = "FAILED:";
4848
5414
  }
4849
5415
  });
4850
- function ownerHash(ownerKey = activeKey()) {
4851
- return createHash("sha256").update(ownerKey).digest("hex").slice(0, 16);
4852
- }
4853
- function ownerPath(area, segments, ownerKey = activeKey()) {
4854
- return join(harnessedSubdir(area), ownerHash(ownerKey), ...segments);
4855
- }
4856
- var init_ownerPath = __esm({
4857
- "src/checkpoint/ownerPath.ts"() {
4858
- init_harnessedRoot();
4859
- init_workflowStore();
4860
- }
4861
- });
4862
5416
  function estimateTokens(s) {
4863
5417
  return Math.ceil(Buffer.byteLength(s, "utf8") / 4);
4864
5418
  }
@@ -4921,6 +5475,11 @@ async function activatePhase(phaseId) {
4921
5475
  return { checkpointPath };
4922
5476
  }
4923
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) {
4924
5483
  if (ctx.phaseId === "unknown") {
4925
5484
  console.error(
4926
5485
  `[harnessed] WARN engineHook: phaseId="unknown" \u2014 checkpoint paths fall back to ${ownerPath("checkpoints", ["unknown.json"])} (Karpathy fail-loud non-blocking; W-04 mitigation)`
@@ -4938,9 +5497,6 @@ async function completePhase(ctx) {
4938
5497
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
4939
5498
  archive_path: `${ownerPath("archive", [`phase-${ctx.phaseId}`])}/`
4940
5499
  });
4941
- if (ctx.transitionWorkflowComplete !== false) {
4942
- await complete();
4943
- }
4944
5500
  }
4945
5501
  var init_engineHook = __esm({
4946
5502
  "src/checkpoint/engineHook.ts"() {
@@ -5014,7 +5570,7 @@ function resolveWindowsBin(bin, env = process.env, isFile = (p8) => existsSync(p
5014
5570
  const candidates = extname(bin) ? [""] : exts;
5015
5571
  for (const dir of dirs) {
5016
5572
  for (const ext of candidates) {
5017
- const p8 = join21(dir, `${bin}${ext}`);
5573
+ const p8 = join22(dir, `${bin}${ext}`);
5018
5574
  if (isFile(p8)) return p8;
5019
5575
  }
5020
5576
  }
@@ -5029,10 +5585,10 @@ function planWindowsSpawn(bin, args, resolved) {
5029
5585
  const line = [escapeCommand(resolved), ...args.map((a) => escapeArgument(a))].join(" ");
5030
5586
  return { command: "cmd.exe", args: ["/d", "/s", "/c", `"${line}"`], verbatim: true };
5031
5587
  }
5032
- var extname, join21, META;
5588
+ var extname, join22, META;
5033
5589
  var init_winSpawn = __esm({
5034
5590
  "src/installers/lib/winSpawn.ts"() {
5035
- ({ extname, join: join21 } = win32);
5591
+ ({ extname, join: join22 } = win32);
5036
5592
  META = /([()\][%!^"`<>&|;, *?])/g;
5037
5593
  }
5038
5594
  });
@@ -5055,7 +5611,7 @@ function withHostInstallEnv(env, hostContext) {
5055
5611
  return { ...result, ...pins };
5056
5612
  }
5057
5613
  function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3, hostContext) {
5058
- return new Promise((resolve42) => {
5614
+ return new Promise((resolve44) => {
5059
5615
  const isWin = (hostContext?.os ?? process.platform) === "win32";
5060
5616
  const envOpts = hostContext ? { env: withHostInstallEnv(process.env, hostContext) } : {};
5061
5617
  const stdio = ["ignore", "pipe", "pipe"];
@@ -5083,17 +5639,17 @@ function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3, hostContext) {
5083
5639
  });
5084
5640
  const timer = setTimeout(() => {
5085
5641
  killProcessTree(child);
5086
- resolve42({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
5642
+ resolve44({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
5087
5643
  }, timeoutMs);
5088
5644
  child.on("error", (e) => {
5089
5645
  clearTimeout(timer);
5090
5646
  const enoent = e.code === "ENOENT";
5091
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;
5092
- resolve42({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
5648
+ resolve44({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
5093
5649
  });
5094
5650
  child.on("close", (code2) => {
5095
5651
  clearTimeout(timer);
5096
- resolve42({ exitCode: code2 ?? -1, stdout: stdout2, stderr });
5652
+ resolve44({ exitCode: code2 ?? -1, stdout: stdout2, stderr });
5097
5653
  });
5098
5654
  });
5099
5655
  }
@@ -5407,8 +5963,8 @@ async function releaseLockIdempotently(release) {
5407
5963
  var sleep;
5408
5964
  var init_lockContention = __esm({
5409
5965
  "src/platform/lockContention.ts"() {
5410
- sleep = (ms) => new Promise((resolve42) => {
5411
- setTimeout(resolve42, ms);
5966
+ sleep = (ms) => new Promise((resolve44) => {
5967
+ setTimeout(resolve44, ms);
5412
5968
  });
5413
5969
  }
5414
5970
  });
@@ -6709,7 +7265,7 @@ function estTokens(x) {
6709
7265
  return Math.ceil(Buffer.byteLength(JSON.stringify(x) ?? "", "utf8") / 4);
6710
7266
  }
6711
7267
  function isEvictable(e) {
6712
- if ((e.fail_count ?? 0) > 0) return false;
7268
+ if ((e.fail_count ?? 0) > 0 || e.result_attempt !== void 0) return false;
6713
7269
  return e.status === "done" || e.status === "skipped" || e.status === "rejected";
6714
7270
  }
6715
7271
  function compactLedger(entries) {
@@ -6737,8 +7293,8 @@ function mergeCounts(prev, next) {
6737
7293
  for (const [k, v] of Object.entries(next)) out[k] = (out[k] ?? 0) + v;
6738
7294
  return out;
6739
7295
  }
6740
- async function compactWorkflow() {
6741
- const wf = await readCurrentWorkflow();
7296
+ async function compactWorkflow(condition) {
7297
+ const wf = await readCurrentWorkflow(true);
6742
7298
  if (!wf) {
6743
7299
  return {
6744
7300
  kept: [],
@@ -6753,8 +7309,9 @@ async function compactWorkflow() {
6753
7309
  }
6754
7310
  const probe = compactLedger(wf.sub_progress ?? []);
6755
7311
  if (probe.evicted === 0) return { ...probe, phase: wf.phase };
6756
- let result = { ...probe, phase: wf.phase };
7312
+ let result = { ...probe, evicted: 0, phase: wf.phase };
6757
7313
  await mutateWorkflow((cur) => {
7314
+ if (condition && !condition(cur)) return cur;
6758
7315
  const r = compactLedger(cur.sub_progress ?? []);
6759
7316
  result = { ...r, phase: cur.phase };
6760
7317
  if (r.evicted === 0) return cur;
@@ -7215,11 +7772,17 @@ async function adoptSlot(options = {}) {
7215
7772
  }
7216
7773
  const sourceKey = candidates[0];
7217
7774
  const slot = source.workflows[sourceKey];
7775
+ if (slot.handoff_authority) return refuse({ kind: "source-enrolled", sourceKey });
7218
7776
  const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
7219
7777
  let archivedKey;
7220
7778
  let retroMeta;
7221
7779
  try {
7222
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
+ }
7223
7786
  const occupant = store.workflows[key];
7224
7787
  if (occupant?.status === "active") {
7225
7788
  throw new AdoptRefused({
@@ -7234,7 +7797,15 @@ async function adoptSlot(options = {}) {
7234
7797
  archivedKey = `${key}${DISPLACED}${updatedAt}`;
7235
7798
  workflows[archivedKey] = occupant;
7236
7799
  }
7237
- 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
+ };
7238
7809
  const next = { ...store, workflows };
7239
7810
  const srcRetro = source.retro_meta?.[key];
7240
7811
  if (srcRetro) {
@@ -7370,15 +7941,8 @@ async function absorbIntentFor(sub) {
7370
7941
  } catch {
7371
7942
  }
7372
7943
  }
7373
- async function readLedgerSafe(deps = defaultRunDeps) {
7374
- try {
7375
- const { readCurrentWorkflow: readCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
7376
- const wf = await readCurrentWorkflow2();
7377
- return wf?.sub_progress ?? [];
7378
- } catch (e) {
7379
- deps.warn(`[harnessed] ledger read skipped (fail-soft): ${e.message}`);
7380
- return [];
7381
- }
7944
+ function sameWorkflowRun(before, current) {
7945
+ return before !== null && before.started_at === current.started_at && before.phase === current.phase;
7382
7946
  }
7383
7947
  function enforceSerialOrder(action, sub, blockers, force, deps = defaultRunDeps) {
7384
7948
  if (blockers.length === 0) return true;
@@ -7404,20 +7968,51 @@ function parseWaitSeconds(raw) {
7404
7968
  return seconds;
7405
7969
  }
7406
7970
  function sleep2(ms) {
7407
- return new Promise((resolve42) => setTimeout(resolve42, ms));
7971
+ return new Promise((resolve44) => setTimeout(resolve44, ms));
7408
7972
  }
7409
- async function waitForResultClaim(resultFile, seconds, pollMs) {
7410
- const { verifyCompletionClaim: verifyCompletionClaim2 } = await Promise.resolve().then(() => (init_completionClaim(), completionClaim_exports));
7973
+ async function waitForResultClaim(input, seconds, pollMs) {
7411
7974
  const deadline = Date.now() + seconds * 1e3;
7412
7975
  for (; ; ) {
7413
- const claim = await verifyCompletionClaim2({ resultFile });
7414
- if (claim.verdict === "complete") return true;
7976
+ const claim = await verifyCompletionClaim(input);
7977
+ const ready = claim.verdict === "complete" && (!input.attemptId || !!claim.attemptDigest);
7415
7978
  const remaining = deadline - Date.now();
7416
- if (remaining <= 0) return false;
7979
+ if (ready || remaining <= 0) return { claim, ready };
7417
7980
  await sleep2(Math.min(pollMs, remaining));
7418
7981
  }
7419
7982
  }
7420
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
+ }
7421
8016
  const { activatePhase: activatePhase2 } = await Promise.resolve().then(() => (init_engineHook(), engineHook_exports));
7422
8017
  try {
7423
8018
  const { stat: statFs } = await import('fs/promises');
@@ -7444,10 +8039,11 @@ async function runCheckpointStart(sub, opts, deps = defaultRunDeps) {
7444
8039
  if (det.active) {
7445
8040
  const ge = await Promise.resolve().then(() => (init_guard_exemption(), guard_exemption_exports));
7446
8041
  const isTty = process.stdin.isTTY === true && process.stdout.isTTY === true;
8042
+ const { withWorkflowEffects: withWorkflowEffects2 } = await Promise.resolve().then(() => (init_state(), state_exports));
7447
8043
  const flowResult = await ge.runExemptionFlow({
7448
8044
  probe: () => ge.probeExemptCapability(),
7449
8045
  readEnvValue: () => ge.readCurrentEnvValue(),
7450
- merge: (value) => ge.applyEnvExemption(value),
8046
+ merge: (value) => withWorkflowEffects2(() => ge.applyEnvExemption(value)),
7451
8047
  print: (line) => deps.error(line),
7452
8048
  ...isTty ? {
7453
8049
  confirm: async () => {
@@ -7511,39 +8107,75 @@ async function runCheckpointStart(sub, opts, deps = defaultRunDeps) {
7511
8107
  }
7512
8108
  async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
7513
8109
  const { completePhase: completePhase2 } = await Promise.resolve().then(() => (init_engineHook(), engineHook_exports));
7514
- const preLedger = await readLedgerSafe(deps);
7515
- 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
+ );
7516
8118
  deps.exit(1);
7517
8119
  return;
7518
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
+ };
7519
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
+ };
7520
8149
  let waitTimeoutMessage;
7521
- if (waitSeconds > 0) {
8150
+ let claim;
8151
+ if (waitSeconds > 0 && opts.resultFile) {
7522
8152
  const resultFile = opts.resultFile;
7523
- if (!resultFile) {
7524
- deps.error(
7525
- "[harnessed] checkpoint complete: --wait \u5FC5\u987B\u642D\u914D --result-file \u2014\u2014 \u6CA1\u6709\u53EF\u7B49\u5F85\u7684\u7ED3\u679C\u6587\u4EF6"
7526
- );
7527
- deps.exit(2);
7528
- return;
7529
- }
7530
8153
  const pollMs = opts.waitPollMs ?? RESULT_WAIT_POLL_MS;
7531
8154
  deps.log(
7532
8155
  `[harnessed] \u7B49\u5F85 ${waitSeconds}s \u5185 ${resultFile} \u643A\u5E26\u5B8C\u6210\u6807\u8BB0\uFF08\u6BCF ${pollMs}ms \u8F6E\u8BE2\u4E00\u6B21\uFF09`
7533
8156
  );
7534
- const ready = await waitForResultClaim(resultFile, waitSeconds, pollMs);
7535
- if (ready) {
8157
+ const waited = await waitForResultClaim(claimInput, waitSeconds, pollMs);
8158
+ claim = waited.claim;
8159
+ if (waited.ready) {
7536
8160
  deps.log(`[harnessed] \u7ED3\u679C\u6587\u4EF6\u5DF2\u5C31\u7EEA: ${resultFile}`);
7537
8161
  } else {
7538
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`;
7539
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;
7540
8172
  }
7541
8173
  const { checkArtifacts: checkArtifacts2 } = await Promise.resolve().then(() => (init_evidence(), evidence_exports));
7542
- const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
7543
8174
  const { getAssetsRoot: getAssetsRoot3 } = await Promise.resolve().then(() => (init_assetsRoot(), assetsRoot_exports));
7544
8175
  const result = await checkArtifacts2(sub, getAssetsRoot3());
7545
8176
  const { checkPlanningSync: checkPlanningSync2 } = await Promise.resolve().then(() => (init_evidence(), evidence_exports));
7546
8177
  const syncResult = await checkPlanningSync2(process.cwd(), null);
8178
+ const syncMissing = sub === "research" && before === null ? [] : syncResult.missing;
7547
8179
  const boundaryBlocks = [];
7548
8180
  try {
7549
8181
  const { checkTddBoundary: checkTddBoundary2, isTddEvidencePath: isTddEvidencePath2 } = await Promise.resolve().then(() => (init_tddBoundary(), tddBoundary_exports));
@@ -7556,11 +8188,6 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
7556
8188
  }
7557
8189
  } catch {
7558
8190
  }
7559
- const { verifyCompletionClaim: verifyCompletionClaim2 } = await Promise.resolve().then(() => (init_completionClaim(), completionClaim_exports));
7560
- const claim = await verifyCompletionClaim2({
7561
- ...opts.result !== void 0 ? { result: opts.result } : {},
7562
- ...opts.resultFile !== void 0 ? { resultFile: opts.resultFile } : {}
7563
- });
7564
8191
  const claimBlocks = claim.verdict === "incomplete" ? [
7565
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`
7566
8193
  ] : [];
@@ -7572,7 +8199,7 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
7572
8199
  const waitBlocks = waitTimeoutMessage !== void 0 ? [waitTimeoutMessage] : [];
7573
8200
  const allMissing = [
7574
8201
  ...result.missing,
7575
- ...syncResult.missing,
8202
+ ...syncMissing,
7576
8203
  ...boundaryBlocks,
7577
8204
  ...claimBlocks,
7578
8205
  ...waitBlocks
@@ -7582,7 +8209,7 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
7582
8209
  `[harnessed] checkpoint complete ${waitTimeoutMessage}\uFF08--force: \u5DF2\u8BB0\u4E3A audited override\uFF09`
7583
8210
  );
7584
8211
  }
7585
- if (allMissing.length > 0 && !opts.force) {
8212
+ if (allMissing.length > 0 && !opts.force && !(attempt && entry?.status === "done")) {
7586
8213
  deps.error(
7587
8214
  `[harnessed] checkpoint complete BLOCKED: ${sub} \u2014 ${allMissing.length} item(s) missing (evidence guard + .planning/ sync, fail-closed):`
7588
8215
  );
@@ -7600,25 +8227,78 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
7600
8227
  evidence_status: evidenceStatus,
7601
8228
  completion_claim: claim.verdict
7602
8229
  };
7603
- await mutateSubProgress2((e) => markIfSeeded(e, sub, "done", markOpts));
7604
- await absorbIntentFor(sub);
7605
8230
  const { collectScaleMetrics: collectScaleMetrics2, assessScale: assessScale2 } = await Promise.resolve().then(() => (init_scale(), scale_exports));
7606
- const { readCurrentWorkflow: readCurrentWorkflow2, mutateWorkflow: mutateWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
7607
- const afterMark = await readCurrentWorkflow2();
7608
- if (afterMark) {
7609
- const metrics = await collectScaleMetrics2(process.cwd(), afterMark.sub_progress ?? []);
7610
- const verifyMode = assessScale2(metrics);
7611
- await mutateWorkflow2((s) => ({ ...s, verify_mode: verifyMode }));
7612
- }
7613
8231
  const { nextPending: nextPending2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
7614
- const allResolved = nextPending2(afterMark?.sub_progress ?? []) === null;
7615
- await completePhase2({
8232
+ const verifyMode = before ? assessScale2(await collectScaleMetrics2(process.cwd(), markIfSeeded(preLedger, sub, "done"))) : void 0;
8233
+ const publish = () => completePhase2({
7616
8234
  phaseId: sub,
7617
8235
  status: "complete",
7618
8236
  lastTask: opts.summary ?? `phase ${sub} complete`,
7619
- transitionWorkflowComplete: allResolved
8237
+ // The callback owns the workflow lock. Do not re-enter it through the engine hook.
8238
+ transitionWorkflowComplete: false
7620
8239
  });
7621
- 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) {
7622
8302
  try {
7623
8303
  const { maybeInitCodeGraph: maybeInitCodeGraph2 } = await Promise.resolve().then(() => (init_codegraphInit(), codegraphInit_exports));
7624
8304
  maybeInitCodeGraph2({ note: (m) => deps.error(m) });
@@ -7627,14 +8307,16 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
7627
8307
  }
7628
8308
  if (allResolved && afterMark) {
7629
8309
  const { captureWorkflowLearnings: captureWorkflowLearnings2 } = await Promise.resolve().then(() => (init_learnings(), learnings_exports));
7630
- 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();
7631
8313
  if (captured > 0) {
7632
8314
  deps.log(`[harnessed] captured ${captured} learning(s) \u2192 .planning/LEARNINGS.md`);
7633
8315
  }
7634
8316
  }
7635
8317
  const { shouldAutoCompact: shouldAutoCompact2, compactWorkflow: compactWorkflow2 } = await Promise.resolve().then(() => (init_compact(), compact_exports));
7636
8318
  if (shouldAutoCompact2(opts.tokens != null ? Number(opts.tokens) : void 0)) {
7637
- const c = await compactWorkflow2();
8319
+ const c = await compactWorkflow2(stillCommitted);
7638
8320
  if (c.evicted > 0) {
7639
8321
  deps.log(
7640
8322
  `[harnessed] auto-compact: evicted ${c.evicted} resolved entries (-${c.pct_saved}% tokens)`
@@ -7646,24 +8328,24 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
7646
8328
  const { defaultShipReady: defaultShipReady2 } = await Promise.resolve().then(() => (init_shipReady(), shipReady_exports));
7647
8329
  const { incrementPhases: incrementPhases2, isRetroDue: isRetroDue2, retroThreshold: retroThreshold2 } = await Promise.resolve().then(() => (init_retroMeta(), retroMeta_exports));
7648
8330
  const { mutateStore: mutateStore2, mutateWorkflow: mutateWorkflow3 } = await Promise.resolve().then(() => (init_state(), state_exports));
7649
- 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));
7650
8332
  const ship = defaultShipReady2(process.cwd());
7651
8333
  const key = repoKey2();
7652
8334
  const threshold = retroThreshold2(process.env);
7653
8335
  let retroDue = false;
7654
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;
7655
8340
  const meta = { ...store.retro_meta ?? {} };
7656
8341
  const next = incrementPhases2(meta[key]);
7657
8342
  meta[key] = next;
7658
8343
  retroDue = isRetroDue2(next.phases_since_retro, threshold);
7659
8344
  return { ...store, retro_meta: meta };
7660
8345
  });
7661
- await mutateWorkflow3((s) => ({
7662
- ...s,
7663
- ship_ready: ship.ready,
7664
- ship_commits: ship.commits,
7665
- retro_due: retroDue
7666
- }));
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
+ );
7667
8349
  } catch {
7668
8350
  }
7669
8351
  }
@@ -7682,7 +8364,15 @@ async function runCheckpointFail(sub, opts, deps = defaultRunDeps) {
7682
8364
  return;
7683
8365
  }
7684
8366
  const spawnFailure = isSpawnFailure2(opts.failure) ? opts.failure : void 0;
7685
- 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
+ }
7686
8376
  if (!enforceSerialOrder("fail", sub, findSerialBlockers(preLedger, sub), opts.force, deps)) {
7687
8377
  deps.exit(1);
7688
8378
  return;
@@ -7704,26 +8394,47 @@ async function runCheckpointFail(sub, opts, deps = defaultRunDeps) {
7704
8394
  });
7705
8395
  const { resolveAttemptBudget: resolveAttemptBudget2, isBudgetExhausted: isBudgetExhausted2 } = await Promise.resolve().then(() => (init_budget(), budget_exports));
7706
8396
  const budget = await resolveAttemptBudget2(sub, assetsRoot);
7707
- const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
7708
- await mutateSubProgress2(
7709
- (e) => markIfSeeded(e, sub, "failed", {
7710
- attempt_budget: budget,
7711
- ...nextProgress ? { progress: nextProgress } : {},
7712
- // T4 — omitted when absent so an untagged failure leaves NO key on the entry
7713
- // (13 eval goldens compare the serialized ledger verbatim).
7714
- ...spawnFailure ? { spawn_failure: spawnFailure } : {}
7715
- })
7716
- );
7717
- await absorbIntentFor(sub);
7718
- await completePhase2({
8397
+ const publish = () => completePhase2({
7719
8398
  phaseId: sub,
7720
8399
  status: "failed",
7721
8400
  lastTask: `FAILED: ${opts.summary ?? ""}`,
7722
8401
  transitionWorkflowComplete: false
7723
8402
  });
7724
- 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);
7725
8437
  const { detectLoop: detectLoop2, LOOP_THRESHOLD: LOOP_THRESHOLD2 } = await Promise.resolve().then(() => (init_breakLoop(), breakLoop_exports));
7726
- const latest = await readCurrentWorkflow2();
7727
8438
  const loops = detectLoop2(latest?.sub_progress ?? []);
7728
8439
  const looped = loops.find((l) => l.sub === sub);
7729
8440
  if (looped) {
@@ -7758,7 +8469,7 @@ async function runCheckpointReopen(sub, opts, deps = defaultRunDeps) {
7758
8469
  return;
7759
8470
  }
7760
8471
  const { readCurrentWorkflow: readCurrentWorkflow2, mutateWorkflow: mutateWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
7761
- const wf = await readCurrentWorkflow2();
8472
+ const wf = await readCurrentWorkflow2(true);
7762
8473
  if (!wf) {
7763
8474
  deps.error("[harnessed] checkpoint reopen: no active workflow \u2014 nothing to send back.");
7764
8475
  deps.exit(1);
@@ -7886,6 +8597,12 @@ function renderAdoptRefusal(r) {
7886
8597
  lines.push(" \u5728\u6E90\u5BBF\u4E3B\u4FA7\u628A\u591A\u4F59\u7684 complete / pause \u6389\u3001\u53EA\u7559\u4E00\u4E2A,\u518D adopt\u3002");
7887
8598
  return lines;
7888
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
+ ];
7889
8606
  case "dest-occupied": {
7890
8607
  const subs = r.mine.total > 0 ? `, ${r.mine.done}/${r.mine.total} subs done` : "";
7891
8608
  return [
@@ -7921,6 +8638,24 @@ function renderAdoptSuccess(r) {
7921
8638
  return lines;
7922
8639
  }
7923
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
+ }
7924
8659
  const { adoptSlot: adoptSlot2 } = await Promise.resolve().then(() => (init_adoptSlot(), adoptSlot_exports));
7925
8660
  const outcome = await adoptSlot2({ ...opts.from !== void 0 ? { from: opts.from } : {} });
7926
8661
  if (!outcome.ok) {
@@ -7935,6 +8670,9 @@ function registerCheckpoint(program2) {
7935
8670
  program2.command("checkpoint <action> [sub]").description(
7936
8671
  "Record workflow progress: intent | start | complete | fail | reopen <sub-workflow>, or adopt (cross-host relay) (writes under the active host state root)"
7937
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(
7938
8676
  "--force",
7939
8677
  "complete/fail \u2014 override a fail-closed guard: the missing-artifact evidence block (complete; records overridden) or the serial-order guard"
7940
8678
  ).option(
@@ -7961,7 +8699,7 @@ function registerCheckpoint(program2) {
7961
8699
  ).option(
7962
8700
  "--from <host>",
7963
8701
  `adopt only \u2014 which host's ledger to copy this repo's slot FROM: ${HOST_IDS.join(" | ")} (omitted \u2192 the other host)`
7964
- ).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(
7965
8703
  async (action, sub, opts) => {
7966
8704
  if (!isAction(action)) {
7967
8705
  console.error(
@@ -7977,6 +8715,31 @@ function registerCheckpoint(program2) {
7977
8715
  process.exit(2);
7978
8716
  return;
7979
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
+ }
7980
8743
  if (action === "adopt") {
7981
8744
  await runCheckpointAdopt(opts);
7982
8745
  return;
@@ -8064,11 +8827,13 @@ function registerCheckpoint(program2) {
8064
8827
  var ACTIONS, RESULT_WAIT_MAX_SECONDS, RESULT_WAIT_POLL_MS;
8065
8828
  var init_checkpoint = __esm({
8066
8829
  "src/cli/checkpoint.ts"() {
8830
+ init_completionClaim();
8067
8831
  init_path_guard();
8068
8832
  init_platform();
8069
8833
  init_runDeps();
8834
+ init_resultArtifact();
8070
8835
  init_ledger();
8071
- ACTIONS = ["start", "complete", "fail", "reopen", "intent", "adopt"];
8836
+ ACTIONS = ["start", "complete", "fail", "reopen", "intent", "adopt", "handoff"];
8072
8837
  RESULT_WAIT_MAX_SECONDS = 600;
8073
8838
  RESULT_WAIT_POLL_MS = 2e3;
8074
8839
  }
@@ -8214,8 +8979,8 @@ function compute(d) {
8214
8979
  }
8215
8980
  const gitFirst = d.where("git")[0];
8216
8981
  if (gitFirst && /git\.exe$/i.test(gitFirst)) {
8217
- const root = dirname15(dirname15(gitFirst));
8218
- 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")]) {
8219
8984
  if (d.exists(cand) && usable(cand)) return { path: cand, source: "git-derived", wslOnPath };
8220
8985
  }
8221
8986
  }
@@ -8223,13 +8988,13 @@ function compute(d) {
8223
8988
  d.env.ProgramFiles,
8224
8989
  d.env.ProgramW6432,
8225
8990
  d.env["ProgramFiles(x86)"],
8226
- d.env.LOCALAPPDATA ? join34(d.env.LOCALAPPDATA, "Programs") : void 0
8991
+ d.env.LOCALAPPDATA ? join35(d.env.LOCALAPPDATA, "Programs") : void 0
8227
8992
  ];
8228
8993
  for (const base of bases) {
8229
8994
  if (!base) continue;
8230
8995
  for (const cand of [
8231
- join34(base, "Git", "bin", "bash.exe"),
8232
- join34(base, "Git", "usr", "bin", "bash.exe")
8996
+ join35(base, "Git", "bin", "bash.exe"),
8997
+ join35(base, "Git", "usr", "bin", "bash.exe")
8233
8998
  ]) {
8234
8999
  if (d.exists(cand) && usable(cand))
8235
9000
  return { path: cand, source: "standard-location", wslOnPath };
@@ -8242,10 +9007,10 @@ function compute(d) {
8242
9007
  }
8243
9008
  return { path: "bash", source: "path-fallback" };
8244
9009
  }
8245
- var dirname15, join34, WSL_STUB_RE, cache4;
9010
+ var dirname16, join35, WSL_STUB_RE, cache4;
8246
9011
  var init_resolveBash = __esm({
8247
9012
  "src/installers/lib/resolveBash.ts"() {
8248
- ({ dirname: dirname15, join: join34 } = win32);
9013
+ ({ dirname: dirname16, join: join35 } = win32);
8249
9014
  WSL_STUB_RE = /[\\/](windows[\\/](system32|sysnative|syswow64)|microsoft[\\/]windowsapps)[\\/]bash\.exe$/i;
8250
9015
  cache4 = null;
8251
9016
  }
@@ -10702,7 +11467,7 @@ async function withAppServer(deps, body) {
10702
11467
  const call = (method, params) => {
10703
11468
  if (closed) return Promise.reject(closed);
10704
11469
  const id = nextId++;
10705
- return new Promise((resolve42, reject) => {
11470
+ return new Promise((resolve44, reject) => {
10706
11471
  const timer = setTimeout(() => {
10707
11472
  pending.delete(id);
10708
11473
  reject(new RpcError("timeout", `${method} timed out after ${timeoutMs}ms`));
@@ -10710,7 +11475,7 @@ async function withAppServer(deps, body) {
10710
11475
  pending.set(id, {
10711
11476
  resolve: (v) => {
10712
11477
  clearTimeout(timer);
10713
- resolve42(v);
11478
+ resolve44(v);
10714
11479
  },
10715
11480
  reject: (e) => {
10716
11481
  clearTimeout(timer);
@@ -11636,25 +12401,25 @@ var init_discipline = __esm({
11636
12401
  );
11637
12402
  }
11638
12403
  });
11639
- async function loadDiscipline(basename10, packageRoot) {
11640
- const cached = _cache.get(basename10);
12404
+ async function loadDiscipline(basename12, packageRoot) {
12405
+ const cached = _cache.get(basename12);
11641
12406
  if (cached) return cached;
11642
- const yamlPath = resolve(packageRoot, "workflows", "disciplines", `${basename10}.yaml`);
12407
+ const yamlPath = resolve(packageRoot, "workflows", "disciplines", `${basename12}.yaml`);
11643
12408
  const raw = await readFile(yamlPath, "utf8");
11644
12409
  const parsedRaw = parse(raw);
11645
12410
  if (!Value.Check(Discipline, parsedRaw)) {
11646
12411
  const errors = [...Value.Errors(Discipline, parsedRaw)].slice(0, 3).map((e) => `${e.path} ${e.message}`).join("; ");
11647
- throw new Error(`Invalid discipline file ${basename10}.yaml: ${errors}`);
12412
+ throw new Error(`Invalid discipline file ${basename12}.yaml: ${errors}`);
11648
12413
  }
11649
12414
  const parsed = parsedRaw;
11650
- _cache.set(basename10, parsed);
12415
+ _cache.set(basename12, parsed);
11651
12416
  return parsed;
11652
12417
  }
11653
12418
  async function loadAllApplied(disciplines_applied, packageRoot) {
11654
12419
  const applied = disciplines_applied && disciplines_applied.length > 0 ? disciplines_applied : DEFAULT_APPLIED;
11655
12420
  const out = /* @__PURE__ */ new Map();
11656
- for (const basename10 of applied) {
11657
- out.set(basename10, await loadDiscipline(basename10, packageRoot));
12421
+ for (const basename12 of applied) {
12422
+ out.set(basename12, await loadDiscipline(basename12, packageRoot));
11658
12423
  }
11659
12424
  return out;
11660
12425
  }
@@ -12176,7 +12941,7 @@ function realSpawn(req) {
12176
12941
  };
12177
12942
  }
12178
12943
  function runOnce(req, spawnFn, timeoutMs, onThreadId) {
12179
- return new Promise((resolve42, reject) => {
12944
+ return new Promise((resolve44, reject) => {
12180
12945
  const events = [];
12181
12946
  let garbageLines = 0;
12182
12947
  let stderr = "";
@@ -12197,7 +12962,7 @@ function runOnce(req, spawnFn, timeoutMs, onThreadId) {
12197
12962
  if (settled || !exited || openStreams > 0) return;
12198
12963
  settled = true;
12199
12964
  clearTimeout(timer);
12200
- resolve42({ exitCode: exited.code, signal: exited.signal, events, garbageLines, stderr });
12965
+ resolve44({ exitCode: exited.code, signal: exited.signal, events, garbageLines, stderr });
12201
12966
  };
12202
12967
  const fail2 = (err2) => {
12203
12968
  if (settled) return;
@@ -13172,6 +13937,9 @@ function loadMaxIterTable(packageRoot) {
13172
13937
  }
13173
13938
  }
13174
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
+ }
13175
13943
  const parsed = loadPhases(yamlPath, vars);
13176
13944
  const yamlDir = dirname(resolve(yamlPath));
13177
13945
  const inferredRoot = resolve(yamlDir, "..", "..");
@@ -13591,25 +14359,6 @@ var init_capabilityResolver = __esm({
13591
14359
  CAPABILITY_CMD_TEMPLATE = /\{\{\s*capabilities\.([a-zA-Z0-9_-]+)\.cmd\s*\}\}/g;
13592
14360
  }
13593
14361
  });
13594
- function resultArtifactScope(cwd = process.cwd()) {
13595
- const base = repoKey(cwd);
13596
- const key = activeKey(cwd);
13597
- const composite = key === base ? `${base}::${NO_SESSION}` : key;
13598
- return createHash("sha256").update(composite, "utf8").digest("hex").slice(0, SCOPE_HEX_LEN);
13599
- }
13600
- function resultArtifactPath(sub, cwd = process.cwd()) {
13601
- checkSafeSegment(sub);
13602
- return resolve(cwd, ".harnessed", "results", resultArtifactScope(cwd), `${sub}.md`);
13603
- }
13604
- var SCOPE_HEX_LEN, NO_SESSION;
13605
- var init_resultArtifact = __esm({
13606
- "src/cli/lib/resultArtifact.ts"() {
13607
- init_workflowStore();
13608
- init_path_guard();
13609
- SCOPE_HEX_LEN = 8;
13610
- NO_SESSION = "nosession";
13611
- }
13612
- });
13613
14362
  function userLangPinPath(hostContext) {
13614
14363
  return join(hostContext?.platform.stateRoot ?? detectPlatform().stateRoot, USER_LANG_PIN);
13615
14364
  }
@@ -13774,14 +14523,16 @@ Respond in ${name}.
13774
14523
  ${preserve}
13775
14524
  `;
13776
14525
  }
13777
- 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.` : "";
13778
14529
  return `
13779
14530
  ## Result delivery
13780
14531
  Write your final result to this exact absolute path:
13781
14532
  ${resultFile}
13782
14533
 
13783
14534
  Rules:
13784
- - 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}
13785
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.
13786
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".
13787
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.
@@ -13825,7 +14576,7 @@ ${opts.task}
13825
14576
  const toolsSection = await buildToolsSection(sub, packageRoot, host);
13826
14577
  const disciplinesSection = await buildDisciplinesSection(sub, packageRoot, locale);
13827
14578
  const languageSection = await buildLanguageSection(packageRoot, host);
13828
- const resultDeliverySection = opts.resultFile ? buildResultDeliverySection(opts.resultFile) : "";
14579
+ const resultDeliverySection = opts.resultFile ? buildResultDeliverySection(opts.resultFile, opts.resultAttemptId) : "";
13829
14580
  return {
13830
14581
  prompt: `${taskSection}${body}
13831
14582
  ${toolsSection}${disciplinesSection}${PROTOCOLS}${resultDeliverySection}${languageSection}`,
@@ -13848,36 +14599,77 @@ function registerPrompt(program2) {
13848
14599
  process.exit(2);
13849
14600
  return;
13850
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`);
13851
14606
  const packageRoot = getAssetsRoot();
13852
- 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);
13853
14638
  const {
13854
14639
  prompt: fullPrompt,
13855
14640
  model,
13856
14641
  specialist
13857
14642
  } = await buildPromptText(sub, packageRoot, {
13858
14643
  ...typeof raw.task === "string" ? { task: raw.task } : {},
13859
- resultFile
14644
+ resultFile,
14645
+ ...dispatch && { resultAttemptId: dispatch.id }
13860
14646
  });
13861
- if (raw.json) {
13862
- const maxIterations = await resolveMaxIterations2(sub, packageRoot);
13863
- console.log(
13864
- JSON.stringify({
13865
- prompt: fullPrompt,
13866
- max_iterations: maxIterations,
13867
- model,
13868
- specialist,
13869
- result_file: resultFile
13870
- })
13871
- );
13872
- 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);
13873
14665
  }
13874
- console.log(fullPrompt);
13875
14666
  process.exit(0);
13876
14667
  });
13877
14668
  }
13878
14669
  var DEFAULT_MAX_ITERATIONS, DEFAULT_MODEL, DEFAULT_SPECIALIST, LANG_NAMES, CHAT_TRIGGER_RE, CHAT_SCOPE_NOTE, PRESERVE_FALLBACK, PROTOCOLS;
13879
14670
  var init_prompt = __esm({
13880
14671
  "src/cli/prompt.ts"() {
14672
+ init_completionClaim();
13881
14673
  init_i18n();
13882
14674
  init_localeYaml();
13883
14675
  init_path_guard();
@@ -16714,10 +17506,10 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
16714
17506
  child.stderr?.setEncoding("utf8").on("data", (chunk) => {
16715
17507
  stderr += chunk;
16716
17508
  });
16717
- return await new Promise((resolve42) => {
17509
+ return await new Promise((resolve44) => {
16718
17510
  const timer = setTimeout(() => {
16719
17511
  killProcessTree(child);
16720
- resolve42({
17512
+ resolve44({
16721
17513
  ok: false,
16722
17514
  phase: "spawn",
16723
17515
  error: {
@@ -16738,7 +17530,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
16738
17530
  child.on("error", (err2) => {
16739
17531
  clearTimeout(timer);
16740
17532
  const bashMissing = triedBash && err2.code === "ENOENT";
16741
- resolve42({
17533
+ resolve44({
16742
17534
  ok: false,
16743
17535
  phase: "spawn",
16744
17536
  error: {
@@ -16753,7 +17545,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
16753
17545
  });
16754
17546
  child.on("close", (code2) => {
16755
17547
  clearTimeout(timer);
16756
- resolve42({ ok: true, exitCode: code2 ?? -1, stdout: stdout2, stderr });
17548
+ resolve44({ ok: true, exitCode: code2 ?? -1, stdout: stdout2, stderr });
16757
17549
  });
16758
17550
  });
16759
17551
  }
@@ -17467,7 +18259,7 @@ function touch(binary, lease, source, scratch, context) {
17467
18259
  if (context) env = withHostInstallEnv(env, context);
17468
18260
  env.GSTACK_LEASE_DIR = shellPath(scratch, context);
17469
18261
  env.GSTACK_LEASE_LOCK_TRIES = "1";
17470
- return new Promise((resolve42, reject) => {
18262
+ return new Promise((resolve44, reject) => {
17471
18263
  const child = execFile(
17472
18264
  binary,
17473
18265
  [
@@ -17496,7 +18288,7 @@ function touch(binary, lease, source, scratch, context) {
17496
18288
  `official lease touch exit ${error.code ?? "unknown"}${error.killed ? " (timeout or termination)" : ""}: ${stderr.trim() || error.message}`
17497
18289
  )
17498
18290
  );
17499
- else resolve42();
18291
+ else resolve44();
17500
18292
  }
17501
18293
  );
17502
18294
  child.stdin?.end();
@@ -18036,7 +18828,7 @@ var init_verifyInstalled = __esm({
18036
18828
  }
18037
18829
  });
18038
18830
  function gitRevParseHead(cwd, timeoutMs = 1e4) {
18039
- return new Promise((resolve42) => {
18831
+ return new Promise((resolve44) => {
18040
18832
  const isWin = process.platform === "win32";
18041
18833
  const child = isWin ? spawn("cmd.exe", ["/c", "git", "rev-parse", "HEAD"], { cwd, windowsHide: true }) : spawn("git", ["rev-parse", "HEAD"], { cwd, shell: false });
18042
18834
  let stdout2 = "";
@@ -18045,15 +18837,15 @@ function gitRevParseHead(cwd, timeoutMs = 1e4) {
18045
18837
  });
18046
18838
  const timer = setTimeout(() => {
18047
18839
  killProcessTree(child);
18048
- resolve42({ sha: "", exit: -1 });
18840
+ resolve44({ sha: "", exit: -1 });
18049
18841
  }, timeoutMs);
18050
18842
  child.on("error", () => {
18051
18843
  clearTimeout(timer);
18052
- resolve42({ sha: "", exit: -1 });
18844
+ resolve44({ sha: "", exit: -1 });
18053
18845
  });
18054
18846
  child.on("close", (code2) => {
18055
18847
  clearTimeout(timer);
18056
- resolve42({ sha: stdout2.trim(), exit: code2 ?? -1 });
18848
+ resolve44({ sha: stdout2.trim(), exit: code2 ?? -1 });
18057
18849
  });
18058
18850
  });
18059
18851
  }
@@ -21043,14 +21835,36 @@ async function buildRecoverLines(workflow, ledger, intent) {
21043
21835
  function registerStatus(program2) {
21044
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) => {
21045
21837
  if (opts.recover) {
21046
- 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);
21047
21861
  const ledger = wf?.sub_progress ?? [];
21048
21862
  let intent = null;
21049
21863
  if (ledger.length === 0) {
21050
21864
  try {
21051
21865
  const { readIntent: readIntent2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
21052
21866
  const { INTENT_TTL_MS: INTENT_TTL_MS2 } = await Promise.resolve().then(() => (init_injectState(), injectState_exports));
21053
- const raw = await readIntent2();
21867
+ const raw = await readIntent2(void 0, true);
21054
21868
  if (raw) {
21055
21869
  const age = Date.now() - Date.parse(raw.ts);
21056
21870
  if (!Number.isNaN(age) && age >= 0 && age <= INTENT_TTL_MS2) {
@@ -23251,7 +24065,7 @@ function decodeUpdateContinuation(encoded) {
23251
24065
  return value;
23252
24066
  }
23253
24067
  async function runContinuationProcess(executablePath, args, options) {
23254
- return new Promise((resolve42, reject) => {
24068
+ return new Promise((resolve44, reject) => {
23255
24069
  const child = spawn(executablePath, args, {
23256
24070
  cwd: options.cwd,
23257
24071
  env: options.env,
@@ -23265,7 +24079,7 @@ async function runContinuationProcess(executablePath, args, options) {
23265
24079
  child.once("error", reject);
23266
24080
  child.once("close", (exitCode, signal) => {
23267
24081
  clearTimeout(timer);
23268
- resolve42({ exitCode, signal });
24082
+ resolve44({ exitCode, signal });
23269
24083
  });
23270
24084
  });
23271
24085
  }
@@ -23600,6 +24414,18 @@ function buildExecutionBody(name, prompt, ctx) {
23600
24414
  ...spawnLoopSteps("").map(
23601
24415
  (s) => s.replace("<sub>", name).replace('--task "<spec>"', '--task "$ARGUMENTS"')
23602
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
+ ] : [],
23603
24429
  ``,
23604
24430
  runWarning(ctx, name, "command_execution"),
23605
24431
  ``,
@@ -24920,14 +25746,14 @@ var manifest_add_exports = {};
24920
25746
  __export(manifest_add_exports, {
24921
25747
  registerManifestAdd: () => registerManifestAdd
24922
25748
  });
24923
- function basename8(upstream) {
25749
+ function basename10(upstream) {
24924
25750
  return (upstream.split("/").pop() ?? upstream).replace(/\.git$/, "");
24925
25751
  }
24926
25752
  function registerManifestAdd(program2) {
24927
25753
  program2.command("manifest-add <upstream>").description(
24928
25754
  "Add a new upstream adapter (EE-5 5-question merge gate; immediate by default \u2014 use --dry-run for preview)"
24929
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) => {
24930
- const name = raw.name ?? basename8(upstream);
25756
+ const name = raw.name ?? basename10(upstream);
24931
25757
  const category = raw.category ?? "skill-packs";
24932
25758
  try {
24933
25759
  checkSafeSegment(category);
@@ -25861,6 +26687,10 @@ function registerRun(program2) {
25861
26687
  process.exit(2);
25862
26688
  return;
25863
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
+ }
25864
26694
  let task = "";
25865
26695
  if (typeof raw.task === "string") {
25866
26696
  task = raw.task;
@@ -28296,7 +29126,7 @@ var init_npmCli3 = __esm({
28296
29126
  cwd: ctx.hostContext.userHome,
28297
29127
  env: withHostInstallEnv(process.env, ctx.hostContext)
28298
29128
  } : {};
28299
- const result = await new Promise((resolve42) => {
29129
+ const result = await new Promise((resolve44) => {
28300
29130
  const child = isWin ? spawn("cmd.exe", ["/c", "npm", "uninstall", "-g", pkg], {
28301
29131
  ...spawnOptions,
28302
29132
  windowsHide: true
@@ -28307,15 +29137,15 @@ var init_npmCli3 = __esm({
28307
29137
  });
28308
29138
  const timer = setTimeout(() => {
28309
29139
  child.kill("SIGKILL");
28310
- resolve42({ exitCode: -1, stderr: `${stderr}[timeout]` });
29140
+ resolve44({ exitCode: -1, stderr: `${stderr}[timeout]` });
28311
29141
  }, 3e4);
28312
29142
  child.on("error", (e) => {
28313
29143
  clearTimeout(timer);
28314
- resolve42({ exitCode: -1, stderr: e.message });
29144
+ resolve44({ exitCode: -1, stderr: e.message });
28315
29145
  });
28316
29146
  child.on("close", (code2) => {
28317
29147
  clearTimeout(timer);
28318
- resolve42({ exitCode: code2 ?? -1, stderr });
29148
+ resolve44({ exitCode: code2 ?? -1, stderr });
28319
29149
  });
28320
29150
  });
28321
29151
  if (result.exitCode !== 0) {
@@ -29011,7 +29841,7 @@ async function writeAutoUpdateNoticeForNewBinary(context) {
29011
29841
  }
29012
29842
  async function spawnOwnedRefresh(execPath, context, deps = {}, timeoutMs = OWNED_REFRESH_TIMEOUT_MS) {
29013
29843
  const spawnImpl = deps.spawn ?? spawn;
29014
- return new Promise((resolve42) => {
29844
+ return new Promise((resolve44) => {
29015
29845
  let child;
29016
29846
  try {
29017
29847
  child = spawnImpl(execPath, [OWNED_REFRESH_FLAG], {
@@ -29025,7 +29855,7 @@ async function spawnOwnedRefresh(execPath, context, deps = {}, timeoutMs = OWNED
29025
29855
  shell: false
29026
29856
  });
29027
29857
  } catch (error) {
29028
- resolve42({
29858
+ resolve44({
29029
29859
  ok: false,
29030
29860
  exitCode: null,
29031
29861
  error: error instanceof Error ? error.message : String(error)
@@ -29037,15 +29867,15 @@ async function spawnOwnedRefresh(execPath, context, deps = {}, timeoutMs = OWNED
29037
29867
  killProcessTree(child);
29038
29868
  } catch {
29039
29869
  }
29040
- resolve42({ ok: false, exitCode: null, error: `timed out after ${timeoutMs}ms` });
29870
+ resolve44({ ok: false, exitCode: null, error: `timed out after ${timeoutMs}ms` });
29041
29871
  }, timeoutMs);
29042
29872
  child.on("error", (error) => {
29043
29873
  clearTimeout(timer);
29044
- resolve42({ ok: false, exitCode: null, error: error.message });
29874
+ resolve44({ ok: false, exitCode: null, error: error.message });
29045
29875
  });
29046
29876
  child.on("close", (code2) => {
29047
29877
  clearTimeout(timer);
29048
- resolve42({ ok: code2 === 0, exitCode: code2 });
29878
+ resolve44({ ok: code2 === 0, exitCode: code2 });
29049
29879
  });
29050
29880
  });
29051
29881
  }
@@ -29364,8 +30194,163 @@ var init_workflows = __esm({
29364
30194
  }
29365
30195
  });
29366
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
+
29367
30250
  // src/cli.ts
29368
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
29369
30354
  var entryArgs = process.argv.slice(2);
29370
30355
  if (entryArgs.length === 1 && entryArgs[0] === "--internal-update-identity") {
29371
30356
  process.stdout.write(`${package_default.version}
@@ -29416,7 +30401,7 @@ var { getAssetsRoot: getAssetsRoot2 } = await Promise.resolve().then(() => (init
29416
30401
  var { captureHostInstallContext: captureHostInstallContext2 } = await Promise.resolve().then(() => (init_hostInstallContext(), hostInstallContext_exports));
29417
30402
  var { migrateLegacyHarnessedRoot: migrateLegacyHarnessedRoot2 } = await Promise.resolve().then(() => (init_harnessedRoot(), harnessedRoot_exports));
29418
30403
  wireMessagesDir2(() => join(getAssetsRoot2(), "messages"));
29419
- var updateInvocation = entryArgs.includes("update");
30404
+ var updateInvocation = entryArgs[entryCommandIndex(entryArgs)] === "update";
29420
30405
  function explicitPlatform(args) {
29421
30406
  for (let index = 0; index < args.length; index++) {
29422
30407
  const arg = args[index];
@@ -29451,14 +30436,21 @@ process.on("unhandledRejection", (reason) => {
29451
30436
  process.on("uncaughtException", (err2) => {
29452
30437
  fatal(err2 instanceof Error ? err2.message : String(err2));
29453
30438
  });
29454
- if (!updateInvocation) {
29455
- const hostId = explicitPlatform(entryArgs);
29456
- migrateLegacyHarnessedRoot2(captureHostInstallContext2(hostId === void 0 ? {} : { hostId }));
29457
- await migrateRepoKeyCase2().catch((e) => {
29458
- console.error(
29459
- `[harnessed] WARN: repo-key case migration deferred: ${e instanceof Error ? e.message : String(e)}`
29460
- );
29461
- });
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
+ }
29462
30454
  }
29463
30455
  var { OWNED_REFRESH_FLAG: OWNED_REFRESH_FLAG2 } = await Promise.resolve().then(() => (init_ownedRefreshFlag(), ownedRefreshFlag_exports));
29464
30456
  if (entryArgs.length === 1 && entryArgs[0] === OWNED_REFRESH_FLAG2) {