oh-my-codex 0.21.47 → 0.22.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 (176) hide show
  1. package/Cargo.lock +6 -6
  2. package/Cargo.toml +1 -1
  3. package/README.md +15 -0
  4. package/crates/omx-mux/src/herdr.rs +481 -0
  5. package/crates/omx-mux/src/lib.rs +5 -0
  6. package/dist/cli/__tests__/plugin-cache-live-pin-3790.test.js +707 -47
  7. package/dist/cli/__tests__/plugin-cache-live-pin-3790.test.js.map +1 -1
  8. package/dist/cli/__tests__/session-compare.test.d.ts +2 -0
  9. package/dist/cli/__tests__/session-compare.test.d.ts.map +1 -0
  10. package/dist/cli/__tests__/session-compare.test.js +183 -0
  11. package/dist/cli/__tests__/session-compare.test.js.map +1 -0
  12. package/dist/cli/__tests__/setup-install-mode.test.js +7 -1
  13. package/dist/cli/__tests__/setup-install-mode.test.js.map +1 -1
  14. package/dist/cli/__tests__/team.test.js +8 -0
  15. package/dist/cli/__tests__/team.test.js.map +1 -1
  16. package/dist/cli/plugin-marketplace.d.ts.map +1 -1
  17. package/dist/cli/plugin-marketplace.js +328 -142
  18. package/dist/cli/plugin-marketplace.js.map +1 -1
  19. package/dist/cli/session-compare.d.ts +11 -0
  20. package/dist/cli/session-compare.d.ts.map +1 -0
  21. package/dist/cli/session-compare.js +172 -0
  22. package/dist/cli/session-compare.js.map +1 -0
  23. package/dist/cli/session-search.d.ts.map +1 -1
  24. package/dist/cli/session-search.js +7 -0
  25. package/dist/cli/session-search.js.map +1 -1
  26. package/dist/cli/team.d.ts.map +1 -1
  27. package/dist/cli/team.js +2 -0
  28. package/dist/cli/team.js.map +1 -1
  29. package/dist/config/__tests__/multiplexer.test.d.ts +2 -0
  30. package/dist/config/__tests__/multiplexer.test.d.ts.map +1 -0
  31. package/dist/config/__tests__/multiplexer.test.js +118 -0
  32. package/dist/config/__tests__/multiplexer.test.js.map +1 -0
  33. package/dist/config/multiplexer.d.ts +29 -0
  34. package/dist/config/multiplexer.d.ts.map +1 -0
  35. package/dist/config/multiplexer.js +91 -0
  36. package/dist/config/multiplexer.js.map +1 -0
  37. package/dist/hooks/__tests__/sunset-routing-contract.test.js +4 -2
  38. package/dist/hooks/__tests__/sunset-routing-contract.test.js.map +1 -1
  39. package/dist/scripts/__tests__/codex-native-hook.test.js +281 -1
  40. package/dist/scripts/__tests__/codex-native-hook.test.js.map +1 -1
  41. package/dist/scripts/__tests__/generate-release-body.test.js +142 -5
  42. package/dist/scripts/__tests__/generate-release-body.test.js.map +1 -1
  43. package/dist/scripts/codex-native-hook.d.ts.map +1 -1
  44. package/dist/scripts/codex-native-hook.js +8 -2
  45. package/dist/scripts/codex-native-hook.js.map +1 -1
  46. package/dist/scripts/generate-release-body.d.ts.map +1 -1
  47. package/dist/scripts/generate-release-body.js +14 -0
  48. package/dist/scripts/generate-release-body.js.map +1 -1
  49. package/dist/scripts/notify-hook/team-worker-lease.d.ts +15 -0
  50. package/dist/scripts/notify-hook/team-worker-lease.d.ts.map +1 -0
  51. package/dist/scripts/notify-hook/team-worker-lease.js +63 -0
  52. package/dist/scripts/notify-hook/team-worker-lease.js.map +1 -0
  53. package/dist/scripts/notify-hook/team-worker-posttooluse.d.ts +1 -0
  54. package/dist/scripts/notify-hook/team-worker-posttooluse.d.ts.map +1 -1
  55. package/dist/scripts/notify-hook/team-worker-posttooluse.js +16 -5
  56. package/dist/scripts/notify-hook/team-worker-posttooluse.js.map +1 -1
  57. package/dist/scripts/notify-hook/team-worker.d.ts +12 -1
  58. package/dist/scripts/notify-hook/team-worker.d.ts.map +1 -1
  59. package/dist/scripts/notify-hook/team-worker.js +16 -4
  60. package/dist/scripts/notify-hook/team-worker.js.map +1 -1
  61. package/dist/session-history/__tests__/compare.test.d.ts +2 -0
  62. package/dist/session-history/__tests__/compare.test.d.ts.map +1 -0
  63. package/dist/session-history/__tests__/compare.test.js +257 -0
  64. package/dist/session-history/__tests__/compare.test.js.map +1 -0
  65. package/dist/session-history/compare.d.ts +74 -0
  66. package/dist/session-history/compare.d.ts.map +1 -0
  67. package/dist/session-history/compare.js +165 -0
  68. package/dist/session-history/compare.js.map +1 -0
  69. package/dist/team/__tests__/api-interop.test.js +3 -3
  70. package/dist/team/__tests__/cross-rebase-smoke.test.js +263 -31
  71. package/dist/team/__tests__/cross-rebase-smoke.test.js.map +1 -1
  72. package/dist/team/__tests__/herdr-session-realherdr.test.d.ts +2 -0
  73. package/dist/team/__tests__/herdr-session-realherdr.test.d.ts.map +1 -0
  74. package/dist/team/__tests__/herdr-session-realherdr.test.js +68 -0
  75. package/dist/team/__tests__/herdr-session-realherdr.test.js.map +1 -0
  76. package/dist/team/__tests__/herdr-session.test.d.ts +2 -0
  77. package/dist/team/__tests__/herdr-session.test.d.ts.map +1 -0
  78. package/dist/team/__tests__/herdr-session.test.js +228 -0
  79. package/dist/team/__tests__/herdr-session.test.js.map +1 -0
  80. package/dist/team/__tests__/idle-nudge.test.js +84 -0
  81. package/dist/team/__tests__/idle-nudge.test.js.map +1 -1
  82. package/dist/team/__tests__/rebalance-policy.test.js +27 -9
  83. package/dist/team/__tests__/rebalance-policy.test.js.map +1 -1
  84. package/dist/team/__tests__/runtime-delivery.test.d.ts +2 -0
  85. package/dist/team/__tests__/runtime-delivery.test.d.ts.map +1 -0
  86. package/dist/team/__tests__/runtime-delivery.test.js +570 -0
  87. package/dist/team/__tests__/runtime-delivery.test.js.map +1 -0
  88. package/dist/team/__tests__/runtime.test.js +332 -18
  89. package/dist/team/__tests__/runtime.test.js.map +1 -1
  90. package/dist/team/__tests__/scaling.test.js +293 -0
  91. package/dist/team/__tests__/scaling.test.js.map +1 -1
  92. package/dist/team/__tests__/state-renewal.test.d.ts +2 -0
  93. package/dist/team/__tests__/state-renewal.test.d.ts.map +1 -0
  94. package/dist/team/__tests__/state-renewal.test.js +555 -0
  95. package/dist/team/__tests__/state-renewal.test.js.map +1 -0
  96. package/dist/team/__tests__/task-lease.test.d.ts +2 -0
  97. package/dist/team/__tests__/task-lease.test.d.ts.map +1 -0
  98. package/dist/team/__tests__/task-lease.test.js +179 -0
  99. package/dist/team/__tests__/task-lease.test.js.map +1 -0
  100. package/dist/team/__tests__/team-ops-contract.test.js +1 -0
  101. package/dist/team/__tests__/team-ops-contract.test.js.map +1 -1
  102. package/dist/team/__tests__/worker-bootstrap.test.js +2 -0
  103. package/dist/team/__tests__/worker-bootstrap.test.js.map +1 -1
  104. package/dist/team/api-interop.d.ts +1 -1
  105. package/dist/team/api-interop.d.ts.map +1 -1
  106. package/dist/team/api-interop.js +13 -1
  107. package/dist/team/api-interop.js.map +1 -1
  108. package/dist/team/goal-workflow.js +1 -1
  109. package/dist/team/herdr-session.d.ts +234 -0
  110. package/dist/team/herdr-session.d.ts.map +1 -0
  111. package/dist/team/herdr-session.js +489 -0
  112. package/dist/team/herdr-session.js.map +1 -0
  113. package/dist/team/idle-nudge.d.ts +16 -4
  114. package/dist/team/idle-nudge.d.ts.map +1 -1
  115. package/dist/team/idle-nudge.js +51 -19
  116. package/dist/team/idle-nudge.js.map +1 -1
  117. package/dist/team/mcp-comm.d.ts +1 -1
  118. package/dist/team/mcp-comm.d.ts.map +1 -1
  119. package/dist/team/rebalance-policy.d.ts.map +1 -1
  120. package/dist/team/rebalance-policy.js +5 -2
  121. package/dist/team/rebalance-policy.js.map +1 -1
  122. package/dist/team/runtime.d.ts.map +1 -1
  123. package/dist/team/runtime.js +356 -81
  124. package/dist/team/runtime.js.map +1 -1
  125. package/dist/team/scaling.d.ts.map +1 -1
  126. package/dist/team/scaling.js +332 -143
  127. package/dist/team/scaling.js.map +1 -1
  128. package/dist/team/state/monitor.d.ts +3 -0
  129. package/dist/team/state/monitor.d.ts.map +1 -1
  130. package/dist/team/state/monitor.js +3 -0
  131. package/dist/team/state/monitor.js.map +1 -1
  132. package/dist/team/state/tasks.d.ts +2 -1
  133. package/dist/team/state/tasks.d.ts.map +1 -1
  134. package/dist/team/state/tasks.js +28 -0
  135. package/dist/team/state/tasks.js.map +1 -1
  136. package/dist/team/state/types.d.ts +8 -0
  137. package/dist/team/state/types.d.ts.map +1 -1
  138. package/dist/team/state/types.js.map +1 -1
  139. package/dist/team/state.d.ts +14 -2
  140. package/dist/team/state.d.ts.map +1 -1
  141. package/dist/team/state.js +29 -5
  142. package/dist/team/state.js.map +1 -1
  143. package/dist/team/task-lease.d.ts +4 -0
  144. package/dist/team/task-lease.d.ts.map +1 -0
  145. package/dist/team/task-lease.js +74 -0
  146. package/dist/team/task-lease.js.map +1 -0
  147. package/dist/team/team-ops.d.ts +2 -1
  148. package/dist/team/team-ops.d.ts.map +1 -1
  149. package/dist/team/team-ops.js +1 -0
  150. package/dist/team/team-ops.js.map +1 -1
  151. package/dist/team/tmux-session.d.ts +1 -1
  152. package/dist/team/tmux-session.d.ts.map +1 -1
  153. package/dist/team/tmux-session.js +10 -2
  154. package/dist/team/tmux-session.js.map +1 -1
  155. package/dist/team/worker-bootstrap.d.ts.map +1 -1
  156. package/dist/team/worker-bootstrap.js +14 -1
  157. package/dist/team/worker-bootstrap.js.map +1 -1
  158. package/package.json +1 -1
  159. package/plugins/oh-my-codex/.codex-plugin/plugin.json +1 -1
  160. package/plugins/oh-my-codex/hooks/codex-native-hook.mjs +208 -25
  161. package/plugins/oh-my-codex/skills/worker/SKILL.md +7 -1
  162. package/prompts/build-fixer.md +2 -1
  163. package/prompts/debugger.md +2 -1
  164. package/prompts/git-master.md +2 -1
  165. package/prompts/style-reviewer.md +2 -1
  166. package/prompts/team-executor.md +3 -2
  167. package/prompts/vision.md +2 -1
  168. package/prompts/writer.md +2 -1
  169. package/skills/worker/SKILL.md +7 -1
  170. package/src/scripts/__tests__/codex-native-hook.test.ts +279 -0
  171. package/src/scripts/__tests__/generate-release-body.test.ts +151 -5
  172. package/src/scripts/codex-native-hook.ts +8 -2
  173. package/src/scripts/generate-release-body.ts +16 -0
  174. package/src/scripts/notify-hook/team-worker-lease.ts +69 -0
  175. package/src/scripts/notify-hook/team-worker-posttooluse.ts +16 -4
  176. package/src/scripts/notify-hook/team-worker.ts +15 -4
