gestalt-mobile 0.60.1 → 0.61.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.
@@ -388,6 +388,138 @@ async function createUnauthorizedProductionApp(root, dataDir) {
388
388
  }
389
389
  describe('production composition', () => {
390
390
  describeCompositionConcern('autopilot', () => {
391
+ it('serves compact supervision deltas and wakes only for the selected host run', async () => {
392
+ let coordinator;
393
+ const f = await createProductionAutopilotFixture({
394
+ autopilotSchedule: () => () => { },
395
+ onAutopilotCoordinator: (value) => {
396
+ coordinator = value;
397
+ },
398
+ });
399
+ onTestFinished(() => f.app.close());
400
+ const exec = promisify(execFile);
401
+ await exec('git', ['init', '-q', f.workspacePath]);
402
+ await exec('git', [
403
+ '-c',
404
+ 'user.name=Fixture',
405
+ '-c',
406
+ 'user.email=fixture@example.invalid',
407
+ 'commit',
408
+ '--allow-empty',
409
+ '-qm',
410
+ 'fixture',
411
+ ], { cwd: f.workspacePath });
412
+ const marker = join(f.dataDir, 'release-test');
413
+ await mkdir(join(f.workspacePath, '.gestalt'), { recursive: true });
414
+ await writeFile(join(f.workspacePath, '.gestalt/host-tests.json'), JSON.stringify({
415
+ version: 1,
416
+ suites: [
417
+ {
418
+ id: 'controlled',
419
+ repository: f.workspacePath,
420
+ command: process.execPath,
421
+ args: [
422
+ '-e',
423
+ "setInterval(()=>{if(require('node:fs').existsSync(process.argv[1]))process.exit(0)},20)",
424
+ marker,
425
+ ],
426
+ timeoutMs: 10_000,
427
+ maxOutputBytes: 4096,
428
+ },
429
+ ],
430
+ }));
431
+ expect((await f.app.inject({
432
+ method: 'POST',
433
+ url: `/api/sessions/${f.sessionId}/turns`,
434
+ payload: { text: 'Synthetic run wait fixture' },
435
+ })).statusCode).toBe(202);
436
+ const session = (await f.app.inject(`/api/sessions/${f.sessionId}`)).json();
437
+ const handle = f.handles.find((value) => value.calls.includes('turn/start'));
438
+ let requestId = 5000;
439
+ const call = async (tool, args) => {
440
+ const response = (await handle.request({
441
+ id: ++requestId,
442
+ method: 'item/tool/call',
443
+ params: {
444
+ threadId: session.threadId,
445
+ turnId: session.activeTurnId,
446
+ tool,
447
+ arguments: args,
448
+ },
449
+ }));
450
+ return JSON.parse(response.contentItems[0].text);
451
+ };
452
+ const initial = await call('gestalt_org_plan_health', { view: 'compact' });
453
+ expect(initial.snapshot).toMatchObject({
454
+ plan: { l1: { id: 'parent' } },
455
+ tests: { running: 0, unread: 0 },
456
+ control: { enabled: true },
457
+ });
458
+ expect(Buffer.byteLength(JSON.stringify(initial))).toBeLessThan(2500);
459
+ const unchanged = await call('gestalt_org_plan_health', {
460
+ view: 'compact',
461
+ sinceRevision: initial.revision,
462
+ });
463
+ expect(unchanged).toEqual({ revision: initial.revision, unchanged: true });
464
+ expect(Buffer.byteLength(JSON.stringify(unchanged))).toBeLessThan(120);
465
+ expect(await call('gestalt_org_plan_health', {})).toMatchObject({
466
+ enabled: true,
467
+ health: expect.any(Object),
468
+ });
469
+ const run = await call('gestalt_test_runner', {
470
+ operation: 'start',
471
+ suite: 'controlled',
472
+ requestId: '00000000-0000-4000-8000-000000000002',
473
+ });
474
+ expect(run.state).toBe('running');
475
+ const changed = await call('gestalt_org_plan_health', {
476
+ view: 'compact',
477
+ sinceRevision: initial.revision,
478
+ });
479
+ expect(changed.changes.tests).toMatchObject({
480
+ running: 1,
481
+ runs: [{ runId: run.runId, state: 'running' }],
482
+ });
483
+ expect(changed.snapshot).toBeUndefined();
484
+ expect(await call('gestalt_test_runner', {
485
+ operation: 'wait',
486
+ runId: run.runId,
487
+ maxWaitMs: 60_000,
488
+ })).toEqual({ accepted: true, runId: run.runId });
489
+ // A retried request must not register another lease or reset its deadline.
490
+ expect(await call('gestalt_test_runner', {
491
+ operation: 'wait',
492
+ runId: run.runId,
493
+ maxWaitMs: 60_000,
494
+ })).toEqual({ accepted: true, runId: run.runId });
495
+ expect(coordinator.rootProcessCompleted(f.sessionId, 'another-run')).toBe(false);
496
+ expect(coordinator.semanticEvent(f.sessionId, 'processResultAvailable')).toBe(false);
497
+ const parked = await call('gestalt_org_plan_health', {
498
+ view: 'compact',
499
+ sinceRevision: changed.revision,
500
+ });
501
+ expect(parked.changes.wait).toMatchObject({ runId: run.runId });
502
+ const database = new DatabaseSync(join(f.dataDir, 'relay.sqlite'));
503
+ onTestFinished(() => database.close());
504
+ const count = (type) => database
505
+ .prepare('SELECT COUNT(*) AS count FROM session_events WHERE session_id=? AND type=?')
506
+ .get(f.sessionId, type)?.count;
507
+ expect(count('autopilot.wait-registered')).toBe(1);
508
+ expect(count('autopilot.wait-woken')).toBe(0);
509
+ await writeFile(marker, 'done');
510
+ await vi.waitFor(() => expect(count('autopilot.wait-woken')).toBe(1), { timeout: 5000 });
511
+ expect(await call('gestalt_test_runner', { operation: 'wait', runId: run.runId })).toMatchObject({
512
+ accepted: false,
513
+ reason: 'runCompleted',
514
+ next: 'continueSameTurn',
515
+ result: { state: 'passed', exitCode: 0 },
516
+ });
517
+ expect(await call('gestalt_test_runner', {
518
+ operation: 'wait',
519
+ runId: '00000000-0000-4000-8000-000000000099',
520
+ })).toEqual({ error: 'runNotFound' });
521
+ expect(count('autopilot.wait-woken')).toBe(1);
522
+ });
391
523
  it('does not park after a host test completes before process-wait registration', async () => {
392
524
  let coordinator;
393
525
  const f = await createProductionAutopilotFixture({
@@ -93,7 +93,8 @@ import { createRelyingPartyConfig } from './config.js';
93
93
  import { parseOrgPlanAttention, parseOrgPlanAttentionToolResponse, toOrgPlanAttentionAcknowledgement, } from '../shared/contracts/org-plan-attention.js';
94
94
  import { autopilotWaitLeaseToolResponse, } from '../shared/contracts/autopilot-wait-lease.js';
95
95
  import { agentCapacityRecoveryToolResponse } from '../shared/contracts/agent-capacity-recovery.js';
96
- import { isOrgPlanHealthCall } from '../shared/contracts/org-plan-health.js';
96
+ import { isOrgPlanHealthCall, parseOrgPlanHealthArguments, } from '../shared/contracts/org-plan-health.js';
97
+ import { compactSupervisionSnapshot, SupervisionSnapshots, } from './features/autopilot/application/supervision-snapshot.js';
97
98
  import { ExecutorModelEvidenceReader } from './features/plans/application/executor-model-evidence.js';
98
99
  import { ExecutorLaunchValidationReader } from './features/plans/application/executor-launch-validation.js';
99
100
  import { requireModelPolicyAdmission } from './features/plans/domain/model-policy-admission.js';
@@ -114,6 +115,7 @@ export async function composeRelayApp(options) {
114
115
  throw new Error('Authorization randomness must return exactly 32 bytes');
115
116
  const root = resolve(options.root);
116
117
  let hostTests;
118
+ const supervisionSnapshots = new SupervisionSnapshots();
117
119
  const databasePath = options.dataDir
118
120
  ? join(resolve(options.dataDir), 'relay.sqlite')
119
121
  : resolveStateDatabasePath(root, process.env.XDG_STATE_HOME ?? join(homedir(), '.local', 'state'));
@@ -264,6 +266,7 @@ export async function composeRelayApp(options) {
264
266
  });
265
267
  const autopilot = new AutopilotCoordinator({
266
268
  pendingProcessResult: (sessionId) => hostTests?.hasUnreadResult(sessionId) ?? false,
269
+ processResultState: (sessionId, runId) => hostTests?.resultState(sessionId, runId) ?? 'missing',
267
270
  modelPolicyStatus: (sessionId) => supervisedPlans.modelPolicyStatus(sessionId),
268
271
  store: autopilotStore,
269
272
  now: () => new Date().toISOString(),
@@ -953,6 +956,26 @@ export async function composeRelayApp(options) {
953
956
  workspace: session.workspacePath,
954
957
  root: origin?.kind === 'root',
955
958
  provider: session.provider,
959
+ waitForRun: (runId, maxWaitMs) => {
960
+ const current = sessions.find(sessionId);
961
+ if (origin?.kind !== 'root' ||
962
+ !current?.activeTurnId ||
963
+ origin.physicalTurnId !== current.activeTurnId)
964
+ return false;
965
+ const state = autopilotStore.find(sessionId);
966
+ if (!state?.requestedEnabled)
967
+ return false;
968
+ const leaseId = `host-test:${runId}:${current.activeTurnId}`;
969
+ if (state.supervision?.waitLease?.id === leaseId)
970
+ return true;
971
+ return autopilot.registerProactiveWait(sessionId, {
972
+ id: leaseId,
973
+ leaseId,
974
+ runId,
975
+ maxWaitMs,
976
+ wakeConditions: ['processResultAvailable'],
977
+ });
978
+ },
956
979
  }, toolCall.arguments);
957
980
  return (runtime?.resolveServerRequest(sessionId, String(request.id), {
958
981
  success: true,
@@ -1004,26 +1027,51 @@ export async function composeRelayApp(options) {
1004
1027
  };
1005
1028
  }
1006
1029
  }
1007
- const modelPolicy = await executorModelEvidence.read(sessionId);
1008
- const executorLaunch = await executorLaunchValidation.read(sessionId);
1030
+ const [modelPolicy, executorLaunch] = await Promise.all([
1031
+ executorModelEvidence.read(sessionId),
1032
+ executorLaunchValidation.read(sessionId),
1033
+ ]);
1009
1034
  const snapshot = autopilot.snapshot(sessionId);
1035
+ const args = parseOrgPlanHealthArguments(toolCall?.arguments);
1036
+ const healthReport = args.view === 'compact'
1037
+ ? supervisionSnapshots.read(sessionId, compactSupervisionSnapshot({
1038
+ autopilot: snapshot,
1039
+ plan: supervisedPlans.find(sessionId),
1040
+ planIdentity: supervisedPlans.identity(sessionId),
1041
+ activity: activity.snapshot(sessionId, new Date().toISOString()),
1042
+ pendingInteractions: blockingInteractions(sessionId).length,
1043
+ tests: hostTests?.supervisionSummary(sessionId) ?? {
1044
+ enabled: false,
1045
+ running: 0,
1046
+ unread: 0,
1047
+ omitted: 0,
1048
+ runs: [],
1049
+ },
1050
+ wait: autopilotStore.find(sessionId)?.supervision?.waitLease ?? null,
1051
+ binding: executorBinding
1052
+ ? { status: executorBinding.status, code: executorBinding.code }
1053
+ : null,
1054
+ modelPolicy,
1055
+ launch: executorLaunch,
1056
+ }), args.sinceRevision)
1057
+ : {
1058
+ state: snapshot.state,
1059
+ enabled: snapshot.enabled,
1060
+ health: snapshot.health,
1061
+ reason: snapshot.reason,
1062
+ ...(snapshot.executionAdmission
1063
+ ? { executionAdmission: snapshot.executionAdmission }
1064
+ : {}),
1065
+ ...(modelPolicy ? { modelPolicy } : {}),
1066
+ ...(executorLaunch ? { executorLaunch } : {}),
1067
+ ...(executorBinding ? { executorBinding } : {}),
1068
+ };
1010
1069
  return (runtime?.resolveServerRequest(sessionId, String(request.id), {
1011
1070
  success: true,
1012
1071
  contentItems: [
1013
1072
  {
1014
1073
  type: 'inputText',
1015
- text: JSON.stringify({
1016
- state: snapshot.state,
1017
- enabled: snapshot.enabled,
1018
- health: snapshot.health,
1019
- reason: snapshot.reason,
1020
- ...(snapshot.executionAdmission
1021
- ? { executionAdmission: snapshot.executionAdmission }
1022
- : {}),
1023
- ...(modelPolicy ? { modelPolicy } : {}),
1024
- ...(executorLaunch ? { executorLaunch } : {}),
1025
- ...(executorBinding ? { executorBinding } : {}),
1026
- }),
1074
+ text: JSON.stringify(healthReport),
1027
1075
  },
1028
1076
  ],
1029
1077
  }) === true);
@@ -274,6 +274,11 @@ export class AutopilotCoordinator {
274
274
  });
275
275
  if (state.supervision.waitLease && validated.health.wait.wakeCategories.length > 0) {
276
276
  this.parkedSubscriptions.set(sessionId, state.supervision.waitLease.id);
277
+ const runId = state.supervision.waitLease.runId;
278
+ if (runId && this.deps.processResultState?.(sessionId, runId) === 'completed') {
279
+ this.rootProcessCompleted(sessionId, runId);
280
+ return;
281
+ }
277
282
  if (state.supervision.waitLease.resumeAt)
278
283
  this.armWaitDeadline(sessionId, state.supervision.waitLease.id, state.supervision.waitLease.resumeAt);
279
284
  return;
@@ -362,7 +367,15 @@ export class AutopilotCoordinator {
362
367
  report.maxWaitMs > AUTOPILOT_WAIT_MAX_MS)
363
368
  return false;
364
369
  const now = this.deps.now();
365
- const processWakeSatisfied = report.wakeConditions.some((condition) => ['processExited', 'processResultAvailable'].includes(condition)) && this.deps.pendingProcessResult?.(sessionId);
370
+ const runState = report.runId
371
+ ? this.deps.processResultState?.(sessionId, report.runId)
372
+ : undefined;
373
+ if (report.runId &&
374
+ (!runState ||
375
+ runState === 'missing' ||
376
+ !report.wakeConditions.some((condition) => ['processExited', 'processResultAvailable'].includes(condition))))
377
+ return false;
378
+ const processWakeSatisfied = report.wakeConditions.some((condition) => ['processExited', 'processResultAvailable'].includes(condition)) && (report.runId ? runState === 'completed' : this.deps.pendingProcessResult?.(sessionId));
366
379
  if (processWakeSatisfied ||
367
380
  this.executorWakeAlreadySatisfied(sessionId, state, report.wakeConditions)) {
368
381
  // The requested edge is already visible. Fence every pending automatic
@@ -483,6 +496,9 @@ export class AutopilotCoordinator {
483
496
  },
484
497
  }),
485
498
  leaseId: wake.leaseId,
499
+ ...(state.supervision.waitLease?.runId
500
+ ? { runId: state.supervision.waitLease.runId }
501
+ : {}),
486
502
  reportId: state.supervision.lastReportId,
487
503
  wakeCondition: wake.condition,
488
504
  resumeAt: state.supervision.waitLease?.resumeAt ?? null,
@@ -543,7 +559,12 @@ export class AutopilotCoordinator {
543
559
  const progressKey = createHash('sha256')
544
560
  .update(`${this.progressKey(sessionId)}\0root-process\0${processId}`)
545
561
  .digest('hex');
546
- return this.observableWake(sessionId, { leaseId: lease.id, condition, progressKey });
562
+ return this.observableWake(sessionId, {
563
+ leaseId: lease.id,
564
+ condition,
565
+ progressKey,
566
+ runId: processId,
567
+ });
547
568
  }
548
569
  enable(sessionId) {
549
570
  const session = this.deps.session(sessionId);
@@ -1620,6 +1641,7 @@ export class AutopilotCoordinator {
1620
1641
  payload: {
1621
1642
  ...this.wakeAttribution(next),
1622
1643
  leaseId: nextLease.id,
1644
+ ...(nextLease.runId ? { runId: nextLease.runId } : {}),
1623
1645
  reportId: next.supervision?.lastReportId,
1624
1646
  resumeAt: nextLease.resumeAt ?? null,
1625
1647
  wakeConditions: nextLease.wakeConditions,
@@ -1892,6 +1914,7 @@ export class AutopilotCoordinator {
1892
1914
  ...this.wakeAttribution(state),
1893
1915
  wakeReason: 'deadline',
1894
1916
  leaseId,
1917
+ ...(lease.runId ? { runId: lease.runId } : {}),
1895
1918
  reportId: state.supervision.lastReportId,
1896
1919
  resumeAt,
1897
1920
  observedAt,
@@ -0,0 +1,165 @@
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
+ import { createHash } from 'node:crypto';
7
+ import { currentExecutableL1Index } from '../../plans/domain/supervised-plan.js';
8
+ import { executionComplete } from './policy.js';
9
+ const id = (value) => (value && value.length <= 128 ? value : null);
10
+ function planRevision(plan) {
11
+ const step = (value) => ({
12
+ id: value.id,
13
+ title: value.title,
14
+ state: value.state,
15
+ priority: value.priority,
16
+ reviewStatus: value.reviewStatus,
17
+ skills: value.skills,
18
+ description: value.description,
19
+ modelPolicy: value.modelPolicy,
20
+ children: value.children.map(step),
21
+ });
22
+ return createHash('sha256')
23
+ .update(JSON.stringify({
24
+ title: plan.title,
25
+ subtitle: plan.subtitle,
26
+ date: plan.date,
27
+ keywords: plan.keywords,
28
+ modelPolicyVersion: plan.modelPolicyVersion,
29
+ modelPolicyAssurance: plan.modelPolicyAssurance,
30
+ steps: plan.steps.map(step),
31
+ }))
32
+ .digest('hex');
33
+ }
34
+ /** No prose, command history, observation clocks or source paths enter the compact read model. */
35
+ export function compactSupervisionSnapshot(input) {
36
+ const { autopilot: a, activity, modelPolicy: m, launch: l } = input;
37
+ const parent = input.plan?.steps[currentExecutableL1Index(input.plan)];
38
+ const barrier = input.plan?.steps.find((step) => step.state === 'SUSPENDED');
39
+ const child = parent?.children.find((step) => step.id === input.plan?.currentStepId || step.state === 'WIP');
40
+ const priority = (agent) => (agent.threadId ?? agent.id) === a.executor?.threadId
41
+ ? 0
42
+ : ['working', 'awaitingAgent', 'awaitingHuman', 'blocked'].includes(agent.state)
43
+ ? 1
44
+ : 2;
45
+ const agents = [...activity.subagents].sort((left, right) => priority(left) - priority(right) || left.id.localeCompare(right.id));
46
+ const admission = a.executionAdmission;
47
+ return {
48
+ control: {
49
+ state: a.state,
50
+ enabled: a.enabled,
51
+ healthy: a.health.healthy,
52
+ phase: a.health.phase,
53
+ supervision: a.health.supervision,
54
+ reason: a.reason ?? null,
55
+ next: a.health.nextExpectedAction,
56
+ pendingInteractions: input.pendingInteractions,
57
+ },
58
+ plan: input.plan
59
+ ? {
60
+ identity: id(input.planIdentity),
61
+ revision: planRevision(input.plan),
62
+ currentStepId: id(input.plan.currentStepId),
63
+ l1: parent
64
+ ? { id: id(parent.id), state: parent.state, review: parent.reviewStatus ?? null }
65
+ : null,
66
+ l2: child ? { id: id(child.id), state: child.state } : null,
67
+ barrier: barrier ? { id: id(barrier.id), state: barrier.state } : null,
68
+ done: input.plan.doneSteps,
69
+ total: input.plan.totalSteps,
70
+ complete: executionComplete(input.plan),
71
+ }
72
+ : null,
73
+ executor: a.executor
74
+ ? {
75
+ threadId: id(a.executor.threadId),
76
+ position: id(a.executor.canonicalPosition),
77
+ generation: a.executor.continuationGeneration,
78
+ outcome: a.executor.outcome,
79
+ }
80
+ : null,
81
+ activity: {
82
+ confidence: activity.confidence,
83
+ root: activity.root.state,
84
+ aggregate: activity.aggregateSubagents,
85
+ total: agents.length,
86
+ agents: agents.slice(0, 8).map((agent) => ({
87
+ id: id(agent.id),
88
+ threadId: id(agent.threadId),
89
+ position: id(agent.canonicalPosition),
90
+ state: agent.state,
91
+ reason: agent.reason,
92
+ })),
93
+ omitted: Math.max(0, agents.length - 8),
94
+ },
95
+ admission: admission
96
+ ? admission.allowed
97
+ ? {
98
+ allowed: true,
99
+ scope: admission.scope,
100
+ runtimeEnforcement: admission.scope === 'configured' ? false : null,
101
+ }
102
+ : { allowed: false, code: admission.code, reason: admission.reason }
103
+ : null,
104
+ binding: input.binding,
105
+ modelPolicy: m
106
+ ? {
107
+ code: m.code,
108
+ configuration: m.configuration,
109
+ requested: m.requested,
110
+ effective: m.effective,
111
+ assurance: m.assurance,
112
+ attested: m.attested,
113
+ runtimeEnforcement: m.runtimeEnforcement,
114
+ }
115
+ : null,
116
+ launch: l
117
+ ? {
118
+ code: l.code,
119
+ requested: l.requested,
120
+ validated: l.validated,
121
+ assurance: l.assurance,
122
+ runtimeEnforcement: l.runtimeEnforcement,
123
+ }
124
+ : null,
125
+ tests: input.tests,
126
+ wait: input.wait
127
+ ? {
128
+ leaseId: id(input.wait.id),
129
+ runId: input.wait.runId ?? null,
130
+ resumeAt: input.wait.resumeAt ?? null,
131
+ conditions: input.wait.wakeConditions,
132
+ }
133
+ : null,
134
+ };
135
+ }
136
+ /** Bounded session-scoped history. A cache miss returns a full view, never a guessed delta. */
137
+ export class SupervisionSnapshots {
138
+ sessions = new Map();
139
+ read(sessionId, snapshot, sinceRevision) {
140
+ const stable = structuredClone(snapshot);
141
+ const revision = createHash('sha256')
142
+ .update(sessionId)
143
+ .update('\0')
144
+ .update(JSON.stringify(stable))
145
+ .digest('hex');
146
+ const history = this.sessions.get(sessionId) ?? new Map();
147
+ const previous = sinceRevision ? history.get(sinceRevision) : undefined;
148
+ history.set(revision, stable);
149
+ while (history.size > 8)
150
+ history.delete(history.keys().next().value);
151
+ this.sessions.set(sessionId, history);
152
+ while (this.sessions.size > 128)
153
+ this.sessions.delete(this.sessions.keys().next().value);
154
+ if (sinceRevision === revision)
155
+ return { revision, unchanged: true };
156
+ if (previous)
157
+ return {
158
+ revision,
159
+ unchanged: false,
160
+ changes: Object.fromEntries(Object.entries(stable).filter(([key, value]) => JSON.stringify(value) !==
161
+ JSON.stringify(previous[key]))),
162
+ };
163
+ return { revision, unchanged: false, reset: Boolean(sinceRevision), snapshot: stable };
164
+ }
165
+ }
@@ -171,12 +171,15 @@ export function registerProactiveWait(state, report) {
171
171
  const wakeConditions = uniqueSupportedWakeConditions(report.wakeConditions);
172
172
  if (!report.leaseId || wakeConditions.length === 0)
173
173
  return state;
174
+ if (report.runId !== undefined && !validRunWait(report.runId, wakeConditions))
175
+ return state;
174
176
  return {
175
177
  ...state,
176
178
  outcome: 'parked',
177
179
  lastReportId: report.id,
178
180
  waitLease: {
179
181
  id: report.leaseId,
182
+ ...(report.runId ? { runId: report.runId } : {}),
180
183
  probeKey: state.progressKey,
181
184
  wakeConditions,
182
185
  resumeAt: report.resumeAt,
@@ -213,6 +216,9 @@ export function consumeObservableWake(state, wake) {
213
216
  !lease ||
214
217
  wake.leaseId !== lease.id ||
215
218
  !lease.wakeConditions.includes(wake.condition) ||
219
+ (lease.runId &&
220
+ ['processExited', 'processResultAvailable'].includes(wake.condition) &&
221
+ wake.runId !== lease.runId) ||
216
222
  wake.progressKey === lease.probeKey)
217
223
  return state;
218
224
  if (lease.resumeAt)
@@ -374,6 +380,9 @@ function parseWaitLease(value) {
374
380
  if (wakeConditions.length !== candidate.wakeConditions.length)
375
381
  return undefined;
376
382
  const resumeAt = candidate.resumeAt;
383
+ const runId = candidate.runId;
384
+ if (runId !== undefined && (!validRunWait(runId, wakeConditions) || resumeAt === undefined))
385
+ return undefined;
377
386
  if (resumeAt !== undefined &&
378
387
  (typeof resumeAt !== 'string' || !Number.isFinite(Date.parse(resumeAt))))
379
388
  return undefined;
@@ -382,5 +391,11 @@ function parseWaitLease(value) {
382
391
  probeKey: candidate.probeKey,
383
392
  wakeConditions,
384
393
  ...(typeof resumeAt === 'string' ? { resumeAt } : {}),
394
+ ...(typeof runId === 'string' ? { runId } : {}),
385
395
  };
386
396
  }
397
+ function validRunWait(runId, conditions) {
398
+ return (typeof runId === 'string' &&
399
+ /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(runId) &&
400
+ conditions.some((condition) => ['processExited', 'processResultAvailable'].includes(condition)));
401
+ }
@@ -11,6 +11,7 @@ const statusTypes = ['autopilot.updated', 'agent.activity.updated', 'session.sta
11
11
  // Export structural telemetry only. Event types alone do not imply payload safety.
12
12
  const diagnosticFields = new Set([
13
13
  'leaseId',
14
+ 'runId',
14
15
  'reportId',
15
16
  'resumeAt',
16
17
  'wakeCondition',
@@ -14,6 +14,30 @@ export async function handleHostTestTool(runner, context, args) {
14
14
  if (!runner)
15
15
  return { error: 'hostTestRunnerDisabled' };
16
16
  try {
17
+ if (parsed.data.operation === 'wait') {
18
+ const { runId, maxWaitMs } = parsed.data;
19
+ const owner = { sessionId: context.sessionId, workspace: context.workspace };
20
+ const read = () => runner.request(owner, { operation: 'status', runId });
21
+ let result = await read();
22
+ if ('error' in result)
23
+ return result;
24
+ const registration = result.state === 'running'
25
+ ? context.waitForRun?.(runId, maxWaitMs)
26
+ : 'wakeAlreadySatisfied';
27
+ if (registration === true)
28
+ return { accepted: true, runId };
29
+ if (registration === 'wakeAlreadySatisfied' && result.state === 'running')
30
+ result = await read();
31
+ return {
32
+ accepted: false,
33
+ runId,
34
+ next: 'continueSameTurn',
35
+ reason: registration === 'wakeAlreadySatisfied'
36
+ ? 'runCompleted'
37
+ : 'automaticContinuationUnavailable',
38
+ result,
39
+ };
40
+ }
17
41
  return await runner.request({ sessionId: context.sessionId, workspace: context.workspace }, parsed.data);
18
42
  }
19
43
  catch {
@@ -334,6 +334,33 @@ export class LocalHostTestRunner {
334
334
  hasUnreadResult(sessionId) {
335
335
  return [...this.results.values()].some((result) => result.sessionId === sessionId && result.state !== 'running' && !result.resultReadAt);
336
336
  }
337
+ resultState(sessionId, runId) {
338
+ const result = this.results.get(runId);
339
+ return !result || result.sessionId !== sessionId
340
+ ? 'missing'
341
+ : result.state === 'running'
342
+ ? 'running'
343
+ : 'completed';
344
+ }
345
+ supervisionSummary(sessionId) {
346
+ const results = [...this.results.values()].filter((result) => result.sessionId === sessionId);
347
+ const pending = results
348
+ .filter((result) => result.state === 'running' || !result.resultReadAt)
349
+ .sort((a, b) => Number(b.state === 'running') - Number(a.state === 'running') ||
350
+ b.startedAt.localeCompare(a.startedAt) ||
351
+ a.runId.localeCompare(b.runId));
352
+ return {
353
+ enabled: true,
354
+ running: results.filter((result) => result.state === 'running').length,
355
+ unread: results.filter((result) => result.state !== 'running' && !result.resultReadAt).length,
356
+ runs: pending.slice(0, 8).map((result) => ({
357
+ runId: result.runId,
358
+ suite: result.suite,
359
+ state: result.state,
360
+ })),
361
+ omitted: Math.max(0, pending.length - 8),
362
+ };
363
+ }
337
364
  async readResult(result) {
338
365
  const pending = this.resultReads.get(result.runId);
339
366
  if (pending)
@@ -4,6 +4,10 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  export const eventRetentionMs = 48 * 60 * 60 * 1000;
7
+ /** Idle turns, recovery and attention do not close a durable session. */
8
+ export const closedSessionIds = `SELECT id FROM relay_sessions
9
+ WHERE state IN ('stopped', 'released') AND desired_state = 'stopped'
10
+ AND active_turn_id IS NULL`;
7
11
  export function eventRetentionCutoff(occurredAt) {
8
12
  const timestamp = Date.parse(occurredAt);
9
13
  return Number.isFinite(timestamp) ? new Date(timestamp - eventRetentionMs).toISOString() : null;
@@ -4,7 +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
+ import { closedSessionIds, eventRetentionCutoff } from './retention.js';
8
8
  import { replayOrResync } from '../events/replay.js';
9
9
  import { mcpStartupActivity, parseMcpStartupStatus, } from '../../../shared/contracts/mcp-startup-failure.js';
10
10
  export const autopilotAuditEventTypes = [
@@ -91,15 +91,15 @@ export class SqliteEventJournal {
91
91
  .run(sessionId);
92
92
  if (this.retain !== undefined) {
93
93
  this.db
94
- .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 ?)')
94
+ .prepare(`DELETE FROM session_events WHERE session_id = ? AND session_id IN (${closedSessionIds}) AND sequence NOT IN (SELECT sequence FROM session_events WHERE session_id = ? ORDER BY sequence DESC LIMIT ?)`)
95
95
  .run(sessionId, sessionId, this.retain);
96
96
  }
97
97
  else {
98
98
  const cutoff = eventRetentionCutoff(occurredAt);
99
99
  if (cutoff)
100
100
  this.db
101
- .prepare('DELETE FROM session_events WHERE session_id = ? AND julianday(occurred_at) < julianday(?)')
102
- .run(sessionId, cutoff);
101
+ .prepare(`DELETE FROM session_events WHERE session_id IN (${closedSessionIds}) AND julianday(occurred_at) < julianday(?)`)
102
+ .run(cutoff);
103
103
  }
104
104
  const event = { sessionId, sequence: row.sequence, type, occurredAt, payload };
105
105
  this.db.exec('COMMIT');
@@ -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 { closedSessionIds } from './retention.js';
6
7
  export const transportLimit = 2048;
7
8
  export const transportRetentionMs = 48 * 60 * 60 * 1000;
8
9
  /** Separate from the replay journal: recording transport must never generate transport traffic. */
@@ -21,7 +22,7 @@ export class SqliteTransportDiagnostics {
21
22
  .prepare('INSERT INTO chat_transport_diagnostics(session_id, occurred_at, metadata_json) VALUES (?, ?, ?)')
22
23
  .run(sessionId, now, JSON.stringify(fields));
23
24
  this.database
24
- .prepare('DELETE FROM chat_transport_diagnostics WHERE occurred_at < ? OR id <= COALESCE((SELECT id FROM chat_transport_diagnostics ORDER BY id DESC LIMIT 1 OFFSET ?), 0)')
25
+ .prepare(`DELETE FROM chat_transport_diagnostics WHERE session_id IN (${closedSessionIds}) AND (occurred_at < ? OR id <= COALESCE((SELECT id FROM chat_transport_diagnostics WHERE session_id IN (${closedSessionIds}) ORDER BY id DESC LIMIT 1 OFFSET ?), 0))`)
25
26
  .run(now - transportRetentionMs, transportLimit);
26
27
  }
27
28
  catch {
@@ -35,14 +36,15 @@ export function readTransportDiagnostics(database, sessionId, now = Date.now())
35
36
  .get());
36
37
  const rows = available
37
38
  ? database
38
- .prepare('SELECT id, occurred_at AS occurredAt, metadata_json FROM chat_transport_diagnostics WHERE session_id = ? AND occurred_at >= ? ORDER BY id DESC LIMIT ?')
39
+ .prepare(`SELECT id, occurred_at AS occurredAt, metadata_json FROM chat_transport_diagnostics WHERE session_id = ? AND (session_id NOT IN (${closedSessionIds}) OR occurred_at >= ?) ORDER BY id DESC LIMIT ?`)
39
40
  .all(sessionId, now - transportRetentionMs, transportLimit)
40
41
  .reverse()
41
42
  : [];
42
43
  return {
43
44
  available,
44
45
  coverage: 'retained-only',
45
- globalRecordLimit: transportLimit,
46
+ closedSessionRecordLimit: transportLimit,
47
+ exportRecordLimit: transportLimit,
46
48
  retentionMs: transportRetentionMs,
47
49
  records: rows.flatMap((row) => {
48
50
  try {
@@ -4,6 +4,7 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { z } from 'zod';
7
+ import { AUTOPILOT_WAIT_MIN_MS, AUTOPILOT_WAIT_MAX_MS } from './autopilot-wait-lease.js';
7
8
  const suite = z.string().regex(/^[a-z][a-z0-9-]{0,63}$/);
8
9
  const runId = z.string().uuid();
9
10
  export const hostTestRequest = z.discriminatedUnion('operation', [
@@ -18,19 +19,36 @@ export const hostTestRequest = z.discriminatedUnion('operation', [
18
19
  .strict(),
19
20
  z.object({ operation: z.literal('status'), runId }).strict(),
20
21
  z.object({ operation: z.literal('cancel'), runId }).strict(),
22
+ z
23
+ .object({
24
+ operation: z.literal('wait'),
25
+ runId,
26
+ maxWaitMs: z
27
+ .number()
28
+ .int()
29
+ .min(AUTOPILOT_WAIT_MIN_MS)
30
+ .max(AUTOPILOT_WAIT_MAX_MS)
31
+ .default(600_000),
32
+ })
33
+ .strict(),
21
34
  ]);
22
35
  export const gestaltTestRunnerDynamicTool = {
23
36
  type: 'function',
24
37
  name: 'gestalt_test_runner',
25
- description: 'Run workspace test suites outside the agent shell sandbox as the host user. Enabled by default; root supervisor only. Create or edit .gestalt/host-tests.json in the session workspace using normal file tools; suites reload at runtime without restart or fingerprint approval. list/inspect do not execute code. start requires suite and an idempotent requestId; status/cancel require runId. Tool arguments never accept commands, environment, or paths. Results retain automatic source fingerprints, UTC observations and private evidence; counts can be unknown. Keep the writer idle during tests. Does not approve milestones or resume Autopilot.',
38
+ description: 'Run workspace test suites as the host user; root supervisor only. Configure .gestalt/host-tests.json in the session workspace; suites reload without restart. list/inspect are read-only. start requires suite and UUID requestId; status/cancel/wait require runId. Prefer wait over polling: it returns a completed result or registers a run-specific Autopilot wait (maxWaitMs defaults to 600000). Yield only when accepted:true; otherwise continue in the same turn. No commands, environment or paths in arguments. Retains source fingerprints and private evidence; counts can be unknown. Keep the writer idle during tests. Never enables Autopilot or approves milestones.',
26
39
  inputSchema: {
27
40
  type: 'object',
28
41
  additionalProperties: false,
29
42
  properties: {
30
- operation: { type: 'string', enum: ['list', 'inspect', 'start', 'status', 'cancel'] },
43
+ operation: { type: 'string', enum: ['list', 'inspect', 'start', 'status', 'cancel', 'wait'] },
31
44
  suite: { type: 'string' },
32
45
  requestId: { type: 'string' },
33
46
  runId: { type: 'string' },
47
+ maxWaitMs: {
48
+ type: 'integer',
49
+ minimum: AUTOPILOT_WAIT_MIN_MS,
50
+ maximum: AUTOPILOT_WAIT_MAX_MS,
51
+ },
34
52
  },
35
53
  required: ['operation'],
36
54
  },
@@ -6,16 +6,38 @@
6
6
  export const gestaltOrgPlanHealthDynamicTool = {
7
7
  type: 'function',
8
8
  name: 'gestalt_org_plan_health',
9
- description: 'Read Org health and reconcile observed canonical executor ownership. executorBinding repairs safe handoffs even during attention or Manual Off, without starting, resuming, replacing or interrupting agents or clearing attention. executorLaunch validates requested model/effort before a child exists; modelPolicy retains unknown child settings. Never enables Autopilot or changes the Org Plan.',
10
- inputSchema: { type: 'object', additionalProperties: false, properties: {} },
9
+ description: 'Read Org health and reconcile observed executor ownership without starting work or enabling Autopilot. Prefer view:compact for combined plan, activity, executor, test-run and wait state. Supply its revision as sinceRevision to receive only changed sections or unchanged:true. A missing/expired revision returns a full compact snapshot. Omit view for detailed launch/model-policy evidence. Never changes the Org Plan or clears attention.',
10
+ inputSchema: {
11
+ type: 'object',
12
+ additionalProperties: false,
13
+ properties: {
14
+ view: { type: 'string', enum: ['full', 'compact'] },
15
+ sinceRevision: { type: 'string', pattern: '^[a-f0-9]{64}$' },
16
+ },
17
+ },
11
18
  };
19
+ export function parseOrgPlanHealthArguments(value) {
20
+ if (!value || typeof value !== 'object' || Array.isArray(value))
21
+ return null;
22
+ const args = value;
23
+ if (Object.keys(args).some((key) => !['view', 'sinceRevision'].includes(key)))
24
+ return null;
25
+ if (args.view !== undefined && args.view !== 'full' && args.view !== 'compact')
26
+ return null;
27
+ if (args.sinceRevision !== undefined &&
28
+ (args.view !== 'compact' ||
29
+ typeof args.sinceRevision !== 'string' ||
30
+ !/^[a-f0-9]{64}$/.test(args.sinceRevision)))
31
+ return null;
32
+ return {
33
+ view: args.view === 'compact' ? 'compact' : 'full',
34
+ ...(typeof args.sinceRevision === 'string' ? { sinceRevision: args.sinceRevision } : {}),
35
+ };
36
+ }
12
37
  export function isOrgPlanHealthCall(input) {
13
38
  if (input.method !== 'item/tool/call' || !input.params || typeof input.params !== 'object')
14
39
  return false;
15
40
  const params = input.params;
16
41
  return (params.tool === gestaltOrgPlanHealthDynamicTool.name &&
17
- params.arguments !== null &&
18
- typeof params.arguments === 'object' &&
19
- !Array.isArray(params.arguments) &&
20
- Object.keys(params.arguments).length === 0);
42
+ parseOrgPlanHealthArguments(params.arguments) !== null);
21
43
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gestalt-mobile",
3
- "version": "0.60.1",
3
+ "version": "0.61.0",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",