@codetreker/daynight 0.21.9 → 0.21.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +359 -27
  2. package/dist/api/client.d.ts +4 -1
  3. package/dist/api/client.js +18 -1
  4. package/dist/api/client.js.map +1 -1
  5. package/dist/api/parse.d.ts +3 -1
  6. package/dist/api/parse.js +27 -0
  7. package/dist/api/parse.js.map +1 -1
  8. package/dist/api/types.d.ts +18 -3
  9. package/dist/cli/commands.js +2 -0
  10. package/dist/cli/commands.js.map +1 -1
  11. package/dist/commands/skill/skills/using-daynight/references/handoff.md +3 -3
  12. package/dist/commands/worker/cleanup.d.ts +6 -0
  13. package/dist/commands/worker/cleanup.js +173 -0
  14. package/dist/commands/worker/cleanup.js.map +1 -0
  15. package/dist/commands/worker/config.d.ts +21 -0
  16. package/dist/commands/worker/config.js +144 -0
  17. package/dist/commands/worker/config.js.map +1 -0
  18. package/dist/commands/worker/control.d.ts +55 -0
  19. package/dist/commands/worker/control.js +151 -0
  20. package/dist/commands/worker/control.js.map +1 -0
  21. package/dist/commands/worker/coordinator.d.ts +35 -0
  22. package/dist/commands/worker/coordinator.js +548 -0
  23. package/dist/commands/worker/coordinator.js.map +1 -0
  24. package/dist/commands/worker/definition.d.ts +2 -0
  25. package/dist/commands/worker/definition.js +50 -0
  26. package/dist/commands/worker/definition.js.map +1 -0
  27. package/dist/commands/worker/diagnostics.d.ts +20 -0
  28. package/dist/commands/worker/diagnostics.js +56 -0
  29. package/dist/commands/worker/diagnostics.js.map +1 -0
  30. package/dist/commands/worker/execution.d.ts +41 -0
  31. package/dist/commands/worker/execution.js +318 -0
  32. package/dist/commands/worker/execution.js.map +1 -0
  33. package/dist/commands/worker/herdr/agents.d.ts +186 -0
  34. package/dist/commands/worker/herdr/agents.js +726 -0
  35. package/dist/commands/worker/herdr/agents.js.map +1 -0
  36. package/dist/commands/worker/herdr/arguments.d.ts +8 -0
  37. package/dist/commands/worker/herdr/arguments.js +58 -0
  38. package/dist/commands/worker/herdr/arguments.js.map +1 -0
  39. package/dist/commands/worker/herdr/codex-input.d.ts +2 -0
  40. package/dist/commands/worker/herdr/codex-input.js +35 -0
  41. package/dist/commands/worker/herdr/codex-input.js.map +1 -0
  42. package/dist/commands/worker/herdr/command.d.ts +22 -0
  43. package/dist/commands/worker/herdr/command.js +115 -0
  44. package/dist/commands/worker/herdr/command.js.map +1 -0
  45. package/dist/commands/worker/herdr/instance.d.ts +56 -0
  46. package/dist/commands/worker/herdr/instance.js +322 -0
  47. package/dist/commands/worker/herdr/instance.js.map +1 -0
  48. package/dist/commands/worker/herdr/preflight.d.ts +40 -0
  49. package/dist/commands/worker/herdr/preflight.js +251 -0
  50. package/dist/commands/worker/herdr/preflight.js.map +1 -0
  51. package/dist/commands/worker/herdr/rpc.d.ts +29 -0
  52. package/dist/commands/worker/herdr/rpc.js +186 -0
  53. package/dist/commands/worker/herdr/rpc.js.map +1 -0
  54. package/dist/commands/worker/herdr.d.ts +95 -0
  55. package/dist/commands/worker/herdr.js +35 -0
  56. package/dist/commands/worker/herdr.js.map +1 -0
  57. package/dist/commands/worker/index.d.ts +18 -0
  58. package/dist/commands/worker/index.js +58 -0
  59. package/dist/commands/worker/index.js.map +1 -0
  60. package/dist/commands/worker/instance-lock.d.ts +5 -0
  61. package/dist/commands/worker/instance-lock.js +11 -1
  62. package/dist/commands/worker/instance-lock.js.map +1 -1
  63. package/dist/commands/worker/prompts.d.ts +4 -0
  64. package/dist/commands/worker/prompts.js +64 -0
  65. package/dist/commands/worker/prompts.js.map +1 -0
  66. package/dist/commands/worker/remote.d.ts +23 -0
  67. package/dist/commands/worker/remote.js +146 -0
  68. package/dist/commands/worker/remote.js.map +1 -0
  69. package/dist/commands/worker/runtime.d.ts +16 -0
  70. package/dist/commands/worker/runtime.js +384 -0
  71. package/dist/commands/worker/runtime.js.map +1 -0
  72. package/dist/commands/worker/store.d.ts +73 -5
  73. package/dist/commands/worker/store.js +475 -36
  74. package/dist/commands/worker/store.js.map +1 -1
  75. package/dist/commands/worker/types.d.ts +37 -1
  76. package/dist/commands/worker/worktrees.d.ts +1 -0
  77. package/dist/commands/worker/worktrees.js +9 -0
  78. package/dist/commands/worker/worktrees.js.map +1 -1
  79. package/dist/config/document.d.ts +1 -1
  80. package/dist/config/document.js +1 -0
  81. package/dist/config/document.js.map +1 -1
  82. package/dist/platform/instance-lock.d.ts +4 -0
  83. package/dist/platform/instance-lock.js +9 -1
  84. package/dist/platform/instance-lock.js.map +1 -1
  85. package/package.json +2 -2
@@ -2,6 +2,7 @@ import path from "node:path";
2
2
  import Database from "better-sqlite3";
3
3
  import { canonicalId } from "../../api/parse.js";
4
4
  import { normalizeServerUrl } from "../../config/server.js";
5
+ import { parseHerdrExecutionLabel } from "./herdr/agents.js";
5
6
  const integer = (value, name, minimum = 0) => {
6
7
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value < minimum)
7
8
  throw new Error(`${name} must be a safe integer of at least ${minimum}.`);
@@ -61,6 +62,10 @@ const parseConfiguration = (value) => {
61
62
  return { agent: oneOf(data.agent, ["copilot", "codex"], "Agent"), model: nullable(data.model, (entry) => text(entry, "Model")),
62
63
  args: data.args.map((entry) => text(entry, "Agent argument", true)), recoveryLimit: integer(data.recoveryLimit, "Recovery limit") };
63
64
  };
