@ignitionai/cogitator 0.5.1 → 0.5.2

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 (63) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/LICENSE +21 -0
  3. package/README.md +80 -56
  4. package/dist/extensions/index.js +66 -29
  5. package/dist/src/app-updates.js +15 -0
  6. package/dist/src/auth-cli.js +18 -8
  7. package/dist/src/auth-http.js +13 -3
  8. package/dist/src/auth-state.js +41 -6
  9. package/dist/src/board.js +3 -1
  10. package/dist/src/browser-http.js +143 -0
  11. package/dist/src/classic-configuration.js +12 -4
  12. package/dist/src/cli.js +29 -2
  13. package/dist/src/config.js +10 -0
  14. package/dist/src/cron.js +91 -15
  15. package/dist/src/db.js +55 -3
  16. package/dist/src/durable/approvals.js +17 -2
  17. package/dist/src/durable/effect-gateway.js +23 -16
  18. package/dist/src/durable/manager.js +13 -4
  19. package/dist/src/durable/mission-runtime.js +204 -46
  20. package/dist/src/durable/recovery.js +37 -0
  21. package/dist/src/durable/workers.js +22 -14
  22. package/dist/src/execution/confinement.js +2 -1
  23. package/dist/src/execution/worker-supervisor.js +222 -0
  24. package/dist/src/git-import.js +187 -0
  25. package/dist/src/github-login.js +101 -0
  26. package/dist/src/history.js +6 -1
  27. package/dist/src/host-pi.js +9 -6
  28. package/dist/src/json-files.js +7 -4
  29. package/dist/src/machine-metrics.js +49 -0
  30. package/dist/src/machine-types.js +1 -0
  31. package/dist/src/mcp-cli.js +63 -0
  32. package/dist/src/mcp-http.js +164 -0
  33. package/dist/src/mcp-oauth.js +502 -0
  34. package/dist/src/mcp-server.js +6 -136
  35. package/dist/src/mcp-tokens.js +104 -0
  36. package/dist/src/mcp-tools.js +264 -0
  37. package/dist/src/native-auth.js +9 -2
  38. package/dist/src/packages.js +190 -0
  39. package/dist/src/paths.js +1 -0
  40. package/dist/src/pi-child.js +180 -0
  41. package/dist/src/pi-rpc-wrap.js +84 -0
  42. package/dist/src/pool.js +58 -7
  43. package/dist/src/project-setup.js +63 -0
  44. package/dist/src/provider-login.js +72 -13
  45. package/dist/src/reap-orphans.js +138 -0
  46. package/dist/src/registry.js +66 -43
  47. package/dist/src/schemas.js +19 -4
  48. package/dist/src/server-compat.js +173 -0
  49. package/dist/src/server-identity.js +69 -0
  50. package/dist/src/server.js +534 -41
  51. package/dist/src/shared-browser.js +357 -0
  52. package/dist/src/skills-import.js +13 -4
  53. package/dist/src/skills-upload.js +68 -0
  54. package/dist/src/spawner.js +20 -4
  55. package/dist/src/subagents.js +242 -0
  56. package/dist/src/team-queue.js +262 -0
  57. package/package.json +8 -3
  58. package/web/dist/assets/{BrandLogo3D-BvZPXohP.js → BrandLogo3D-CHGXwTbZ.js} +1 -1
  59. package/web/dist/assets/index-DGLkhrE7.css +1 -0
  60. package/web/dist/assets/index-P0WoXBgX.js +84 -0
  61. package/web/dist/index.html +2 -2
  62. package/web/dist/assets/index-7Dyl-4v7.css +0 -1
  63. package/web/dist/assets/index-CdqzcBU-.js +0 -83