package/prompts/writer.md CHANGED
@@ -45,7 +45,8 @@ Inaccurate documentation is worse than no documentation -- it actively misleads.
45
45
  </success_criteria>
46
46
 
47
47
  <verification_loop>
48
- - Default effort: low (concise, accurate documentation).
48
+ - Recommend a supported reasoning effort from task demands, remaining uncertainty, available proof, and resource limits; briefly compare plausible alternatives without a role-based default.
49
+ - Preserve explicit effort requirements and the leader's selected effort. Report justified changes to the caller; do not change runtime settings.
49
50
  - Stop when documentation is complete, accurate, and verified.
50
51
  - Continue through clear, low-risk next steps automatically; ask only when the next step materially changes scope or requires user preference.
51
52
  </verification_loop>
@@ -24,10 +24,16 @@ Use only when the session was started as an OMX Team worker. Read `AGENTS.md#dur
24
24
  ```
25
25
  2. Read `<team_state_root>/team/<teamName>/workers/<workerName>/inbox.md` and take the first unblocked assignment.
26
26
  3. Read `<team_state_root>/team/<teamName>/tasks/task-<id>.json`; APIs use the bare numeric `task_id` (for example `"1"`).
27
- 4. Claim before editing:
27
+ 4. Claim an unclaimed task before editing:
28
28
  ```bash
29
29
  omx team api claim-task --input '{"team_name":"<teamName>","task_id":"<id>","worker":"<workerName>"}' --json
30
30
  ```
