maka-agent 0.2.0-dev.53.20260927 → 0.2.0-dev.62.20260928

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 (55) hide show
  1. package/LICENSE +6 -5
  2. package/dist/workspace-root.js +2 -2
  3. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  4. package/node_modules/@maka/acp-executor-plugin/dist/index.js +333 -28
  5. package/node_modules/@maka/acp-executor-plugin/dist/plugin.mjs +283 -27
  6. package/node_modules/@maka/core/dist/executor-catalog.js +10 -1
  7. package/node_modules/@maka/core/dist/message-queue-order.js +47 -0
  8. package/node_modules/@maka/core/dist/model-metadata.js +2 -1
  9. package/node_modules/@maka/core/dist/redaction.js +42 -3
  10. package/node_modules/@maka/core/dist/relative-time-policy.js +71 -0
  11. package/node_modules/@maka/core/dist/relative-time.js +3 -54
  12. package/node_modules/@maka/core/package.json +1 -0
  13. package/node_modules/@maka/eval/dist/egress-audit.js +127 -0
  14. package/node_modules/@maka/eval/dist/harness-executor.js +16 -96
  15. package/node_modules/@maka/eval/harbor/egress-proxy/entrypoint.sh +4 -4
  16. package/node_modules/@maka/eval/harbor/egress_filter.py +153 -104
  17. package/node_modules/@maka/eval/harbor/eval_framework.py +37 -14
  18. package/node_modules/@maka/eval/harbor/relay_agent.py +4 -6
  19. package/node_modules/@maka/eval/harbor/run_trial.py +11 -4
  20. package/node_modules/@maka/runtime/dist/agent-graph-supervisor-wake.js +33 -6
  21. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +1 -1
  22. package/node_modules/@maka/runtime/dist/plugin-executor-backend.js +26 -5
  23. package/node_modules/@maka/runtime/dist/plugin-executor-service.js +36 -0
  24. package/node_modules/@maka/runtime/dist/provider-error-classification.js +8 -73
  25. package/node_modules/@maka/runtime/dist/provider-error-signals.js +31 -0
  26. package/node_modules/@maka/runtime/dist/provider-retry-policy.js +79 -0
  27. package/node_modules/@maka/runtime/dist/session-manager.js +6 -4
  28. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +2 -0
  29. package/node_modules/@maka/runtime/dist/shell-run-manager.js +8 -8
  30. package/node_modules/@maka/runtime/dist/terminal-run-commit.js +7 -1
  31. package/node_modules/@maka/runtime/dist/tool-runtime.js +5 -4
  32. package/node_modules/@maka/runtime-host/dist/adapter/provider-retry-projector.js +63 -0
  33. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +7 -51
  34. package/node_modules/@maka/runtime-host/dist/protocol/index.js +9 -3
  35. package/node_modules/@maka/runtime-host/dist/protocol/message-queue-limits.js +21 -0
  36. package/node_modules/@maka/runtime-host/dist/protocol/message.js +6 -104
  37. package/node_modules/@maka/runtime-host/dist/protocol/queue-mutation.js +136 -0
  38. package/node_modules/@maka/runtime-host/dist/protocol/turn-provider-retry.js +69 -0
  39. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +2 -43
  40. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +42 -5
  41. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +105 -233
  42. package/node_modules/@maka/runtime-host/dist/server/message-queue-state.js +69 -0
  43. package/node_modules/@maka/runtime-host/dist/server/provider-retry-projection.js +71 -0
  44. package/node_modules/@maka/runtime-host/dist/server/queued-mutation-executor.js +94 -0
  45. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +1 -1
  46. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +9 -58
  47. package/node_modules/@maka/storage/dist/agent-run-store-contract.js +0 -3
  48. package/node_modules/@maka/storage/dist/agent-run-store.js +15 -6
  49. package/node_modules/@maka/storage/dist/execution-persistence-provider.js +1 -0
  50. package/node_modules/@maka/storage/dist/execution-stores.js +1 -0
  51. package/node_modules/@maka/storage/dist/project-catalog.js +41 -42
  52. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +102 -31
  53. package/node_modules/@maka/storage/dist/sqlite-session-metadata-schema.js +52 -1
  54. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +34 -2
  55. package/package.json +1 -1
