gestalt-mobile 0.67.2 → 0.68.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 (35) hide show
  1. package/dist/client/assets/index-BZ3ivopC.js +183 -0
  2. package/dist/client/assets/index-DRbCnCbk.css +1 -0
  3. package/dist/client/index.html +2 -2
  4. package/dist/server/server/composition.contracts.js +976 -0
  5. package/dist/server/server/composition.js +330 -57
  6. package/dist/server/server/features/autopilot/application/service.js +18 -1
  7. package/dist/server/server/features/plans/application/org-plan-launch-store.js +6 -0
  8. package/dist/server/server/features/plans/application/prepare-org-plan-settings.js +66 -0
  9. package/dist/server/server/features/plans/application/prepare-org-plan-supervision.js +86 -0
  10. package/dist/server/server/features/plans/application/start-org-plan-supervision.js +323 -0
  11. package/dist/server/server/features/plans/execute-plan/endpoint.js +27 -0
  12. package/dist/server/server/features/plans/get-workspace-plan/endpoint.js +2 -1
  13. package/dist/server/server/features/plans/open-plan/endpoint.js +2 -1
  14. package/dist/server/server/features/plans/prepare-supervision/endpoint.js +52 -0
  15. package/dist/server/server/features/plans/register-routes.js +6 -0
  16. package/dist/server/server/features/sessions/application/resolve-session-skills.js +35 -0
  17. package/dist/server/server/features/sessions/application/start-settings.js +2 -1
  18. package/dist/server/server/features/sessions/register-routes.js +1 -0
  19. package/dist/server/server/features/sessions/start-session/endpoint.js +5 -0
  20. package/dist/server/server/features/sessions/start-session/use-case.js +7 -32
  21. package/dist/server/server/features/sessions/start-turn/endpoint.js +9 -167
  22. package/dist/server/server/features/sessions/start-turn/use-case.js +243 -0
  23. package/dist/server/server/features/skills/application/read-global-profiles.js +34 -0
  24. package/dist/server/server/features/skills/list-profiles/endpoint.js +9 -33
  25. package/dist/server/server/platform/catalog/filesystem-workspace-catalog.js +11 -0
  26. package/dist/server/server/platform/codex/session-runtime.js +20 -6
  27. package/dist/server/server/platform/persistence/migrate.js +12 -0
  28. package/dist/server/server/platform/persistence/sqlite-org-plan-launch-store.js +215 -0
  29. package/dist/server/server/platform/plans/filesystem-org-plan-context.js +99 -0
  30. package/dist/server/server/platform/plans/filesystem-workspace-plan-catalog.js +36 -3
  31. package/dist/server/shared/contracts/org-plan-execution.js +46 -0
  32. package/dist/server/shared/contracts/session-defaults.js +33 -3
  33. package/package.json +1 -1
  34. package/dist/client/assets/index-DcXYn8rY.js +0 -128
  35. package/dist/client/assets/index-DxsD-jG4.css +0 -1
@@ -16,10 +16,15 @@ import { describe, expect, it, onTestFinished, vi } from 'vitest';
16
16
  import WebSocket from 'ws';
17
17
  import { composeRelayApp } from './composition.js';
18
18
  import { autopilotExecutorLaunchPrompt } from './features/autopilot/application/policy.js';
19
+ import { AutopilotCoordinator } from './features/autopilot/application/service.js';
19
20
  import { CodexJsonRpcError } from './platform/codex/json-rpc-client.js';
20
21
  import { CodexSessionRuntime } from './platform/codex/session-runtime.js';
21
22
  import { SqliteAuthorizationStore } from './platform/auth/sqlite-authorization-store.js';
22
23
  import { SqliteEventJournal } from './platform/persistence/sqlite-event-journal.js';
24
+ import { SqliteIdempotencyStore } from './platform/persistence/sqlite-idempotency-store.js';
25
+ import { SqliteOrgPlanLaunchStore } from './platform/persistence/sqlite-org-plan-launch-store.js';
26
+ import { SqliteSessionRepository } from './platform/persistence/sqlite-session-repository.js';
27
+ import { RelaySession } from './features/sessions/model/relay-session.js';
23
28
  import { SqliteAutopilotStore } from './platform/persistence/sqlite-autopilot-store.js';
24
29
  import { startSupervisionProtocol } from './features/autopilot/domain/supervision-protocol.js';
25
30
  import { exportControlPlaneTrace } from './features/control-plane-trace/export-trace.js';
@@ -455,6 +460,135 @@ async function createUnauthorizedProductionApp(root, dataDir) {
455
460
  installedCodexVersion: null,
456
461
  });
457
462
  }