31
+ If the leader already claimed the task for you, do not re-claim it. Use the inbox handoff's current claim token, version, and lease; verify they match the task file. If they differ or the lease has expired, stop and ask the leader for a current assignment.
32
+ Save the current `claimToken` and write `{"state":"working","current_task_id":"<id>","current_claim_token":"<claimToken>","updated_at":"<ISO timestamp>"}` to your worker `status.json`. Notify/PostToolUse heartbeats renew that unexpired token automatically. Renew at least every 5 minutes while working:
33
+ ```bash
34
+ omx team api renew-task-claim --input '{"team_name":"<teamName>","task_id":"<id>","worker":"<workerName>","claim_token":"<claimToken>"}' --json
35
+ ```
36
+ For commands/tool waits over 5 minutes, use the executable `with_task_lease` Bash wrapper in your generated inbox instructions: it renews before starting and periodically while the command runs, validates both API success layers, propagates renewal failure, and cleans up its own direct children. Commands spawning grandchildren must manage their own descendants. If renewal fails, stop editing and contact the leader; expired claims cannot be revived.
31
37
  5. Do the assigned work. Do not write task lifecycle fields directly.
32
38
  6. Complete or fail through the lifecycle API, from `in_progress` to `completed` or `failed`:
33
39
  ```bash
@@ -21,6 +21,7 @@ import { buildManagedCodexHooksConfig } from "../../config/codex-hooks.js";
21
21
  import { DOCUMENT_REFRESH_EXEMPTION_PREFIX } from "../../document-refresh/enforcer.js";
22
22
  import {
23
23
  initTeamState,
24
+ createTask, claimTask, withTeamTaskBarrier, transitionTaskStatus, writeWorkerStatus,
24
25
  readTeamConfig,
25
26
  readTeamLeaderAttention,
26
27
  readTeamPhase,
@@ -16887,6 +16888,284 @@ exit 0
16887
16888
  }
16888
16889
  });
16889
16890
 
16891
+ it("renews the captured claim on real-wire plain-string PostToolUse without checkpoint or dedupe", async () => {
16892
+ const cwd = await mkdtemp(join(tmpdir(), "omx-native-hook-real-wire-renewal-"));
16893
+ const teamName = "native-real-wire";
16894
+ const stateRoot = join(cwd, ".omx/state");
16895
+ try {
16896
+ await configureAuthoritativeTeamWorker(cwd, teamName);
16897
+ const task = await createTask(teamName, { subject: "work", description: "work", status: "pending" }, cwd);
16898
+ const claim = await claimTask(teamName, task.id, "worker-1", null, cwd);
16899
+ assert.ok(claim.ok);
16900
+ const workerRoot = join(stateRoot, "team", teamName, "workers/worker-1");
16901
+ await writeWorkerStatus(teamName, "worker-1", {
16902
+ state: "working", current_task_id: task.id, current_claim_token: claim.claimToken, updated_at: new Date().toISOString(),
16903
+ }, cwd);
16904
+ const result = await dispatchCodexNativeHook({
16905
+ hook_event_name: "PostToolUse", cwd, tool_name: "Bash", tool_use_id: "real-wire-renewal",
16906
+ tool_input: { command: "printf ok" }, tool_response: "ok\n",
16907
+ }, { cwd });
16908
+ assert.doesNotMatch(JSON.stringify(result.outputJson), /LEASE LOST|STOP editing/);
16909
+ const after = JSON.parse(await readFile(join(stateRoot, "team", teamName, "tasks", `task-${task.id}.json`), "utf8"));
16910
+ assert.equal(after.version, claim.task.version + 1);
16911
+ assert.equal(after.claim.token, claim.claimToken);
16912
+ assert.equal(JSON.parse(await readFile(join(workerRoot, "heartbeat.json"), "utf8")).source, "posttooluse");
16913
+ assert.equal(existsSync(join(workerRoot, "posttooluse-dedupe.json")), false);
16914
+ assert.equal(existsSync(join(cwd, ".omx/reports/team-commit-hygiene", `${teamName}.ledger.json`)), false);
16915
+ } finally {
16916
+ await rm(cwd, { recursive: true, force: true });
16917
+ }
16918
+ });
16919
+
16920
+ for (const outcome of ['live', 'expired', 'wrong-token'] as const) {
16921
+ it(`heartbeat directory does not bypass native PostToolUse ${outcome === 'live' ? 'renewal' : 'STOP'} for a ${outcome} claim`, async () => {
16922
+ const cwd = await mkdtemp(join(tmpdir(), "omx-native-hook-heartbeat-io-"));
16923
+ const teamName = "native-heartbeat-io";
16924
+ const stateRoot = join(cwd, ".omx/state");
16925
+ try {
16926
+ await configureAuthoritativeTeamWorker(cwd, teamName);
16927
+ const task = await createTask(teamName, { subject: "work", description: "work", status: "pending" }, cwd);
16928
+ const claim = await claimTask(teamName, task.id, "worker-1", null, cwd);
16929
+ assert.ok(claim.ok);
16930
+ const workerRoot = join(stateRoot, "team", teamName, "workers/worker-1");
16931
+ await writeWorkerStatus(teamName, "worker-1", {
16932
+ state: "working", current_task_id: task.id,
16933
+ current_claim_token: outcome === 'wrong-token' ? 'wrong-captured-token' : claim.claimToken,
16934
+ updated_at: new Date().toISOString(),
16935
+ }, cwd);
16936
+ await mkdir(join(workerRoot, "heartbeat.json"));
16937
+ const taskPath = join(stateRoot, "team", teamName, "tasks", `task-${task.id}.json`);
16938
+ if (outcome !== 'wrong-token') {
16939
+ await writeJson(taskPath, { ...claim.task, claim: { ...claim.task.claim, leased_until: new Date(outcome === 'expired' ? 0 : Date.now() + 60_000).toISOString() } });
16940
+ }
16941
+ const taskBefore = await readFile(taskPath, "utf8");
16942
+ const statusBefore = await readFile(join(workerRoot, "status.json"), "utf8");
16943
+ const git = (args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
16944
+ git(["init"]);
16945
+ git(["config", "user.email", "test@example.com"]);
16946
+ git(["config", "user.name", "Test User"]);
16947
+ await writeFile(join(cwd, "work.txt"), "before\n");
16948
+ git(["add", "work.txt"]);
16949
+ git(["commit", "-m", "initial"]);
16950
+ const head = git(["rev-parse", "HEAD"]);
16951
+ await writeFile(join(cwd, "work.txt"), "unverified output\n");
16952
+ const result = await dispatchCodexNativeHook({
16953
+ hook_event_name: "PostToolUse", cwd, tool_name: "Bash", tool_use_id: "heartbeat-io",
16954
+ tool_input: { command: "printf ok" }, tool_response: "plain stdout/stderr\n",
16955
+ }, { cwd });
16956
+ if (outcome === 'live') {
16957
+ assert.doesNotMatch(JSON.stringify(result.outputJson), /LEASE LOST|STOP editing/);
16958
+ const after = JSON.parse(await readFile(taskPath, "utf8"));
16959
+ assert.equal(after.version, claim.task.version + 1);
16960
+ assert.equal(after.claim.token, claim.claimToken);
16961
+ assert.ok(Date.parse(after.claim.leased_until) > Date.parse(JSON.parse(taskBefore).claim.leased_until));
16962
+ } else {
16963
+ const stop = outcome === 'expired' ? /lease_expired.*STOP editing/ : /claim_conflict.*STOP editing/;
16964
+ assert.match(String(result.outputJson?.systemMessage), stop);
16965
+ const hookOutput = result.outputJson?.hookSpecificOutput as Record<string, unknown>;
16966
+ assert.equal(hookOutput.additionalContext, result.outputJson?.systemMessage);
16967
+ assert.equal(await readFile(taskPath, "utf8"), taskBefore);
16968
+ assert.match(await readFile(join(workerRoot, "lease-loss.json"), "utf8"), stop);
16969
+ }
16970
+ assert.equal(await readFile(join(workerRoot, "status.json"), "utf8"), statusBefore);
16971
+ assert.equal(existsSync(join(workerRoot, "posttooluse-dedupe.json")), false);
16972
+ assert.equal(existsSync(join(cwd, ".omx/reports/team-commit-hygiene", `${teamName}.ledger.json`)), false);
16973
+ assert.equal(git(["rev-parse", "HEAD"]), head);
16974
+ assert.equal(git(["diff", "--cached"]), "");
16975
+ assert.equal(await readFile(join(cwd, "work.txt"), "utf8"), "unverified output\n");
16976
+ } finally {
16977
+ await rm(cwd, { recursive: true, force: true });
16978
+ }
16979
+ });
16980
+ }
16981
+
16982
+ it("surfaces unexpected status I/O as native real-wire PostToolUse STOP without task mutation", async () => {
16983
+ const cwd = await mkdtemp(join(tmpdir(), "omx-native-hook-status-io-"));
16984
+ const teamName = "native-status-io";
16985
+ const stateRoot = join(cwd, ".omx/state");
16986
+ try {
16987
+ await configureAuthoritativeTeamWorker(cwd, teamName);
16988
+ const task = await createTask(teamName, { subject: "work", description: "work", status: "pending" }, cwd);
16989
+ const claim = await claimTask(teamName, task.id, "worker-1", null, cwd);
16990
+ assert.ok(claim.ok);
16991
+ const workerRoot = join(stateRoot, "team", teamName, "workers/worker-1");
16992
+ await mkdir(join(workerRoot, "status.json"));
16993
+ const taskPath = join(stateRoot, "team", teamName, "tasks", `task-${task.id}.json`);
16994
+ const taskBefore = await readFile(taskPath, "utf8");
16995
+ const git = (args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
16996
+ git(["init"]);
16997
+ git(["config", "user.email", "test@example.com"]);
16998
+ git(["config", "user.name", "Test User"]);
16999
+ await writeFile(join(cwd, "work.txt"), "before\n");
17000
+ git(["add", "work.txt"]);
17001
+ git(["commit", "-m", "initial"]);
17002
+ const head = git(["rev-parse", "HEAD"]);
17003
+ await writeFile(join(cwd, "work.txt"), "unverified output\n");
17004
+ const result = await dispatchCodexNativeHook({
17005
+ hook_event_name: "PostToolUse", cwd, tool_name: "Bash", tool_use_id: "status-io",
17006
+ tool_input: { command: "printf ok" }, tool_response: "plain stdout/stderr\n",
17007
+ }, { cwd });
17008
+ assert.match(String(result.outputJson?.systemMessage), /LEASE LOST:.*renewal_error:.*EISDIR.*STOP editing/);
17009
+ const hookOutput = result.outputJson?.hookSpecificOutput as Record<string, unknown>;
17010
+ assert.equal(hookOutput.additionalContext, result.outputJson?.systemMessage);
17011
+ assert.equal(await readFile(taskPath, "utf8"), taskBefore);
17012
+ assert.equal(existsSync(join(workerRoot, "posttooluse-dedupe.json")), false);
17013
+ assert.equal(existsSync(join(cwd, ".omx/reports/team-commit-hygiene", `${teamName}.ledger.json`)), false);
17014
+ assert.match(await readFile(join(workerRoot, "lease-loss.json"), "utf8"), /EISDIR.*STOP editing/);
17015
+ assert.equal(git(["rev-parse", "HEAD"]), head);
17016
+ assert.equal(git(["diff", "--cached"]), "");
17017
+ assert.equal(await readFile(join(cwd, "work.txt"), "utf8"), "unverified output\n");
17018
+ } finally {
17019
+ await rm(cwd, { recursive: true, force: true });
17020
+ }
17021
+ });
17022
+
17023
+ it("surfaces lease loss from PostToolUse without checkpointing stale work", async () => {
17024
+ const cwd = await mkdtemp(join(tmpdir(), "omx-native-hook-lease-loss-"));
17025
+ const teamName = "native-lease-loss";
17026
+ const stateRoot = join(cwd, ".omx/state");
17027
+ try {
17028
+ await configureAuthoritativeTeamWorker(cwd, teamName);
17029
+ const task = await createTask(teamName, { subject: "work", description: "work", status: "pending" }, cwd);
17030
+ const claim = await claimTask(teamName, task.id, "worker-1", null, cwd);
17031
+ assert.ok(claim.ok);
17032
+ const workerRoot = join(stateRoot, "team", teamName, "workers/worker-1");
17033
+ await writeJson(join(workerRoot, "status.json"), {
17034
+ state: "working", current_task_id: task.id, current_claim_token: claim.claimToken,
17035
+ });
17036
+ const taskPath = join(stateRoot, "team", teamName, "tasks", `task-${task.id}.json`);
17037
+ await writeJson(taskPath, { ...claim.task, claim: { ...claim.task.claim, leased_until: new Date(0).toISOString() } });
17038
+ process.env.OMX_TEAM_INTERNAL_WORKER = `${teamName}/worker-1`;
17039
+ process.env.OMX_TEAM_WORKER = `${teamName}/worker-1`;
17040
+ process.env.OMX_TEAM_STATE_ROOT = stateRoot;
17041
+ const result = await dispatchCodexNativeHook({
17042
+ hook_event_name: "PostToolUse", cwd, tool_name: "Bash",
17043
+ tool_input: { command: "printf ok" }, tool_response: "ok\n",
17044
+ }, { cwd });
17045
+ assert.match(String(result.outputJson?.systemMessage), /LEASE LOST:.*lease_expired.*STOP editing/);
17046
+ const hookOutput = result.outputJson?.hookSpecificOutput as Record<string, unknown>;
17047
+ assert.equal(hookOutput.additionalContext, result.outputJson?.systemMessage);
17048
+ assert.equal(existsSync(join(workerRoot, "posttooluse-dedupe.json")), false);
17049
+ assert.equal(existsSync(join(workerRoot, "lease-loss.json")), true);
17050
+ } finally {
17051
+ await rm(cwd, { recursive: true, force: true });
17052
+ }
17053
+ });
17054
+
17055
+ for (const terminalStatus of ['completed', 'failed'] as const) {
17056
+ it(`allows separate idle status after native PostToolUse for an own ${terminalStatus} handoff without checkpointing`, async () => {
17057
+ const cwd = await mkdtemp(join(tmpdir(), "omx-native-hook-terminal-handoff-"));
17058
+ const teamName = "native-terminal-handoff";
17059
+ const stateRoot = join(cwd, ".omx/state");
17060
+ try {
17061
+ await configureAuthoritativeTeamWorker(cwd, teamName);
17062
+ const task = await createTask(teamName, { subject: "research", description: "no code", status: "pending", requires_code_change: false }, cwd);
17063
+ await createTask(teamName, { subject: "other ongoing work", description: "keep team active", status: "pending" }, cwd);
17064
+ const claim = await claimTask(teamName, task.id, "worker-1", null, cwd);
17065
+ assert.ok(claim.ok);
17066
+ await writeWorkerStatus(teamName, "worker-1", {
17067
+ state: "working", current_task_id: task.id, current_claim_token: claim.claimToken, updated_at: new Date().toISOString(),
17068
+ }, cwd);
17069
+ const workerRoot = join(stateRoot, "team", teamName, "workers/worker-1");
17070
+ const statusPath = join(workerRoot, "status.json");
17071
+ const taskPath = join(stateRoot, "team", teamName, "tasks", `task-${task.id}.json`);
17072
+ assert.ok((await transitionTaskStatus(teamName, task.id, "in_progress", terminalStatus, claim.claimToken, cwd, {
17073
+ result: "Research complete; no code changes.", error: "Research could not finish.",
17074
+ })).ok);
17075
+ const statusBefore = await readFile(statusPath, "utf8");
17076
+ const taskBefore = await readFile(taskPath, "utf8");
17077
+ const git = (args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
17078
+ git(["init"]);
17079
+ git(["config", "user.email", "test@example.com"]);
17080
+ git(["config", "user.name", "Test User"]);
17081
+ await writeFile(join(cwd, "work.txt"), "before\n");
17082
+ git(["add", "work.txt"]);
17083
+ git(["commit", "-m", "initial"]);
17084
+ const headBefore = git(["rev-parse", "HEAD"]);
17085
+ await writeFile(join(cwd, "work.txt"), "unverified terminal edits\n");
17086
+ const result = await dispatchCodexNativeHook({
17087
+ hook_event_name: "PostToolUse", cwd, tool_name: "Bash", tool_use_id: "terminal-handoff",
17088
+ tool_input: { command: "omx team api transition-task-status" }, tool_response: "handoff complete\n",
17089
+ }, { cwd });
17090
+ assert.doesNotMatch(JSON.stringify(result.outputJson), /LEASE LOST|STOP editing/);
17091
+ for (const file of ["lease-loss.json", "posttooluse-dedupe.json"]) assert.equal(existsSync(join(workerRoot, file)), false);
17092
+ assert.equal(existsSync(join(cwd, ".omx/reports/team-commit-hygiene", `${teamName}.ledger.json`)), false);
17093
+ assert.equal(git(["rev-parse", "HEAD"]), headBefore);
17094
+ assert.equal(git(["diff", "--cached"]), "");
17095
+ assert.equal(await readFile(join(cwd, "work.txt"), "utf8"), "unverified terminal edits\n");
17096
+ assert.equal(await readFile(taskPath, "utf8"), taskBefore);
17097
+ assert.equal(await readFile(statusPath, "utf8"), statusBefore);
17098
+ await writeWorkerStatus(teamName, "worker-1", { state: "idle", updated_at: new Date().toISOString() }, cwd);
17099
+ const idle = await dispatchCodexNativeHook({
17100
+ hook_event_name: "PostToolUse", cwd, tool_name: "Bash", tool_response: "idle\n",
17101
+ tool_input: { command: "write idle worker status" },
17102
+ }, { cwd });
17103
+ assert.doesNotMatch(JSON.stringify(idle.outputJson), /LEASE LOST|STOP editing/);
17104
+ assert.equal(JSON.parse(await readFile(statusPath, "utf8")).state, "idle");
17105
+ } finally {
17106
+ await rm(cwd, { recursive: true, force: true });
17107
+ }
17108
+ });
17109
+ }
17110
+
17111
+ it("surfaces a thrown automatic renewal membership timeout as native PostToolUse STOP without checkpoint or dedupe", async () => {
17112
+ const cwd = await mkdtemp(join(tmpdir(), "omx-native-hook-renewal-timeout-"));
17113
+ const teamName = "native-renewal-timeout";
17114
+ const stateRoot = join(cwd, ".omx/state");
17115
+ let release!: () => void;
17116
+ let barrier: Promise<void> | undefined;
17117
+ try {
17118
+ await configureAuthoritativeTeamWorker(cwd, teamName);
17119
+ const task = await createTask(teamName, { subject: "work", description: "work", status: "pending" }, cwd);
17120
+ const claim = await claimTask(teamName, task.id, "worker-1", null, cwd);
17121
+ assert.ok(claim.ok);
17122
+ const workerRoot = join(stateRoot, "team", teamName, "workers/worker-1");
17123
+ const statusPath = join(workerRoot, "status.json");
17124
+ await writeJson(statusPath, {
17125
+ state: "working", current_task_id: task.id, current_claim_token: claim.claimToken,
17126
+ });
17127
+ const taskPath = join(stateRoot, "team", teamName, "tasks", `task-${task.id}.json`);
17128
+ const taskBefore = await readFile(taskPath, "utf8");
17129
+ const statusBefore = await readFile(statusPath, "utf8");
17130
+ const git = (args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
17131
+ git(["init"]);
17132
+ git(["config", "user.email", "test@example.com"]);
17133
+ git(["config", "user.name", "Test User"]);
17134
+ await writeFile(join(cwd, "work.txt"), "before\n");
17135
+ git(["add", "work.txt"]);
17136
+ git(["commit", "-m", "initial"]);
17137
+ const headBefore = git(["rev-parse", "HEAD"]);
17138
+ await writeFile(join(cwd, "work.txt"), "unverified edits\n");
17139
+ process.env.OMX_TEAM_INTERNAL_WORKER = `${teamName}/worker-1`;
17140
+ process.env.OMX_TEAM_WORKER = `${teamName}/worker-1`;
17141
+ process.env.OMX_TEAM_STATE_ROOT = stateRoot;
17142
+ let acquired!: () => void;
17143
+ const ready = new Promise<void>((resolve) => { acquired = resolve; });
17144
+ const held = new Promise<void>((resolve) => { release = resolve; });
17145
+ barrier = withTeamTaskBarrier(teamName, cwd, async () => { acquired(); await held; });
17146
+ await ready;
17147
+ // Dispatch outside the barrier callback so ALS reentrancy cannot bypass its deadline.
17148
+ const result = await dispatchCodexNativeHook({
17149
+ hook_event_name: "PostToolUse", cwd, tool_name: "Bash", tool_use_id: "renewal-timeout",
17150
+ tool_input: { command: "printf ok" }, tool_response: "plain stdout/stderr\n",
17151
+ }, { cwd });
17152
+ assert.match(String(result.outputJson?.systemMessage), /LEASE LOST:.*Timed out acquiring team task lock.*STOP editing/);
17153
+ const hookOutput = result.outputJson?.hookSpecificOutput as Record<string, unknown>;
17154
+ assert.equal(hookOutput.additionalContext, result.outputJson?.systemMessage);
17155
+ assert.equal(existsSync(join(workerRoot, "posttooluse-dedupe.json")), false);
17156
+ assert.equal(existsSync(join(cwd, ".omx/reports/team-commit-hygiene", `${teamName}.ledger.json`)), false);
17157
+ assert.equal(existsSync(join(workerRoot, "lease-loss.json")), true);
17158
+ assert.equal(git(["rev-parse", "HEAD"]), headBefore);
17159
+ assert.equal(git(["diff", "--cached"]), "");
17160
+ assert.equal(await readFile(taskPath, "utf8"), taskBefore);
17161
+ assert.equal(await readFile(statusPath, "utf8"), statusBefore);
17162
+ } finally {
17163
+ release?.();
17164
+ await barrier;
17165
+ await rm(cwd, { recursive: true, force: true });
17166
+ }
17167
+ });
17168
+
16890
17169
  it("rejects foreign explicit worker roots for completed Stop/PostToolUse and ignores malformed internal identity", async () => {
16891
17170
  const cwd = await mkdtemp(join(tmpdir(), "omx-native-hook-team-worker-foreign-root-"));
16892
17171
  const workerCwd = join(cwd, "worker");
@@ -22,7 +22,7 @@ function git(cwd: string, args: string[], env: NodeJS.ProcessEnv = {}): string {
22
22
  return String(result.stdout || '').trim();
23
23
  }
24
24
 
25
- const TEMPLATE = `# oh-my-codex v0.0.0
25
+ const TEMPLATE = `# oh-my-codex v0.13.0
26
26
 
27
27
  ## Summary
28
28
 
@@ -107,7 +107,26 @@ describe('generate-release-body', () => {
107
107
  git(root, ['commit', '-m', 'release']);
108
108
  git(root, ['tag', 'v0.13.1']);
109
109
 
110
- await writeFile(join(root, 'RELEASE_BODY.md'), TEMPLATE);
110
+ await writeFile(join(root, 'RELEASE_BODY.md'), `# oh-my-codex v0.13.1
111
+
112
+ ## Summary
113
+
114
+ Custom summary that must stay intact.
115
+
116
+ ## Fixed
117
+
118
+ - Keep this handwritten section.
119
+
120
+ ## Verification
121
+
122
+ - npm test
123
+
124
+ ## Contributors
125
+
126
+ Outdated contributor text.
127
+
128
+ **Full Changelog**: [\`v0.0.0...v0.0.1\`](https://github.com/example/compare/v0.0.0...v0.0.1)
129
+ `);
111
130
  const originalFetch = global.fetch;
