gestalt-mobile 0.49.7 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/README.md +12 -3
  2. package/dist/client/assets/{index-BxgQCQyH.js → index-IkBR-U3-.js} +2 -2
  3. package/dist/client/index.html +1 -1
  4. package/dist/server/server/composition.contracts.js +234 -17
  5. package/dist/server/server/composition.js +16 -39
  6. package/dist/server/server/features/autopilot/application/policy.js +27 -2
  7. package/dist/server/server/features/autopilot/application/service.js +97 -13
  8. package/dist/server/server/features/autopilot/domain/supervised-lifecycle.js +11 -2
  9. package/dist/server/server/features/control-plane-trace/export-trace.js +1 -0
  10. package/dist/server/server/features/org-plan-checkpoint/application/validate.js +3 -1
  11. package/dist/server/server/features/plans/application/parse-supervised-plan.js +45 -2
  12. package/dist/server/server/features/plans/domain/supervised-plan.js +12 -1
  13. package/dist/server/server/features/self-debug/create-session.js +5 -9
  14. package/dist/server/server/features/sessions/start-session/use-case.js +27 -24
  15. package/dist/server/server/platform/codex/codex-process-launcher.js +3 -2
  16. package/dist/server/server/platform/codex/session-runtime.js +5 -1
  17. package/dist/server/server/platform/kimi/kimi-web-server-manager.js +1 -0
  18. package/dist/server/server/platform/persistence/migrate.js +1 -0
  19. package/dist/server/server/platform/persistence/retention.js +4 -3
  20. package/dist/server/server/platform/persistence/sqlite-event-journal.js +14 -4
  21. package/dist/server/server/platform/plans/org-plan-capabilities.js +7 -0
  22. package/dist/server/server/platform/plans/plan-measurement-command.js +2 -0
  23. package/dist/server/server/platform/plans/plan-measurement-refresh.js +4 -1
  24. package/dist/server/shared/contracts/autopilot-audit.js +2 -2
  25. package/gestalt-supervision-capabilities.json +2 -1
  26. package/package.json +2 -1
@@ -8,6 +8,7 @@ import { AutopilotStateError } from '../domain/persisted-state-error.js';
8
8
  import { canTransitionExecutorCommand, retainExecutorCommands, } from '../domain/executor-commands.js';
9
9
  import { deriveSessionStatus } from '../../sessions/session-status.js';
10
10
  import { createHash } from 'node:crypto';
11
+ import { currentExecutableL1Index, } from '../../plans/domain/supervised-plan.js';
11
12
  import { AUTOPILOT_WAIT_MAX_MS, AUTOPILOT_WAIT_MIN_MS, } from '../../../../shared/contracts/autopilot-wait-lease.js';
12
13
  import { autopilotSnapshot, disabledAutopilot, } from '../domain/autopilot-session.js';
13
14
  import { classifyExecutorOutcome, decideSupervisedLifecycle, executorIdentity, validStructuredBlock, checkpointTarget, executorAssignment, } from '../domain/supervised-lifecycle.js';
@@ -874,6 +875,24 @@ export class AutopilotCoordinator {
874
875
  return;
875
876
  }
876
877
  this.supersedeExecutorCommands(sessionId, plan.identity, plan.plan);
878
+ const retainedExecutor = this.deps.store.find(sessionId)?.executor;
879
+ const assignedStep = retainedExecutor
880
+ ? plan.plan.steps[Number(retainedExecutor.canonicalPosition.slice(1)) - 1]
881
+ : undefined;
882
+ if (retainedExecutor &&
883
+ assignedStep?.state === 'SUSPENDED' &&
884
+ retainedExecutor.l1State !== 'SUSPENDED') {
885
+ const latest = this.deps.store.find(sessionId);
886
+ this.persist({
887
+ ...latest,
888
+ executor: {
889
+ ...retainedExecutor,
890
+ l1State: 'SUSPENDED',
891
+ ...(retainedExecutor.l2State === 'WIP' ? { l2State: 'SUSPENDED' } : {}),
892
+ },
893
+ updatedAt: this.deps.now(),
894
+ });
895
+ }
877
896
  // Supersession persists independently. Re-read before reopening epochs so
878
897
  // this update cannot restore commands from the stale pre-supersession row.
879
898
  const current = this.deps.store.find(sessionId) ?? prior;