@@ -0,0 +1,94 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+ import { isDeepStrictEqual } from 'node:util';
20
+ import { RuntimeMessageAuthorityInvariantError } from '@maka/runtime/message-authority';
21
+ /** Epoch-local idempotency and Session admission for all queue mutations. */
22
+ export class QueuedMutationExecutor {
23
+ #hostEpoch;
24
+ #admissions;
25
+ #isFailStopped;
26
+ #readCompleted;
27
+ #pending = new Map();
28
+ constructor(options) {
29
+ this.#hostEpoch = options.hostEpoch;
30
+ this.#admissions = options.admissions;
31
+ this.#isFailStopped = options.isFailStopped;
32
+ this.#readCompleted = options.readCompleted;
33
+ }
34
+ run(request) {
35
+ const currentEpoch = request.input.originHostEpoch === this.#hostEpoch;
36
+ const key = mutationKey(request.kind, request.input.sessionId, request.id);
37
+ if (currentEpoch) {
38
+ const pending = this.#pending.get(key);
39
+ if (pending) {
40
+ return isDeepStrictEqual(pending.payload, request.input)
41
+ ? pending.result
42
+ : Promise.resolve(conflict(`${request.verb} identity has a different payload`));
43
+ }
44
+ }
45
+ if (this.#isFailStopped())
46
+ return Promise.resolve(draining());
47
+ if (!currentEpoch) {
48
+ return Promise.resolve(failed('outcome_unknown', `${request.verb} outcome is not durable across Host Epochs`));
49
+ }
50
+ const result = this.#admit(request);
51
+ this.#pending.set(key, { payload: request.input, result });
52
+ void result.then(() => this.#settle(key, result), () => this.#settle(key, result));
53
+ return result;
54
+ }
55
+ pendingResults(sessionId) {
56
+ return [...this.#pending.values()]
57
+ .filter(({ payload }) => payload.sessionId === sessionId)
58
+ .map(({ result }) => result);
59
+ }
60
+ #admit(request) {
61
+ return this.#admissions.run(request.input.sessionId, async () => {
62
+ if (this.#isFailStopped())
63
+ return draining();
64
+ const completed = this.#readCompleted(request.kind, request.input.sessionId, request.id);
65
+ if (!completed)
66
+ return request.execute();
67
+ if (!isDeepStrictEqual(completed.payloadIdentity, request.payloadIdentity)) {
68
+ return conflict(`${request.verb} identity has a different payload`);
69
+ }
70
+ try {
71
+ return { ok: true, result: request.spec.decodeOutput(completed.result) };
72
+ }
73
+ catch (error) {
74
+ throw new RuntimeMessageAuthorityInvariantError(`Invalid queued mutation replay outcome: ${error instanceof Error ? error.message : 'malformed'}`);
75
+ }
76
+ });
77
+ }
78
+ #settle(key, result) {
79
+ if (this.#pending.get(key)?.result === result)
80
+ this.#pending.delete(key);
81
+ }
82
+ }
83
+ function mutationKey(kind, sessionId, operationId) {
84
+ return `${kind}\0${sessionId}\0${operationId}`;
85
+ }
86
+ function draining() {
87
+ return failed('host_draining', 'Runtime Host message authority has failed');
88
+ }
89
+ function conflict(message) {
90
+ return failed('operation_conflict', message);
91
+ }
92
+ function failed(code, message) {
93
+ return { ok: false, error: { code, message } };
94
+ }
@@ -2366,7 +2366,7 @@ export class RootTurnCoordinator {
2366
2366
  sessionId,
2367
2367
  turnId: active.turnId,
2368
2368
  runId: active.runId,
2369
- });
2369
+ }, { source: 'host_shutdown' });
2370
2370
  }
