gestalt-mobile 0.60.0 → 0.60.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -388,6 +388,73 @@ async function createUnauthorizedProductionApp(root, dataDir) {
388
388
  }
389
389
  describe('production composition', () => {
390
390
  describeCompositionConcern('autopilot', () => {
391
+ it('does not park after a host test completes before process-wait registration', 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
+ await mkdir(join(f.workspacePath, '.gestalt'), { recursive: true });
413
+ await writeFile(join(f.workspacePath, '.gestalt/host-tests.json'), JSON.stringify({
414
+ version: 1,
415
+ suites: [
416
+ {
417
+ id: 'fast',
418
+ repository: f.workspacePath,
419
+ command: process.execPath,
420
+ args: ['-e', 'process.exit(0)'],
421
+ timeoutMs: 5000,
422
+ maxOutputBytes: 4096,
423
+ },
424
+ ],
425
+ }));
426
+ const session = (await f.app.inject(`/api/sessions/${f.sessionId}`)).json();
427
+ const call = async (id, args) => {
428
+ const response = (await f.handles.find((handle) => handle.request).request({
429
+ id,
430
+ method: 'item/tool/call',
431
+ params: { threadId: session.threadId, tool: 'gestalt_test_runner', arguments: args },
432
+ }));
433
+ return JSON.parse(response.contentItems[0].text);
434
+ };
435
+ const run = await call(900, {
436
+ operation: 'start',
437
+ suite: 'fast',
438
+ requestId: '00000000-0000-4000-8000-000000000001',
439
+ });
440
+ expect(run.state).toBe('running');
441
+ const database = new DatabaseSync(join(f.dataDir, 'relay.sqlite'));
442
+ onTestFinished(() => database.close());
443
+ await vi.waitFor(() => expect(database
444
+ .prepare("SELECT COUNT(*) AS count FROM session_events WHERE session_id=? AND type='host-test.completed'")
445
+ .get(f.sessionId)?.count).toBe(1), { timeout: 5000 });
446
+ const report = {
447
+ id: 'focused-running',
448
+ leaseId: 'focused-wait',
449
+ wakeConditions: ['processResultAvailable'],
450
+ maxWaitMs: 600_000,
451
+ };
452
+ expect(coordinator.registerProactiveWait(f.sessionId, report)).toBe('wakeAlreadySatisfied');
453
+ expect(await call(901, { operation: 'status', runId: run.runId })).toMatchObject({
454
+ state: 'passed',
455
+ });
456
+ expect(coordinator.registerProactiveWait(f.sessionId, report)).toBe(true);
457
+ });
391
458
  const versionedText = (state = 'TODO', strict = false) => '#+MODEL_POLICY_VERSION: 1\n' +
392
459
  (strict ? '#+MODEL_POLICY_ASSURANCE: runtime-attested\n' : '') +
393
460
  autopilotPlanText(state).replace(':REVIEW_STATUS: UNREVIEWED', `:REVIEW_STATUS: UNREVIEWED
@@ -263,6 +263,7 @@ export async function composeRelayApp(options) {
263
263
  },
264
264
  });
265
265
  const autopilot = new AutopilotCoordinator({
266
+ pendingProcessResult: (sessionId) => hostTests?.hasUnreadResult(sessionId) ?? false,
266
267
  modelPolicyStatus: (sessionId) => supervisedPlans.modelPolicyStatus(sessionId),
267
268
  store: autopilotStore,
268
269
  now: () => new Date().toISOString(),
@@ -330,8 +330,10 @@ export class AutopilotCoordinator {
330
330
  const nextProtocol = reportProbe(protocol, report);
331
331
  if (nextProtocol === protocol)
332
332
  return false;
333
- if (nextProtocol.outcome === 'parked' && nextProtocol.waitLease)
333
+ if (nextProtocol.outcome === 'parked' && nextProtocol.waitLease) {
334
334
  this.parkedSubscriptions.set(sessionId, nextProtocol.waitLease.id);
335
+ this.activityEventKeys.set(sessionId, this.progressKey(sessionId, false));
336
+ }
335
337
  else
336
338
  this.parkedSubscriptions.delete(sessionId);
337
339
  const now = this.deps.now();
@@ -360,8 +362,10 @@ export class AutopilotCoordinator {
360
362
  report.maxWaitMs > AUTOPILOT_WAIT_MAX_MS)
361
363
  return false;
362
364
  const now = this.deps.now();
363
- if (this.executorWakeAlreadySatisfied(sessionId, state, report.wakeConditions)) {
364
- // The executor edge is already visible. Fence every pending automatic
365
+ const processWakeSatisfied = report.wakeConditions.some((condition) => ['processExited', 'processResultAvailable'].includes(condition)) && this.deps.pendingProcessResult?.(sessionId);
366
+ if (processWakeSatisfied ||
367
+ this.executorWakeAlreadySatisfied(sessionId, state, report.wakeConditions)) {
368
+ // The requested edge is already visible. Fence every pending automatic
365
369
  // callback before returning control to the still-active root; otherwise
366
370
  // a scheduled executor resume could race same-turn supervision.
367
371
  const cancelled = this.cancelScheduledControl(state, now);
@@ -389,6 +393,7 @@ export class AutopilotCoordinator {
389
393
  this.completionTimers.get(sessionId)?.();
390
394
  this.completionTimers.delete(sessionId);
391
395
  this.parkedSubscriptions.set(sessionId, report.leaseId);
396
+ this.activityEventKeys.set(sessionId, this.progressKey(sessionId, false));
392
397
  this.persist({
393
398
  ...state,
394
399
  state: 'monitoring',
@@ -1437,7 +1442,9 @@ export class AutopilotCoordinator {
1437
1442
  // Reuse the canonical semantic projection: child order, timestamps, and
1438
1443
  // activity prose cannot manufacture an extra wake, while a child-only
1439
1444
  // lifecycle transition remains visible with an unchanged root.
1440
- const eventKey = this.progressKey(sessionId);
1445
+ // The root finishing the turn that registered a lease is not a new work event.
1446
+ // Keep child transitions observable without letting the waiter wake itself.
1447
+ const eventKey = this.progressKey(sessionId, prior.supervision?.outcome !== 'parked');
1441
1448
  if (this.activityEventKeys.get(sessionId) === eventKey)
1442
1449
  return;
1443
1450
  this.activityEventKeys.set(sessionId, eventKey);
@@ -3169,12 +3176,12 @@ export class AutopilotCoordinator {
3169
3176
  policy: this.deps.policy,
3170
3177
  });
3171
3178
  }
3172
- progressKey(sessionId) {
3179
+ progressKey(sessionId, includeRootActivity = true) {
3173
3180
  const retained = this.deps.plan(sessionId);
3174
3181
  const state = this.deps.store.find(sessionId);
3175
- return this.progressKeyFor(sessionId, state, retained);
3182
+ return this.progressKeyFor(sessionId, state, retained, includeRootActivity);
3176
3183
  }
3177
- progressKeyFor(sessionId, state, retained) {
3184
+ progressKeyFor(sessionId, state, retained, includeRootActivity = true) {
3178
3185
  const activity = this.deps.activity(sessionId);
3179
3186
  const interactions = this.deps.pendingInteraction(sessionId)
3180
3187
  ? [{ id: 'pending', kind: 'session', state: 'pending' }]
@@ -3215,7 +3222,7 @@ export class AutopilotCoordinator {
3215
3222
  })),
3216
3223
  })),
3217
3224
  agentActivity: [
3218
- ...(activity
3225
+ ...(activity && includeRootActivity
3219
3226
  ? [
3220
3227
  {
3221
3228
  agentId: 'root',
@@ -33,6 +33,7 @@ export class LocalHostTestRunner {
33
33
  active = new Map();
34
34
  reservations = new Set();
35
35
  requests = new Map();
36
+ resultReads = new Map();
36
37
  sessionGenerations = new Map();
37
38
  closing = false;
38
39
  constructor(evidenceRoot, completed = () => { }, workspaceSuites = loadWorkspaceHostTestConfig) {
@@ -108,13 +109,13 @@ export class LocalHostTestRunner {
108
109
  return { error: 'runNotFound' };
109
110
  if (input.operation === 'cancel')
110
111
  this.active.get(result.runId)?.stop('cancelled');
111
- return structuredClone(result);
112
+ return this.readResult(result);
112
113
  }
113
114
  if (input.operation === 'start') {
114
115
  const previous = [...this.results.values()].find((result) => result.sessionId === owner.sessionId && result.requestId === input.requestId);
115
116
  if (previous) {
116
117
  return previous.suite === input.suite
117
- ? structuredClone(previous)
118
+ ? this.readResult(previous)
118
119
  : { error: 'requestIdConflict' };
119
120
  }
120
121
  }
@@ -329,6 +330,31 @@ export class LocalHostTestRunner {
329
330
  })();
330
331
  });
331
332
  }
333
+ /** Completed evidence is a level-triggered wake until its owning supervisor reads it. */
334
+ hasUnreadResult(sessionId) {
335
+ return [...this.results.values()].some((result) => result.sessionId === sessionId && result.state !== 'running' && !result.resultReadAt);
336
+ }
337
+ async readResult(result) {
338
+ const pending = this.resultReads.get(result.runId);
339
+ if (pending)
340
+ return structuredClone(await pending);
341
+ const snapshot = structuredClone(result);
342
+ if (snapshot.state !== 'running' && !snapshot.resultReadAt) {
343
+ snapshot.resultReadAt = new Date().toISOString();
344
+ const read = this.persist(snapshot).then(() => {
345
+ this.results.set(snapshot.runId, snapshot);
346
+ return snapshot;
347
+ });
348
+ this.resultReads.set(snapshot.runId, read);
349
+ try {
350
+ return structuredClone(await read);
351
+ }
352
+ finally {
353
+ this.resultReads.delete(snapshot.runId);
354
+ }
355
+ }
356
+ return snapshot;
357
+ }
332
358
  async persist(result) {
333
359
  const temporary = result.resultPath + '.tmp';
334
360
  await writeFile(temporary, JSON.stringify(result) + '\n', { mode: 0o600 });
@@ -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 {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gestalt-mobile",
3
- "version": "0.60.0",
3
+ "version": "0.60.2",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",