@@ -1324,7 +1343,12 @@ export class AutopilotCoordinator {
1324
1343
  executor: {
1325
1344
  ...executor,
1326
1345
  commands: executor.commands.map((command) => command.status === 'scheduled'
1327
- ? { ...command, status: 'cancelled', updatedAt: this.deps.now() }
1346
+ ? {
1347
+ ...command,
1348
+ status: 'cancelled',
1349
+ supersededBeforeIssue: true,
1350
+ updatedAt: this.deps.now(),
1351
+ }
1328
1352
  : command),
1329
1353
  },
1330
1354
  updatedAt: this.deps.now(),
@@ -1484,16 +1508,16 @@ export class AutopilotCoordinator {
1484
1508
  const epoch = epochs.get(target);
1485
1509
  return Boolean(epoch?.reopened || epoch?.completed === false);
1486
1510
  };
1487
- return plan.steps.some((l1) => l1.children.some((l2) => l2.state === 'DONE' &&
1488
- (!reportedL2.has(JSON.stringify([l1.id, l2.id])) ||
1489
- epochNeedsReport(checkpointTarget('l2', l1.id, l2.id)))) ||
1511
+ return plan.steps.some((l1) => (l1.state !== 'SUSPENDED' &&
1512
+ l1.children.some((l2) => l2.state === 'DONE' &&
1513
+ (!reportedL2.has(JSON.stringify([l1.id, l2.id])) ||
1514
+ epochNeedsReport(checkpointTarget('l2', l1.id, l2.id))))) ||
1490
1515
  (l1.state === 'DONE' &&
1491
1516
  l1.reviewStatus === 'REVIEWED' &&
1492
1517
  (!reportedL1.has(l1.id) || epochNeedsReport(checkpointTarget('l1', l1.id)))));
1493
1518
  }
1494
1519
  currentExecutor(sessionId, plan, continuationCount, persisted, activity = this.deps.activity(sessionId)) {
1495
- const stepIndex = plan.steps.findIndex((step) => step.id === plan.currentStepId || step.state === 'WIP');
1496
- const index = stepIndex >= 0 ? stepIndex : plan.steps.findIndex((step) => step.state !== 'DONE');
1520
+ const index = currentExecutableL1Index(plan);
1497
1521
  if (index < 0)
1498
1522
  return undefined;
1499
1523
  const step = plan.steps[index];
@@ -1638,6 +1662,18 @@ export class AutopilotCoordinator {
1638
1662
  return true;
1639
1663
  }
1640
1664
  executorCommand(fence, executor, generation, trigger) {
1665
+ const unissued = (executor.commands ?? [])
1666
+ .filter((command) => command.supersededBeforeIssue &&
1667
+ !command.processAction &&
1668
+ command.planIdentity === fence.planIdentity &&
1669
+ command.planFingerprint === fence.planFingerprint &&
1670
+ command.threadId === fence.executorThreadId &&
1671
+ command.taskPath === executor.taskPath &&
1672
+ command.canonicalTaskName === executor.canonicalTaskName &&
1673
+ command.generation === generation &&
1674
+ command.trigger === trigger.kind)
1675
+ .map((command) => command.commandId)
1676
+ .sort();
1641
1677
  const commandId = createHash('sha256')
1642
1678
  .update(JSON.stringify([
1643
1679
  fence.planIdentity,
@@ -1649,6 +1685,7 @@ export class AutopilotCoordinator {
1649
1685
  generation,
1650
1686
  ...(executor.resumeFailures ? [executor.resumeFailures] : []),
1651
1687
  trigger.kind,
1688
+ ...(unissued.length ? [unissued] : []),
1652
1689
  ]))
1653
1690
  .digest('hex');
1654
1691
  const now = this.deps.now();
@@ -1714,6 +1751,9 @@ export class AutopilotCoordinator {
1714
1751
  return state?.requestedEnabled &&
1715
1752
  retained &&
1716
1753
  executor &&
1754
+ (command.processAction ||
1755
+ currentExecutableL1Index(retained.plan) ===
1756
+ Number(command.canonicalPosition.slice(1)) - 1) &&
1717
1757
  executor.commands?.some((entry) => entry.commandId === command.commandId &&
1718
1758
  (['scheduled', 'issued'].includes(entry.status) ||
1719
1759
  (command.processAction && entry.status === 'failed'))) &&
@@ -1883,7 +1923,12 @@ export class AutopilotCoordinator {
1883
1923
  if (!stale || !['scheduled', 'issued'].includes(command.status))
1884
1924
  return command;
1885
1925
  changed = true;
1886
- return { ...command, status: 'superseded', updatedAt: this.deps.now() };
1926
+ return {
1927
+ ...command,
1928
+ status: 'superseded',
1929
+ ...(command.status === 'scheduled' ? { supersededBeforeIssue: true } : {}),
1930
+ updatedAt: this.deps.now(),
1931
+ };
1887
1932
  });
1888
1933
  if (!changed)
1889
1934
  return false;
@@ -1925,8 +1970,7 @@ export class AutopilotCoordinator {
1925
1970
  const plan = this.deps.plan(sessionId)?.plan;
1926
1971
  if (!plan)
1927
1972
  return undefined;
1928
- const stepIndex = plan.steps.findIndex((step) => step.id === plan.currentStepId || step.state === 'WIP');
1929
- const index = stepIndex >= 0 ? stepIndex : plan.steps.findIndex((step) => step.state !== 'DONE');
1973
+ const index = currentExecutableL1Index(plan);
1930
1974
  if (index < 0)
1931
1975
  return undefined;
1932
1976
  const canonicalTaskName = `l${index + 1}`;
@@ -1953,7 +1997,7 @@ export class AutopilotCoordinator {
1953
1997
  retained.identity !== replacement.planIdentity ||
1954
1998
  fingerprint(retained.plan) !== replacement.planFingerprint)
1955
1999
  return false;
1956
- const index = retained.plan.steps.findIndex((step) => step.id === retained.plan.currentStepId || step.state === 'WIP');
2000
+ const index = currentExecutableL1Index(retained.plan);
1957
2001
  return index >= 0 && replacement.canonicalPosition === `L${index + 1}`;
1958
2002
  }
1959
2003
  /** Converts an exhausted physical executor into one durable root-owned handoff. */
@@ -2344,8 +2388,7 @@ export class AutopilotCoordinator {
2344
2388
  authoritativeExecutorActive(next, plan, activity) {
2345
2389
  if (!plan || activity?.confidence !== 'fresh')
2346
2390
  return false;
2347
- const selected = plan.steps.findIndex((step) => step.id === plan.currentStepId || step.state === 'WIP');
2348
- const index = selected >= 0 ? selected : plan.steps.findIndex((step) => step.state !== 'DONE');
2391
+ const index = currentExecutableL1Index(plan);
2349
2392
  if (index < 0)
2350
2393
  return false;
2351
2394
  const position = `L${index + 1}`;
@@ -2627,6 +2670,7 @@ export class AutopilotCoordinator {
2627
2670
  */
2628
2671
  containOperationFailure(sessionId, error, operation = 'queuedOperation') {
2629
2672
  const code = operationFailureCode(error);
2673
+ const rpcCode = operationRpcCode(error);
2630
2674
  try {
2631
2675
  this.deps.diagnostic?.(sessionId, `operationFailed:${code}`);
2632
2676
  }
@@ -2659,12 +2703,27 @@ export class AutopilotCoordinator {
2659
2703
  if (!current?.requestedEnabled)
2660
2704
  return;
2661
2705
  const now = this.deps.now();
2706
+ const protocol = current.supervision ?? startSupervisionProtocol(this.progressKey(sessionId));
2707
+ const requireRootRecovery = operation === 'executorResume' &&
2708
+ !['attentionRequired', 'safetyPaused'].includes(protocol.outcome);
2662
2709
  const recovery = {
2663
2710
  ...current,
2664
2711
  state: 'monitoring',
2665
2712
  generation: current.generation + 1,
2666
2713
  nextEvaluationAt: null,
2667
2714
  stopReason: 'reconcileFailed',
2715
+ ...(requireRootRecovery
2716
+ ? {
2717
+ supervision: {
2718
+ ...protocol,
2719
+ outcome: 'probeRequired',
2720
+ probeKey: this.progressKey(sessionId),
2721
+ waitLease: null,
2722
+ retryKey: null,
2723
+ safetyPauseReason: null,
2724
+ },
2725
+ }
2726
+ : {}),
2668
2727
  updatedAt: now,
2669
2728
  };
2670
2729
  try {
@@ -2674,7 +2733,12 @@ export class AutopilotCoordinator {
2674
2733
  {
2675
2734
  sessionId,
2676
2735
  type: 'autopilot.operation-failed',
2677
- payload: { code, kind: operation, reason: operationErrorKind(error) },
2736
+ payload: {
2737
+ code,
2738
+ kind: operation,
2739
+ reason: operationErrorKind(error),
2740
+ ...(rpcCode !== undefined ? { rpcCode } : {}),
2741
+ },
2678
2742
  occurredAt: now,
2679
2743
  },
2680
2744
  ],
@@ -2699,6 +2763,17 @@ export class AutopilotCoordinator {
2699
2763
  return;
2700
2764
  }
2701
2765
  try {
2766
+ if (requireRootRecovery) {
2767
+ // The issued executor command must stay fenced: a lost reply may hide
2768
+ // accepted work. Reinspection alone cannot resolve that uncertainty.
2769
+ // Give the root one diagnostic continuation through the normal gates
2770
+ // instead of mechanically retrying the same executor indefinitely.
2771
+ this.cancelWaitTimer(sessionId);
2772
+ this.parkedSubscriptions.delete(sessionId);
2773
+ this.evaluate(sessionId);
2774
+ if (this.timers.has(sessionId))
2775
+ return;
2776
+ }
2702
2777
  this.armExecutorRefresh(sessionId, this.deps.policy.executorContinuationMaxMs);
2703
2778
  }
2704
2779
  catch {
@@ -2760,6 +2835,15 @@ function operationFailureCode(error) {
2760
2835
  return 'OPERATION';
2761
2836
  }
2762
2837
  /** Fixed protocol categories only; exception prose and arbitrary codes stay private. */
2838
+ function operationRpcCode(error) {
2839
+ if (error &&
2840
+ typeof error === 'object' &&
2841
+ 'code' in error &&
2842
+ typeof error.code === 'number' &&
2843
+ Number.isSafeInteger(error.code))
2844
+ return error.code;
2845
+ return undefined;
2846
+ }
2763
2847
  function operationErrorKind(error) {
2764
2848
  if (error &&
2765
2849
  typeof error === 'object' &&
@@ -164,8 +164,8 @@ export function parsePersistedSupervisedLifecycle(value) {
164
164
  const canonicalTaskName = boundedText(executorValue.canonicalTaskName);
165
165
  const taskPath = boundedText(executorValue.taskPath);
166
166
  const threadId = boundedText(executorValue.threadId);
167
- const l1State = stringValue(executorValue.l1State, ['TODO', 'WIP', 'DONE']);
168
- const l2State = stringValue(executorValue.l2State, ['TODO', 'WIP', 'DONE']);
167
+ const l1State = stringValue(executorValue.l1State, ['TODO', 'WIP', 'DONE', 'SUSPENDED']);
168
+ const l2State = stringValue(executorValue.l2State, ['TODO', 'WIP', 'DONE', 'SUSPENDED']);
169
169
  const lastActivityAt = boundedText(executorValue.lastActivityAt);
170
170
  const outcome = stringValue(executorValue.outcome, [
171
171
  'objective_complete',
@@ -273,6 +273,8 @@ export function parsePersistedSupervisedLifecycle(value) {
273
273
  typeof generation === 'number' &&
274
274
  typeof attempt === 'number' &&
275
275
  trigger &&
276
+ (command.supersededBeforeIssue === undefined ||
277
+ (command.supersededBeforeIssue === true && ['cancelled', 'superseded'].includes(status))) &&
276
278
  createdAt &&
277
279
  updatedAt &&
278
280
  (command.processAction === undefined ||
@@ -289,6 +291,7 @@ export function parsePersistedSupervisedLifecycle(value) {
289
291
  threadId: commandThreadId,
290
292
  generation,
291
293
  ...(attempt ? { attempt } : {}),
294
+ ...(command.supersededBeforeIssue ? { supersededBeforeIssue: true } : {}),
292
295
  trigger,
293
296
  ...(processActionValue && processActionKind && processActionKey
294
297
  ? { processAction: { kind: processActionKind, processKey: processActionKey } }
@@ -535,6 +538,12 @@ export function decideSupervisedLifecycle(input) {
535
538
  finalAllowed: true,
536
539
  action: { kind: 'invokeAttention', ...input.attention },
537
540
  };
541
+ if (input.executor &&
542
+ (input.executor.l1State === 'SUSPENDED' ||
543
+ input.executor.l2State === 'SUSPENDED' ||
544
+ input.plan.steps[Number(input.executor.canonicalPosition.slice(1)) - 1]?.state ===
545
+ 'SUSPENDED'))
546
+ return { finalAllowed: false, action: { kind: 'continueSupervisor' } };
538
547
  const processes = input.executor?.ownedProcesses ?? [];
539
548
  const overBudget = processes.find((process) => (process.state === 'running' || process.state === 'detached-active') &&
540
549
  (process.elapsedMs > input.policy.processMaxElapsedMs ||
@@ -20,6 +20,7 @@ const diagnosticFields = new Set([
20
20
  'status',
21
21
  'reason',
22
22
  'code',
23
+ 'rpcCode',
23
24
  'enabled',
24
25
  'requestedEnabled',
25
26
  'desiredState',
@@ -28,7 +28,7 @@ export function resolveOrgPlanCheckpointSignal(kind, plan, planIdentity, publica
28
28
  const allReviewed = plan.steps.filter((step) => step.state === 'DONE' && step.reviewStatus === 'REVIEWED');
29
29
  const unreportedReviewed = allReviewed.filter((step) => !completedTargets.includes(checkpointTarget('l1', step.id)));
30
30
  const reviewed = reviewedId || !unreportedReviewed.length ? allReviewed : unreportedReviewed;
31
- const allCompleted = plan.steps.flatMap((parent) => parent.reviewStatus === 'UNREVIEWED'
31
+ const allCompleted = plan.steps.flatMap((parent) => parent.state !== 'SUSPENDED' && parent.reviewStatus === 'UNREVIEWED'
32
32
  ? parent.children
33
33
  .filter((child) => child.state === 'DONE' &&
34
34
  (!completedId || child.id === completedId) &&
@@ -98,6 +98,8 @@ export function validateOrgPlanCheckpoint(input) {
98
98
  const l1 = plan.steps.find((step) => step.id === checkpoint.l1Id);
99
99
  if (!l1)
100
100
  return { valid: false, reasonCode: 'l1NotFound' };
101
+ if (l1.state === 'SUSPENDED')
102
+ return { valid: false, reasonCode: 'l1Suspended' };
101
103
  const position = `L${plan.steps.indexOf(l1) + 1}`;
102
104
  if (checkpoint.kind === 'l2Completed') {
103
105
  const l2 = l1.children.find((step) => step.id === checkpoint.l2Id);
@@ -4,7 +4,7 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { isAbsolute, relative, resolve } from 'node:path';
7
- const headingPattern = /^(\*{1,2}) (TODO|WIP|DONE) \[#([ABC])\] (.+)$/;
7
+ const headingPattern = /^(\*{1,2}) (TODO|WIP|DONE|SUSPENDED) \[#([ABC])\] (.+)$/;
8
8
  const propertyPattern = /^:([A-Z_]+):(?:[ \t](.*))?$/;
9
9
  const descriptionPattern = /^- ([A-Za-z][A-Za-z ]*?) ::(?:[ \t](.*))?$/;
10
10
  /**
@@ -98,6 +98,8 @@ export function parseSupervisedPlan(input) {
98
98
  return unavailable('MALFORMED_ORG');
99
99
  if (new Set(headings.map((heading) => heading.id)).size !== headings.length)
100
100
  return unavailable('DUPLICATE_ID');
101
+ if (!hasValidSuspension(headings))
102
+ return unavailable('MALFORMED_ORG');
101
103
  if (!hasValidWipPath(headings))
102
104
  return unavailable('MULTIPLE_WIP');
103
105
  const built = buildSteps(headings);
@@ -278,6 +280,43 @@ function descriptionFor(heading) {
278
280
  doneWhen: description.get('Done when'),
279
281
  };
280
282
  }
283
+ /** Match the helper's bounded suspension-v1 lifecycle dialect. */
284
+ function hasValidSuspension(headings) {
285
+ const parents = headings.filter((heading) => heading.level === 1);
286
+ const suspended = parents.filter((heading) => heading.state === 'SUSPENDED');
287
+ if (suspended.length > 1 ||
288
+ headings.filter((heading) => heading.level === 2 && heading.state === 'SUSPENDED').length > 1)
289
+ return false;
290
+ let parent;
291
+ for (const heading of headings) {
292
+ if (heading.level === 1)
293
+ parent = heading;
294
+ const dependency = heading.properties.get('SUSPENDED_FOR');
295
+ if (heading.level === 1 && heading.state === 'SUSPENDED') {
296
+ const index = parents.findIndex((candidate) => candidate.id === dependency);
297
+ if (index < 0 ||
298
+ index >= parents.indexOf(heading) ||
299
+ heading.properties.get('REVIEW_STATUS') !== 'UNREVIEWED')
300
+ return false;
301
+ }
302
+ else if (dependency !== undefined)
303
+ return false;
304
+ if (heading.level === 2) {
305
+ if (!parent)
306
+ return false;
307
+ if (heading.state === 'SUSPENDED' && parent.state !== 'SUSPENDED')
308
+ return false;
309
+ if (parent.state === 'SUSPENDED' && heading.state === 'WIP')
310
+ return false;
311
+ if (parent.state === 'DONE' && heading.state !== 'DONE')
312
+ return false;
313
+ if (parent.state === 'TODO' && heading.state !== 'TODO')
314
+ return false;
315
+ }
316
+ }
317
+ return (!suspended.length ||
318
+ !parents.some((heading) => heading.state === 'WIP' && parents.indexOf(heading) >= parents.indexOf(suspended[0])));
319
+ }
281
320
  function hasValidWipPath(headings) {
282
321
  const wipByLevel = new Map();
283
322
  for (const heading of headings) {
@@ -310,9 +349,13 @@ function findCurrentStepId(headings, allDone) {
310
349
  heading.properties.get('REVIEW_STATUS') === 'UNREVIEWED');
311
350
  if (review)
312
351
  return review.id;
313
- const todo = headings.find((heading) => heading.state === 'TODO');
352
+ const suspended = headings.find((heading) => heading.level === 1 && heading.state === 'SUSPENDED');
353
+ const todo = headings.find((heading) => heading.state === 'TODO' &&
354
+ (!suspended || headings.indexOf(heading) < headings.indexOf(suspended)));
314
355
  if (todo)
315
356
  return todo.id;
357
+ if (suspended)
358
+ return suspended.id;
316
359
  return allDone ? (headings.findLast((heading) => heading.level === 1)?.id ?? null) : null;
317
360
  }
318
361
  function freezePlan(plan) {
@@ -3,4 +3,15 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
- export {};
6
+ /** Suspended work is a barrier: no later implementation may be selected. */
7
+ export function currentExecutableL1Index(plan) {
8
+ const boundary = plan.steps.findIndex((step) => step.state === 'SUSPENDED');
9
+ const eligible = (index) => boundary < 0 || index < boundary;
10
+ const selected = plan.steps.findIndex((step, index) => eligible(index) &&
11
+ (step.id === plan.currentStepId ||
12
+ step.children.some((child) => child.id === plan.currentStepId) ||
13
+ step.state === 'WIP'));
14
+ if (selected >= 0)
15
+ return selected;
16
+ return plan.steps.findIndex((step, index) => eligible(index) && step.state !== 'DONE');
17
+ }
@@ -7,16 +7,12 @@ import { selfDebugPrompt, } from '../../../shared/contracts/self-debug.js';
7
7
  import { RelaySession } from '../sessions/model/relay-session.js';
8
8
  export async function createSelfDebugSession(context, deps) {
9
9
  const id = deps.createId();
10
- const agent = await deps.settings();
10
+ const source = deps.find(context.mobileSession);
11
+ if (!source || source.threadId !== (context.sourceThread ?? context.codexThread))
12
+ throw new Error('DEBUG_SOURCE_UNAVAILABLE');
13
+ const agent = await deps.settings(source);
11
14
  const captured = await deps.capture(id, context, agent);
12
- // Diagnostic collection is best effort; source-agent failure never blocks the new root.
13
- try {
14
- await deps.askSource(id, context, captured.debug);
15
- }
16
- catch {
17
- /* Captured evidence remains sufficient to begin. */
18
- }
19
- let session = await deps.createSession(id, captured.root, agent);
15
+ let session = await deps.createSession(id, captured.root, agent, source);
20
16
  session = { ...session, selfDebug: captured.debug };
21
17
  deps.save(session);
22
18
  try {
@@ -3,7 +3,7 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
- import { RelaySession } from '../model/relay-session.js';
6
+ import { RelaySession, } from '../model/relay-session.js';
7
7
  import { DEFAULT_SESSION_MODEL } from '../application/start-settings.js';
8
8
  import { reconcileSkillSelectionSnapshot, } from '../../skills/model/skill-profile.js';
9
9
  import { SkillProfileError } from '../../skills/model/errors.js';
@@ -31,29 +31,32 @@ export async function startSession(input, deps) {
31
31
  else {
32
32
  model ??= DEFAULT_SESSION_MODEL;
33
33
  }
34
- const selectedProfile = input.skillProfile
35
- ? await deps.skillProfiles.readGlobalProfile(input.skillProfile)
36
- : deps.defaultSkillProfile;
37
- if (input.skillProfile && !selectedProfile)
38
- throw new SkillProfileError('UNKNOWN_SKILL_PROFILE', 'The selected skill profile does not exist.');
39
- const [projectProfile, catalog] = await Promise.all([
40
- deps.skillProfiles.readWorkspaceDefault(workspace.realPath),
41
- deps.skillCatalog(input.provider, input.profile).list(workspace.realPath),
42
- ]);
43
- const sourceProfile = selectedProfile ?? projectProfile;
44
- const reconciledSkills = reconcileSkillSelectionSnapshot(catalog.skills, sourceProfile?.skills);
45
- const effectiveSkillSelection = {
46
- ...(selectedProfile ? { selectedProfileName: selectedProfile.name } : {}),
47
- skills: [
48
- ...reconciledSkills.skills.map((skill) => ({
49
- name: skill.name,
50
- path: skill.path,
51
- enabled: skill.enabled,
52
- })),
53
- ...reconciledSkills.missing,
54
- ],
55
- ...(reconciledSkills.warnings.length > 0 ? { warnings: reconciledSkills.warnings } : {}),
56
- };
34
+ let effectiveSkillSelection = deps.inheritedSkillSelection;
35
+ if (!effectiveSkillSelection) {
36
+ const selectedProfile = input.skillProfile
37
+ ? await deps.skillProfiles.readGlobalProfile(input.skillProfile)
38
+ : deps.defaultSkillProfile;
39
+ if (input.skillProfile && !selectedProfile)
40
+ throw new SkillProfileError('UNKNOWN_SKILL_PROFILE', 'The selected skill profile does not exist.');
41
+ const [projectProfile, catalog] = await Promise.all([
42
+ deps.skillProfiles.readWorkspaceDefault(workspace.realPath),
43
+ deps.skillCatalog(input.provider, input.profile).list(workspace.realPath),
44
+ ]);
45
+ const sourceProfile = selectedProfile ?? projectProfile;
46
+ const reconciledSkills = reconcileSkillSelectionSnapshot(catalog.skills, sourceProfile?.skills);
47
+ effectiveSkillSelection = {
48
+ ...(selectedProfile ? { selectedProfileName: selectedProfile.name } : {}),
49
+ skills: [
50
+ ...reconciledSkills.skills.map((skill) => ({
51
+ name: skill.name,
52
+ path: skill.path,
53
+ enabled: skill.enabled,
54
+ })),
55
+ ...reconciledSkills.missing,
56
+ ],
57
+ ...(reconciledSkills.warnings.length > 0 ? { warnings: reconciledSkills.warnings } : {}),
58
+ };
59
+ }
57
60
  const branch = await deps.gitBranch?.(workspace.realPath);
58
61
  const session = RelaySession.create({
59
62
  id: deps.createId(),
@@ -27,8 +27,9 @@ export function launchCodexAppServer(input) {
27
27
  };
28
28
  }
29
29
  /** Prevents a relay's own ambient status path from reaching discovery-only children. */
30
- export function codexChildEnvironment(environment) {
31
- const inherited = { ...process.env };
30
+ export function codexChildEnvironment(environment, launchEnvironment = process.env) {
31
+ const inherited = { ...launchEnvironment };
32
+ delete inherited.GESTALT_MOBILE_ORG_PLAN_CAPABILITIES;
32
33
  delete inherited.GESTALT_MOBILE_ORG_PLAN_STATUS_FILE;
33
34
  delete inherited.GESTALT_MOBILE_ORG_PLAN_STATUS_DIRECTORY;
34
35
  delete inherited.GESTALT_MOBILE_ORG_PLAN_MEASUREMENT_URL;
@@ -3,6 +3,7 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
+ import { ORG_PLAN_CAPABILITIES } from '../plans/org-plan-capabilities.js';
6
7
  import { RelaySession, } from '../../features/sessions/model/relay-session.js';
7
8
  import { randomUUID } from 'node:crypto';
8
9
  import { createPlanMeasurementSnapshot, } from '../../features/plans/application/measurement-snapshot.js';
@@ -917,7 +918,10 @@ export class CodexSessionRuntime {
917
918
  ? {
918
919
  environment: {
919
920
  ...(lease
920
- ? { GESTALT_MOBILE_ORG_PLAN_STATUS_DIRECTORY: lease.statusDirectory }
921
+ ? {
922
+ GESTALT_MOBILE_ORG_PLAN_STATUS_DIRECTORY: lease.statusDirectory,
923
+ GESTALT_MOBILE_ORG_PLAN_CAPABILITIES: ORG_PLAN_CAPABILITIES,
924
+ }
921
925
  : {}),
922
926
  ...(this.planMeasurementBaseUrl
923
927
  ? {
@@ -143,6 +143,7 @@ export class KimiWebServerManager {
143
143
  /** Prevents relay state from leaking into kimi web children, and pins KIMI_SHARE_DIR. */
144
144
  export function kimiChildEnvironment(overrides) {
145
145
  const inherited = { ...process.env };
146
+ delete inherited.GESTALT_MOBILE_ORG_PLAN_CAPABILITIES;
146
147
  delete inherited.GESTALT_MOBILE_ORG_PLAN_STATUS_FILE;
147
148
  delete inherited.GESTALT_MOBILE_ORG_PLAN_STATUS_DIRECTORY;
148
149
  delete inherited.GESTALT_MOBILE_ORG_PLAN_MEASUREMENT_URL;
@@ -28,6 +28,7 @@ function migrateWorkspaceGitDefaults(database) {
28
28
  }
29
29
  export function migrate(database) {
30
30
  database.exec(schema);
31
+ database.exec('CREATE INDEX IF NOT EXISTS session_events_retention ON session_events(session_id, julianday(occurred_at))');
31
32
  database.exec('CREATE TABLE IF NOT EXISTS autopilot_state_quarantine (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL REFERENCES relay_sessions(id) ON DELETE CASCADE, record_json TEXT NOT NULL, created_at TEXT NOT NULL)');
32
33
  database.exec("CREATE INDEX IF NOT EXISTS session_events_autopilot_audit_tail_v3 ON session_events(session_id, type, sequence DESC) WHERE type IN ('autopilot.continuation-scheduled','autopilot.control-issued','autopilot.turn-started','autopilot.turn-failed','autopilot.progress-reset','autopilot.final-rejected','autopilot.executor-resumed','autopilot.process-monitoring','autopilot.process-result-consumed','autopilot.process-terminated','autopilot.updated','org-plan.attention-required','org-plan.attention-resolved')");
33
34
  const columns = database.prepare('PRAGMA table_info(relay_sessions)').all();
@@ -3,7 +3,8 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
- export const eventRetention = 2000;
7
- export function retainedSequences(sequences) {
8
- return sequences.slice(-eventRetention);
6
+ export const eventRetentionMs = 48 * 60 * 60 * 1000;
7
+ export function eventRetentionCutoff(occurredAt) {
8
+ const timestamp = Date.parse(occurredAt);
9
+ return Number.isFinite(timestamp) ? new Date(timestamp - eventRetentionMs).toISOString() : null;
9
10
  }
@@ -4,6 +4,7 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { boundedAttentionReport } from '../../../shared/contracts/attention-report.js';
7
+ import { eventRetentionCutoff } from './retention.js';
7
8
  export const autopilotAuditEventTypes = [
8
9
  'autopilot.turn-started',
9
10
  'autopilot.turn-failed',
@@ -34,7 +35,7 @@ const renderableAutopilotAuditWhere = `
34
35
  export class SqliteEventJournal {
35
36
  db;
36
37
  retain;
37
- constructor(db, retain = 2000) {
38
+ constructor(db, retain) {
38
39
  this.db = db;
39
40
  this.retain = retain;
40
41
  }
@@ -67,9 +68,18 @@ export class SqliteEventJournal {
67
68
  this.db
68
69
  .prepare('UPDATE relay_sessions SET next_sequence = next_sequence + 1 WHERE id = ?')
69
70
  .run(sessionId);
70
- this.db
71
- .prepare('DELETE FROM session_events WHERE session_id = ? AND sequence NOT IN (SELECT sequence FROM session_events WHERE session_id = ? ORDER BY sequence DESC LIMIT ?)')
72
- .run(sessionId, sessionId, this.retain);
71
+ if (this.retain !== undefined) {
72
+ this.db
73
+ .prepare('DELETE FROM session_events WHERE session_id = ? AND sequence NOT IN (SELECT sequence FROM session_events WHERE session_id = ? ORDER BY sequence DESC LIMIT ?)')
74
+ .run(sessionId, sessionId, this.retain);
75
+ }
76
+ else {
77
+ const cutoff = eventRetentionCutoff(occurredAt);
78
+ if (cutoff)
79
+ this.db
80
+ .prepare('DELETE FROM session_events WHERE session_id = ? AND julianday(occurred_at) < julianday(?)')
81
+ .run(sessionId, cutoff);
82
+ }
73
83
  const event = { sessionId, sequence: row.sequence, type, occurredAt, payload };
74
84
  this.db.exec('COMMIT');
75
85
  return event;
@@ -0,0 +1,7 @@
1
+ /*
2
+ * Copyright (C) 2026 Dyne.org foundation
3
+ * Designed by Denis Roio <jaromil@dyne.org>
4
+ * SPDX-License-Identifier: AGPL-3.0-or-later
5
+ */
6
+ /** Compiled host assertion; never supplied by config, request or ambient env. */
7
+ export const ORG_PLAN_CAPABILITIES = 'suspension-v1';
@@ -5,11 +5,13 @@
5
5
  */
6
6
  import { execFile } from 'node:child_process';
7
7
  import { promisify } from 'node:util';
8
+ import { ORG_PLAN_CAPABILITIES } from './org-plan-capabilities.js';
8
9
  const execute = promisify(execFile);
9
10
  export const PLAN_MEASUREMENT_COMMAND_TIMEOUT_MS = 15_000;
10
11
  /** Invokes the explicitly configured Org Plan helper without a shell. */
11
12
  export async function checkpointPlanMeasurement(helperPath, planPath, stepId, snapshot) {
12
13
  await execute(helperPath, ['measure', 'checkpoint', planPath, stepId, JSON.stringify(snapshot)], {
14
+ env: { ...process.env, GESTALT_MOBILE_ORG_PLAN_CAPABILITIES: ORG_PLAN_CAPABILITIES },
13
15
  shell: false,
14
16
  timeout: PLAN_MEASUREMENT_COMMAND_TIMEOUT_MS,
15
17
  });
@@ -54,7 +54,10 @@ export class PlanMeasurementRefresh {
54
54
  return;
55
55
  this.inFlight.add(sessionId);
56
56
  try {
57
- await this.checkpoint(active.planPath, active.stepId, await this.readSnapshot(sessionId));
57
+ const snapshot = await this.readSnapshot(sessionId);
58
+ // Suspension/reselection may arrive while the provider read is in flight.
59
+ if (this.active.get(sessionId) === active)
60
+ await this.checkpoint(active.planPath, active.stepId, snapshot);
58
61
  }
59
62
  catch {
60
63
  // A transient Codex or helper failure makes this tick unavailable only.
@@ -53,8 +53,8 @@ export function autopilotAuditLabel(type, payload) {
53
53
  const reason = property(payload, 'reason');
54
54
  if (state === 'completed')
55
55
  return 'Completed the supervised plan';
56
- if (state === 'monitoring' && reason === 'reconcileFailed')
57
- return 'Automatic continuation waiting for recovery: agent status unavailable';
56
+ // Recovery health updates belong to the status and notification pipeline.
57
+ // They may repeat on every reconciliation and are not dialogue milestones.
58
58
  if (state === 'attentionRequired' && reason === 'noPlanProgress')
59
59
  return 'Automatic continuation stopped: no agent progress';
60
60
  if (state === 'attentionRequired' && reason === 'reconcileFailed')