65
+ const parseClaimAttempt = (value) => {
66
+ const data = record(value, ["taskId", "claimId", "worktreeId", "workerId", "userId", "expectedVersion", "configuration"], "Claim attempt");
67
+ return { taskId: id(data.taskId, "Attempt task ID"), claimId: id(data.claimId, "Attempt claim ID"), worktreeId: id(data.worktreeId, "Attempt worktree ID"), workerId: id(data.workerId, "Attempt worker ID"), userId: id(data.userId, "Attempt user ID"), expectedVersion: version(data.expectedVersion), configuration: parseConfiguration(data.configuration) };
68
+ };
64
69
  const parseWorktree = (value) => {
65
70
  const data = record(value, ["repositoryPath", "commonDirectory", "worktreePath", "branch"], "Worktree binding");
66
71
  return { repositoryPath: absolutePath(data.repositoryPath, "Repository path"), commonDirectory: absolutePath(data.commonDirectory, "Git common directory"), worktreePath: absolutePath(data.worktreePath, "Worktree path"), branch: text(data.branch, "Worktree branch") };
@@ -77,20 +82,100 @@ const parseResources = (value) => {
77
82
  const data = record(value, ["worktree", "herdr", "nativeSession"], "Execution resources");
78
83
  return { worktree: nullable(data.worktree, parseWorktree), herdr: nullable(data.herdr, parseHerdr), nativeSession: nullable(data.nativeSession, parseNative) };
79
84
  };
85
+ const parseTaskBinding = (value) => {
86
+ const data = record(value, ["session", "workspaceId", "paneId", "terminalId"], "Local Herdr binding");
87
+ return { session: text(data.session, "Herdr session"), workspaceId: text(data.workspaceId, "Herdr workspace ID"), paneId: text(data.paneId, "Herdr pane ID"), terminalId: text(data.terminalId, "Herdr terminal ID") };
88
+ };
89
+ const parseWorkspaceEvidence = (value) => {
90
+ const data = record(value, ["binding", "ownerLabel", "environment"], "Herdr workspace evidence");
91
+ const environment = record(data.environment, ["XDG_CONFIG_HOME", "XDG_STATE_HOME"], "Herdr workspace environment");
92
+ const config = text(environment.XDG_CONFIG_HOME, "Workspace XDG_CONFIG_HOME", true);
93
+ const state = text(environment.XDG_STATE_HOME, "Workspace XDG_STATE_HOME", true);
94
+ if (config.includes("\0") || state.includes("\0"))
95
+ throw new Error("The workspace environment cannot contain NUL.");
96
+ return { binding: parseTaskBinding(data.binding), ownerLabel: text(data.ownerLabel, "Workspace owner label"), environment: { XDG_CONFIG_HOME: config, XDG_STATE_HOME: state } };
97
+ };
98
+ const parseLaunchEvidence = (value) => {
99
+ const data = record(value, ["binding", "ownerLabel", "agent", "argv", "referenceBaseline", "workspaceEvidence"], "Herdr launch evidence");
100
+ if (!Array.isArray(data.argv) || data.argv.length === 0)
101
+ throw new Error("Herdr launch arguments must be a nonempty array.");
102
+ return { binding: parseTaskBinding(data.binding), ownerLabel: text(data.ownerLabel, "Launch owner label"), agent: oneOf(data.agent, ["codex", "copilot"], "Launch agent"), argv: data.argv.map((value) => text(value, "Launch argument", true)), referenceBaseline: oneOf(data.referenceBaseline, ["empty"], "Launch reference baseline"), workspaceEvidence: parseWorkspaceEvidence(data.workspaceEvidence) };
103
+ };
104
+ const processId = (value) => {
105
+ const result = integer(value, "Herdr process ID", 1);
106
+ if (result > 2_147_483_647)
107
+ throw new Error("Herdr process ID exceeds the supported process identifier range.");
108
+ return result;
109
+ };
110
+ const parseStopObservation = (value) => {
111
+ const data = record(value, ["binding", "ownerLabel", "agent", "nativeSessionId", "shellPid", "processIds", "nativeProcessIds", "observedAt"], "Herdr stop observation");
112
+ if (!Array.isArray(data.processIds) || data.processIds.length === 0)
113
+ throw new Error("The original native process observation must be nonempty.");
114
+ const shellPid = processId(data.shellPid);
115
+ const processIds = data.processIds.map(processId);
116
+ if (new Set(processIds).size !== processIds.length || processIds.includes(shellPid))
117
+ throw new Error("The original native process observation contains duplicate or shell process IDs.");
118
+ const nativeProcessIds = nullable(data.nativeProcessIds, (value) => {
119
+ if (!Array.isArray(value) || value.length === 0)
120
+ throw new Error("Native process IDs must be a nonempty array.");
121
+ const native = value.map(processId);
122
+ if (new Set(native).size !== native.length || native.includes(shellPid) || native.some((entry) => !processIds.includes(entry)))
123
+ throw new Error("Native process IDs must be unique original process IDs and exclude the task shell.");
124
+ return native;
125
+ });
126
+ return { binding: parseTaskBinding(data.binding), ownerLabel: text(data.ownerLabel, "Stop owner label"), agent: oneOf(data.agent, ["codex", "copilot"], "Stop agent"), nativeSessionId: nullable(data.nativeSessionId, (value) => id(value, "Stopped native session ID")), shellPid, processIds, nativeProcessIds, observedAt: integer(data.observedAt, "Stop observation time") };
127
+ };
128
+ const parseExecutionSummary = (value) => {
129
+ const data = record(value, ["version", "herdr", "nativeSessionId", "phase", "submission"], "Execution summary mutation");
130
+ return { version: version(data.version), herdr: nullable(data.herdr, parseHerdr), nativeSessionId: nullable(data.nativeSessionId, (value) => id(value, "Summary native session ID")), phase: oneOf(data.phase, ["preparing", "executing", "verifying", "completing", "waiting", "paused"], "Summary phase"), submission: oneOf(data.submission, ["unknown", "confirmed", "rejected"], "Summary submission") };
131
+ };
132
+ const parseNativeExecution = (value) => {
133
+ const data = record(value, ["terminalId", "workspaceSubmission", "workspaceEvidence", "launchEvidence", "launchSubmission", "promptSubmission", "stopObservation", "summary"], "Native execution state");
134
+ const result = { terminalId: nullable(data.terminalId, (value) => text(value, "Herdr terminal ID")), workspaceSubmission: oneOf(data.workspaceSubmission, ["not-submitted", "unknown", "acknowledged"], "Herdr workspace submission"), workspaceEvidence: nullable(data.workspaceEvidence, parseWorkspaceEvidence), launchEvidence: nullable(data.launchEvidence, parseLaunchEvidence), launchSubmission: oneOf(data.launchSubmission, ["never-submitted", "unknown", "acknowledged"], "Native launch submission"), promptSubmission: oneOf(data.promptSubmission, ["not-submitted", "unknown", "submitted"], "Native prompt submission"), stopObservation: nullable(data.stopObservation, parseStopObservation), summary: nullable(data.summary, parseExecutionSummary) };
135
+ if ((result.launchSubmission === "acknowledged") !== (result.launchEvidence !== null))
136
+ throw new Error("Acknowledged native launch requires its original launch evidence.");
137
+ if (result.launchSubmission === "never-submitted" && (result.promptSubmission !== "not-submitted" || result.stopObservation !== null))
138
+ throw new Error("An unlaunched native execution cannot have submitted input or original native process evidence.");
139
+ return result;
140
+ };
141
+ const freshNativeExecution = () => ({ terminalId: null, workspaceSubmission: "not-submitted", workspaceEvidence: null, launchEvidence: null, launchSubmission: "never-submitted", promptSubmission: "not-submitted", stopObservation: null, summary: null });
142
+ const unknownNativeExecution = () => ({ ...freshNativeExecution(), workspaceSubmission: "unknown", launchSubmission: "unknown", promptSubmission: "unknown" });
143
+ const withUserScope = (task, userId) => {
144
+ const owner = id(userId, "Claim user ID");
145
+ if (task.userId !== null && task.userId !== owner)
146
+ throw new Error("The original authenticated claim owner cannot be replaced.");
147
+ if (task.userId === null && (task.cleanup?.kind === "terminal" || task.control !== null))
148
+ throw new Error("An existing terminal or control intent with unknown authenticated scope cannot acquire an inferred owner.");
149
+ return { ...task, userId: owner };
150
+ };
151
+ export const isUnstartedPendingSource = (task) => {
152
+ const native = task.nativeExecution;
153
+ return task.status === "pending" && task.cleanup === null && task.resources.worktree === null && task.resources.herdr === null && task.resources.nativeSession === null
154
+ && native !== null && native.terminalId === null && native.workspaceSubmission === "not-submitted" && native.workspaceEvidence === null
155
+ && native.launchSubmission === "never-submitted" && native.launchEvidence === null && native.promptSubmission === "not-submitted" && native.stopObservation === null && native.summary === null;
156
+ };
157
+ export const isUnstartedPending = (task) => task.control === null && isUnstartedPendingSource(task);
80
158
  const parseRecovery = (value) => {
81
159
  const data = record(value, ["count", "pauseReason", "retryAuthorized"], "Recovery state");
82
160
  return { count: integer(data.count, "Recovery count"), pauseReason: nullable(data.pauseReason, (entry) => text(entry, "Pause reason")), retryAuthorized: bool(data.retryAuthorized, "Recovery retry authorization") };
83
161
  };
162
+ const parseCleanupBaseline = (value) => {
163
+ const data = record(value, ["stateChangeSeq", "completionSeq"], "Cleanup completion baseline");
164
+ return { stateChangeSeq: integer(data.stateChangeSeq, "Cleanup state-change sequence"), completionSeq: integer(data.completionSeq, "Cleanup completion sequence") };
165
+ };
84
166
  const parseCleanup = (value) => {
85
- const data = record(value, ["kind", "startedAt", "deadline", "input", "result", "error", "agentStopped", "workspaceClosed", "worktreeDeleted"], "Cleanup state");
167
+ const data = record(value, ["kind", "startedAt", "deadline", "input", "baseline", "result", "error", "agentStopped", "workspaceClosed", "worktreeDeleted"], "Cleanup state");
86
168
  const result = { kind: oneOf(data.kind, ["terminal", "shutdown"], "Cleanup kind"), startedAt: integer(data.startedAt, "Cleanup start"), deadline: integer(data.deadline, "Cleanup deadline"),
87
169
  input: oneOf(data.input, ["not-submitted", "unknown", "submitted", "rejected", "unavailable"], "Cleanup input state"),
170
+ baseline: nullable(data.baseline, parseCleanupBaseline),
88
171
  result: nullable(data.result, (entry) => oneOf(entry, ["completed", "timed-out", "failed", "unavailable"], "Cleanup result")), error: nullable(data.error, (entry) => text(entry, "Cleanup error")),
89
172
  agentStopped: bool(data.agentStopped, "Agent stopped"), workspaceClosed: bool(data.workspaceClosed, "Workspace closed"), worktreeDeleted: bool(data.worktreeDeleted, "Worktree deleted") };
90
173
  if (result.deadline < result.startedAt || result.deadline - result.startedAt > 600_000)
91
174
  throw new Error("Cleanup deadline must be within ten minutes of its original start.");
92
175
  if ((result.workspaceClosed && !result.agentStopped) || (result.worktreeDeleted && !result.workspaceClosed))
93
176
  throw new Error("Cleanup progress is out of order.");
177
+ if (result.baseline !== null && result.input !== "submitted")
178
+ throw new Error("A cleanup completion baseline requires confirmed input submission.");
94
179
  return result;
95
180
  };
96
181
  const parseIntent = (value) => {
@@ -120,32 +205,73 @@ const parseControl = (value) => {
120
205
  return result;
121
206
  };
122
207
  const same = (left, right) => JSON.stringify(left) === JSON.stringify(right);
123
- const projectColumns = "server_origin AS serverOrigin, project_id AS projectId, repo_url AS repoUrl, local_path AS localPath";
208
+ const validateNativeExecution = (task) => {
209
+ const state = task.nativeExecution;
210
+ if (state === null)
211
+ return task;
212
+ const binding = task.resources.herdr === null || state.terminalId === null ? null : { ...task.resources.herdr, terminalId: state.terminalId };
213
+ if (state.terminalId !== null && task.resources.herdr === null)
214
+ throw new Error("The local terminal requires its core Herdr binding.");
215
+ if (state.workspaceSubmission === "acknowledged" && binding === null)
216
+ throw new Error("An acknowledged workspace requires its full original Herdr binding.");
217
+ const owner = { ...claimKey(task), worktreeId: task.worktreeId };
218
+ const evidence = (value) => {
219
+ if (binding === null || !same(value.binding, binding))
220
+ throw new Error("Native execution evidence differs from its original Herdr binding.");
221
+ if (!same(parseHerdrExecutionLabel(value.ownerLabel), owner))
222
+ throw new Error("Native execution evidence belongs to another claim or worktree.");
223
+ };
224
+ if (state.workspaceEvidence !== null)
225
+ evidence(state.workspaceEvidence);
226
+ if (state.launchEvidence !== null) {
227
+ evidence(state.launchEvidence);
228
+ evidence(state.launchEvidence.workspaceEvidence);
229
+ if (!same(state.workspaceEvidence, state.launchEvidence.workspaceEvidence))
230
+ throw new Error("The native launch does not preserve its original workspace evidence.");
231
+ if (task.configuration !== null && state.launchEvidence.agent !== task.configuration.agent)
232
+ throw new Error("The native launch agent differs from its frozen configuration.");
233
+ if (state.launchEvidence.argv[0] !== state.launchEvidence.agent)
234
+ throw new Error("The native launch arguments name another executable.");
235
+ }
236
+ if (state.stopObservation !== null) {
237
+ evidence(state.stopObservation);
238
+ if (task.configuration !== null && state.stopObservation.agent !== task.configuration.agent)
239
+ throw new Error("The stopped agent differs from its frozen configuration.");
240
+ if (state.stopObservation.nativeSessionId !== null && task.resources.nativeSession !== null && state.stopObservation.nativeSessionId !== task.resources.nativeSession.sessionId)
241
+ throw new Error("The stopped native session differs from the original session.");
242
+ }
243
+ return task;
244
+ };
245
+ const projectColumns = "server_origin AS serverOrigin, project_id AS projectId, repo_url AS repoUrl, local_path AS localPath, claim_attempt AS claimAttempt";
246
+ const asProject = (row) => ({ ...row, claimAttempt: row.claimAttempt === null ? null : parseClaimAttempt(JSON.parse(row.claimAttempt)) });
124
247
  const taskColumns = `server_origin AS serverOrigin, project_id AS projectId, task_id AS taskId, claim_id AS claimId,
125
- worker_id AS workerId, worktree_id AS worktreeId, status, repo_url AS repoUrl, repository_path AS repositoryPath,
126
- configuration, resources, recovery, cleanup, control, created_at AS createdAt, updated_at AS updatedAt`;
127
- const asTask = (row) => ({ ...row,
248
+ worker_id AS workerId, worktree_id AS worktreeId, user_id AS userId, status, repo_url AS repoUrl, repository_path AS repositoryPath,
249
+ configuration, resources, native_execution AS nativeExecution, recovery, cleanup, control, created_at AS createdAt, updated_at AS updatedAt`;
250
+ const asTask = (row) => validateNativeExecution({ ...row,
251
+ userId: row.userId === null ? null : id(row.userId, "Claim user ID"),
128
252
  configuration: row.configuration === null ? null : parseConfiguration(JSON.parse(row.configuration)),
253
+ nativeExecution: row.nativeExecution === null ? null : parseNativeExecution(JSON.parse(row.nativeExecution)),
129
254
  resources: parseResources(JSON.parse(row.resources)), recovery: parseRecovery(JSON.parse(row.recovery)),
130
255
  cleanup: row.cleanup === null ? null : parseCleanup(JSON.parse(row.cleanup)), control: row.control === null ? null : parseControl(JSON.parse(row.control)) });
131
256
  const schema = `
132
257
  CREATE TABLE projects (
133
258
  server_origin TEXT NOT NULL, project_id TEXT NOT NULL, repo_url TEXT NOT NULL, local_path TEXT NOT NULL,
259
+ claim_attempt TEXT CHECK(claim_attempt IS NULL OR json_valid(claim_attempt)),
134
260
  PRIMARY KEY(server_origin, project_id)
135
261
  ) STRICT;
136
262
  CREATE TABLE tasks (
137
263
  server_origin TEXT NOT NULL, project_id TEXT NOT NULL, task_id TEXT NOT NULL, claim_id TEXT NOT NULL,
138
- worker_id TEXT NOT NULL, worktree_id TEXT NOT NULL,
264
+ worker_id TEXT NOT NULL, worktree_id TEXT NOT NULL, user_id TEXT,
139
265
  status TEXT NOT NULL CHECK(status IN ('pending', 'active', 'done')),
140
266
  repo_url TEXT NOT NULL, repository_path TEXT NOT NULL,
141
267
  configuration TEXT CHECK(configuration IS NULL OR json_valid(configuration)),
142
- resources TEXT NOT NULL CHECK(json_valid(resources)), recovery TEXT NOT NULL CHECK(json_valid(recovery)),
268
+ resources TEXT NOT NULL CHECK(json_valid(resources)), native_execution TEXT CHECK(native_execution IS NULL OR json_valid(native_execution)), recovery TEXT NOT NULL CHECK(json_valid(recovery)),
143
269
  cleanup TEXT CHECK(cleanup IS NULL OR json_valid(cleanup)), control TEXT CHECK(control IS NULL OR json_valid(control)),
144
270
  created_at INTEGER NOT NULL CHECK(created_at >= 0), updated_at INTEGER NOT NULL CHECK(updated_at >= 0),
145
271
  PRIMARY KEY(server_origin, project_id, task_id, claim_id), UNIQUE(server_origin, claim_id)
146
272
  ) STRICT;
147
273
  CREATE UNIQUE INDEX tasks_one_active_per_task ON tasks(server_origin, project_id, task_id) WHERE status = 'active';
148
- PRAGMA user_version = 1;
274
+ PRAGMA user_version = 3;
149
275
  `;
150
276
  export const openWorkerStore = (databaseFile, options = {}) => {
151
277
  absolutePath(databaseFile, "The SQLite database path");
@@ -162,8 +288,8 @@ export const openWorkerStore = (databaseFile, options = {}) => {
162
288
  throw new Error("SQLite refused synchronous=FULL.");
163
289
  db.transaction(() => {
164
290
  const currentVersion = db.pragma("user_version", { simple: true });
165
- if (currentVersion !== 0 && currentVersion !== 1)
166
- throw new Error(`Unsupported worker SQLite schema version ${currentVersion}; supported version is 1.`);
291
+ if (currentVersion !== 0 && currentVersion !== 1 && currentVersion !== 2 && currentVersion !== 3)
292
+ throw new Error(`Unsupported worker SQLite schema version ${currentVersion}; supported version is 3.`);
167
293
  const tables = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").all();
168
294
  if (currentVersion === 0) {
169
295
  if (tables.length !== 0)
@@ -172,6 +298,10 @@ export const openWorkerStore = (databaseFile, options = {}) => {
172
298
  }
173
299
  else if (!same(tables.map(({ name }) => name), ["projects", "tasks"]))
174
300
  throw new Error("The worker database does not contain its projects/tasks schema.");
301
+ if (currentVersion === 1)
302
+ db.exec("ALTER TABLE tasks ADD COLUMN native_execution TEXT CHECK(native_execution IS NULL OR json_valid(native_execution)); ALTER TABLE tasks ADD COLUMN user_id TEXT; ALTER TABLE projects ADD COLUMN claim_attempt TEXT CHECK(claim_attempt IS NULL OR json_valid(claim_attempt)); UPDATE tasks SET cleanup = json_set(cleanup, '$.baseline', json('null')) WHERE cleanup IS NOT NULL; PRAGMA user_version = 2;");
303
+ if (currentVersion === 1 || currentVersion === 2)
304
+ db.exec("UPDATE tasks SET native_execution = json_set(native_execution, '$.stopObservation.nativeProcessIds', json('null')) WHERE native_execution IS NOT NULL AND json_type(native_execution, '$.stopObservation') = 'object'; PRAGMA user_version = 3;");
175
305
  db.prepare(`SELECT ${projectColumns} FROM projects LIMIT 0`).all();
176
306
  db.prepare(`SELECT ${taskColumns} FROM tasks LIMIT 0`).all();
177
307
  }).immediate();
@@ -186,7 +316,10 @@ export const openWorkerStore = (databaseFile, options = {}) => {
186
316
  throw error;
187
317
  }
188
318
  const atomic = (operation) => db.transaction(operation).immediate();
189
- const getProject = (identity) => db.prepare(`SELECT ${projectColumns} FROM projects WHERE server_origin = @serverOrigin AND project_id = @projectId`).get(projectKey(identity)) ?? null;
319
+ const getProject = (identity) => {
320
+ const row = db.prepare(`SELECT ${projectColumns} FROM projects WHERE server_origin = @serverOrigin AND project_id = @projectId`).get(projectKey(identity));
321
+ return row === undefined ? null : asProject(row);
322
+ };
190
323
  const getTask = (identity) => {
191
324
  const row = db.prepare(`SELECT ${taskColumns} FROM tasks WHERE server_origin = @serverOrigin AND project_id = @projectId AND task_id = @taskId AND claim_id = @claimId`).get(claimKey(identity));
192
325
  return row === undefined ? null : asTask(row);
@@ -198,9 +331,10 @@ export const openWorkerStore = (databaseFile, options = {}) => {
198
331
  return task;
199
332
  };
200
333
  const writeTask = (task) => {
201
- const values = { ...task, configuration: task.configuration === null ? null : JSON.stringify(parseConfiguration(task.configuration)), resources: JSON.stringify(parseResources(task.resources)), recovery: JSON.stringify(parseRecovery(task.recovery)),
334
+ validateNativeExecution(task);
335
+ const values = { ...task, configuration: task.configuration === null ? null : JSON.stringify(parseConfiguration(task.configuration)), resources: JSON.stringify(parseResources(task.resources)), nativeExecution: task.nativeExecution === null ? null : JSON.stringify(parseNativeExecution(task.nativeExecution)), recovery: JSON.stringify(parseRecovery(task.recovery)),
202
336
  cleanup: task.cleanup === null ? null : JSON.stringify(parseCleanup(task.cleanup)), control: task.control === null ? null : JSON.stringify(parseControl(task.control)) };
203
- db.prepare(`UPDATE tasks SET status = @status, configuration = @configuration, resources = @resources, recovery = @recovery,
337
+ db.prepare(`UPDATE tasks SET user_id = @userId, status = @status, configuration = @configuration, resources = @resources, native_execution = @nativeExecution, recovery = @recovery,
204
338
  cleanup = @cleanup, control = @control, updated_at = @updatedAt
205
339
  WHERE server_origin = @serverOrigin AND project_id = @projectId AND task_id = @taskId AND claim_id = @claimId`).run(values);
206
340
  return needTask(task);
@@ -228,47 +362,129 @@ export const openWorkerStore = (databaseFile, options = {}) => {
228
362
  if (cleanup.kind !== "terminal" || cleanup.result === null || !cleanup.agentStopped || !cleanup.workspaceClosed || !cleanup.worktreeDeleted)
229
363
  throw new Error("Terminal cleanup must record its result and confirm agent stopped, workspace closed and worktree deleted.");
230
364
  };
365
+ const controlIntent = (task, input) => {
366
+ const intent = parseIntent(input);
367
+ if (intent.sourceClaimId !== task.claimId)
368
+ throw new Error("The control intent must name the original claim.");
369
+ if (intent.kind === "transfer" && (intent.targetClaimId === task.claimId || intent.target.worktreeId === task.worktreeId))
370
+ throw new Error("Transfer requires new claim and worktree identities.");
371
+ return intent;
372
+ };
373
+ const unsubmittedControl = (intent, requestedAt) => ({ intent, requestedAt, submission: "not-submitted", submittedAt: null, outcome: null, resultVersion: null, error: null });
374
+ const authorizeRecoveryRetry = (task, expectedCount) => {
375
+ requireOrdinary(task);
376
+ if (expectedCount !== undefined && task.recovery.count !== integer(expectedCount, "Expected recovery count"))
377
+ throw new Error("The recovery count changed after the explicit retry decision.");
378
+ if (task.status !== "active" || task.recovery.pauseReason === null)
379
+ throw new Error("An extra recovery requires a paused active execution.");
380
+ return { ...task, recovery: { ...task.recovery, retryAuthorized: true } };
381
+ };
231
382
  return {
232
383
  close: () => { db.close(); },
233
384
  getProject,
234
- listProjects: () => db.prepare(`SELECT ${projectColumns} FROM projects ORDER BY server_origin, project_id`).all(),
385
+ listProjects: () => db.prepare(`SELECT ${projectColumns} FROM projects ORDER BY server_origin, project_id`).all().map(asProject),
235
386
  registerProject: (project) => atomic(() => {
236
387
  const value = { ...projectKey(project), repoUrl: text(project.repoUrl, "Repository URL"), localPath: absolutePath(project.localPath, "Project local path") };
237
388
  const existing = getProject(value);
238
389
  if (existing !== null && (existing.repoUrl !== value.repoUrl || existing.localPath !== value.localPath)) {
390
+ if (existing.claimAttempt !== null)
391
+ throw new Error("An unresolved claim attempt prevents changing its project repository binding.");
239
392
  const unfinished = db.prepare("SELECT 1 FROM tasks WHERE server_origin = @serverOrigin AND project_id = @projectId AND status <> 'done' LIMIT 1").get(value);
240
393
  if (unfinished !== undefined)
241
394
  throw new Error("An unfinished execution prevents changing its project repository binding.");
242
395
  }
243
396
  db.prepare(`INSERT INTO projects(server_origin, project_id, repo_url, local_path) VALUES (@serverOrigin, @projectId, @repoUrl, @localPath)
244
397
  ON CONFLICT(server_origin, project_id) DO UPDATE SET repo_url = excluded.repo_url, local_path = excluded.local_path`).run(value);
245
- return value;
398
+ return getProject(value);
399
+ }),
400
+ getClaimAttempt: (identity) => {
401
+ const project = getProject(identity);
402
+ if (project === null)
403
+ throw new Error("The project repository binding is not registered.");
404
+ return project.claimAttempt;
405
+ },
406
+ listClaimAttempts: () => db.prepare(`SELECT ${projectColumns} FROM projects WHERE claim_attempt IS NOT NULL ORDER BY server_origin, project_id`).all().map(asProject).map((project) => ({ ...projectKey(project), attempt: project.claimAttempt })),
407
+ beginClaimAttempt: (identity, input) => atomic(() => {
408
+ const key = projectKey(identity);
409
+ const project = getProject(key);
410
+ if (project === null)
411
+ throw new Error("The project repository binding must be persisted before claiming a task.");
412
+ const attempt = parseClaimAttempt(input);
413
+ if (project.claimAttempt !== null)
414
+ throw new Error("The project already has an unresolved claim attempt; it cannot be replayed or replaced.");
415
+ db.prepare("UPDATE projects SET claim_attempt = @claimAttempt WHERE server_origin = @serverOrigin AND project_id = @projectId").run({ ...key, claimAttempt: JSON.stringify(attempt) });
416
+ return attempt;
417
+ }),
418
+ rejectClaimAttempt: (identity, expectedClaimId, proof) => atomic(() => {
419
+ const key = projectKey(identity);
420
+ const project = getProject(key);
421
+ if (project === null || project.claimAttempt === null || project.claimAttempt.claimId !== id(expectedClaimId, "Rejected claim ID"))
422
+ throw new Error("The original unresolved claim attempt does not match.");
423
+ if (!("definiteRejection" in proof && proof.definiteRejection === true) && !("notSubmitted" in proof && proof.notSubmitted === true))
424
+ throw new Error("Clearing a claim attempt requires definite rejection or proven non-submission of the original mutation.");
425
+ db.prepare("UPDATE projects SET claim_attempt = NULL WHERE server_origin = @serverOrigin AND project_id = @projectId").run(key);
246
426
  }),
247
427
  getTask,
248
428
  listTasks: () => db.prepare(`SELECT ${taskColumns} FROM tasks ORDER BY created_at, server_origin, project_id, task_id, claim_id`).all().map(asTask),
249
429
  listUnfinishedTasks: () => db.prepare(`SELECT ${taskColumns} FROM tasks WHERE status <> 'done' ORDER BY created_at, server_origin, project_id, task_id, claim_id`).all().map(asTask),
250
- registerPending: (claim, input, now) => atomic(() => {
430
+ recordObservedUnattemptedWorkspace: (owner, now) => atomic(() => {
431
+ const key = { ...claimKey(owner), workerId: id(owner.workerId, "Observed worker ID"), worktreeId: id(owner.worktreeId, "Observed worktree ID") };
432
+ integer(now, "Workspace observation time");
433
+ const task = getTask(key);
434
+ if (task === null)
435
+ return null;
436
+ if (task.workerId !== key.workerId || task.worktreeId !== key.worktreeId)
437
+ throw new Error("The observed workspace does not match the original execution's worker and worktree identity.");
438
+ const native = task.nativeExecution;
439
+ if (task.status === "done" || task.resources.herdr !== null || native === null || native.workspaceSubmission !== "not-submitted" || native.launchSubmission !== "never-submitted")
440
+ return task;
441
+ return writeTask({ ...task, nativeExecution: { ...unknownNativeExecution(), summary: native.summary }, updatedAt: now });
442
+ }),
443
+ registerPending: (claim, input, now, verifiedUserId = null) => atomic(() => {
251
444
  const key = { ...claimKey(claim), workerId: id(claim.workerId, "Worker ID"), worktreeId: id(claim.worktreeId, "Worktree ID") };
445
+ const owner = verifiedUserId === null ? null : id(verifiedUserId, "Verified claim user ID");
252
446
  integer(now, "Task creation time");
253
447
  oneOf(input.kind, ["new", "recovered"], "Pending registration kind");
254
448
  if (input.kind === "new" && input.configuration === null)
255
449
  throw new Error("A new execution requires its frozen configuration.");
256
450
  const configuration = input.configuration === null ? null : parseConfiguration(input.configuration);
451
+ const project = getProject(key);
452
+ if (project === null)
453
+ throw new Error("The project repository binding must be persisted before claiming a task.");
454
+ const confirmAttempt = (originalConfiguration) => {
455
+ const attempt = project.claimAttempt;
456
+ if (attempt === null || attempt.claimId !== key.claimId)
457
+ return originalConfiguration;
458
+ if (attempt.taskId !== key.taskId || attempt.worktreeId !== key.worktreeId || attempt.workerId !== key.workerId || (originalConfiguration !== null && !same(attempt.configuration, originalConfiguration)))
459
+ throw new Error("The actual granted claim does not preserve its original claim attempt and frozen configuration.");
460
+ if (owner === null)
461
+ return originalConfiguration;
462
+ if (attempt.userId !== owner)
463
+ throw new Error("The actual granted claim does not preserve its original authenticated claim attempt owner.");
464
+ db.prepare("UPDATE projects SET claim_attempt = NULL WHERE server_origin = @serverOrigin AND project_id = @projectId").run(projectKey(key));
465
+ return originalConfiguration === null ? attempt.configuration : originalConfiguration;
466
+ };
257
467
  const existing = getTask(key);
258
468
  if (existing !== null) {
259
469
  if (existing.workerId !== key.workerId || existing.worktreeId !== key.worktreeId)
260
470
  throw new Error("The claim is already bound to a different worker or worktree identity.");
471
+ const scoped = owner === null ? existing : withUserScope(existing, owner);
472
+ const originalConfiguration = confirmAttempt(existing.configuration);
473
+ if (scoped.userId !== existing.userId || originalConfiguration !== existing.configuration) {
474
+ if (existing.status === "done")
475
+ throw new Error("The local execution is already done; its unknown authenticated scope cannot be replaced.");
476
+ return writeTask({ ...scoped, configuration: originalConfiguration, updatedAt: now });
477
+ }
261
478
  return existing;
262
479
  }
263
- const project = getProject(key);
264
- if (project === null)
265
- throw new Error("The project repository binding must be persisted before claiming a task.");
266
- const values = { ...key, configuration: configuration === null ? null : JSON.stringify(configuration), repoUrl: project.repoUrl, repositoryPath: project.localPath,
267
- resources: JSON.stringify({ worktree: null, herdr: null, nativeSession: null }), recovery: JSON.stringify({ count: 0, pauseReason: configuration === null ? "Original frozen execution configuration is missing." : null, retryAuthorized: false }), now };
268
- db.prepare(`INSERT INTO tasks(server_origin, project_id, task_id, claim_id, worker_id, worktree_id, status, repo_url, repository_path, configuration, resources, recovery, created_at, updated_at)
269
- VALUES (@serverOrigin, @projectId, @taskId, @claimId, @workerId, @worktreeId, 'pending', @repoUrl, @repositoryPath, @configuration, @resources, @recovery, @now, @now)`).run(values);
480
+ const originalConfiguration = confirmAttempt(configuration);
481
+ const values = { ...key, userId: owner, configuration: originalConfiguration === null ? null : JSON.stringify(originalConfiguration), repoUrl: project.repoUrl, repositoryPath: project.localPath,
482
+ resources: JSON.stringify({ worktree: null, herdr: null, nativeSession: null }), nativeExecution: input.kind === "new" ? JSON.stringify(freshNativeExecution()) : null, recovery: JSON.stringify({ count: 0, pauseReason: originalConfiguration === null ? "Original frozen execution configuration is missing." : null, retryAuthorized: false }), now };
483
+ db.prepare(`INSERT INTO tasks(server_origin, project_id, task_id, claim_id, worker_id, worktree_id, user_id, status, repo_url, repository_path, configuration, resources, native_execution, recovery, created_at, updated_at)
484
+ VALUES (@serverOrigin, @projectId, @taskId, @claimId, @workerId, @worktreeId, @userId, 'pending', @repoUrl, @repositoryPath, @configuration, @resources, @nativeExecution, @recovery, @now, @now)`).run(values);
270
485
  return needTask(key);
271
486
  }),
487
+ bindUserScope: (identity, userId, now) => change(identity, now, (task) => withUserScope(task, userId)),
272
488
  restoreOriginalConfiguration: (identity, configuration, now) => change(identity, now, (task) => {
273
489
  const original = parseConfiguration(configuration);
274
490
  if (task.configuration !== null && !same(task.configuration, original))
@@ -281,6 +497,13 @@ export const openWorkerStore = (databaseFile, options = {}) => {
281
497
  throw new Error("The execution is paused.");
282
498
  return { ...task, status: "active" };
283
499
  }),
500
+ activatePausedRecovery: (identity, reason, now) => change(identity, now, (task) => {
501
+ if (task.control !== null || task.cleanup !== null)
502
+ throw new Error("A control or cleanup intent prevents recovery promotion.");
503
+ if (task.nativeExecution?.launchSubmission === "never-submitted" && task.resources.worktree === null && task.resources.herdr === null && task.resources.nativeSession === null)
504
+ throw new Error("Paused recovery requires unknown original provenance or existing execution resources.");
505
+ return { ...task, status: "active", recovery: { ...task.recovery, pauseReason: text(reason, "Recovery pause reason") } };
506
+ }),
284
507
  bindWorktree: (identity, binding, now) => change(identity, now, (task) => {
285
508
  if (task.status !== "active")
286
509
  throw new Error("Resource creation requires an active execution.");
@@ -299,6 +522,125 @@ export const openWorkerStore = (databaseFile, options = {}) => {
299
522
  throw new Error("The execution already has a different Herdr binding.");
300
523
  return { ...task, resources: { ...task.resources, herdr: value } };
301
524
  }),
525
+ bindHerdrExecution: (identity, binding, workspaceEvidence, now) => change(identity, now, (task) => {
526
+ if (task.status !== "active" || task.resources.worktree === null)
527
+ throw new Error("Herdr binding requires an active execution and its original worktree.");
528
+ const value = parseTaskBinding(binding);
529
+ const core = { session: value.session, workspaceId: value.workspaceId, paneId: value.paneId };
530
+ if (task.resources.herdr !== null && !same(task.resources.herdr, core))
531
+ throw new Error("The execution already has a different Herdr binding.");
532
+ const state = task.nativeExecution === null ? unknownNativeExecution() : task.nativeExecution;
533
+ if (state.terminalId !== null && state.terminalId !== value.terminalId)
534
+ throw new Error("The original terminal cannot change without confirmed stop and workspace closure.");
535
+ if (state.workspaceSubmission === "unknown" && state.terminalId !== null && task.resources.herdr !== null)
536
+ throw new Error("An unresolved replacement workspace cannot be acknowledged by its previous binding.");
537
+ const evidence = workspaceEvidence === null ? state.workspaceEvidence : parseWorkspaceEvidence(workspaceEvidence);
538
+ if (state.workspaceEvidence !== null && !same(state.workspaceEvidence, evidence))
539
+ throw new Error("The original workspace evidence cannot be replaced.");
540
+ return { ...task, resources: { ...task.resources, herdr: core }, nativeExecution: { ...state, terminalId: value.terminalId, workspaceSubmission: "acknowledged", workspaceEvidence: evidence } };
541
+ }),
542
+ markWorkspaceSubmitting: (identity, now) => change(identity, now, (task) => {
543
+ requireOrdinary(task);
544
+ const state = task.nativeExecution;
545
+ if (task.status !== "active" || task.resources.worktree === null || state === null)
546
+ throw new Error("Workspace creation requires its active original worktree and persisted provenance.");
547
+ if (state.workspaceSubmission === "unknown")
548
+ throw new Error("The original workspace creation is unresolved and cannot be replayed.");
549
+ if (state.launchSubmission !== "never-submitted" && task.resources.nativeSession === null)
550
+ throw new Error("The original native session ID is missing; workspace replacement cannot start a new conversation.");
551
+ if (task.resources.herdr !== null && state.launchSubmission !== "never-submitted" && state.stopObservation === null)
552
+ throw new Error("Workspace replacement requires its durable original native stop observation.");
553
+ return { ...task, nativeExecution: { ...state, workspaceSubmission: "unknown" } };
554
+ }),
555
+ recordWorkspaceNotSubmitted: (identity, proof, now) => change(identity, now, (task) => {
556
+ const state = task.nativeExecution;
557
+ if (state === null || state.workspaceSubmission !== "unknown")
558
+ throw new Error("Workspace non-submission requires its original unresolved create attempt.");
559
+ if (!("notSubmitted" in proof && proof.notSubmitted === true) && !("definiteRejection" in proof && proof.definiteRejection === true))
560
+ throw new Error("Resetting workspace creation requires proven non-submission or definite rejection before dispatch.");
561
+ return { ...task, nativeExecution: { ...state, workspaceSubmission: "not-submitted" } };
562
+ }),
563
+ markNativeLaunchSubmitting: (identity, now) => change(identity, now, (task) => {
564
+ requireOrdinary(task);
565
+ const state = task.nativeExecution;
566
+ if (task.status !== "active" || task.recovery.pauseReason !== null || state === null || state.terminalId === null || state.workspaceSubmission !== "acknowledged" || state.workspaceEvidence === null || state.launchSubmission !== "never-submitted")
567
+ throw new Error("Native launch requires a proven unlaunched active execution and its verified workspace.");
568
+ return { ...task, nativeExecution: { ...state, launchSubmission: "unknown", promptSubmission: "unknown" } };
569
+ }),
570
+ recordNativeLaunchNotSubmitted: (identity, proof, now) => change(identity, now, (task) => {
571
+ const state = task.nativeExecution;
572
+ if (task.status !== "active" || state === null || state.launchSubmission !== "unknown" || state.launchEvidence !== null || state.stopObservation !== null || state.promptSubmission === "submitted")
573
+ throw new Error("A native launch can be unsubmitted only before acknowledged launch, prompt submission or native process evidence.");
574
+ if (!("notSubmitted" in proof && proof.notSubmitted === true) && !("definiteRejection" in proof && proof.definiteRejection === true))
575
+ throw new Error("Resetting a native launch requires proven non-submission or definite rejection before native dispatch.");
576
+ return { ...task, nativeExecution: { ...state, launchSubmission: "never-submitted", promptSubmission: "not-submitted" } };
577
+ }),
578
+ markNativePromptSubmitting: (identity, now) => change(identity, now, (task) => {
579
+ requireOrdinary(task);
580
+ const state = task.nativeExecution;
581
+ if (task.status !== "active" || task.recovery.pauseReason !== null || state === null || state.workspaceSubmission !== "acknowledged" || state.launchSubmission !== "acknowledged" || state.launchEvidence === null || state.promptSubmission !== "not-submitted")
582
+ throw new Error("Deferred startup input requires its original acknowledged launch and a proven unsubmitted prompt.");
583
+ return { ...task, nativeExecution: { ...state, promptSubmission: "unknown" } };
584
+ }),
585
+ recordNativeStartOutcome: (identity, input, now) => change(identity, now, (task) => {
586
+ const state = task.nativeExecution;
587
+ if (task.status !== "active" || state === null || state.terminalId === null || state.launchSubmission === "never-submitted")
588
+ throw new Error("Native startup outcome requires the original persisted submission attempt.");
589
+ const promptSubmission = oneOf(input.promptSubmission, ["not-submitted", "unknown", "submitted"], "Native prompt outcome");
590
+ if (state.promptSubmission === "submitted" && promptSubmission !== "submitted")
591
+ throw new Error("A confirmed startup prompt cannot become unsubmitted or unknown.");
592
+ const launchEvidence = input.launchEvidence === undefined ? state.launchEvidence : parseLaunchEvidence(input.launchEvidence);
593
+ if (state.launchEvidence !== null && !same(state.launchEvidence, launchEvidence))
594
+ throw new Error("The original native launch evidence cannot be replaced.");
595
+ return { ...task, nativeExecution: { ...state, launchEvidence, launchSubmission: launchEvidence === null ? state.launchSubmission : "acknowledged", promptSubmission } };
596
+ }),
597
+ recordStopObservation: (identity, observation, now) => change(identity, now, (task) => {
598
+ const state = task.nativeExecution;
599
+ if (task.status !== "active" || state === null || state.terminalId === null || state.launchSubmission === "never-submitted")
600
+ throw new Error("A native stop observation requires the original possibly launched terminal.");
601
+ const evidence = parseStopObservation(observation);
602
+ if (state.stopObservation !== null && !same(state.stopObservation, evidence))
603
+ throw new Error("The original native process observation cannot be replaced before confirmed closure.");
604
+ return { ...task, nativeExecution: { ...state, stopObservation: evidence } };
605
+ }),
606
+ markExecutionSummarySubmitting: (identity, input, now) => change(identity, now, (task) => {
607
+ requireOrdinary(task);
608
+ if (task.status !== "active")
609
+ throw new Error("Execution summary publication requires an active execution.");
610
+ const state = task.nativeExecution === null ? unknownNativeExecution() : task.nativeExecution;
611
+ if (state.summary?.submission === "unknown")
612
+ throw new Error("The original execution summary mutation is unresolved and cannot be replayed or replaced.");
613
+ const summary = parseExecutionSummary({ ...input, submission: "unknown" });
614
+ if (!same(summary.herdr, task.resources.herdr) || summary.nativeSessionId !== (task.resources.nativeSession === null ? null : task.resources.nativeSession.sessionId))
615
+ throw new Error("Execution summary must describe its original actual resource bindings.");
616
+ return { ...task, nativeExecution: { ...state, summary } };
617
+ }),
618
+ recordExecutionSummaryOutcome: (identity, expectedVersion, submission, now) => change(identity, now, (task) => {
619
+ const state = task.nativeExecution;
620
+ const summary = state === null ? null : state.summary;
621
+ const outcome = oneOf(submission, ["confirmed", "rejected"], "Summary mutation outcome");
622
+ if (summary === null || summary.version !== version(expectedVersion) || (summary.submission !== "unknown" && summary.submission !== outcome))
623
+ throw new Error("The original execution summary submission does not match this outcome.");
624
+ return { ...task, nativeExecution: { ...state, summary: { ...summary, submission: outcome } } };
625
+ }),
626
+ recordExecutionSummaryNotSubmitted: (identity, expectedVersion, proof, now) => change(identity, now, (task) => {
627
+ const state = task.nativeExecution;
628
+ const summary = state === null ? null : state.summary;
629
+ if (summary === null || summary.submission !== "unknown" || summary.version !== version(expectedVersion))
630
+ throw new Error("The original unresolved execution summary does not match this non-submission.");
631
+ if (proof.notSubmitted !== true)
632
+ throw new Error("Clearing an execution summary requires proven non-submission before dispatch.");
633
+ return { ...task, nativeExecution: { ...state, summary: null } };
634
+ }),
635
+ reconcileExecutionSummary: (identity, input, now) => change(identity, now, (task) => {
636
+ const state = task.nativeExecution;
637
+ const summary = state === null ? null : state.summary;
638
+ const observed = parseExecutionSummary({ ...input, submission: "confirmed" });
639
+ if (summary === null || summary.submission !== "unknown" || BigInt(observed.version) <= BigInt(summary.version))
640
+ return task;
641
+ const matched = same(observed.herdr, summary.herdr) && observed.nativeSessionId === summary.nativeSessionId && observed.phase === summary.phase;
642
+ return { ...task, nativeExecution: { ...state, summary: matched ? { ...summary, submission: "confirmed" } : null } };
643
+ }),
302
644
  rebindHerdr: (identity, expectedPrevious, next, proof, now) => change(identity, now, (task) => {
303
645
  requireOrdinary(task);
304
646
  if (task.status !== "active" || task.resources.worktree === null || task.resources.herdr === null)
@@ -307,7 +649,26 @@ export const openWorkerStore = (databaseFile, options = {}) => {
307
649
  throw new Error("The previous Herdr binding does not match the original execution.");
308
650
  if (proof.originalAgentStopped !== true || proof.oldWorkspaceClosed !== true)
309
651
  throw new Error("Herdr rebinding requires confirmed original agent stop and old workspace closure.");
310
- return { ...task, resources: { ...task.resources, herdr: parseHerdr(next) } };
652
+ if (task.resources.nativeSession === null && task.nativeExecution?.launchSubmission !== "never-submitted")
653
+ throw new Error("The original native session ID is missing; rebinding cannot start a new conversation.");
654
+ return { ...task, resources: { ...task.resources, herdr: parseHerdr(next) }, nativeExecution: { ...unknownNativeExecution(), summary: task.nativeExecution === null ? null : task.nativeExecution.summary } };
655
+ }),
656
+ rebindHerdrExecution: (identity, expectedPrevious, next, workspaceEvidence, proof, now) => change(identity, now, (task) => {
657
+ requireOrdinary(task);
658
+ const previous = parseTaskBinding(expectedPrevious);
659
+ const state = task.nativeExecution;
660
+ if (task.status !== "active" || task.resources.worktree === null || task.resources.herdr === null || state === null || !same({ ...task.resources.herdr, terminalId: state.terminalId }, previous))
661
+ throw new Error("The previous full Herdr binding does not match the active execution.");
662
+ if (proof.originalAgentStopped !== true || proof.oldWorkspaceClosed !== true || (state.stopObservation === null && state.launchSubmission !== "never-submitted"))
663
+ throw new Error("Herdr rebinding requires durable original stop provenance and confirmed old workspace closure.");
664
+ if (state.launchSubmission !== "never-submitted" && task.resources.nativeSession === null)
665
+ throw new Error("The original native session ID is missing; rebinding cannot start a new conversation.");
666
+ if (state.workspaceSubmission !== "unknown")
667
+ throw new Error("Herdr rebinding requires the persisted new workspace creation attempt.");
668
+ const binding = parseTaskBinding(next);
669
+ if (same(binding, previous))
670
+ throw new Error("A fresh Herdr execution must use a new workspace or terminal binding.");
671
+ return { ...task, resources: { ...task.resources, herdr: { session: binding.session, workspaceId: binding.workspaceId, paneId: binding.paneId } }, nativeExecution: { ...freshNativeExecution(), terminalId: binding.terminalId, workspaceSubmission: "acknowledged", workspaceEvidence: workspaceEvidence === null ? null : parseWorkspaceEvidence(workspaceEvidence), summary: state.summary } };
311
672
  }),
312
673
  bindNativeSession: (identity, reference, now) => change(identity, now, (task) => {
313
674
  if (task.status !== "active" || task.resources.herdr === null)
@@ -323,11 +684,9 @@ export const openWorkerStore = (databaseFile, options = {}) => {
323
684
  return { ...task, recovery: { ...task.recovery, pauseReason: null } };
324
685
  }),
325
686
  authorizeRecoveryRetry: (identity, now) => change(identity, now, (task) => {
326
- requireOrdinary(task);
327
- if (task.status !== "active" || task.recovery.pauseReason === null)
328
- throw new Error("An extra recovery requires a paused active execution.");
329
- return { ...task, recovery: { ...task.recovery, retryAuthorized: true } };
687
+ return authorizeRecoveryRetry(task);
330
688
  }),
689
+ authorizeRecoveryRetryAtCount: (identity, expectedCount, now) => change(identity, now, (task) => authorizeRecoveryRetry(task, expectedCount)),
331
690
  beginRecovery: (identity, now) => change(identity, now, (task) => {
332
691
  requireOrdinary(task);
333
692
  if (task.status !== "active")
@@ -348,7 +707,7 @@ export const openWorkerStore = (databaseFile, options = {}) => {
348
707
  return { ...task, cleanup: { ...existing, kind: existing.kind === "terminal" ? "terminal" : input.kind } };
349
708
  if (task.control !== null && input.kind !== "terminal")
350
709
  throw new Error("A source control intent requires terminal cleanup.");
351
- return { ...task, status: "active", cleanup: parseCleanup({ kind: input.kind, startedAt: now, deadline: input.deadline, input: "not-submitted", result: null, error: null, agentStopped: false, workspaceClosed: false, worktreeDeleted: false }) };
710
+ return { ...task, status: "active", cleanup: parseCleanup({ kind: input.kind, startedAt: now, deadline: input.deadline, input: "not-submitted", baseline: null, result: null, error: null, agentStopped: false, workspaceClosed: false, worktreeDeleted: false }) };
352
711
  }),
353
712
  markCleanupInputSubmitting: (identity, now) => change(identity, now, (task) => {
354
713
  const cleanup = needCleanup(task);
@@ -365,6 +724,15 @@ export const openWorkerStore = (databaseFile, options = {}) => {
365
724
  throw new Error("The cleanup input outcome conflicts with the original submission.");
366
725
  return { ...task, cleanup: { ...cleanup, input } };
367
726
  }),
727
+ recordCleanupInputEvidence: (identity, baseline, now) => change(identity, now, (task) => {
728
+ const cleanup = needCleanup(task);
729
+ if (cleanup.input !== "submitted")
730
+ throw new Error("Cleanup completion evidence requires the original confirmed input submission.");
731
+ const evidence = parseCleanupBaseline(baseline);
732
+ if (cleanup.baseline !== null && !same(cleanup.baseline, evidence))
733
+ throw new Error("The original cleanup completion baseline cannot be replaced.");
734
+ return { ...task, cleanup: { ...cleanup, baseline: evidence } };
735
+ }),
368
736
  recordCleanupResult: (identity, result, error, now) => change(identity, now, (task) => {
369
737
  const cleanup = needCleanup(task);
370
738
  oneOf(result, ["completed", "timed-out", "failed", "unavailable"], "Cleanup result");
@@ -398,20 +766,33 @@ export const openWorkerStore = (databaseFile, options = {}) => {
398
766
  throw new Error("Shutdown resume requires the original agent stopped, workspace closed and its cleanup result recorded.");
399
767
  if (task.configuration === null)
400
768
  throw new Error("The original frozen execution configuration is missing.");
401
- return { ...task, cleanup: null, resources: { ...task.resources, herdr: null } };
769
+ if (task.resources.nativeSession === null && task.nativeExecution?.launchSubmission !== "never-submitted")
770
+ return { ...task, cleanup: null, recovery: { ...task.recovery, pauseReason: "The original native session ID is missing; recover its exact history identity before resuming this claim." } };
771
+ return { ...task, cleanup: null, resources: { ...task.resources, herdr: null }, nativeExecution: { ...freshNativeExecution(), summary: task.nativeExecution === null ? null : task.nativeExecution.summary } };
402
772
  }),
403
773
  recordControlIntent: (identity, input, now) => change(identity, now, (task) => {
404
- const intent = parseIntent(input);
405
- if (intent.sourceClaimId !== task.claimId)
406
- throw new Error("The control intent must name the original claim.");
407
- if (intent.kind === "transfer" && (intent.targetClaimId === task.claimId || intent.target.worktreeId === task.worktreeId))
408
- throw new Error("Transfer requires new claim and worktree identities.");
774
+ const intent = controlIntent(task, input);
409
775
  if (task.control !== null) {
410
776
  if (!same(task.control.intent, intent))
411
777
  throw new Error("A different source control intent is already recorded.");
412
778
  return task;
413
779
  }
414
- return { ...task, cleanup: task.cleanup === null ? null : { ...task.cleanup, kind: "terminal" }, control: { intent, requestedAt: now, submission: "not-submitted", submittedAt: null, outcome: null, resultVersion: null, error: null } };
780
+ return { ...task, cleanup: task.cleanup === null ? null : { ...task.cleanup, kind: "terminal" }, control: unsubmittedControl(intent, now) };
781
+ }),
782
+ replaceRejectedControlIntent: (identity, input, proof, now) => change(identity, now, (task) => {
783
+ const intent = controlIntent(task, input);
784
+ if (task.control?.submission !== "rejected")
785
+ throw new Error("A new explicit control decision can replace only a definitely rejected submission; unknown writes remain fenced.");
786
+ if (exactVersion(proof.observedVersion) !== intent.version)
787
+ throw new Error("The replacement decision must use its newly observed explicit version.");
788
+ return { ...task, control: unsubmittedControl(intent, now) };
789
+ }),
790
+ confirmUnstartedControlCleanup: (identity, proof, deadline, now) => change(identity, now, (task) => {
791
+ if (proof.completeHerdrInventory !== true || proof.noOwnedResources !== true)
792
+ throw new Error("An unstarted source cleanup requires a complete Herdr inventory proving no original resources.");
793
+ if (task.userId === null || task.control === null || !isUnstartedPendingSource(task))
794
+ throw new Error("Only a scoped unstarted pending source with a saved control intent can finish without activation.");
795
+ return { ...task, cleanup: parseCleanup({ kind: "terminal", startedAt: now, deadline, input: "unavailable", baseline: null, result: "completed", error: null, agentStopped: true, workspaceClosed: true, worktreeDeleted: true }) };
415
796
  }),
416
797
  markControlSubmitting: (identity, expectedVersion, now) => change(identity, now, (task) => {
417
798
  fullyCleaned(task);
@@ -444,6 +825,53 @@ export const openWorkerStore = (databaseFile, options = {}) => {
444
825
  return task;
445
826
  return { ...task, control: { ...control, submission: "confirmed", outcome: "ownership-ended", resultVersion: null, error: null } };
446
827
  }),
828
+ confirmControlOwnershipEndedByTask: (identity, proof, now) => change(identity, now, (task) => {
829
+ fullyCleaned(task);
830
+ const control = task.control;
831
+ if (control === null)
832
+ throw new Error("A source control intent is required for targeted management reconciliation.");
833
+ const observedClaimId = nullable(proof.observedClaimId, (value) => id(value, "Observed claim ID"));
834
+ const observedState = nullable(proof.observedState, (value) => oneOf(value, ["active", "released", "completed"], "Observed claim state"));
835
+ if ((observedClaimId === null) !== (observedState === null))
836
+ throw new Error("The targeted task observation must include both claim identity and state, or neither.");
837
+ if (observedClaimId === task.claimId && observedState === "active")
838
+ throw new Error("The targeted task observation still contains the original active claim.");
839
+ if (control.submission === "confirmed")
840
+ return task;
841
+ return { ...task, control: { ...control, submission: "confirmed", outcome: "ownership-ended", resultVersion: null, error: null } };
842
+ }),
843
+ completeAppliedControl: (identity, expectedIntent, resultVersion, now) => atomic(() => {
844
+ const task = needTask(identity);
845
+ fullyCleaned(task);
846
+ const control = task.control;
847
+ if (control === null || !same(control.intent, parseIntent(expectedIntent)))
848
+ throw new Error("The observed remote result does not belong to the current concrete management decision.");
849
+ if (task.status === "done") {
850
+ if (control.submission !== "confirmed")
851
+ throw new Error("A completed source must have a confirmed management result.");
852
+ return task;
853
+ }
854
+ if (control.submission !== "unknown" && control.submission !== "confirmed")
855
+ throw new Error("An applied control result requires the original submitted decision.");
856
+ return writeTask({ ...task, status: "done", control: { ...control, submission: "confirmed", outcome: "applied", resultVersion: exactVersion(resultVersion), error: null }, updatedAt: integer(now, "Task update time") });
857
+ }),
858
+ completeEndedControl: (identity, expectedIntent, proof, now) => atomic(() => {
859
+ const task = needTask(identity);
860
+ fullyCleaned(task);
861
+ const control = task.control;
862
+ if (control === null || !same(control.intent, parseIntent(expectedIntent)))
863
+ throw new Error("The observed ownership exit does not belong to the current concrete management decision.");
864
+ if (task.status === "done") {
865
+ if (control.submission !== "confirmed")
866
+ throw new Error("A completed source must have a confirmed management result.");
867
+ return task;
868
+ }
869
+ const observedClaimId = nullable(proof.observedClaimId, (value) => id(value, "Observed claim ID"));
870
+ const observedState = nullable(proof.observedState, (value) => oneOf(value, ["active", "released", "completed"], "Observed claim state"));
871
+ if ((observedClaimId === null) !== (observedState === null) || (observedClaimId === task.claimId && observedState === "active"))
872
+ throw new Error("The targeted task observation does not prove the original active claim ended.");
873
+ return writeTask({ ...task, status: "done", control: { ...control, submission: "confirmed", outcome: "ownership-ended", resultVersion: null, error: null }, updatedAt: integer(now, "Task update time") });
874
+ }),
447
875
  rejectControlSubmission: (identity, error, now) => change(identity, now, (task) => {
448
876
  if (task.control === null || task.control.submission !== "unknown")
449
877
  throw new Error("A definite control rejection requires an original unknown submission.");
@@ -455,6 +883,17 @@ export const openWorkerStore = (databaseFile, options = {}) => {
455
883
  throw new Error("The source control outcome must be reconciled before local completion.");
456
884
  return { ...task, status: "done" };
457
885
  }),
886
+ completeUnstartedPending: (identity, proof, now) => change(identity, now, (task) => {
887
+ if (proof.completeOwnClaimInventory !== true || proof.claimAbsent !== true)
888
+ throw new Error("Completing an unstarted pending claim requires its absence from a successful complete own-claim inventory.");
889
+ if (!isUnstartedPending(task))
890
+ throw new Error("Only a proven unstarted pending execution with no resources or outstanding actions can complete directly.");
891
+ if (task.userId === null || task.userId !== id(proof.authenticatedUserId, "Authenticated user ID"))
892
+ throw new Error("The complete own-claim inventory must belong to the original authenticated claim owner.");
893
+ const completed = { ...task, status: "done", cleanup: { kind: "terminal", startedAt: now, deadline: now, input: "unavailable", baseline: null, result: "completed", error: null, agentStopped: true, workspaceClosed: true, worktreeDeleted: true } };
894
+ fullyCleaned(completed);
895
+ return completed;
896
+ }),
458
897
  };
459
898
  };
460
899
  //# sourceMappingURL=store.js.map