463
+ async function orgPlanActivationFixture() {
464
+ const root = await mkdtemp(join(tmpdir(), 'gestalt-plan-activation-root-'));
465
+ const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-plan-activation-state-'));
466
+ ownTemporaryPaths(root, dataDir);
467
+ const workspacePath = join(root, 'workspace');
468
+ const codexHome = join(dataDir, 'codex-home');
469
+ await mkdir(join(workspacePath, '.gestalt'), { recursive: true });
470
+ await mkdir(join(codexHome, 'agents'), { recursive: true });
471
+ await writeFile(join(workspacePath, '.gestalt', 'activation.org'), autopilotPlanText());
472
+ await writeFile(join(codexHome, 'agents', 'org-plan-executor.toml'), 'name = "org-plan-executor"\nmodel = "gpt-5.6-terra"\nmodel_reasoning_effort = "high"\ndeveloper_instructions = "Keep milestone ownership."\n');
473
+ vi.stubEnv('CODEX_HOME', codexHome);
474
+ onTestFinished(() => {
475
+ vi.unstubAllEnvs();
476
+ });
477
+ const handles = [];
478
+ const launch = liveAppServer(handles);
479
+ const controls = {
480
+ failInitialize: false,
481
+ failThread: false,
482
+ initializationGate: null,
483
+ threadGate: null,
484
+ held: null,
485
+ };
486
+ const open = () => composeAuthorizedApp({
487
+ root,
488
+ dataDir,
489
+ relyingParty,
490
+ installedCodexVersion: 'codex-cli 0.144.3',
491
+ startAppServers: true,
492
+ sessionModelCatalog: { list: async () => ['gpt-6.1-sol', 'gpt-5.6-terra'] },
493
+ profiles: {
494
+ list: async () => [{ name: 'default', state: 'ok', status: 'ready' }],
495
+ require: async () => ({ name: 'default', state: 'ok', status: 'ready' }),
496
+ },
497
+ launchAppServer: () => {
498
+ const server = launch();
499
+ let runtime = false;
500
+ handles.at(-1).respond = async (method, params) => {
501
+ if (method === 'initialize') {
502
+ runtime =
503
+ params.capabilities
504
+ ?.experimentalApi === true;
505
+ if (runtime) {
506
+ const gate = controls.initializationGate;
507
+ controls.initializationGate = null;
508
+ if (gate) {
509
+ controls.held = 'initialization';
510
+ try {
511
+ await gate;
512
+ }
513
+ finally {
514
+ controls.held = null;
515
+ }
516
+ }
517
+ if (controls.failInitialize) {
518
+ controls.failInitialize = false;
519
+ throw new Error('INJECTED_INITIAL_RUNTIME_FAILURE');
520
+ }
521
+ }
522
+ }
523
+ if (runtime && method === 'thread/start') {
524
+ const gate = controls.threadGate;
525
+ controls.threadGate = null;
526
+ if (gate) {
527
+ controls.held = 'thread';
528
+ try {
529
+ await gate;
530
+ }
531
+ finally {
532
+ controls.held = null;
533
+ }
534
+ }
535
+ if (controls.failThread) {
536
+ controls.failThread = false;
537
+ throw new Error('INJECTED_THREAD_RECEIPT_LOSS');
538
+ }
539
+ }
540
+ if (method === 'skills/list')
541
+ return {
542
+ data: [
543
+ {
544
+ cwd: params.cwds[0],
545
+ skills: [
546
+ {
547
+ name: 'gestalt:org-plan',
548
+ description: 'Supervise an Org plan.',
549
+ path: join(root, 'skills', 'org-plan', 'SKILL.md'),
550
+ enabled: true,
551
+ },
552
+ ],
553
+ errors: [],
554
+ },
555
+ ],
556
+ };
557
+ return undefined;
558
+ };
559
+ return server;
560
+ },
561
+ });
562
+ const requests = (method) => handles.flatMap((handle) => handle.requests.filter((request) => request.method === method));
563
+ const prepare = async (app) => {
564
+ const workspace = (await app.inject('/api/bootstrap'))
565
+ .json()
566
+ .workspaces[0].children.find((item) => item.name === 'workspace');
567
+ const reference = {
568
+ kind: 'workspace',
569
+ workspaceId: workspace.id,
570
+ planName: '.gestalt/activation.org',
571
+ };
572
+ const prepared = (await app.inject({ method: 'POST', url: '/api/plans/prepare', payload: reference })).json();
573
+ expect(prepared).toMatchObject({ kind: 'eligible' });
574
+ return {
575
+ reference,
576
+ expectedRevision: prepared.revision,
577
+ skillProfile: prepared.settings.skillProfile,
578
+ launchId: 'initial-activation-recovery',
579
+ };
580
+ };
581
+ const database = (read) => {
582
+ const db = new DatabaseSync(join(dataDir, 'relay.sqlite'));
583
+ try {
584
+ return read(db);
585
+ }
586
+ finally {
587
+ db.close();
588
+ }
589
+ };
590
+ return { open, prepare, controls, requests, database, workspacePath, handles };
591
+ }
458
592
  describe('production composition', () => {
459
593
  describeCompositionConcern('autopilot', () => {
460
594
  it('persists a bounded executor after 64 exited results and new active work, including a plan watcher update', async () => {
@@ -5709,6 +5843,846 @@ describe('production composition', () => {
5709
5843
  });
5710
5844
  });
5711
5845
  describeCompositionConcern('lifecycle', () => {
5846
+ it('recovers a published Org-plan supervisor after initial runtime failure without replacing its session', async () => {
5847
+ const f = await orgPlanActivationFixture();
5848
+ const app = await f.open();
5849
+ try {
5850
+ const payload = await f.prepare(app);
5851
+ f.controls.failInitialize = true;
5852
+ const first = (await app.inject({ method: 'POST', url: '/api/plans/execute', payload })).json();
5853
+ expect(f.controls.failInitialize).toBe(false);
5854
+ expect(first).toMatchObject({ kind: 'partial', stage: 'activation' });
5855
+ const id = first.session.id;
5856
+ expect((await app.inject(`/api/sessions/${id}`)).json()).toMatchObject({
5857
+ threadId: null,
5858
+ });
5859
+ expect((await app.inject({
5860
+ method: 'PUT',
5861
+ url: '/api/session-defaults',
5862
+ payload: {
5863
+ workspaceId: payload.reference.workspaceId,
5864
+ skillProfile: '',
5865
+ provider: 'codex',
5866
+ model: 'gpt-5.6-terra',
5867
+ reasoningEffort: 'high',
5868
+ executorModel: 'gpt-6.1-sol',
5869
+ executorReasoningEffort: 'medium',
5870
+ sandbox: 'read-only',
5871
+ approvalPolicy: 'on-request',
5872
+ },
5873
+ })).statusCode).toBe(200);
5874
+ const replay = (await app.inject({ method: 'POST', url: '/api/plans/execute', payload })).json();
5875
+ expect(replay).toMatchObject({
5876
+ kind: 'started',
5877
+ session: {
5878
+ id,
5879
+ workspacePath: f.workspacePath,
5880
+ model: 'gpt-6.1-sol',
5881
+ modelSettings: { executorModel: 'gpt-5.6-terra', reasoningEffort: 'medium' },
5882
+ executionPolicy: { sandbox: 'workspace-git', approvalPolicy: 'never' },
5883
+ },
5884
+ bootstrap: { kind: 'accepted' },
5885
+ });
5886
+ expect((await app.inject('/api/sessions')).json()).toHaveLength(1);
5887
+ expect(f.requests('turn/start')).toHaveLength(1);
5888
+ expect(f.requests('thread/start')).toHaveLength(1);
5889
+ }
5890
+ finally {
5891
+ await app.close();
5892
+ }
5893
+ });
5894
+ it('recovers the same Org-plan session across restart after publication before activation', async () => {
5895
+ const f = await orgPlanActivationFixture();
5896
+ let app = await f.open();
5897
+ const original = SqliteOrgPlanLaunchStore.prototype.publishSession;
5898
+ const publication = vi.spyOn(SqliteOrgPlanLaunchStore.prototype, 'publishSession');
5899
+ try {
5900
+ const payload = await f.prepare(app);
5901
+ publication.mockImplementationOnce(function (...args) {
5902
+ original.apply(this, args);
5903
+ throw new Error('INJECTED_POST_PUBLICATION_CRASH');
5904
+ });
5905
+ const first = (await app.inject({ method: 'POST', url: '/api/plans/execute', payload })).json();
5906
+ expect(first).toMatchObject({ kind: 'partial', stage: 'activation' });
5907
+ const id = first.session.id;
5908
+ expect((await app.inject(`/api/sessions/${id}`)).json()).toMatchObject({ threadId: null });
5909
+ expect(f.database((db) => db.prepare('SELECT phase FROM org_plan_initial_activations WHERE session_id=?').get(id))).toEqual({ phase: 'idle' });
5910
+ expect(f.requests('thread/start')).toHaveLength(0);
5911
+ await app.close();
5912
+ app = await f.open();
5913
+ const replay = (await app.inject({ method: 'POST', url: '/api/plans/execute', payload })).json();
5914
+ expect(replay).toMatchObject({
5915
+ kind: 'started',
5916
+ session: { id },
5917
+ bootstrap: { kind: 'accepted' },
5918
+ });
5919
+ expect((await app.inject('/api/sessions')).json()).toHaveLength(1);
5920
+ expect(f.requests('thread/start')).toHaveLength(1);
5921
+ expect(f.requests('turn/start')).toHaveLength(1);
5922
+ }
5923
+ finally {
5924
+ publication.mockRestore();
5925
+ await app.close();
5926
+ }
5927
+ });
5928
+ it('recovers a tracked initial Org-plan activation through ordinary Chat without later bootstrap replay', async () => {
5929
+ const f = await orgPlanActivationFixture();
5930
+ const app = await f.open();
5931
+ try {
5932
+ const payload = await f.prepare(app);
5933
+ f.controls.failInitialize = true;
5934
+ const first = (await app.inject({ method: 'POST', url: '/api/plans/execute', payload })).json();
5935
+ expect(first).toMatchObject({ kind: 'partial', stage: 'activation' });
5936
+ const id = first.session.id;
5937
+ const guidance = 'Continue this saved supervisor session using the confirmed plan.';
5938
+ const chat = await app.inject({
5939
+ method: 'POST',
5940
+ url: `/api/sessions/${id}/turns`,
5941
+ headers: { 'idempotency-key': 'explicit-activation-recovery' },
5942
+ payload: { text: guidance },
5943
+ });
5944
+ expect(chat.statusCode).toBe(202);
5945
+ const session = chat.json();
5946
+ expect(session).toMatchObject({ id, state: 'turnActive' });
5947
+ expect(f.requests('turn/start')).toHaveLength(1);
5948
+ expect(f.requests('turn/start')[0].params).toMatchObject({
5949
+ input: [{ type: 'text', text: guidance }],
5950
+ });
5951
+ const owner = f.handles.find((handle) => handle.requests.some((request) => request.method === 'turn/start'));
5952
+ owner.notify?.({
5953
+ method: 'turn/completed',
5954
+ params: {
5955
+ threadId: session.threadId,
5956
+ turn: { id: session.activeTurnId, status: 'completed', items: [] },
5957
+ },
5958
+ });
5959
+ await vi.waitFor(async () => expect((await app.inject(`/api/sessions/${id}`)).json().state).toBe('ready'));
5960
+ const replay = (await app.inject({ method: 'POST', url: '/api/plans/execute', payload })).json();
5961
+ expect(replay).toMatchObject({
5962
+ kind: 'partial',
5963
+ session: { id },
5964
+ bootstrap: { kind: 'pending' },
5965
+ });
5966
+ expect(replay.reason).toContain('ordinary Chat');
5967
+ expect(f.requests('thread/start')).toHaveLength(1);
5968
+ expect(f.requests('turn/start')).toHaveLength(1);
5969
+ expect((await app.inject('/api/sessions')).json()).toHaveLength(1);
5970
+ }
5971
+ finally {
5972
+ await app.close();
5973
+ }
5974
+ });
5975
+ it.each(['execute-completion', 'chat-completion', 'chat-turn'])('preserves independent Stop at the committed initial activation boundary: %s', async (boundary) => {
5976
+ const f = await orgPlanActivationFixture();
5977
+ const app = await f.open();
5978
+ const completion = SqliteOrgPlanLaunchStore.prototype.completeInitialActivation;
5979
+ const turn = CodexSessionRuntime.prototype.startTurn;
5980
+ const completionSpy = vi.spyOn(SqliteOrgPlanLaunchStore.prototype, 'completeInitialActivation');
5981
+ const turnSpy = vi.spyOn(CodexSessionRuntime.prototype, 'startTurn');
5982
+ let injected = false;
5983
+ const stopIndependently = (id) => {
5984
+ f.database((db) => {
5985
+ const repository = new SqliteSessionRepository(db);
5986
+ const current = repository.find(id);
5987
+ repository.save(RelaySession.rehydrate(current).stop(new Date().toISOString()).snapshot);
5988
+ });
5989
+ injected = true;
5990
+ };
5991
+ try {
5992
+ const payload = await f.prepare(app);
5993
+ let id;
5994
+ if (boundary !== 'execute-completion') {
5995
+ f.controls.failInitialize = true;
5996
+ const first = (await app.inject({ method: 'POST', url: '/api/plans/execute', payload })).json();
5997
+ expect(first).toMatchObject({ kind: 'partial', stage: 'activation' });
5998
+ id = first.session.id;
5999
+ }
6000
+ else
6001
+ id = '';
6002
+ if (boundary === 'chat-turn')
6003
+ turnSpy.mockImplementationOnce(function (...args) {
6004
+ stopIndependently(args[0].id);
6005
+ return turn.apply(this, args);
6006
+ });
6007
+ else
6008
+ completionSpy.mockImplementationOnce(function (...args) {
6009
+ const accepted = completion.apply(this, args);
6010
+ expect(accepted).toBe(true);
6011
+ stopIndependently(args[1].id);
6012
+ return accepted;
6013
+ });
6014
+ const response = await app.inject(boundary === 'execute-completion'
6015
+ ? { method: 'POST', url: '/api/plans/execute', payload }
6016
+ : {
6017
+ method: 'POST',
6018
+ url: `/api/sessions/${id}/turns`,
6019
+ payload: { text: 'Recover this initial activation.' },
6020
+ });
6021
+ expect(injected).toBe(true);
6022
+ if (boundary === 'execute-completion') {
6023
+ const result = response.json();
6024
+ expect(result).toMatchObject({ kind: 'partial', stage: 'activation' });
6025
+ id = result.session.id;
6026
+ }
6027
+ else
6028
+ expect(response.statusCode).toBe(boundary === 'chat-turn' ? 500 : 503);
6029
+ expect((await app.inject(`/api/sessions/${id}`)).json()).toMatchObject({
6030
+ state: 'stopped',
6031
+ desiredState: 'stopped',
6032
+ autopilot: { enabled: false },
6033
+ });
6034
+ expect((await app.inject('/api/sessions')).json()).toHaveLength(1);
6035
+ expect(f.requests('turn/start')).toHaveLength(0);
6036
+ const replay = (await app.inject({ method: 'POST', url: '/api/plans/execute', payload })).json();
6037
+ expect(replay).toMatchObject({ kind: 'partial', session: { id } });
6038
+ expect(f.requests('thread/start')).toHaveLength(1);
6039
+ expect(f.requests('turn/start')).toHaveLength(0);
6040
+ }
6041
+ finally {
6042
+ completionSpy.mockRestore();
6043
+ turnSpy.mockRestore();
6044
+ await app.close();
6045
+ }
6046
+ });
6047
+ it.each(['initialization', 'thread'])('fences held %s against concurrent same-intent Org-plan retries', async (boundary) => {
6048
+ const f = await orgPlanActivationFixture();
6049
+ const app = await f.open();
6050
+ let second;
6051
+ const gate = Promise.withResolvers();
6052
+ const pending = [];
6053
+ try {
6054
+ const payload = await f.prepare(app);
6055
+ if (boundary === 'initialization')
6056
+ f.controls.initializationGate = gate.promise;
6057
+ else
6058
+ f.controls.threadGate = gate.promise;
6059
+ pending.push(app.inject({ method: 'POST', url: '/api/plans/execute', payload }));
6060
+ await vi.waitFor(() => expect(f.controls.held).toBe(boundary));
6061
+ const id = (await app.inject('/api/sessions')).json()[0].id;
6062
+ pending.push(app.inject({ method: 'POST', url: '/api/plans/execute', payload }));
6063
+ second = await f.open();
6064
+ const winner = (await second.inject({ method: 'POST', url: '/api/plans/execute', payload })).json();
6065
+ expect(winner).toMatchObject({
6066
+ kind: boundary === 'initialization' ? 'started' : 'partial',
6067
+ session: { id },
6068
+ bootstrap: { kind: boundary === 'initialization' ? 'accepted' : 'pending' },
6069
+ });
6070
+ gate.resolve();
6071
+ const settled = (await Promise.all(pending)).map((response) => response.json());
6072
+ expect(settled.every((result) => result.session?.id === id)).toBe(true);
6073
+ expect(settled[1]).toMatchObject({ kind: 'started', bootstrap: { kind: 'accepted' } });
6074
+ const replay = (await second.inject({ method: 'POST', url: '/api/plans/execute', payload })).json();
6075
+ expect(replay).toMatchObject({ kind: 'started', bootstrap: settled[1].bootstrap });
6076
+ expect(f.requests('thread/start')).toHaveLength(1);
6077
+ expect(f.requests('turn/start')).toHaveLength(1);
6078
+ expect((await app.inject('/api/sessions')).json()).toHaveLength(1);
6079
+ }
6080
+ finally {
6081
+ gate.resolve();
6082
+ await Promise.allSettled(pending);
6083
+ expect(f.controls.held).toBeNull();
6084
+ await second?.close();
6085
+ await app.close();
6086
+ }
6087
+ });
6088
+ it.each([
6089
+ ['stop', 'initialization'],
6090
+ ['stop', 'thread'],
6091
+ ['forget', 'initialization'],
6092
+ ['forget', 'thread'],
6093
+ ])('does not revive an Org-plan session after %s while initial %s is held', async (action, boundary) => {
6094
+ const f = await orgPlanActivationFixture();
6095
+ const app = await f.open();
6096
+ const gate = Promise.withResolvers();
6097
+ let pending;
6098
+ try {
6099
+ const payload = await f.prepare(app);
6100
+ if (boundary === 'initialization')
6101
+ f.controls.initializationGate = gate.promise;
6102
+ else
6103
+ f.controls.threadGate = gate.promise;
6104
+ pending = app.inject({ method: 'POST', url: '/api/plans/execute', payload });
6105
+ await vi.waitFor(() => expect(f.controls.held).toBe(boundary));
6106
+ const id = (await app.inject('/api/sessions')).json()[0].id;
6107
+ const stopped = await app.inject({
6108
+ method: action === 'forget' ? 'DELETE' : 'POST',
6109
+ url: action === 'forget' ? `/api/sessions/${id}` : `/api/sessions/${id}/stop`,
6110
+ });
6111
+ expect(stopped.statusCode).toBe(action === 'forget' ? 204 : 202);
6112
+ gate.resolve();
6113
+ await pending;
6114
+ const replay = (await app.inject({ method: 'POST', url: '/api/plans/execute', payload })).json();
6115
+ if (action === 'forget') {
6116
+ expect((await app.inject(`/api/sessions/${id}`)).statusCode).toBe(404);
6117
+ expect(replay).toMatchObject({ kind: 'blocked', code: 'REFERENCE_UNAVAILABLE' });
6118
+ expect((await app.inject('/api/sessions')).json()).toHaveLength(0);
6119
+ }
6120
+ else {
6121
+ expect((await app.inject(`/api/sessions/${id}`)).json()).toMatchObject({
6122
+ state: 'stopped',
6123
+ desiredState: 'stopped',
6124
+ autopilot: { enabled: false },
6125
+ });
6126
+ expect(replay).toMatchObject({ kind: 'partial', session: { id } });
6127
+ }
6128
+ expect(f.requests('thread/start')).toHaveLength(boundary === 'thread' ? 1 : 0);
6129
+ expect(f.requests('turn/start')).toHaveLength(0);
6130
+ }
6131
+ finally {
6132
+ gate.resolve();
6133
+ await pending;
6134
+ expect(f.controls.held).toBeNull();
6135
+ await app.close();
6136
+ }
6137
+ });
6138
+ it.each(['unknown-request', 'untracked'])('keeps %s Org-plan activation fenced across retry and restart', async (boundary) => {
6139
+ const f = await orgPlanActivationFixture();
6140
+ let app = await f.open();
6141
+ try {
6142
+ const payload = await f.prepare(app);
6143
+ if (boundary === 'unknown-request')
6144
+ f.controls.failThread = true;
6145
+ else
6146
+ f.controls.failInitialize = true;
6147
+ const first = (await app.inject({ method: 'POST', url: '/api/plans/execute', payload })).json();
6148
+ expect(first).toMatchObject({ kind: 'partial', stage: 'activation' });
6149
+ const id = first.session.id;
6150
+ expect((await app.inject(`/api/sessions/${id}`)).json()).toMatchObject({
6151
+ threadId: null,
6152
+ });
6153
+ if (boundary === 'untracked')
6154
+ f.database((db) => db.prepare('DELETE FROM org_plan_initial_activations WHERE session_id=?').run(id));
6155
+ else
6156
+ expect(f.database((db) => db
6157
+ .prepare('SELECT phase FROM org_plan_initial_activations WHERE session_id=?')
6158
+ .get(id))).toEqual({ phase: 'requested' });
6159
+ for (const restart of [false, true]) {
6160
+ if (restart) {
6161
+ await app.close();
6162
+ app = await f.open();
6163
+ }
6164
+ const replay = (await app.inject({ method: 'POST', url: '/api/plans/execute', payload })).json();
6165
+ expect(replay).toMatchObject({
6166
+ kind: 'partial',
6167
+ session: { id },
6168
+ bootstrap: { kind: 'pending' },
6169
+ });
6170
+ expect((await app.inject('/api/sessions')).json()).toHaveLength(1);
6171
+ const chat = await app.inject({
6172
+ method: 'POST',
6173
+ url: `/api/sessions/${id}/turns`,
6174
+ payload: { text: 'Inspect this unresolved activation.' },
6175
+ });
6176
+ expect(chat.statusCode).toBe(503);
6177
+ }
6178
+ expect(f.requests('thread/start')).toHaveLength(boundary === 'unknown-request' ? 1 : 0);
6179
+ expect(f.requests('turn/start')).toHaveLength(0);
6180
+ }
6181
+ finally {
6182
+ await app.close();
6183
+ }
6184
+ });
6185
+ it.each(['stop-late-signal', 'uncertain-manual'])('launches an ordinary plan supervisor and activates only on its real supervision publication: %s', async (recoveryScenario) => {
6186
+ const root = await mkdtemp(join(tmpdir(), 'gestalt-plan-launch-root-'));
6187
+ const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-plan-launch-state-'));
6188
+ ownTemporaryPaths(root, dataDir);
6189
+ const codexHome = join(dataDir, 'codex-home');
6190
+ await mkdir(join(codexHome, 'agents'), { recursive: true });
6191
+ await writeFile(join(codexHome, 'agents', 'org-plan-executor.toml'), 'name = "org-plan-executor"\nmodel = "gpt-5.6-terra"\nmodel_reasoning_effort = "high"\ndeveloper_instructions = "Keep the assigned milestone ownership and review gates."\n');
6192
+ vi.stubEnv('CODEX_HOME', codexHome);
6193
+ onTestFinished(() => {
6194
+ vi.unstubAllEnvs();
6195
+ });
6196
+ const workspacePath = join(root, 'workspace');
6197
+ await mkdir(join(workspacePath, '.gestalt'), { recursive: true });
6198
+ const planPath = join(workspacePath, '.gestalt', 'Plan ü space.org');
6199
+ await writeFile(planPath, autopilotPlanText());
6200
+ const handles = [];
6201
+ const launch = liveAppServer(handles);
6202
+ const providerHistory = new Map();
6203
+ let turnIndex = 0;
6204
+ const bootstrapGate = Promise.withResolvers();
6205
+ const scheduled = [];
6206
+ let coordinator;
6207
+ let pendingExecution;
6208
+ let firstTurn = true;
6209
+ const drainTimers = async () => {
6210
+ for (const task of scheduled.splice(0))
6211
+ if (!task.cancelled)
6212
+ task.callback();
6213
+ await new Promise((resolve) => setImmediate(resolve));
6214
+ };
6215
+ const attach = vi.spyOn(FilesystemPlanStatusSource.prototype, 'attach');
6216
+ const supervisionStarted = vi.spyOn(AutopilotCoordinator.prototype, 'supervisionStarted');
6217
+ const runtimeStart = vi.spyOn(CodexSessionRuntime.prototype, 'start');
6218
+ const options = {
6219
+ root,
6220
+ dataDir,
6221
+ relyingParty,
6222
+ installedCodexVersion: 'codex-cli 0.144.3',
6223
+ startAppServers: true,
6224
+ sessionModelCatalog: { list: async () => ['gpt-6.1-sol', 'gpt-5.6-terra'] },
6225
+ profiles: {
6226
+ list: async () => [{ name: 'default', state: 'ok', status: 'ready' }],
6227
+ require: async () => ({ name: 'default', state: 'ok', status: 'ready' }),
6228
+ },
6229
+ onAutopilotCoordinator: (value) => {
6230
+ coordinator = value;
6231
+ },
6232
+ autopilotSchedule: (callback) => {
6233
+ const task = { callback, cancelled: false };
6234
+ scheduled.push(task);
6235
+ return () => {
6236
+ task.cancelled = true;
6237
+ };
6238
+ },
6239
+ autopilotActivity: (sessionId) => {
6240
+ const observedAt = new Date().toISOString();
6241
+ return {
6242
+ sessionId,
6243
+ root: {
6244
+ state: 'idle',
6245
+ reason: 'turnCompleted',
6246
+ observedAt,
6247
+ lastActivityAt: observedAt,
6248
+ },
6249
+ subagents: [],
6250
+ aggregateSubagents: 'idle',
6251
+ confidence: 'fresh',
6252
+ };
6253
+ },
6254
+ launchAppServer: () => {
6255
+ const server = launch();
6256
+ handles.at(-1).respond = async (method, params) => {
6257
+ if (method === 'turn/start') {
6258
+ const input = params;
6259
+ const turnId = firstTurn ? 'bootstrap-turn' : `smoke-turn-${++turnIndex}`;
6260
+ if (firstTurn) {
6261
+ firstTurn = false;
6262
+ await bootstrapGate.promise;
6263
+ }
6264
+ const turns = providerHistory.get(input.threadId) ?? [];
6265
+ turns.push({
6266
+ id: turnId,
6267
+ status: 'inProgress',
6268
+ items: [
6269
+ {
6270
+ id: `user-${turnId}`,
6271
+ type: 'userMessage',
6272
+ clientId: input.clientUserMessageId,
6273
+ content: input.input,
6274
+ },
6275
+ ],
6276
+ });
6277
+ providerHistory.set(input.threadId, turns);
6278
+ return { turn: { id: turnId } };
6279
+ }
6280
+ if (method === 'thread/read') {
6281
+ const id = params.threadId;
6282
+ return {
6283
+ thread: { id, status: { type: 'idle' }, turns: providerHistory.get(id) ?? [] },
6284
+ };
6285
+ }
6286
+ return method === 'skills/list'
6287
+ ? {
6288
+ data: [
6289
+ {
6290
+ cwd: params.cwds[0],
6291
+ skills: [
6292
+ {
6293
+ name: 'gestalt:org-plan',
6294
+ description: 'Supervise an Org plan.',
6295
+ path: join(root, 'skills', 'org-plan', 'SKILL.md'),
6296
+ enabled: true,
6297
+ },
6298
+ ],
6299
+ errors: [],
6300
+ },
6301
+ ],
6302
+ }
6303
+ : undefined;
6304
+ };
6305
+ return server;
6306
+ },
6307
+ };
6308
+ const app = await composeAuthorizedApp(options);
6309
+ try {
6310
+ await app.listen({ host: '127.0.0.1', port: 0 });
6311
+ const skillProfile = 'launch-supervisor';
6312
+ expect((await app.inject({
6313
+ method: 'PUT',
6314
+ url: `/api/skill-profiles/${skillProfile}`,
6315
+ payload: {
6316
+ version: 1,
6317
+ name: skillProfile,
6318
+ skills: [
6319
+ {
6320
+ name: 'gestalt:org-plan',
6321
+ path: join(root, 'skills', 'org-plan', 'SKILL.md'),
6322
+ enabled: true,
6323
+ },
6324
+ ],
6325
+ },
6326
+ })).statusCode).toBe(201);
6327
+ expect((await app.inject({
6328
+ method: 'PUT',
6329
+ url: '/api/session-defaults',
6330
+ payload: {
6331
+ workspaceId: 'unrelated-selected-workspace',
6332
+ skillProfile,
6333
+ provider: 'codex',
6334
+ model: 'gpt-5.6-terra',
6335
+ reasoningEffort: 'high',
6336
+ executorModel: 'gpt-6.1-sol',
6337
+ executorReasoningEffort: 'medium',
6338
+ sandbox: 'workspace-git',
6339
+ approvalPolicy: 'never',
6340
+ },
6341
+ })).statusCode).toBe(200);
6342
+ const workspace = (await app.inject('/api/bootstrap'))
6343
+ .json()
6344
+ .workspaces[0].children.find((item) => item.name === 'workspace');
6345
+ const reference = {
6346
+ kind: 'workspace',
6347
+ workspaceId: workspace.id,
6348
+ planName: '.gestalt/Plan ü space.org',
6349
+ };
6350
+ const prepared = (await app.inject({ method: 'POST', url: '/api/plans/prepare', payload: reference })).json();
6351
+ expect(prepared, JSON.stringify({ kind: prepared.kind, code: prepared.code, reason: prepared.reason })).toMatchObject({ kind: 'eligible', workspace: { path: workspacePath } });
6352
+ pendingExecution = app.inject({
6353
+ method: 'POST',
6354
+ url: '/api/plans/execute',
6355
+ payload: {
6356
+ reference,
6357
+ expectedRevision: prepared.revision,
6358
+ skillProfile,
6359
+ launchId: 'ordinary-launch',
6360
+ },
6361
+ });
6362
+ await vi.waitFor(() => expect(handles.flatMap((handle) => handle.requests.filter((request) => request.method === 'turn/start'))).toHaveLength(1));
6363
+ const id = (await app.inject('/api/sessions')).json()[0].id;
6364
+ const readOnlyDatabase = new DatabaseSync(join(dataDir, 'relay.sqlite'));
6365
+ try {
6366
+ const reservationBefore = readOnlyDatabase
6367
+ .prepare('SELECT canonical_path,record_json FROM org_plan_launches WHERE launch_id=?')
6368
+ .get('ordinary-launch');
6369
+ const pendingPreparation = (await app.inject({ method: 'POST', url: '/api/plans/prepare', payload: reference })).json();
6370
+ expect(pendingPreparation).toMatchObject({
6371
+ kind: 'blocked',
6372
+ code: 'ACTIVE_SUPERVISION',
6373
+ existingSessionId: id,
6374
+ });
6375
+ expect(readOnlyDatabase
6376
+ .prepare('SELECT canonical_path,record_json FROM org_plan_launches WHERE launch_id=?')
6377
+ .get('ordinary-launch')).toEqual(reservationBefore);
6378
+ }
6379
+ finally {
6380
+ readOnlyDatabase.close();
6381
+ }
6382
+ expect((await app.inject(`/api/sessions/${id}`)).json()).toMatchObject({
6383
+ autopilot: { enabled: false, state: 'disabled' },
6384
+ });
6385
+ expect((await app.inject(`/api/sessions/${id}/plan`)).statusCode).toBe(204);
6386
+ expect(attach).not.toHaveBeenCalled();
6387
+ expect(supervisionStarted).not.toHaveBeenCalled();
6388
+ const signal = {
6389
+ schemaVersion: 1,
6390
+ planPath,
6391
+ reason: 'supervision-start',
6392
+ updatedAt: new Date().toISOString(),
6393
+ };
6394
+ await writeFile(planStatusFilePath(planStatusDirectoryPath(workspacePath, id), planPath), JSON.stringify(signal));
6395
+ await expect
6396
+ .poll(async () => (await app.inject(`/api/sessions/${id}`)).json().lastOrgPlan)
6397
+ .toMatchObject({ attached: true, path: planPath });
6398
+ await expect
6399
+ .poll(async () => (await app.inject(`/api/sessions/${id}`)).json().autopilot.enabled)
6400
+ .toBe(true);
6401
+ coordinator.activityChanged(id);
6402
+ coordinator.evaluate(id);
6403
+ await drainTimers();
6404
+ const safetyDatabase = new DatabaseSync(join(dataDir, 'relay.sqlite'));
6405
+ try {
6406
+ expect(safetyDatabase.prepare('SELECT count(*) AS count FROM autopilot_controls').get()).toEqual({ count: 0 });
6407
+ }
6408
+ finally {
6409
+ safetyDatabase.close();
6410
+ }
6411
+ expect(handles.flatMap((handle) => handle.requests.filter((request) => request.method === 'turn/start'))).toHaveLength(1);
6412
+ expect(supervisionStarted).toHaveBeenCalledExactlyOnceWith(id);
6413
+ bootstrapGate.resolve();
6414
+ const response = await pendingExecution;
6415
+ expect(response.statusCode).toBe(200);
6416
+ const result = response.json();
6417
+ const startErrors = await Promise.all(runtimeStart.mock.results.map(async (call) => {
6418
+ try {
6419
+ await call.value;
6420
+ return null;
6421
+ }
6422
+ catch (error) {
6423
+ return error instanceof Error && /^[A-Z0-9_]{1,100}$/.test(error.message)
6424
+ ? error.message
6425
+ : 'UNCLASSIFIED_START_FAILURE';
6426
+ }
6427
+ }));
6428
+ expect(result, JSON.stringify({
6429
+ kind: result.kind,
6430
+ stage: result.stage,
6431
+ reason: result.reason,
6432
+ state: result.session?.state,
6433
+ threadPresent: Boolean(result.session?.threadId),
6434
+ startErrors,
6435
+ })).toMatchObject({
6436
+ kind: 'started',
6437
+ session: {
6438
+ workspacePath,
6439
+ provider: 'codex',
6440
+ profile: 'default',
6441
+ state: 'turnActive',
6442
+ model: 'gpt-5.6-terra',
6443
+ modelSettings: {
6444
+ reasoningEffort: 'high',
6445
+ executorModel: 'gpt-6.1-sol',
6446
+ executorReasoningEffort: 'medium',
6447
+ },
6448
+ executionPolicy: { sandbox: 'workspace-git', approvalPolicy: 'never' },
6449
+ effectiveSkillSelection: {
6450
+ selectedProfileName: skillProfile,
6451
+ },
6452
+ },
6453
+ bootstrap: { kind: 'accepted' },
6454
+ });
6455
+ expect(result.session.id).toBe(id);
6456
+ expect(result.session.effectiveSkillSelection.skills).toEqual(expect.arrayContaining([
6457
+ expect.objectContaining({ name: 'gestalt:org-plan', enabled: true }),
6458
+ ]));
6459
+ const history = await app.inject(`/api/sessions/${id}/history`);
6460
+ expect(history.statusCode).toBe(200);
6461
+ expect(history
6462
+ .json()
6463
+ .items.filter((item) => item.kind === 'user' && item.operationId === result.bootstrap.requestId)).toHaveLength(1);
6464
+ const address = app.server.address();
6465
+ if (!address || typeof address === 'string')
6466
+ throw new Error('EXPECTED_TEST_SERVER_ADDRESS');
6467
+ const socket = new WebSocket(`ws://127.0.0.1:${address.port}/api/sessions/${id}/events?after=0`, {
6468
+ headers: {
6469
+ origin: relyingParty.publicOrigin,
6470
+ cookie: 'gestalt_mobile_session=test-session',
6471
+ },
6472
+ });
6473
+ const events = [];
6474
+ socket.on('message', (data) => {
6475
+ const message = JSON.parse(String(data));
6476
+ if (message.event)
6477
+ events.push({
6478
+ type: message.event.type,
6479
+ sequence: message.event.sequence,
6480
+ sessionId: message.event.sessionId,
6481
+ });
6482
+ });
6483
+ try {
6484
+ await vi.waitFor(() => expect(socket.readyState).toBe(WebSocket.OPEN));
6485
+ await vi.waitFor(() => expect(events.map((event) => event.type)).toEqual(expect.arrayContaining(['session.updated', 'plan.updated'])));
6486
+ expect(events.every((event) => event.sessionId === id && event.sequence > 0)).toBe(true);
6487
+ expect(new Set(events.map((event) => event.sequence)).size).toBe(events.length);
6488
+ }
6489
+ finally {
6490
+ socket.terminate();
6491
+ }
6492
+ expect((await app.inject('/api/sessions')).json()).toEqual(expect.arrayContaining([expect.objectContaining({ id })]));
6493
+ const replay = await app.inject({
6494
+ method: 'POST',
6495
+ url: '/api/plans/execute',
6496
+ payload: {
6497
+ reference,
6498
+ expectedRevision: prepared.revision,
6499
+ skillProfile,
6500
+ launchId: 'ordinary-launch',
6501
+ },
6502
+ });
6503
+ expect(replay.json()).toMatchObject({
6504
+ kind: 'started',
6505
+ session: { id },
6506
+ bootstrap: result.bootstrap,
6507
+ });
6508
+ coordinator.evaluate(id);
6509
+ await drainTimers();
6510
+ expect(handles.flatMap((handle) => handle.requests.filter((request) => request.method === 'turn/start'))).toHaveLength(1);
6511
+ expect(supervisionStarted).toHaveBeenCalledExactlyOnceWith(id);
6512
+ expect(await readFile(planPath, 'utf8')).toBe(autopilotPlanText());
6513
+ // Forget must finish ordinary writer/scratch release before another intent can own this file.
6514
+ expect((await app.inject({ method: 'DELETE', url: `/api/sessions/${id}` })).statusCode).toBe(204);
6515
+ const forgottenDatabase = new DatabaseSync(join(dataDir, 'relay.sqlite'));
6516
+ try {
6517
+ const ownerBefore = forgottenDatabase
6518
+ .prepare('SELECT canonical_path FROM org_plan_launches WHERE launch_id=?')
6519
+ .get('ordinary-launch');
6520
+ expect(ownerBefore).toEqual({ canonical_path: planPath });
6521
+ const preparedAgain = (await app.inject({ method: 'POST', url: '/api/plans/prepare', payload: reference })).json();
6522
+ expect(preparedAgain).toMatchObject({ kind: 'eligible' });
6523
+ expect(forgottenDatabase
6524
+ .prepare('SELECT canonical_path FROM org_plan_launches WHERE launch_id=?')
6525
+ .get('ordinary-launch')).toEqual(ownerBefore);
6526
+ const originalPut = SqliteIdempotencyStore.prototype.put;
6527
+ let failReceipt = recoveryScenario === 'uncertain-manual';
6528
+ const receiptFault = vi
6529
+ .spyOn(SqliteIdempotencyStore.prototype, 'put')
6530
+ .mockImplementation(function (scope, key, status, body) {
6531
+ if (failReceipt && key === 'org-plan-bootstrap:after-forget') {
6532
+ failReceipt = false;
6533
+ throw new Error('INJECTED_ACCEPTANCE_RECEIPT_FAILURE');
6534
+ }
6535
+ return originalPut.call(this, scope, key, status, body);
6536
+ });
6537
+ onTestFinished(() => {
6538
+ receiptFault.mockRestore();
6539
+ });
6540
+ const nextLaunch = (await app.inject({
6541
+ method: 'POST',
6542
+ url: '/api/plans/execute',
6543
+ payload: {
6544
+ reference,
6545
+ expectedRevision: preparedAgain.revision,
6546
+ skillProfile,
6547
+ launchId: 'after-forget',
6548
+ },
6549
+ })).json();
6550
+ expect(nextLaunch).toMatchObject(recoveryScenario === 'uncertain-manual'
6551
+ ? { kind: 'partial', stage: 'bootstrap', bootstrap: { kind: 'pending' } }
6552
+ : { kind: 'started', bootstrap: { kind: 'accepted' } });
6553
+ expect(nextLaunch.session.id).not.toBe(id);
6554
+ expect(forgottenDatabase
6555
+ .prepare('SELECT canonical_path FROM org_plan_launches WHERE launch_id=?')
6556
+ .get('ordinary-launch')).toEqual({ canonical_path: null });
6557
+ expect(forgottenDatabase
6558
+ .prepare('SELECT session_id FROM org_plan_launches WHERE canonical_path=?')
6559
+ .get(planPath)).toEqual({ session_id: nextLaunch.session.id });
6560
+ expect((await app.inject('/api/sessions')).json()).toHaveLength(1);
6561
+ expect((await app.inject(`/api/sessions/${nextLaunch.session.id}`)).json()).toMatchObject({ autopilot: { enabled: false } });
6562
+ const nextId = nextLaunch.session.id;
6563
+ const nextSignal = {
6564
+ schemaVersion: 1,
6565
+ planPath,
6566
+ reason: 'supervision-start',
6567
+ updatedAt: new Date().toISOString(),
6568
+ };
6569
+ if (recoveryScenario === 'stop-late-signal') {
6570
+ expect((await app.inject({
6571
+ method: 'POST',
6572
+ url: `/api/sessions/${nextId}/stop`,
6573
+ payload: {},
6574
+ })).statusCode).toBe(202);
6575
+ await writeFile(planStatusFilePath(planStatusDirectoryPath(workspacePath, nextId), planPath), JSON.stringify(nextSignal));
6576
+ await app.close();
6577
+ const restarted = await composeAuthorizedApp(options);
6578
+ try {
6579
+ await restarted.listen({ host: '127.0.0.1', port: 0 });
6580
+ await expect
6581
+ .poll(async () => (await restarted.inject(`/api/sessions/${nextId}`)).json().lastOrgPlan)
6582
+ .toMatchObject({ attached: true, path: planPath });
6583
+ expect((await restarted.inject(`/api/sessions/${nextId}`)).json()).toMatchObject({
6584
+ state: 'stopped',
6585
+ desiredState: 'stopped',
6586
+ autopilot: { enabled: false },
6587
+ });
6588
+ const retained = (await restarted.inject({
6589
+ method: 'POST',
6590
+ url: '/api/plans/execute',
6591
+ payload: {
6592
+ reference,
6593
+ expectedRevision: preparedAgain.revision,
6594
+ skillProfile,
6595
+ launchId: 'after-forget',
6596
+ },
6597
+ })).json();
6598
+ expect(retained).toMatchObject({
6599
+ kind: 'started',
6600
+ session: { id: nextId, state: 'stopped' },
6601
+ bootstrap: nextLaunch.bootstrap,
6602
+ });
6603
+ coordinator.evaluate(nextId);
6604
+ await drainTimers();
6605
+ expect(handles.flatMap((handle) => handle.requests.filter((request) => request.method === 'turn/start'))).toHaveLength(2);
6606
+ }
6607
+ finally {
6608
+ await restarted.close();
6609
+ }
6610
+ }
6611
+ else {
6612
+ const manual = await app.inject({
6613
+ method: 'POST',
6614
+ url: `/api/sessions/${nextId}/turns`,
6615
+ headers: { 'idempotency-key': 'manual-recovery' },
6616
+ payload: {
6617
+ text: 'Inspect the existing request and continue this ordinary supervisor session.',
6618
+ },
6619
+ });
6620
+ expect(manual.statusCode).toBe(202);
6621
+ const recoveredRecord = JSON.parse(forgottenDatabase
6622
+ .prepare('SELECT record_json FROM org_plan_launches WHERE launch_id=?')
6623
+ .get('after-forget').record_json);
6624
+ expect(recoveredRecord).toMatchObject({
6625
+ phase: 'submitting',
6626
+ manualRecoveryTurnId: manual.json().activeTurnId,
6627
+ });
6628
+ await writeFile(planStatusFilePath(planStatusDirectoryPath(workspacePath, nextId), planPath), JSON.stringify(nextSignal));
6629
+ await expect
6630
+ .poll(async () => (await app.inject(`/api/sessions/${nextId}`)).json().autopilot.enabled)
6631
+ .toBe(true);
6632
+ const live = handles.find((handle) => handle.requests.some((request) => request.method === 'turn/start' &&
6633
+ request.params.threadId === manual.json().threadId));
6634
+ expect(live?.notify).toBeTypeOf('function');
6635
+ live.notify({
6636
+ method: 'turn/completed',
6637
+ params: {
6638
+ threadId: manual.json().threadId,
6639
+ turn: { id: manual.json().activeTurnId, status: 'completed' },
6640
+ },
6641
+ });
6642
+ await expect
6643
+ .poll(async () => (await app.inject(`/api/sessions/${nextId}`)).json().state)
6644
+ .toBe('ready');
6645
+ await expect
6646
+ .poll(async () => {
6647
+ coordinator.activityChanged(nextId);
6648
+ coordinator.evaluate(nextId);
6649
+ await drainTimers();
6650
+ return forgottenDatabase
6651
+ .prepare('SELECT count(*) AS count FROM autopilot_controls WHERE session_id=?')
6652
+ .get(nextId).count;
6653
+ })
6654
+ .toBeGreaterThan(0);
6655
+ const replayed = (await app.inject({
6656
+ method: 'POST',
6657
+ url: '/api/plans/execute',
6658
+ payload: {
6659
+ reference,
6660
+ expectedRevision: preparedAgain.revision,
6661
+ skillProfile,
6662
+ launchId: 'after-forget',
6663
+ },
6664
+ })).json();
6665
+ expect(replayed).toMatchObject({
6666
+ kind: 'partial',
6667
+ bootstrap: { kind: 'pending' },
6668
+ session: { id: nextId },
6669
+ });
6670
+ }
6671
+ }
6672
+ finally {
6673
+ forgottenDatabase.close();
6674
+ }
6675
+ }
6676
+ finally {
6677
+ bootstrapGate.resolve();
6678
+ if (pendingExecution)
6679
+ await Promise.allSettled([pendingExecution]);
6680
+ await app.close();
6681
+ attach.mockRestore();
6682
+ supervisionStarted.mockRestore();
6683
+ runtimeStart.mockRestore();
6684
+ }
6685
+ });
5712
6686
  it('retains an authored plan without starting supervision', async () => {
5713
6687
  const root = await mkdtemp(join(tmpdir(), 'gestalt-mobile-root-'));
5714
6688
  const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-mobile-state-'));
@@ -6366,6 +7340,8 @@ describe('production composition', () => {
6366
7340
  '/api/workspaces/workspace-1/plans',
6367
7341
  'protected',
6368
7342
  ],
7343
+ ['POST', '/api/plans/prepare', '/api/plans/prepare', 'protected'],
7344
+ ['POST', '/api/plans/execute', '/api/plans/execute', 'protected'],
6369
7345
  [
6370
7346
  'HEAD',
6371
7347
  '/api/workspaces/:workspaceId/plans',