@@ -69,8 +69,19 @@ export function findValidGrant(grants, effect, now) {
69
69
  */
70
70
  export function consumeGrantForEffect(doc, effect, now) {
71
71
  const prior = doc.receipts.find((r) => r.intentKey === effect.intentKey);
72
- if (prior)
72
+ if (prior) {
73
+ const sameScope = prior.operation === effect.operation && prior.target === effect.target &&
74
+ prior.artifactDigest === effect.artifactDigest && prior.argumentDigest === effect.argumentDigest;
75
+ if (!sameScope)
76
+ return { kind: "rejected", blocked: true, reason: "intent scope mismatch: opération/cible/digests différents" };
73
77
  return { kind: "duplicate", receipt: prior };
78
+ }
79
+ if (doc.receipts.some((receipt) => receipt.status !== "observed")) {
80
+ return { kind: "rejected", blocked: true, reason: "issue externe non établie : réconcilier avant tout nouvel effet" };
81
+ }
82
+ if (doc.pendingActions.some((action) => action.decision === "denied")) {
83
+ return { kind: "rejected", blocked: true, reason: "action_denied: refus durable exigeant une décision owner explicite" };
84
+ }
74
85
  const found = findValidGrant(doc.grants, effect, now);
75
86
  if ("reason" in found)
76
87
  return { kind: "rejected", reason: found.reason };
@@ -155,6 +166,10 @@ export function recordObservedReceipt(doc, intentKey, observed, now) {
155
166
  const receipt = doc.receipts.find((r) => r.intentKey === intentKey);
156
167
  if (!receipt)
157
168
  return { ok: false, reason: "intent inconnu : la tentative n'a pas été associée à un grant" };
169
+ if (receipt.status === "observed")
170
+ return { ok: true, receipt };
171
+ if (receipt.status === "unknown")
172
+ return { ok: false, reason: "réconciliation requise : le receipt inconnu ne peut être résolu par un nouvel appel" };
158
173
  receipt.status = "observed";
159
174
  receipt.observed = { at: now, ...observed };
160
175
  receipt.updatedAt = now;
@@ -163,7 +178,7 @@ export function recordObservedReceipt(doc, intentKey, observed, now) {
163
178
  /** Marque une tentative dont l'issue externe ne peut être établie (réconciliation requise). */
164
179
  export function markReceiptUnknown(doc, intentKey, reason, now) {
165
180
  const receipt = doc.receipts.find((r) => r.intentKey === intentKey);
166
- if (!receipt)
181
+ if (!receipt || receipt.status !== "intent_committed")
167
182
  return;
168
183
  receipt.status = "unknown";
169
184
  receipt.unknownReason = reason;
@@ -26,20 +26,21 @@ export async function runProtectedEffect(api, context, descriptor, intentKey, pe
26
26
  if (result.kind === "rejected") {
27
27
  // Pas de grant valide : le serveur crée l'action en attente (immumable) ;
28
28
  // l'appel est bloqué, la mission passe visiblement en waiting_approval.
29
- createPendingAction(doc, {
30
- ...descriptor,
31
- consequence: descriptor.operation,
32
- expiresAt: now + 24 * 60 * 60 * 1000,
33
- allowedUses: 1,
34
- }, now);
35
- return { kind: "rejected", reason: result.reason };
29
+ if (!result.blocked)
30
+ createPendingAction(doc, {
31
+ ...descriptor,
32
+ consequence: descriptor.operation,
33
+ expiresAt: now + 24 * 60 * 60 * 1000,
34
+ allowedUses: 1,
35
+ }, now);
36
+ return { kind: "rejected", reason: result.reason, blocked: result.blocked };
36
37
  }
37
38
  if (result.kind === "duplicate")
38
- return { kind: "duplicate", receipt: result.receipt };
39
+ return { kind: "duplicate", receipt: { ...result.receipt, observed: result.receipt.observed ? { ...result.receipt.observed } : undefined } };
39
40
  return { kind: "consumed" };
40
41
  }, context);
41
42
  if (decision.kind === "rejected") {
42
- throw new GrantRejectedError(`${decision.reason} — action en attente de décision owner`);
43
+ throw new GrantRejectedError(decision.blocked ? decision.reason : `${decision.reason} — action en attente de décision owner`);
43
44
  }
44
45
  if (decision.kind === "duplicate") {
45
46
  if (decision.receipt.status === "observed") {
@@ -53,16 +54,22 @@ export async function runProtectedEffect(api, context, descriptor, intentKey, pe
53
54
  // Intent associé sans issue établie : réconciliation owner explicite.
54
55
  throw new GrantRejectedError(`tentative ${intentKey} déjà associée sans issue établie : réconcilier l'issue externe avant toute reprise`);
55
56
  }
56
- let observed;
57
57
  try {
58
- observed = await perform();
58
+ const observed = await perform();
59
+ await api.commit(async (tx) => {
60
+ const doc = await tx.doc(MissionApprovals, api.conversationId);
61
+ const recorded = recordObservedReceipt(doc, intentKey, observed, Date.now());
62
+ if (!recorded.ok)
63
+ throw new GrantRejectedError(recorded.reason);
64
+ }, context);
65
+ return { kind: "performed" };
59
66
  }
60
67
  catch (err) {
61
- // L'issue externe est inconnue : on la conserve comme telle (jamais de
62
- // rejeu implicite) et on propage l'échec à l'outil.
63
- await api.commit((tx) => tx.doc(MissionApprovals, api.conversationId).then((doc) => markReceiptUnknown(doc, intentKey, err instanceof Error ? err.message : String(err), Date.now())), context);
68
+ // Neither connector failure nor receipt-write failure proves no external effect.
69
+ await api.commit(async (tx) => {
70
+ const doc = await tx.doc(MissionApprovals, api.conversationId);
71
+ markReceiptUnknown(doc, intentKey, err instanceof Error ? err.message : String(err), Date.now());
72
+ }, context);
64
73
  throw err;
65
74
  }
66
- await api.commit((tx) => tx.doc(MissionApprovals, api.conversationId).then((doc) => recordObservedReceipt(doc, intentKey, observed, Date.now())), context);
67
- return { kind: "performed" };
68
75
  }
@@ -66,8 +66,12 @@ export class DurableRuntimeManager {
66
66
  }
67
67
  return { admitted: true };
68
68
  },
69
- release() {
70
- claims.release(workspaceDir, conv.id);
69
+ retainWorkspaceClaim() {
70
+ claims.acquire(workspaceDir, conv.id);
71
+ },
72
+ release(opts) {
73
+ if (!opts?.retainWorkspace)
74
+ claims.release(workspaceDir, conv.id);
71
75
  const promoted = slots.release(conv.id);
72
76
  // La mission promue dispatche SA file immédiatement ; les autres en
73
77
  // file re-tentent ensuite leur admission (un slot vient de se libérer).
@@ -96,6 +100,7 @@ export class DurableRuntimeManager {
96
100
  mcpServers: [...this.opts.toolchain.approvedMcpServers],
97
101
  },
98
102
  control,
103
+ workerBackend: this.opts.workerBackend,
99
104
  });
100
105
  const entry = { runtime, closed: false };
101
106
  this.open.set(conv.id, entry);
@@ -144,13 +149,17 @@ export class DurableRuntimeManager {
144
149
  /** Ferme la runtime d'une conversation (le stockage Durable, lui, survit). */
145
150
  async release(convId) {
146
151
  const managed = this.open.get(convId);
152
+ const retainWorkspace = managed && !managed.closed
153
+ ? !(await managed.runtime.canReleaseWorkspace())
154
+ : false;
147
155
  this.open.delete(convId);
148
156
  if (managed && !managed.closed) {
149
157
  managed.closed = true;
150
158
  await managed.runtime.close();
151
159
  }
152
- // La fermeture relâche aussi slot et claim détenus (sinon fuite d'admission).
153
- this.claims.releaseByMission(convId);
160
+ // Le claim workspace reste tant qu'un worker peut encore écrire.
161
+ if (!retainWorkspace)
162
+ this.claims.releaseByMission(convId);
154
163
  const promoted = this.slots.release(convId);
155
164
  if (promoted) {
156
165
  const next = this.open.get(promoted);
@@ -10,8 +10,9 @@
10
10
  * 2. stockage SQLite en `synchronous = FULL` (le défaut du SDK est NORMAL) ;
11
11
  * 3. profil de mission gelé vérifié (SDK pin, snapshot preset, toolchain) —
12
12
  * toute divergence rejette l'ouverture (fail closed) ;
13
- * 4. workers orphelins classés (vivant → orphelin à observer/arrêter ; mort
14
- * sans disposition → issue inconnue) avant d'activer la planification ;
13
+ * 4. workers orphelins classés (identité vérifiée → orphelin à arrêter ;
14
+ * mort sans preuve de sortie → inconnu ; identité discordante → attention)
15
+ * avant d'activer la planification ;
15
16
  * 5. la planification Durable n'est activée qu'après ces vérifications.
16
17
  *
17
18
  * Admission (P3b, ticket #16) : les envois sont acceptés durablement, mais ne
@@ -30,8 +31,10 @@ import { openNodeSqliteDatabase } from "@earendil-works/pi-durable/storage/sqlit
30
31
  import { join } from "node:path";
31
32
  import { acquireRuntimeLease } from "./lease.js";
32
33
  import { MissionProfile, freezeMissionProfile, assertProfileFrozen } from "./profile.js";
33
- import { WorkerRecords, classifyWorkers, unresolvedWorkers } from "./workers.js";
34
- import { MissionApprovals, GrantRejectedError, createPendingAction, decidePendingAction, findValidGrant, revokeGrant, } from "./approvals.js";
34
+ import { WorkerRecords, unresolvedWorkers } from "./workers.js";
35
+ import { ProcessWorkerBackend, WorkerSupervisor } from "../execution/worker-supervisor.js";
36
+ import { MissionApprovals, GrantRejectedError, createPendingAction, decidePendingAction, findValidGrant, revokeGrant, markReceiptUnknown, } from "./approvals.js";
37
+ import { attentionCases } from "./recovery.js";
35
38
  import { dailyUsage, evaluateBudget, rollDailyBaseline, } from "./admission.js";
36
39
  /** requestId borné et stable (caractères sûrs, 1–128). Miroir de schemas.ts. */
37
40
  export const REQUEST_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
@@ -63,6 +66,7 @@ const PERMISSIVE_CONTROL = {
63
66
  workspaceDir: "",
64
67
  tryAdmit: () => ({ admitted: true }),
65
68
  release: () => undefined,
69
+ retainWorkspaceClaim: () => undefined,
66
70
  claimHolder: () => undefined,
67
71
  emit: () => undefined,
68
72
  };
@@ -72,12 +76,15 @@ export class DurableMissionRuntime {
72
76
  lease;
73
77
  registry;
74
78
  control;
79
+ supervisor;
75
80
  recovery;
76
81
  /** Écritures en cours (turns dispatchés) : le claim se relâche à zéro. */
77
82
  activeWrites = 0;
83
+ schedulingEnabled = false;
84
+ admissionReason;
78
85
  draining = false;
79
86
  closed = false;
80
- constructor(harness, root, lease, registry, control,
87
+ constructor(harness, root, lease, registry, control, supervisor,
81
88
  /** État de récupération à l'ouverture (workers orphelins classés). */
82
89
  recovery) {
83
90
  this.harness = harness;
@@ -85,8 +92,15 @@ export class DurableMissionRuntime {
85
92
  this.lease = lease;
86
93
  this.registry = registry;
87
94
  this.control = control;
95
+ this.supervisor = supervisor;
88
96
  this.recovery = recovery;
89
97
  }
98
+ get workspaceDir() {
99
+ return this.control.workspaceDir;
100
+ }
101
+ get missionId() {
102
+ return String(this.root.id);
103
+ }
90
104
  static async open(opts) {
91
105
  const lease = acquireRuntimeLease(opts.dir);
92
106
  try {
@@ -118,17 +132,20 @@ export class DurableMissionRuntime {
118
132
  Object.assign(doc, { ...versions, createdAt: Date.now() });
119
133
  },
120
134
  });
121
- const runtime = new DurableMissionRuntime(harness, root, lease, opts.registry, opts.control ?? PERMISSIVE_CONTROL, {
135
+ const runtime = new DurableMissionRuntime(harness, root, lease, opts.registry, opts.control ?? PERMISSIVE_CONTROL, new WorkerSupervisor(opts.workerBackend ?? new ProcessWorkerBackend()), {
122
136
  workers: [],
123
137
  needsAttention: false,
124
138
  reasons: [],
125
139
  });
126
140
  await runtime.verifyFrozenProfile(versions);
127
141
  await runtime.reconcileWorkers();
142
+ await runtime.reconcileEffects();
128
143
  // Planification activée seulement après vérification bail/versions/état ;
129
144
  // si un orphelin n'est pas classé, la readiness reste fausse (Plan 0002 §8.2).
130
- if (!runtime.recovery.needsAttention)
145
+ if (!(await runtime.blockingReason())) {
131
146
  harness.resume();
147
+ runtime.schedulingEnabled = true;
148
+ }
132
149
  // Reprise : les inputs retenus en file (slots/budget à l'ancienne session)
133
150
  // restent durables ; on retente l'admission maintenant que la runtime est ouverte.
134
151
  void runtime.tryDrainQueue();
@@ -148,13 +165,153 @@ export class DurableMissionRuntime {
148
165
  /** Reclasse les workers persistés (§5.7) et expose le résultat de récupération. */
149
166
  async reconcileWorkers() {
150
167
  const doc = await this.harness.snapshot(WorkerRecords, this.root.id, context);
151
- const workers = classifyWorkers(doc?.workers ?? []);
168
+ const reconciled = [];
169
+ for (const raw of doc?.workers ?? []) {
170
+ if (raw.intent && !raw.identity && !raw.exitProof) {
171
+ const bound = await this.supervisor.reconcileCreation(raw);
172
+ if (bound.kind === "created" && bound.record.identity) {
173
+ await this.writeWorker(bound.record);
174
+ reconciled.push(bound.record);
175
+ continue;
176
+ }
177
+ const attention = {
178
+ ...raw,
179
+ lifecycle: "attention",
180
+ attentionReason: bound.kind === "attention" ? bound.reason : "intent_unbound",
181
+ revision: (raw.revision ?? 0) + 1,
182
+ };
183
+ await this.writeWorker(attention);
184
+ reconciled.push(attention);
185
+ continue;
186
+ }
187
+ reconciled.push(raw);
188
+ }
189
+ const workers = [];
190
+ for (const record of reconciled) {
191
+ workers.push(await this.supervisor.classify(record));
192
+ }
152
193
  const unresolved = unresolvedWorkers(workers);
153
194
  this.recovery.workers = workers;
154
195
  this.recovery.needsAttention = unresolved.length > 0;
155
- this.recovery.reasons = unresolved.map((u) => u.kind === "live-orphan"
156
- ? `worker ${u.record.id} (pid ${u.record.pid}) toujours vivant : observer/arrêter avant remplacement`
157
- : `worker ${u.record.id} (pid ${u.record.pid}) mort sans issue établie : réconciliation requise`);
196
+ this.recovery.reasons = unresolved.map((u) => {
197
+ switch (u.kind) {
198
+ case "live-orphan":
199
+ return `worker ${u.record.id} toujours vivant : observer/arrêter avant remplacement`;
200
+ case "exited-unknown":
201
+ return `worker ${u.record.id} mort sans preuve de sortie : réconciliation requise`;
202
+ case "attention":
203
+ return `worker ${u.record.id} identité incertaine (${u.reason}) : aucun signal`;
204
+ case "resolved":
205
+ return `worker ${u.record.id} résolu`;
206
+ default: {
207
+ const exhaustive = u;
208
+ return exhaustive;
209
+ }
210
+ }
211
+ });
212
+ if (unresolved.length)
213
+ this.control.retainWorkspaceClaim();
214
+ }
215
+ async writeWorker(next) {
216
+ await this.root.commit(async (tx) => {
217
+ const doc = await tx.doc(WorkerRecords, this.root.id);
218
+ const index = doc.workers.findIndex((w) => w.id === next.id);
219
+ if (index < 0)
220
+ doc.workers.push(next);
221
+ else
222
+ doc.workers[index] = next;
223
+ }, context);
224
+ }
225
+ async persistWorkerIntent(intent) {
226
+ await this.writeWorker({
227
+ id: intent.workerId,
228
+ pid: 0,
229
+ command: "pending-create",
230
+ dispatchedAt: intent.createdAt,
231
+ intent,
232
+ revision: 1,
233
+ lifecycle: "intent",
234
+ });
235
+ this.control.retainWorkspaceClaim();
236
+ await this.reconcileWorkers();
237
+ }
238
+ async bindWorkerIdentity(identity) {
239
+ const doc = await this.harness.snapshot(WorkerRecords, this.root.id, context);
240
+ const existing = doc?.workers.find((w) => w.id === identity.workerId);
241
+ if (!existing)
242
+ throw new Error(`worker inconnu: ${identity.workerId}`);
243
+ await this.writeWorker({
244
+ ...existing,
245
+ pid: identity.observationalPid,
246
+ identity,
247
+ lifecycle: "started",
248
+ revision: (existing.revision ?? 0) + 1,
249
+ });
250
+ this.control.retainWorkspaceClaim();
251
+ await this.reconcileWorkers();
252
+ }
253
+ async canReleaseWorkspace() {
254
+ const doc = await this.harness.snapshot(WorkerRecords, this.root.id, context);
255
+ for (const record of doc?.workers ?? []) {
256
+ const classified = await this.supervisor.classify(record);
257
+ if (classified.kind !== "resolved")
258
+ return false;
259
+ }
260
+ return true;
261
+ }
262
+ async retireWorker(workerId) {
263
+ const doc = await this.harness.snapshot(WorkerRecords, this.root.id, context);
264
+ const record = doc?.workers.find((w) => w.id === workerId);
265
+ if (!record)
266
+ throw new Error(`worker inconnu: ${workerId}`);
267
+ await this.writeWorker({ ...record, lifecycle: "stop_requested", revision: (record.revision ?? 0) + 1 });
268
+ const waited = await this.supervisor.stopThenWait(record);
269
+ if (waited.kind !== "exited") {
270
+ await this.reconcileWorkers();
271
+ throw new Error(`sortie non confirmée: worker ${workerId} (${waited.kind})`);
272
+ }
273
+ await this.writeWorker({
274
+ ...record,
275
+ exitProof: { writingStopped: true, observedAt: Date.now() },
276
+ lifecycle: "exit_verified",
277
+ revision: (record.revision ?? 0) + 2,
278
+ });
279
+ await this.reconcileWorkers();
280
+ if (!(await this.blockingReason())) {
281
+ this.harness.resume();
282
+ this.schedulingEnabled = true;
283
+ }
284
+ this.control.emit(await this.missionStatus());
285
+ }
286
+ /** Only reopening classifies abandoned intents; status reads never do. */
287
+ async reconcileEffects() {
288
+ await this.root.commit(async (tx) => {
289
+ const doc = await tx.doc(MissionApprovals, this.root.id);
290
+ for (const receipt of doc.receipts) {
291
+ if (receipt.status === "intent_committed") {
292
+ markReceiptUnknown(doc, receipt.intentKey, "intent interrompu avant receipt observé : réconciliation requise", Date.now());
293
+ }
294
+ }
295
+ }, context);
296
+ }
297
+ async blockingReason() {
298
+ if (this.recovery.needsAttention)
299
+ return this.recovery.reasons.join("; ");
300
+ const cases = attentionCases(await this.approvalsView());
301
+ if (cases.length)
302
+ return cases.map((item) => item.reason).join("; ");
303
+ const queue = await this.harness.snapshot(MissionQueue, this.root.id, context);
304
+ return queue?.attention?.reason;
305
+ }
306
+ tryAdmit() {
307
+ const admission = this.control.tryAdmit();
308
+ this.admissionReason = admission.admitted ? undefined : admission.reason;
309
+ return admission;
310
+ }
311
+ async assertContinuationAllowed() {
312
+ const reason = await this.blockingReason();
313
+ if (reason)
314
+ throw new NeedsAttentionError(reason);
158
315
  }
159
316
  // ---------- File d'attente durable et admission ----------
160
317
  async queuedInputs() {
@@ -162,7 +319,7 @@ export class DurableMissionRuntime {
162
319
  return doc?.inputs ?? [];
163
320
  }
164
321
  /** État budget courant : cumuls re-lus depuis le transcript et pi.usage, base journalière roulée à UTC. */
165
- async budgetState(now = Date.now()) {
322
+ async budgetState(now = Date.now(), persist = true) {
166
323
  // Requêtes modèle = entrées d'assistant commitées (authoritative, indépendant
167
324
  // du reporting d'usage du provider) ; tokens depuis pi.usage quand le provider
168
325
  // les rapporte (sinon 0 — la limite tokens reste applicable dès qu'ils sont là).
@@ -178,7 +335,7 @@ export class DurableMissionRuntime {
178
335
  const policy = doc?.policy ?? {};
179
336
  const missionUsed = { calls, tokens };
180
337
  const baseline = rollDailyBaseline(doc?.baseline ?? { day: "", calls: 0, tokens: 0 }, missionUsed, now);
181
- if (doc && (doc.missionCalls !== calls || doc.missionTokens !== tokens || doc.baseline.day !== baseline.day)) {
338
+ if (persist && doc && (doc.missionCalls !== calls || doc.missionTokens !== tokens || doc.baseline.day !== baseline.day)) {
182
339
  await this.root.commit(async (tx) => {
183
340
  const d = await tx.doc(MissionBudget, this.root.id);
184
341
  d.missionCalls = calls;
@@ -212,11 +369,12 @@ export class DurableMissionRuntime {
212
369
  * needs_attention > budget_paused > waiting_approval > queued > running/idle.
213
370
  */
214
371
  async missionStatus(now = Date.now()) {
215
- const budget = await this.budgetState(now);
372
+ const budget = await this.budgetState(now, false);
216
373
  const queue = await this.queuedInputs();
217
374
  const approvals = await this.approvalsView();
218
375
  const holder = this.control.claimHolder();
219
376
  const base = {
377
+ attentionCases: attentionCases(approvals),
220
378
  queueLength: queue.length,
221
379
  budget,
222
380
  workspaceDir: this.control.workspaceDir,
@@ -226,6 +384,9 @@ export class DurableMissionRuntime {
226
384
  if (this.recovery.needsAttention) {
227
385
  return { state: "needs_attention", reason: this.recovery.reasons.join("; "), ...base };
228
386
  }
387
+ if (base.attentionCases.length) {
388
+ return { state: "needs_attention", reason: base.attentionCases.map((item) => item.reason).join("; "), ...base };
389
+ }
229
390
  const queueDoc = await this.harness.snapshot(MissionQueue, this.root.id, context);
230
391
  if (queueDoc?.attention) {
231
392
  return { state: "needs_attention", reason: queueDoc.attention.reason, ...base };
@@ -237,10 +398,9 @@ export class DurableMissionRuntime {
237
398
  return { state: "waiting_approval", reason: "action sensible en attente de décision owner", ...base };
238
399
  }
239
400
  if (queue.length > 0) {
240
- const admission = this.control.tryAdmit();
241
401
  return {
242
402
  state: "queued",
243
- ...(admission.admitted ? {} : { reason: admission.reason }),
403
+ ...(this.admissionReason ? { reason: this.admissionReason } : {}),
244
404
  ...base,
245
405
  };
246
406
  }
@@ -257,7 +417,7 @@ export class DurableMissionRuntime {
257
417
  this.draining = true;
258
418
  try {
259
419
  for (;;) {
260
- if (this.closed)
420
+ if (this.closed || await this.blockingReason())
261
421
  break;
262
422
  const queue = await this.queuedInputs();
263
423
  if (queue.length === 0)
@@ -265,7 +425,7 @@ export class DurableMissionRuntime {
265
425
  const budget = await this.budgetState();
266
426
  if (budget.binding)
267
427
  break; // budget_paused : la file reste visible, aucun dispatch
268
- const admission = this.control.tryAdmit();
428
+ const admission = this.tryAdmit();
269
429
  if (!admission.admitted)
270
430
  break;
271
431
  const input = queue[0];
@@ -307,11 +467,6 @@ export class DurableMissionRuntime {
307
467
  if (!REQUEST_ID_PATTERN.test(requestId)) {
308
468
  throw new Error(`requestId invalide (1–128, [A-Za-z0-9._-]): ${requestId}`);
309
469
  }
310
- const unresolved = unresolvedWorkers(this.recovery.workers);
311
- if (unresolved.length > 0) {
312
- // Pas de travail de remplacement tant qu'un worker orphelin n'est pas classé.
313
- throw new NeedsAttentionError(this.recovery.reasons.join("; "));
314
- }
315
470
  const prior = await this.root.commit((tx) => tx.submissionByRequest(this.root.id, requestId), context);
316
471
  if (prior)
317
472
  return { submissionId: prior.id, duplicate: true, queued: false };
@@ -319,6 +474,7 @@ export class DurableMissionRuntime {
319
474
  if (queued.some((i) => i.requestId === requestId)) {
320
475
  return { duplicate: true, queued: true };
321
476
  }
477
+ await this.assertContinuationAllowed();
322
478
  // Admission : budget d'abord (budget_paused nomme la limite liante), puis
323
479
  // slots + claim via le plan de contrôle. En écriture active, la mission
324
480
  // détient déjà slot et claim : dispatch direct.
@@ -343,13 +499,9 @@ export class DurableMissionRuntime {
343
499
  }
344
500
  /** Soumission effective au SDK + suivi d'écritures (relâchement à l'idle). */
345
501
  async dispatch(text, requestId) {
502
+ await this.assertContinuationAllowed();
346
503
  const submission = await this.root.submit({ type: "input", content: text, requestId }, context);
347
- // Un dispatch réussi lève toute condition de denégation antérieure.
348
- await this.root.commit(async (tx) => {
349
- const doc = await tx.doc(MissionQueue, this.root.id);
350
- if (doc.attention)
351
- delete doc.attention;
352
- }, context);
504
+ this.schedulingEnabled = true;
353
505
  this.trackWrites();
354
506
  return submission.id;
355
507
  }
@@ -361,8 +513,7 @@ export class DurableMissionRuntime {
361
513
  .finally(() => {
362
514
  this.activeWrites -= 1;
363
515
  if (this.activeWrites === 0) {
364
- this.control.release();
365
- void this.tryDrainQueue();
516
+ void this.releaseWhenQuiet();
366
517
  }
367
518
  });
368
519
  }
@@ -388,14 +539,23 @@ export class DurableMissionRuntime {
388
539
  async requestPendingAction(input) {
389
540
  const action = await this.root.commit(async (tx) => {
390
541
  const doc = await tx.doc(MissionApprovals, this.root.id);
391
- return createPendingAction(doc, input, Date.now());
542
+ return { ...createPendingAction(doc, input, Date.now()) };
392
543
  }, context);
393
544
  this.control.emit(await this.missionStatus());
394
545
  return action;
395
546
  }
396
547
  /** Décision owner (approve/deny) sur une action serveur ; denial durable (UA1). */
397
548
  async decideApproval(pendingActionId, decision, denialReason) {
398
- const result = await this.root.commit((tx) => tx.doc(MissionApprovals, this.root.id).then((doc) => decidePendingAction(doc, pendingActionId, decision, Date.now(), denialReason)), context);
549
+ const result = await this.root.commit(async (tx) => {
550
+ const doc = await tx.doc(MissionApprovals, this.root.id);
551
+ const result = decidePendingAction(doc, pendingActionId, decision, Date.now(), denialReason);
552
+ if (result.kind === "error")
553
+ return result;
554
+ return {
555
+ ...result, pendingAction: { ...result.pendingAction },
556
+ ...(result.grant ? { grant: { ...result.grant } } : {}),
557
+ };
558
+ }, context);
399
559
  if (result.kind === "decided" && decision === "denied") {
400
560
  // Dénégation durable : la mission passe en needs_attention (reason
401
561
  // action_denied) ; aucun effet ne court, rien n'est re-demandé (UA1).
@@ -414,20 +574,15 @@ export class DurableMissionRuntime {
414
574
  return result;
415
575
  }
416
576
  // ---------- Accès existants ----------
417
- /** Enregistre la disposition terminale d'un worker après observation/arrêt. */
577
+ async releaseWhenQuiet() {
578
+ const retainWorkspace = !(await this.canReleaseWorkspace());
579
+ this.control.release({ retainWorkspace });
580
+ void this.tryDrainQueue();
581
+ }
582
+ /** Arrêt vérifié : inspect, signal seulement si l'identité correspond, preuve de sortie avant reprise. */
418
583
  async resolveWorker(workerId, disposition) {
419
- await this.root.commit(async (tx) => {
420
- const doc = await tx.doc(WorkerRecords, this.root.id);
421
- const record = doc.workers.find((w) => w.id === workerId);
422
- if (!record)
423
- throw new Error(`worker inconnu: ${workerId}`);
424
- record.disposition = disposition;
425
- }, context);
426
- await this.reconcileWorkers();
427
- // Tout orphelin classé : la runtime redevient prête.
428
- if (!this.recovery.needsAttention)
429
- this.harness.resume();
430
- this.control.emit(await this.missionStatus());
584
+ void disposition;
585
+ await this.retireWorker(workerId);
431
586
  }
432
587
  /** Transcript brut (vérité Durable — jamais recopié dans le catalogue, ADR-006 amendé). */
433
588
  async transcript() {
@@ -442,6 +597,9 @@ export class DurableMissionRuntime {
442
597
  };
443
598
  }
444
599
  async waitForIdle() {
600
+ // The pinned SDK enables scheduling on waitForIdle too.
601
+ if (!this.schedulingEnabled)
602
+ await this.assertContinuationAllowed();
445
603
  await this.root.waitForIdle(context);
446
604
  }
447
605
  /** Arrêt : retire les entrées en file et marque les tâches vivantes. */
@@ -0,0 +1,37 @@
1
+ function effectScope(effect) {
2
+ return {
3
+ operation: effect.operation, target: effect.target,
4
+ artifactDigest: effect.artifactDigest, argumentDigest: effect.argumentDigest,
5
+ };
6
+ }
7
+ export function attentionCases(doc) {
8
+ const effects = doc.receipts.filter((receipt) => receipt.status === "unknown").map((receipt) => ({
9
+ version: 1, revision: 1, id: `effect:${receipt.intentKey}`,
10
+ reasonCode: "effect_outcome_unknown",
11
+ reason: receipt.unknownReason ?? "issue externe inconnue : réconciliation requise",
12
+ effect: effectScope(receipt), intentKey: receipt.intentKey, receipt: structuredClone(receipt),
13
+ grantId: receipt.grantId, taskId: receipt.taskId,
14
+ pendingActionId: doc.grants.find((grant) => grant.id === receipt.grantId)?.pendingActionId,
15
+ evidenceAt: receipt.updatedAt,
16
+ unknowns: ["Whether the exact external effect occurred and its authoritative outcome/reference."],
17
+ ownerTask: "Inspect the exact target using the intent identity and connector evidence; reconcile the outcome before continuing. No resolution API is available in this slice.",
18
+ continuationConditions: [
19
+ "Authoritative external evidence must establish and reconcile this intent's outcome.",
20
+ "Do not replay an unresolved intent; a new grant or message is not reconciliation evidence.",
21
+ "Consumed uses stay consumed; a new effect requires separate exact, valid authorization.",
22
+ ],
23
+ }));
24
+ const denials = doc.pendingActions.filter((action) => action.decision === "denied").map((action) => ({
25
+ version: 1, revision: 1, id: `denial:${action.id}`, reasonCode: "action_denied",
26
+ reason: `action_denied: ${action.denialReason ?? "refus owner"}`,
27
+ effect: effectScope(action), pendingActionId: action.id, evidenceAt: action.decidedAt,
28
+ unknowns: ["The owner's explicit decision about how this mission may continue."],
29
+ ownerTask: "Review the refused action and decide whether to cancel, revise the mission or explicitly reopen authorization. No resolution/reopening API is available in this slice.",
30
+ continuationConditions: [
31
+ "The durable refusal must be addressed through an explicit supported owner workflow before continuation.",
32
+ "A new message or unrelated grant does not clear the refusal.",
33
+ "Any uncertain effect requires independent reconciliation before new authorization.",
34
+ ],
35
+ }));
36
+ return [...effects, ...denials].sort((left, right) => left.id < right.id ? -1 : left.id > right.id ? 1 : 0);
37
+ }
@@ -1,8 +1,9 @@
1
1
  /**
2
- * Identité et classification des workers de mission (Plan 0002 §5.7) : un
3
- * crash peut laisser une commande worker en vie ; l'identité est persistée
4
- * AVANT le dispatch, et au redémarrage on observe/arrête et on classe avant
5
- * tout travail de remplacement.
2
+ * Identité et classification des workers de mission (Plan 0002 §5.7, #47) :
3
+ * l'intention de création est persistée AVANT le lancement ; l'identité
4
+ * immuable (exécution, mission, workspace, backend, handle) est vérifiée à
5
+ * chaque inspect/stop/wait. Une disposition déclarative n'est pas une preuve
6
+ * de sortie.
6
7
  */
7
8
  import { defineDoc } from "@earendil-works/pi-durable";
8
9
  export const WorkerRecords = defineDoc({
@@ -25,18 +26,25 @@ export function pidAlive(pid) {
25
26
  return err.code === "EPERM";
26
27
  }
27
28
  }
28
- export function classifyWorker(record) {
29
- if (record.disposition)
29
+ export function classifyWorker(record, observation) {
30
+ if (record.exitProof?.writingStopped)
30
31
  return { kind: "resolved", record };
31
- if (pidAlive(record.pid))
32
- return { kind: "live-orphan", record };
33
- // Plus de processus et aucune disposition/receipt : l'issue est inétablie.
34
- return { kind: "exited-unknown", record };
35
- }
36
- export function classifyWorkers(records) {
37
- return records.map(classifyWorker);
32
+ switch (observation.kind) {
33
+ case "running":
34
+ return { kind: "live-orphan", record };
35
+ case "missing":
36
+ return { kind: "exited-unknown", record };
37
+ case "pid_reuse":
38
+ case "identity_mismatch":
39
+ case "unavailable":
40
+ return { kind: "attention", record, reason: observation.kind };
41
+ default: {
42
+ const exhaustive = observation;
43
+ return exhaustive;
44
+ }
45
+ }
38
46
  }
39
- /** Des workers non résolus (orphelin vivant OU issue inconnue) bloquent la reprise. */
47
+ /** Des workers non résolus (orphelin, inconnu, attention) bloquent la reprise. */
40
48
  export function unresolvedWorkers(classifications) {
41
49
  return classifications.filter((c) => c.kind !== "resolved");
42
50
  }