112
131
  global.fetch = (async () => new Response(JSON.stringify({
113
132
  commits: [
@@ -162,7 +181,26 @@ describe('generate-release-body', () => {
162
181
  git(root, ['tag', 'v0.15.0']);
163
182
  git(root, ['checkout', 'v0.15.1']);
164
183
 
165
- await writeFile(join(root, 'RELEASE_BODY.md'), TEMPLATE);
184
+ await writeFile(join(root, 'RELEASE_BODY.md'), `# oh-my-codex v0.15.1
185
+
186
+ ## Summary
187
+
188
+ Custom summary that must stay intact.
189
+
190
+ ## Fixed
191
+
192
+ - Keep this handwritten section.
193
+
194
+ ## Verification
195
+
196
+ - npm test
197
+
198
+ ## Contributors
199
+
200
+ Outdated contributor text.
201
+
202
+ **Full Changelog**: [\`v0.0.0...v0.0.1\`](https://github.com/example/compare/v0.0.0...v0.0.1)
203
+ `);
166
204
  await generateReleaseBody({
167
205
  cwd: root,
168
206
  templatePath: 'RELEASE_BODY.md',
@@ -205,7 +243,26 @@ describe('generate-release-body', () => {
205
243
  /invalid release compare range: v0\.13\.1 is not an ancestor of v0\.13\.0/,
206
244
  );
207
245
 
208
- await writeFile(join(root, 'RELEASE_BODY.md'), TEMPLATE);
246
+ await writeFile(join(root, 'RELEASE_BODY.md'), `# oh-my-codex v0.13.1
247
+
248
+ ## Summary
249
+
250
+ Custom summary that must stay intact.
251
+
252
+ ## Fixed
253
+
254
+ - Keep this handwritten section.
255
+
256
+ ## Verification
257
+
258
+ - npm test
259
+
260
+ ## Contributors
261
+
262
+ Outdated contributor text.
263
+
264
+ **Full Changelog**: [\`v0.0.0...v0.0.1\`](https://github.com/example/compare/v0.0.0...v0.0.1)
265
+ `);
209
266
  await assert.rejects(
210
267
  generateReleaseBody({
211
268
  cwd: root,
@@ -238,7 +295,7 @@ describe('generate-release-body', () => {
238
295
  git(root, ['commit', '-m', 'release']);
239
296
  git(root, ['tag', 'v0.13.1']);
240
297
 
241
- await writeFile(join(root, 'RELEASE_BODY.md'), `# oh-my-codex v0.0.0
298
+ await writeFile(join(root, 'RELEASE_BODY.md'), `# oh-my-codex v0.13.1
242
299
 
243
300
  ## Summary
244
301
 
@@ -272,4 +329,93 @@ Missing required sections.
272
329
  '**Full Changelog**: [`v0.1.0`](https://github.com/example/oh-my-codex/releases/tag/v0.1.0)',
273
330
  );
274
331
  });
332
+
333
+ it('rejects stale release body template with mismatched version', async () => {
334
+ const root = await mkdtemp(join(tmpdir(), 'omx-generate-release-body-stale-'));
335
+ try {
336
+ git(root, ['init']);
337
+ git(root, ['config', 'user.name', 'Release Bot']);
338
+ git(root, ['config', 'user.email', 'release@example.com']);
339
+
340
+ await writeFile(join(root, 'RELEASE_BODY.md'), `# oh-my-codex v0.21.46
341
+
342
+ ## Contributors
343
+
344
+ Thanks to the contributors who made this release possible.
345
+
346
+ **Full Changelog**: [\`v0.21.45...v0.21.46\`](https://github.com/example/compare/v0.21.45...v0.21.46)
347
+ `);
348
+ await writeFile(join(root, 'notes.txt'), 'release notes');
349
+ git(root, ['add', '.']);
350
+ git(root, ['commit', '-m', 'base']);
351
+ git(root, ['tag', 'v0.21.46']);
352
+
353
+ await writeFile(join(root, 'notes.txt'), 'new release notes');
354
+ git(root, ['add', 'notes.txt']);
355
+ git(root, ['commit', '-m', 'release']);
356
+ git(root, ['tag', 'v0.21.47']);
357
+
358
+ await assert.rejects(
359
+ generateReleaseBody({
360
+ cwd: root,
361
+ templatePath: 'RELEASE_BODY.md',
362
+ outPath: 'RELEASE_BODY.generated.md',
363
+ currentTag: 'v0.21.47',
364
+ previousTag: 'v0.21.46',
365
+ repo: 'example/oh-my-codex',
366
+ }),
367
+ /stale template detected/,
368
+ );
369
+ } finally {
370
+ await rm(root, { recursive: true, force: true });
371
+ }
372
+ });
373
+
374
+ it('accepts release body template with matching version', async () => {
375
+ const root = await mkdtemp(join(tmpdir(), 'omx-generate-release-body-valid-'));
376
+ try {
377
+ git(root, ['init']);
378
+ git(root, ['config', 'user.name', 'Release Bot']);
379
+ git(root, ['config', 'user.email', 'release@example.com']);
380
+
381
+ await writeFile(join(root, 'RELEASE_BODY.md'), `# oh-my-codex v0.21.46
382
+
383
+ ## Contributors
384
+
385
+ Thanks to the contributors who made this release possible.
386
+
387
+ **Full Changelog**: [\`v0.21.45...v0.21.46\`](https://github.com/example/compare/v0.21.45...v0.21.46)
388
+ `);
389
+ await writeFile(join(root, 'notes.txt'), 'release notes');
390
+ git(root, ['add', '.']);
391
+ git(root, ['commit', '-m', 'base']);
392
+ git(root, ['tag', 'v0.21.46']);
393
+
394
+ await writeFile(join(root, 'RELEASE_BODY.md'), `# oh-my-codex v0.21.47
395
+
396
+ ## Contributors
397
+
398
+ Thanks to the contributors who made this release possible.
399
+
400
+ **Full Changelog**: [\`v0.21.46...v0.21.47\`](https://github.com/example/compare/v0.21.46...v0.21.47)
401
+ `);
402
+ await writeFile(join(root, 'notes.txt'), 'new release notes');
403
+ git(root, ['add', '.']);
404
+ git(root, ['commit', '-m', 'release']);
405
+ git(root, ['tag', 'v0.21.47']);
406
+
407
+ const generated = await generateReleaseBody({
408
+ cwd: root,
409
+ templatePath: 'RELEASE_BODY.md',
410
+ outPath: 'RELEASE_BODY.generated.md',
411
+ currentTag: 'v0.21.47',
412
+ previousTag: 'v0.21.46',
413
+ repo: 'example/oh-my-codex',
414
+ });
415
+ assert.match(generated, /# oh-my-codex v0\.21\.47/);
416
+ assert.match(generated, /## Contributors/);
417
+ } finally {
418
+ await rm(root, { recursive: true, force: true });
419
+ }
420
+ });
275
421
  });
@@ -22866,10 +22866,16 @@ export async function dispatchCodexNativeHook(
22866
22866
  await markTeamTransportFailure(cwd, payload);
22867
22867
  }
22868
22868
  if (hasCanonicalInternalTeamWorkerDeclaration()) {
22869
- await handleTeamWorkerPostToolUseSuccess(payload, cwd);
22869
+ const workerResult = await handleTeamWorkerPostToolUseSuccess(payload, cwd);
22870
+ if (workerResult.stopMessage) {
22871
+ outputJson = {
22872
+ systemMessage: workerResult.stopMessage,
22873
+ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: workerResult.stopMessage },
22874
+ };
22875
+ }
22870
22876
  }
22871
22877
  }
22872
- outputJson = buildNativePostToolUseOutput(payload);
22878
+ outputJson ??= buildNativePostToolUseOutput(payload);
22873
22879
  } else if (hookEventName === "Stop") {
22874
22880
  if (declaredTeamWorkerStopOnly) {
22875
22881
  outputJson = await buildStopHookOutput(payload, cwd, stateDir, { teamWorkerOnly: true });
@@ -178,6 +178,21 @@ export function buildFullChangelogLine(repo: string, currentTag: string, previou
178
178
  return `**Full Changelog**: [\`${currentTag}\`](https://github.com/${repo}/releases/tag/${currentTag})`;
179
179
  }
180
180
 
181
+ function extractTemplateVersion(markdown: string): string | undefined {
182
+ const match = markdown.match(/^#\s+oh-my-codex\s+(v\d+\.\d+\.\d+)/m);
183
+ return match?.[1];
184
+ }
185
+
186
+ function validateTemplateVersion(markdown: string, currentTag: string): void {
187
+ const templateVersion = extractTemplateVersion(markdown);
188
+ if (!templateVersion) {
189
+ throw new Error('release body template is missing a top-level title with version (expected: # oh-my-codex <version>)');
190
+ }
191
+ if (templateVersion !== currentTag) {
192
+ throw new Error(`release body template version (${templateVersion}) does not match the current tag (${currentTag}); stale template detected`);
193
+ }
194
+ }
195
+
181
196
  function replaceTitle(markdown: string, currentTag: string): string {
182
197
  if (!/^#\s+/m.test(markdown)) {
183
198
  throw new Error('release body template is missing a top-level title');
@@ -298,6 +313,7 @@ export async function generateReleaseBody(options: GenerateReleaseBodyOptions):
298
313
  });
299
314
 
300
315
  let markdown = readFileSync(templatePath, 'utf-8');
316
+ validateTemplateVersion(markdown, currentTag);
301
317
  markdown = replaceTitle(markdown, currentTag);
302
318
  markdown = replaceSectionBody(markdown, 'Contributors', renderContributorsSection(contributors));
303
319
  markdown = replaceFullChangelogLine(markdown, buildFullChangelogLine(repo || '', currentTag, previousTag));
@@ -0,0 +1,69 @@
1
+ import { readFile, writeFile } from 'node:fs/promises';
2
+ import { join, resolve } from 'node:path';
3
+ import { teamReadTask, teamRenewTaskClaim, teamSendMessage, type RenewTaskClaimResult, type TeamTask } from '../../team/team-ops.js';
4
+ import { resolveCanonicalTeamStateRoot } from '../../team/state-root.js';
5
+
6
+ type WorkerTaskLeaseRenewalResult = RenewTaskClaimResult
7
+ | { ok: false; error: string }
8
+ // Local automatic-hook outcome only: terminal handoff grants no lease or editing authority.
9
+ | { ok: true; task: TeamTask; terminalHandoff: true };
10
+
11
+ /** Heartbeats carry the worker's captured token, never a token looked up from the current task. */
12
+ export async function renewWorkerTaskLease(
13
+ stateRoot: string,
14
+ teamName: string,
15
+ workerName: string,
16
+ ): Promise<WorkerTaskLeaseRenewalResult | null> {
17
+ let status: { state?: string; current_task_id?: string; current_claim_token?: string };
18
+ try {
19
+ status = JSON.parse(await readFile(join(stateRoot, 'team', teamName, 'workers', workerName, 'status.json'), 'utf8'));
20
+ } catch (error) {
21
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT' || error instanceof SyntaxError) return null;
22
+ return { ok: false, error: `renewal_error:${String(error)}` };
23
+ }
24
+ if (!status) return null;
25
+ if (status.state !== 'working' || typeof status.current_task_id !== 'string' || typeof status.current_claim_token !== 'string'
26
+ || !status.current_task_id || !status.current_claim_token) return null;
27
+ try {
28
+ const config = JSON.parse(await readFile(join(stateRoot, 'team', teamName, 'config.json'), 'utf8'));
29
+ const cwd = typeof config.leader_cwd === 'string' && config.leader_cwd ? config.leader_cwd : resolve(stateRoot, '../..');
30
+ // Do not let a cross-worktree hook renew a different team's local state.
31
+ if (resolveCanonicalTeamStateRoot(cwd) !== resolve(stateRoot)) return null;
32
+ const renewal = await teamRenewTaskClaim(teamName, status.current_task_id, workerName, status.current_claim_token, cwd);
33
+ if (!renewal.ok && renewal.error === 'already_terminal') {
34
+ const task = await teamReadTask(teamName, status.current_task_id, cwd);
35
+ if (task && (task.status === 'completed' || task.status === 'failed') && task.owner === workerName && !task.claim) {
36
+ return { ok: true, task, terminalHandoff: true };
37
+ }
38
+ }
39
+ return renewal;
40
+ } catch (error) {
41
+ // Automatic callers must report STOP, not lose renewal exceptions in their outer hook catch.
42
+ return { ok: false, error: `renewal_error:${String(error)}` };
43
+ }
44
+ }
45
+
46
+ /** Keep lease loss visible even when notify treats hook errors as non-critical. */
47
+ export async function reportWorkerTaskLeaseLoss(
48
+ stateRoot: string,
49
+ teamName: string,
50
+ workerName: string,
51
+ error: string,
52
+ ): Promise<string> {
53
+ const message = `LEASE LOST: ${teamName}/${workerName} renewal rejected (${error}). STOP editing and claim-dependent work; contact the leader. Do not adopt another token or revive an expired claim.`;
54
+ const warn = (detail = ''): void => {
55
+ try { process.stderr.write(`${message}${detail}\n`); } catch { /* Diagnostics must not erase the returned STOP. */ }
56
+ };
57
+ warn();
58
+ const config = await readFile(join(stateRoot, 'team', teamName, 'config.json'), 'utf8').then(JSON.parse).catch(() => ({}));
59
+ const cwd = typeof config?.leader_cwd === 'string' && config.leader_cwd ? config.leader_cwd : resolve(stateRoot, '../..');
60
+ await writeFile(join(stateRoot, 'team', teamName, 'workers', workerName, 'lease-loss.json'), JSON.stringify({ message, error, updated_at: new Date().toISOString() })).catch((cause) => {
61
+ warn(` Lease-loss record failed: ${String(cause)}`);
62
+ });
63
+ for (const recipient of [workerName, 'leader-fixed']) {
64
+ await teamSendMessage(teamName, workerName, recipient, message, cwd).catch((cause) => {
65
+ warn(` Notification to ${recipient} failed: ${String(cause)}`);
66
+ });
67
+ }
68
+ return message;
69
+ }