2371
2371
  async readCanonicalSnapshot(sessionId, turnId, runId, knownRun) {
2372
2372
  return this.executionProjection.read({ sessionId, turnId, runId }, knownRun);
@@ -23,6 +23,7 @@ import { resolveReadInput } from '@maka/runtime/read-page';
23
23
  import { decodeRuntimeResourceRef, encodeProtocolMessage, RUNTIME_HOST_MAX_MESSAGE_BYTES, SESSION_LIVE_DELTA_MAX_BYTES, SESSION_RUNTIME_RESOURCE_PTY_DATA_MAX_BYTES, SESSION_RUNTIME_RESOURCE_CHANGES_MAX, SESSION_SUBSCRIPTION_FRAME_MAX_BYTES, SUBSCRIPTION_OPEN_RESULT_MAX_BYTES, SESSION_TOOL_ARGS_PREVIEW_MAX_BYTES, SESSION_TOOL_INTENT_MAX_BYTES, SESSION_TOOL_NAME_MAX_BYTES, } from '../protocol/index.js';
24
24
  import { boundedFailureDiagnostic } from './failure-diagnostic.js';
25
25
  import { createSessionContinuitySnapshot, } from './canonical-session-projection.js';
26
+ import { carryProviderRetry, clearProviderRetry, recordProviderRetry, } from './provider-retry-projection.js';
26
27
  import { createSessionTranscriptBootstrap, readSessionTranscriptPage, TranscriptPageRequestError, updateSubscriberTranscriptHighWater, } from './session-transcript-pager.js';
27
28
  import { projectSharedSessionMessageContent } from './shared-session-transcript.js';
28
29
  const MAX_CONNECTION_SUBSCRIPTIONS = 16;
@@ -505,10 +506,10 @@ export class SessionContinuityCoordinator {
505
506
  throw new Error('Runtime event does not belong to the canonical active root Turn');
506
507
  }
507
508
  if (event.type === 'provider_retry') {
508
- this.#publishCanonical(state, withProviderRetry(state.canonical, event));
509
+ this.#commitLiveProjection(state, recordProviderRetry(state.canonical, event));
509
510
  return;
510
511
  }
511
- this.#publishCanonical(state, withoutProviderRetry(state.canonical));
512
+ this.#commitLiveProjection(state, clearProviderRetry(state.canonical));
512
513
  if (event.type === 'text_delta' || event.type === 'thinking_delta') {
513
514
  const kind = event.type === 'text_delta' ? 'text' : 'thinking';
514
515
  const prefixKey = assistantStreamKey(kind, event.messageId);
@@ -1293,7 +1294,7 @@ export class SessionContinuityCoordinator {
1293
1294
  this.#sessions.set(sessionId, state);
1294
1295
  return { changed: true, state, value };
1295
1296
  }
1296
- canonical = preserveProviderRetry(state.canonical, canonical);
1297
+ canonical = carryProviderRetry(state.canonical, canonical);
1297
1298
  const changed = !isDeepStrictEqual(state.canonical, canonical);
1298
1299
  if (changed) {
1299
1300
  if (state.canonical.rootTurn?.runId !== canonical.rootTurn?.runId) {
@@ -1312,14 +1313,12 @@ export class SessionContinuityCoordinator {
1312
1313
  value: createSessionContinuitySnapshot(state.canonical, state.revision),
1313
1314
  };
1314
1315
  }
1315
- #publishCanonical(state, canonical) {
1316
- if (isDeepStrictEqual(state.canonical, canonical))
1316
+ #commitLiveProjection(state, next) {
1317
+ if (isDeepStrictEqual(state.canonical, next))
1317
1318
  return;
1318
- const nextRevision = state.revision + 1;
1319
- const snapshot = createSessionContinuitySnapshot(canonical, nextRevision);
1320
- state.canonical = immutableClone(canonical);
1321
- state.revision = nextRevision;
1322
- this.#broadcastProjection(state, snapshot);
1319
+ state.revision += 1;
1320
+ state.canonical = immutableClone(next);
1321
+ this.#broadcastProjection(state, createSessionContinuitySnapshot(next, state.revision));
1323
1322
  }
1324
1323
  #broadcastProjection(state, snapshot) {
1325
1324
  for (const subscriber of state.subscribers.values()) {
@@ -1442,54 +1441,6 @@ function requirePublicationFenceIdentity(canonical, sessionId, fence) {
1442
1441
  function isTerminalTurn(turn) {
1443
1442
  return turn.status === 'completed' || turn.status === 'failed' || turn.status === 'cancelled';
1444
1443
  }
1445
- function isLiveTurn(turn) {
1446
- return !isTerminalTurn(turn);
1447
- }
1448
- function withProviderRetry(canonical, event) {
1449
- const rootTurn = canonical.rootTurn;
1450
- if (!rootTurn || !isLiveTurn(rootTurn))
1451
- return canonical;
1452
- const providerRetry = event.phase === 'scheduled'
1453
- ? {
1454
- phase: 'scheduled',
1455
- attempt: event.attempt,
1456
- maxAttempts: event.maxAttempts,
1457
- delayMs: event.delayMs,
1458
- ts: event.ts,
1459
- reason: event.reason,
1460
- }
1461
- : {
1462
- phase: 'started',
1463
- attempt: event.attempt,
1464
- maxAttempts: event.maxAttempts,
1465
- reason: event.reason,
1466
- };
1467
- return { ...canonical, rootTurn: { ...rootTurn, providerRetry } };
1468
- }
1469
- function withoutProviderRetry(canonical) {
1470
- const rootTurn = canonical.rootTurn;
1471
- if (!rootTurn || !isLiveTurn(rootTurn) || rootTurn.providerRetry === undefined) {
1472
- return canonical;
1473
- }
1474
- const { providerRetry: _providerRetry, ...cleared } = rootTurn;
1475
- return { ...canonical, rootTurn: cleared };
1476
- }
1477
- function preserveProviderRetry(current, next) {
1478
- const currentTurn = current.rootTurn;
1479
- const nextTurn = next.rootTurn;
1480
- if (!currentTurn ||
1481
- !nextTurn ||
1482
- !isLiveTurn(currentTurn) ||
1483
- !isLiveTurn(nextTurn) ||
1484
- currentTurn.runId !== nextTurn.runId ||
1485
- currentTurn.turnId !== nextTurn.turnId ||
1486
- currentTurn.providerRetry === undefined) {
1487
- return next;
1488
- }
1489
- if (nextTurn.providerRetry !== undefined)
1490
- return next;
1491
- return { ...next, rootTurn: { ...nextTurn, providerRetry: currentTurn.providerRetry } };
1492
- }
1493
1444
  function wireTextByteLimit(frame) {
1494
1445
  return RUNTIME_HOST_MAX_MESSAGE_BYTES - encodeProtocolMessage(frame).byteLength;
1495
1446
  }
@@ -954,6 +954,3 @@ export function hasExactKeys(record, expected) {
954
954
  const keys = Object.keys(record);
955
955
  return keys.length === expected.length && expected.every((key) => Object.hasOwn(record, key));
956
956
  }
957
- export function sanitizeJson(_key, value) {
958
- return value === undefined ? undefined : value;
959
- }
@@ -25,7 +25,7 @@ import { MODEL_CALL_ATTEMPT_EVENT_TYPE } from '@maka/core/model-call-attempt';
25
25
  import { LATEST_CONTEXT_PROJECTION_TYPE, RUN_COMPOSITION_RECORDED_EVENT_TYPE, supersedesLatestContext, } from '@maka/core/agent-run';
26
26
  import { isSessionInlineInvocation } from '@maka/core/runtime-invocation';
27
27
  import { decodeRuntimeInvocationOpened, runtimeEventInvocationOpening, } from '@maka/core/runtime-event';
28
- import { normalizeRootTurnStartRejection, normalizeStoredRootTurnStartRejection, normalizeAdmitRootTurnInput, shouldPreserveCheckpointProjectionDuringAppend, shouldPreserveProjectionDuringRepair, isProjectedAgentRunEvent, assertSafeId, normalizeRootTurnAdmission, orderRootTurnAdmissionChain, rootTurnAdmissionPayloadsEqual, sanitizeJson, } from './agent-run-store-contract.js';
28
+ import { normalizeRootTurnStartRejection, normalizeStoredRootTurnStartRejection, normalizeAdmitRootTurnInput, shouldPreserveCheckpointProjectionDuringAppend, shouldPreserveProjectionDuringRepair, isProjectedAgentRunEvent, assertSafeId, normalizeRootTurnAdmission, orderRootTurnAdmissionChain, rootTurnAdmissionPayloadsEqual, } from './agent-run-store-contract.js';
29
29
  export { ROOT_TURN_ADMISSION_SCHEMA_VERSION, ROOT_TURN_ADMISSION_MAX_SOURCE_MESSAGES, ROOT_TURN_ADMISSION_MAX_CONTENT_BYTES, ROOT_TURN_ADMISSION_MAX_RECORD_BYTES, rootTurnSourceMessagePayloadsEqual, rootTurnAdmissionRecordFits, normalizeRootTurnAdmissionPayload, } from './agent-run-store-contract.js';
30
30
  class RuntimeEventPostEffectError extends Error {
31
31
  cause;
@@ -52,7 +52,13 @@ class SqliteAgentRunStore {
52
52
  this.#lease.transaction('write', () => {
53
53
  const anchor = readSqliteRunAnchor(this.#lease.database, sessionId, runId);
54
54
  this.#openLedgerStream(sessionId, runId, anchor.openedAt);
55
- const normalized = decodeAgentRunEvent(JSON.parse(JSON.stringify(event, sanitizeJson)), {
55
+ // One serialization serves both the validated clone and the ledger row.
56
+ // `decodeAgentRunEvent` only validates — it injects no fields — so the
57
+ // string form of the caller's event and of the decoded clone are
58
+ // identical, and the JSON round-trip stays what detaches the store's
59
+ // copy from an object the caller may still hold.
60
+ const json = JSON.stringify(event);
61
+ const normalized = decodeAgentRunEvent(JSON.parse(json), {
56
62
  sessionId,
57
63
  runId,
58
64
  turnId: anchor.turnId,
@@ -76,7 +82,7 @@ class SqliteAgentRunStore {
76
82
  const projection = projectsCheckpoint
77
83
  ? inspectSqliteAgentRunProjection(this.#lease.database, sessionId, type)
78
84
  : undefined;
79
- insertAgentRunEvent(this.#lease.database, normalized);
85
+ insertAgentRunEvent(this.#lease.database, normalized, json);
80
86
  if (projection && projection.state !== 'malformed') {
81
87
  const current = projectionValue(projection);
82
88
  const row = shouldPreserveCheckpointProjectionDuringAppend(current, normalized)
@@ -587,7 +593,10 @@ function readBoundedSqliteAgentRunEvents(db, sessionId, runId, budget, type) {
587
593
  ...measurement,
588
594
  };
589
595
  }
590
- function insertAgentRunEvent(db, event) {
596
+ /** `recordJson` lets the append path hand in the serialization it already
597
+ * produced: the decoded event and the caller's event stringify identically,
598
+ * so the row reuses the string instead of paying for it a second time. */
599
+ function insertAgentRunEvent(db, event, recordJson) {
591
600
  const row = db
592
601
  .prepare(`
593
602
  SELECT COALESCE(MAX(sequence), -1) + 1 AS sequence
@@ -602,7 +611,7 @@ function insertAgentRunEvent(db, event) {
602
611
  INSERT INTO core_agent_run_events(
603
612
  session_id, run_id, sequence, event_id, event_type, event_ts, record_json
604
613
  ) VALUES (?, ?, ?, ?, ?, ?, ?)
605
- `).run(event.sessionId, event.runId, row.sequence, event.id, event.type, event.ts, JSON.stringify(event, sanitizeJson));
614
+ `).run(event.sessionId, event.runId, row.sequence, event.id, event.type, event.ts, recordJson ?? JSON.stringify(event));
606
615
  if (event.type === MODEL_CALL_ATTEMPT_EVENT_TYPE) {
607
616
  const updated = db
608
617
  .prepare(`
@@ -662,7 +671,7 @@ function writeSqliteAgentRunProjection(db, sessionId, type, event) {
662
671
  INSERT INTO core_agent_run_projections(session_id, event_type, event_json)
663
672
  VALUES (?, ?, ?)
664
673
  ON CONFLICT(session_id, event_type) DO UPDATE SET event_json = excluded.event_json
665
- `).run(sessionId, type, event === null ? null : JSON.stringify(event, sanitizeJson));
674
+ `).run(sessionId, type, event === null ? null : JSON.stringify(event));
666
675
  }
667
676
  function readSqliteRootTurnAdmission(db, sessionId, turnId) {
668
677
  const row = db
@@ -35,6 +35,7 @@ export const EXECUTION_GRAPH_METHODS = [
35
35
  'claimAgentGraphSupervisorWake',
36
36
  'beginAgentGraphSupervisorWakeAttempt',
37
37
  'completeAgentGraphSupervisorWakeAttempt',
38
+ 'exhaustAgentGraphSupervisorWake',
38
39
  'supersedeAgentGraphSupervisorWakes',
39
40
  'readAgentGraphSupervisorWake',
40
41
  'listAgentGraphSupervisorWakeAttempts',
@@ -352,6 +352,7 @@ async function createExecutionStoresForWrite(lease, provider) {
352
352
  appendRuntimePartialBatch: (sessionId, runId, events) => run(() => runtimeEventStore.appendRuntimePartialBatch(sessionId, runId, events)),
353
353
  importConversationCopyRuntimeEvents: (sessionId, batches) => run(() => runtimeEventStore.importConversationCopyRuntimeEvents(sessionId, batches)),
354
354
  ensureTerminalRuntimeEventDurable: (sessionId, runId, event) => run(() => runtimeEventStore.ensureTerminalRuntimeEventDurable(sessionId, runId, event)),
355
+ ensureRecoveredTerminalRuntimeEventDurable: (sessionId, runId, event, operationIds) => run(() => runtimeEventStore.ensureRecoveredTerminalRuntimeEventDurable(sessionId, runId, event, operationIds)),
355
356
  readRuntimeEvents: (sessionId, runId) => run(() => runtimeEventStore.readRuntimeEvents(sessionId, runId)),
356
357
  scanRuntimeEvents: (sessionId, runId, budget, visit) => run(() => runtimeEventStore.scanRuntimeEvents(sessionId, runId, budget, visit)),
357
358
  readRuntimeEventsBounded: (sessionId, runId, budget) => run(() => runtimeEventStore.readRuntimeEventsBounded(sessionId, runId, budget)),
@@ -120,7 +120,7 @@ class SqliteProjectCatalog {
120
120
  return Promise.all(projects.map((project) => this.present(project)));
121
121
  }
122
122
  async register(path, options) {
123
- const resolved = await resolveUserSelectedProjectLocation(path);
123
+ const resolved = await resolveProjectLocation({ path, intent: 'selected' });
124
124
  if (options?.withinRoot && !isPathWithin(options.withinRoot, resolved.canonicalPath)) {
125
125
  throw new ProjectPathBoundaryError(resolved.canonicalPath);
126
126
  }
@@ -224,24 +224,14 @@ class SqliteProjectCatalog {
224
224
  return { project: await this.present(selected), path: selectedPath };
225
225
  }
226
226
  async touch(projectId, path) {
227
- let canonicalPath;
228
- if (path) {
229
- try {
230
- canonicalPath = normalize(await realpath(resolve(path)));
231
- }
232
- catch {
233
- throw new ProjectUnavailableError(projectId);
234
- }
235
- }
227
+ const requestedPath = path ? await canonicalTouchPath(projectId, path) : undefined;
236
228
  const touched = await this.mutate((file) => {
237
229
  const project = findProjectById(file.projects, projectId);
238
230
  if (!project)
239
231
  throw new ProjectNotFoundError(projectId);
240
- const location = canonicalPath
241
- ? project.locations.find((item) => item.path === canonicalPath)
242
- : [...project.locations].sort((a, b) => b.lastUsedAt - a.lastUsedAt || a.path.localeCompare(b.path))[0];
243
- if (canonicalPath && !location) {
244
- throw new ProjectPathMismatchError(projectId, canonicalPath);
232
+ const location = locationForTouch(project, requestedPath);
233
+ if (requestedPath && !location) {
234
+ throw new ProjectPathMismatchError(projectId, requestedPath);
245
235
  }
246
236
  const timestamp = this.now();
247
237
  if (location)
@@ -252,7 +242,7 @@ class SqliteProjectCatalog {
252
242
  return this.present(touched);
253
243
  }
254
244
  async relink(projectId, path) {
255
- const resolved = await resolveUserSelectedProjectLocation(path);
245
+ const resolved = await resolveProjectLocation({ path, intent: 'selected' });
256
246
  const timestamp = this.now();
257
247
  const locationPath = resolved.kind === 'git' ? resolved.git.worktreeRoot : resolved.canonicalPath;
258
248
  const relinked = await this.mutate((file) => {
@@ -267,7 +257,7 @@ class SqliteProjectCatalog {
267
257
  return this.present(relinked);
268
258
  }
269
259
  async relinkWithSessions(projectId, path) {
270
- const resolved = await resolveUserSelectedProjectLocation(path);
260
+ const resolved = await resolveProjectLocation({ path, intent: 'selected' });
271
261
  const timestamp = this.now();
272
262
  const locationPath = resolved.kind === 'git' ? resolved.git.worktreeRoot : resolved.canonicalPath;
273
263
  let committed;
@@ -645,12 +635,33 @@ async function isDirectory(path) {
645
635
  return false;
646
636
  }
647
637
  }
638
+ async function canonicalTouchPath(projectId, path) {
639
+ try {
640
+ return normalize(await realpath(resolve(path)));
641
+ }
642
+ catch {
643
+ throw new ProjectUnavailableError(projectId);
644
+ }
645
+ }
646
+ function locationForTouch(project, requestedPath) {
647
+ if (requestedPath) {
648
+ return project.locations.find((location) => location.path === requestedPath);
649
+ }
650
+ return project.locations.reduce((preferred, location) => {
651
+ if (!preferred)
652
+ return location;
653
+ if (location.lastUsedAt !== preferred.lastUsedAt) {
654
+ return location.lastUsedAt > preferred.lastUsedAt ? location : preferred;
655
+ }
656
+ return location.path.localeCompare(preferred.path) < 0 ? location : preferred;
657
+ }, undefined);
658
+ }
648
659
  export async function resolveProjectLocation(input) {
649
660
  const canonicalPath = normalize(await realpath(resolve(input.path)));
650
- // Regular files are not valid projects. Without this check, a file inside a
651
- // Git worktree reaches `git -C <file> rev-parse ...`, whose numeric failure
652
- // is not treated as an invalid path by the Host coordinator and drains it.
653
- if (!(await stat(canonicalPath)).isDirectory()) {
661
+ const location = await stat(canonicalPath);
662
+ // Reject files before Git discovery: `git -C <file>` reports a generic
663
+ // process failure that callers cannot classify as an invalid project path.
664
+ if (!location.isDirectory()) {
654
665
  throw new TypeError(`Project path is not a directory: ${canonicalPath}`);
655
666
  }
656
667
  if (!(await hasEnclosingGitEntry(canonicalPath))) {
@@ -661,6 +672,15 @@ export async function resolveProjectLocation(input) {
661
672
  };
662
673
  }
663
674
  const git = await resolveGitLocation(canonicalPath);
675
+ // A chooser selection names this directory exactly. Historical working
676
+ // directories may resolve upward to their enclosing worktree instead.
677
+ if (input.intent === 'selected' && canonicalPath !== git.worktreeRoot) {
678
+ return {
679
+ canonicalPath,
680
+ identity: `folder:${canonicalPath}`,
681
+ kind: 'folder',
682
+ };
683
+ }
664
684
  return {
665
685
  canonicalPath,
666
686
  identity: `git:${git.commonDir}`,
@@ -668,27 +688,6 @@ export async function resolveProjectLocation(input) {
668
688
  git,
669
689
  };
670
690
  }
671
- /**
672
- * A directory the user picked in the add/relink chooser.
673
- *
674
- * `resolveProjectLocation` still walks to the enclosing Git worktree so a
675
- * historical session cwd inside a repository stays on that repository.
676
- * The chooser must not do that: selecting `repo/child` would otherwise
677
- * silently become `repo` and reopen the parent project.
678
- */
679
- async function resolveUserSelectedProjectLocation(path) {
680
- const resolved = await resolveProjectLocation({ path });
681
- if (resolved.kind !== 'git' ||
682
- !resolved.git ||
683
- resolved.canonicalPath === resolved.git.worktreeRoot) {
684
- return resolved;
685
- }
686
- return {
687
- canonicalPath: resolved.canonicalPath,
688
- identity: `folder:${resolved.canonicalPath}`,
689
- kind: 'folder',
690
- };
691
- }
692
691
  function isPathWithin(root, candidate) {
693
692
  const path = relative(normalize(root), normalize(candidate));
694
693
  return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith(`..${sep}`));
@@ -250,6 +250,71 @@ export class SqliteRuntimeStore {
250
250
  }
251
251
  await this.importRuntimeEvent(sessionId, runId, canonicalEvent);
252
252
  }
253
+ async ensureRecoveredTerminalRuntimeEventDurable(sessionId, runId, event, unsettledOperationIds) {
254
+ const terminal = canonicalizeRuntimeEventForStorage(event);
255
+ assertNoReservedToolLedgerFact(terminal);
256
+ if (terminal.sessionId !== sessionId ||
257
+ terminal.runId !== runId ||
258
+ terminal.partial ||
259
+ !isTerminalRuntimeEvent(terminal) ||
260
+ terminal.status !== 'failed' ||
261
+ terminal.actions?.stateDelta?.recovered !== true ||
262
+ terminal.actions.stateDelta.recoveryReason !== 'outcome_unknown') {
263
+ throw new Error('Unknown-outcome recovery requires a failed terminal RuntimeEvent');
264
+ }
265
+ const expected = new Set(unsettledOperationIds);
266
+ if (expected.size === 0 || expected.size !== unsettledOperationIds.length) {
267
+ throw new Error('Recovery terminal requires distinct unsettled operation ids');
268
+ }
269
+ this.transaction(() => {
270
+ const existing = this.readRuntimeEventJson(terminal.id);
271
+ if (existing !== undefined) {
272
+ assertStoredRuntimeEventEquals(terminal, existing);
273
+ const tail = this.db
274
+ .prepare('SELECT event_id FROM runtime_events WHERE session_id = ? AND run_id = ? ORDER BY event_seq DESC LIMIT 1')
275
+ .get(sessionId, runId);
276
+ if (tail?.event_id !== terminal.id) {
277
+ throw new Error('Recovery terminal RuntimeEvent is not the immutable run tail');
278
+ }
279
+ const settled = this.db
280
+ .prepare("SELECT operation_id FROM tool_journal_events WHERE runtime_event_id = ? AND state IN ('abandoned', 'interrupted_unknown')")
281
+ .all(terminal.id);
282
+ if (settled.length !== expected.size ||
283
+ settled.some(({ operation_id }) => !expected.has(operation_id))) {
284
+ throw new Error('Recovery terminal settled operations do not match the durable ledger');
285
+ }
286
+ for (const operationId of expected) {
287
+ const operation = this.readToolOperationSync(operationId);
288
+ if (!operation ||
289
+ operation.invocationId !== terminal.invocationId ||
290
+ operation.runId !== runId ||
291
+ operation.turnId !== terminal.turnId ||
292
+ operation.currentState !== terminalToolProjectionState(operation)) {
293
+ throw new Error(`Recovery terminal tool projection is incomplete: ${operationId}`);
294
+ }
295
+ }
296
+ return;
297
+ }
298
+ const pending = this.listUnsettledToolOperationsSync([sessionId]).filter((operation) => operation.invocationId === terminal.invocationId);
299
+ if (pending.length !== expected.size ||
300
+ pending.some((operation) => !expected.has(operation.operationId) ||
301
+ operation.runId !== runId ||
302
+ operation.turnId !== terminal.turnId)) {
303
+ throw new Error('Recovery terminal unsettled operations do not match the durable ledger');
304
+ }
305
+ this.importRuntimeEventSync(terminal, true);
306
+ this.options.failpoint?.('after_recovery_terminal_insert');
307
+ const terminalRow = this.db
308
+ .prepare('SELECT event_id, event_seq, committed_at FROM runtime_events WHERE event_id = ?')
309
+ .get(terminal.id);
310
+ for (const operation of pending) {
311
+ if (!this.settleTerminalToolProjectionSync(operation, terminalRow)) {
312
+ throw new Error(`Recovery terminal precedes tool dispatch ${operation.operationId}`);
313
+ }
314
+ }
315
+ this.options.failpoint?.('after_recovery_terminal_projection');
316
+ });
317
+ }
253
318
  async importRuntimeEvent(sessionId, runId, event) {
254
319
  const canonicalEvent = canonicalizeRuntimeEventForStorage(event);
255
320
  assertNoReservedToolLedgerFact(canonicalEvent);
@@ -2622,6 +2687,9 @@ export class SqliteRuntimeStore {
2622
2687
  return this.readToolOperationSync(operationId);
2623
2688
  }
2624
2689
  async listUnsettledToolOperations(sessionIds) {
2690
+ return this.listUnsettledToolOperationsSync(sessionIds);
2691
+ }
2692
+ listUnsettledToolOperationsSync(sessionIds) {
2625
2693
  const selectedSessionIds = sessionIds === undefined
2626
2694
  ? undefined
2627
2695
  : [...new Set(typeof sessionIds === 'string' ? [sessionIds] : sessionIds)];
@@ -2681,15 +2749,8 @@ export class SqliteRuntimeStore {
2681
2749
  * or older than the RuntimeEvent schema understood by this build.
2682
2750
  */
2683
2751
  async rebuildTerminalToolProjectionsForSessions(sessionIds) {
2684
- const operations = await this.listUnsettledToolOperations(sessionIds);
2685
- if (operations.length === 0)
2686
- return;
2687
2752
  this.transaction(() => {
2688
- const dispatchSequence = this.db.prepare(`
2689
- SELECT event_seq
2690
- FROM runtime_events
2691
- WHERE event_id = ? AND session_id = ? AND invocation_id = ?
2692
- `);
2753
+ const operations = this.listUnsettledToolOperationsSync(sessionIds);
2693
2754
  const firstTerminal = this.db.prepare(`
2694
2755
  SELECT event_id, event_seq, committed_at
2695
2756
  FROM runtime_events
@@ -2698,36 +2759,41 @@ export class SqliteRuntimeStore {
2698
2759
  ORDER BY event_seq ASC, event_id ASC
2699
2760
  LIMIT 1
2700
2761
  `);
2701
- const insertJournal = this.db.prepare(`
2762
+ for (const operation of operations) {
2763
+ const terminal = firstTerminal.get(operation.sessionId, operation.invocationId);
2764
+ if (terminal)
2765
+ this.settleTerminalToolProjectionSync(operation, terminal);
2766
+ }
2767
+ });
2768
+ }
2769
+ settleTerminalToolProjectionSync(operation, terminal) {
2770
+ if (!operation.dispatchEventId)
2771
+ return false;
2772
+ const dispatch = this.db
2773
+ .prepare('SELECT event_seq FROM runtime_events WHERE event_id = ? AND session_id = ? AND invocation_id = ?')
2774
+ .get(operation.dispatchEventId, operation.sessionId, operation.invocationId);
2775
+ if (!dispatch || terminal.event_seq <= dispatch.event_seq)
2776
+ return false;
2777
+ const state = terminalToolProjectionState(operation);
2778
+ this.db
2779
+ .prepare(`
2702
2780
  INSERT INTO tool_journal_events (
2703
2781
  journal_event_id, operation_id, invocation_id, run_id, turn_id, state,
2704
2782
  runtime_event_id, canonical_args_hash, recovery_mode, committed_at
2705
2783
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2706
- `);
2707
- const updateOperation = this.db.prepare(`
2784
+ `)
2785
+ .run(journalEventIdFor(operation.operationId, terminal.event_id, state), operation.operationId, operation.invocationId, operation.runId, operation.turnId, state, terminal.event_id, operation.canonicalArgsHash, operation.recoveryMode, terminal.committed_at);
2786
+ const updated = this.db
2787
+ .prepare(`
2708
2788
  UPDATE tool_operations
2709
2789
  SET current_state = ?, version = version + 1
2710
2790
  WHERE operation_id = ? AND current_state = 'prepared' AND result_event_id IS NULL
2711
- `);
2712
- for (const operation of operations) {
2713
- if (!operation.dispatchEventId)
2714
- continue;
2715
- const dispatch = dispatchSequence.get(operation.dispatchEventId, operation.sessionId, operation.invocationId);
2716
- if (!dispatch)
2717
- continue;
2718
- const terminal = firstTerminal.get(operation.sessionId, operation.invocationId);
2719
- if (!terminal || terminal.event_seq <= dispatch.event_seq)
2720
- continue;
2721
- const state = operation.toolName === 'AskUserQuestion' && operation.recoveryMode === 'never_auto_retry'
2722
- ? 'abandoned'
2723
- : 'interrupted_unknown';
2724
- insertJournal.run(journalEventIdFor(operation.operationId, terminal.event_id, state), operation.operationId, operation.invocationId, operation.runId, operation.turnId, state, terminal.event_id, operation.canonicalArgsHash, operation.recoveryMode, terminal.committed_at);
2725
- const updated = updateOperation.run(state, operation.operationId);
2726
- if (updated.changes !== 1) {
2727
- throw new Error(`Tool operation projection changed during export: ${operation.operationId}`);
2728
- }
2729
- }
2730
- });
2791
+ `)
2792
+ .run(state, operation.operationId);
2793
+ if (updated.changes !== 1) {
2794
+ throw new Error(`Tool operation projection changed: ${operation.operationId}`);
2795
+ }
2796
+ return true;
2731
2797
  }
2732
2798
  rebuildToolProjectionsFromRuntimeEventsSync(sessionId) {
2733
2799
  const statement = this.db.prepare(`
@@ -4057,6 +4123,11 @@ function requireRuntimeEventOrder(eventOrder, eventId) {
4057
4123
  throw new Error(`Missing RuntimeEvent order for ${eventId}`);
4058
4124
  return order;
4059
4125
  }
4126
+ function terminalToolProjectionState(operation) {
4127
+ return operation.toolName === 'AskUserQuestion' && operation.recoveryMode === 'never_auto_retry'
4128
+ ? 'abandoned'
4129
+ : 'interrupted_unknown';
4130
+ }
4060
4131
  function journalEventIdFor(operationId, eventId, state) {
4061
4132
  if (state === 'outcome_committed')
4062
4133
  return `${operationId}_outcome`;