gestalt-mobile 0.62.1 → 0.62.3
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.
- package/README.md +16 -2
- package/dist/server/server/composition.contracts.js +265 -3
- package/dist/server/server/composition.js +98 -0
- package/dist/server/server/features/agent-activity/registry.js +6 -2
- package/dist/server/server/features/autopilot/application/policy.js +3 -2
- package/dist/server/server/features/autopilot/application/service.js +14 -2
- package/dist/server/server/features/autopilot/application/takeover-supervision.js +206 -0
- package/dist/server/server/features/autopilot/domain/autopilot-session.js +5 -5
- package/dist/server/server/features/autopilot/domain/supervised-lifecycle.js +5 -1
- package/dist/server/server/features/sessions/application/writer-acquisition.js +7 -0
- package/dist/server/server/platform/codex/codex-capabilities.js +1 -1
- package/dist/server/server/platform/codex/session-runtime.js +132 -0
- package/dist/server/server/platform/persistence/migrate.js +2 -0
- package/dist/server/server/platform/persistence/sqlite-supervision-takeover-store.js +122 -0
- package/dist/server/server/platform/retrieval/codex-xerj.js +13 -4
- package/dist/server/server/platform/retrieval/xerj-index-diagnostic.js +41 -0
- package/dist/server/server/platform/retrieval/xerj-indexer.js +34 -4
- package/dist/server/shared/contracts/org-plan-takeover.js +32 -0
- package/gestalt-supervision-capabilities.json +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,206 @@
|
|
|
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 { disabledAutopilot } from '../domain/autopilot-session.js';
|
|
7
|
+
import { currentExecutableL1Index, } from '../../plans/domain/supervised-plan.js';
|
|
8
|
+
import { fingerprint as planFingerprint } from './service.js';
|
|
9
|
+
import { executorAssignment, executorIdentity, } from '../domain/supervised-lifecycle.js';
|
|
10
|
+
import { startSupervisionProtocol } from '../domain/supervision-protocol.js';
|
|
11
|
+
/** Explicit user direction supplies authority. Runtime quiescence supplies sole-writer evidence. */
|
|
12
|
+
export class SupervisionTakeover {
|
|
13
|
+
deps;
|
|
14
|
+
running = new Map();
|
|
15
|
+
constructor(deps) {
|
|
16
|
+
this.deps = deps;
|
|
17
|
+
}
|
|
18
|
+
takeOver(sessionId, threadId, turnId) {
|
|
19
|
+
const prior = this.running.get(sessionId);
|
|
20
|
+
if (prior)
|
|
21
|
+
return prior;
|
|
22
|
+
const run = this.run(sessionId, threadId, turnId).catch(() => ({
|
|
23
|
+
accepted: false,
|
|
24
|
+
code: 'TAKEOVER_RUNTIME_UNAVAILABLE',
|
|
25
|
+
}));
|
|
26
|
+
this.running.set(sessionId, run);
|
|
27
|
+
void run.finally(() => {
|
|
28
|
+
if (this.running.get(sessionId) === run)
|
|
29
|
+
this.running.delete(sessionId);
|
|
30
|
+
});
|
|
31
|
+
return run;
|
|
32
|
+
}
|
|
33
|
+
async run(sessionId, threadId, turnId) {
|
|
34
|
+
const before = this.deps.context(sessionId);
|
|
35
|
+
if (!before ||
|
|
36
|
+
before.session.provider !== 'codex' ||
|
|
37
|
+
before.session.threadId !== threadId ||
|
|
38
|
+
before.session.activeTurnId !== turnId)
|
|
39
|
+
return { accepted: false, code: 'CURRENT_ROOT_REQUIRED' };
|
|
40
|
+
if (!before.admission)
|
|
41
|
+
return { accepted: false, code: 'EXECUTION_POLICY_UNAVAILABLE' };
|
|
42
|
+
if (before.held)
|
|
43
|
+
return { accepted: false, code: 'PENDING_INTERACTION' };
|
|
44
|
+
const index = currentExecutableL1Index(before.plan);
|
|
45
|
+
if (index < 0 || before.plan.executionComplete)
|
|
46
|
+
return { accepted: false, code: 'NO_UNFINISHED_MILESTONE' };
|
|
47
|
+
const existing = this.deps.store.owner(before.identity);
|
|
48
|
+
if (existing?.sessionId === sessionId && existing.phase === 'ready') {
|
|
49
|
+
const pending = before.state?.executor?.replacement;
|
|
50
|
+
const identity = pending &&
|
|
51
|
+
pending.planIdentity === before.identity &&
|
|
52
|
+
pending.planFingerprint === planFingerprint(before.plan) &&
|
|
53
|
+
pending.canonicalPosition === `L${index + 1}`
|
|
54
|
+
? executorIdentity(pending.canonicalTaskName, pending.generation)
|
|
55
|
+
: !before.state?.executor
|
|
56
|
+
? executorIdentity(`l${index + 1}`, 1)
|
|
57
|
+
: null;
|
|
58
|
+
if (!before.localExecutor && identity)
|
|
59
|
+
return {
|
|
60
|
+
accepted: true,
|
|
61
|
+
alreadyOwner: true,
|
|
62
|
+
identity,
|
|
63
|
+
previousSessionIds: [],
|
|
64
|
+
boundaryFinalRequired: Boolean(before.state?.checkpoints?.pendingTurnId),
|
|
65
|
+
};
|
|
66
|
+
return { accepted: true, alreadyOwner: true };
|
|
67
|
+
}
|
|
68
|
+
if (before.localExecutor)
|
|
69
|
+
return { accepted: false, code: 'CURRENT_EXECUTOR_ALREADY_PRESENT' };
|
|
70
|
+
const previous = this.deps
|
|
71
|
+
.predecessors(before)
|
|
72
|
+
.filter((p) => p.session.id !== sessionId &&
|
|
73
|
+
p.session.provider === 'codex' &&
|
|
74
|
+
p.session.workspacePath === before.session.workspacePath &&
|
|
75
|
+
p.state.planIdentity === before.identity);
|
|
76
|
+
if (!previous.length)
|
|
77
|
+
return { accepted: false, code: 'PREVIOUS_SUPERVISOR_NOT_FOUND' };
|
|
78
|
+
if (existing &&
|
|
79
|
+
existing.sessionId !== sessionId &&
|
|
80
|
+
!previous.some((p) => p.session.id === existing.sessionId))
|
|
81
|
+
return { accepted: false, code: 'PREVIOUS_SUPERVISOR_NOT_FOUND' };
|
|
82
|
+
const fingerprint = planFingerprint(before.plan);
|
|
83
|
+
const generation = before.state?.generation ?? 0;
|
|
84
|
+
const claim = this.deps.store.claim(before.identity, sessionId);
|
|
85
|
+
if (!claim)
|
|
86
|
+
return { accepted: false, code: 'TAKEOVER_IN_PROGRESS' };
|
|
87
|
+
if (!this.deps.store.retire(claim, previous.map((p) => p.session.id)))
|
|
88
|
+
return { accepted: false, code: 'TAKEOVER_CONTEXT_CHANGED' };
|
|
89
|
+
// Fence every predecessor before the first asynchronous process operation.
|
|
90
|
+
for (const p of previous)
|
|
91
|
+
if (!this.deps.store.stopped(before.identity, p.session.id))
|
|
92
|
+
this.deps.fence(p.session.id);
|
|
93
|
+
for (const p of previous) {
|
|
94
|
+
if (this.deps.store.stopped(before.identity, p.session.id))
|
|
95
|
+
continue;
|
|
96
|
+
if (!(await this.deps.stop(p)))
|
|
97
|
+
return { accepted: false, code: 'PREVIOUS_WRITER_NOT_STOPPED' };
|
|
98
|
+
if (!this.deps.store.markStopped(claim, p.session.id))
|
|
99
|
+
return { accepted: false, code: 'TAKEOVER_CONTEXT_CHANGED' };
|
|
100
|
+
}
|
|
101
|
+
const current = this.deps.context(sessionId);
|
|
102
|
+
if (!current ||
|
|
103
|
+
current.session.threadId !== threadId ||
|
|
104
|
+
current.session.activeTurnId !== turnId ||
|
|
105
|
+
current.identity !== before.identity ||
|
|
106
|
+
planFingerprint(current.plan) !== fingerprint ||
|
|
107
|
+
(current.state?.generation ?? 0) !== generation ||
|
|
108
|
+
current.held ||
|
|
109
|
+
current.localExecutor ||
|
|
110
|
+
!current.admission)
|
|
111
|
+
return { accepted: false, code: 'TAKEOVER_CONTEXT_CHANGED' };
|
|
112
|
+
const canonicalTaskName = `l${index + 1}`;
|
|
113
|
+
const executors = previous
|
|
114
|
+
.map((p) => p.state.executor)
|
|
115
|
+
.filter((e) => e?.canonicalTaskName === canonicalTaskName);
|
|
116
|
+
const source = executors.sort((a, b) => (b.replacement?.generation ?? b.continuationGeneration) -
|
|
117
|
+
(a.replacement?.generation ?? a.continuationGeneration))[0];
|
|
118
|
+
const nextGeneration = source
|
|
119
|
+
? Math.max(...executors.map((e) => e.replacement?.generation ?? e.continuationGeneration)) +
|
|
120
|
+
1
|
|
121
|
+
: 1;
|
|
122
|
+
const identity = executorIdentity(canonicalTaskName, nextGeneration);
|
|
123
|
+
const history = current.state?.checkpoints ??
|
|
124
|
+
[...previous]
|
|
125
|
+
.filter((p) => p.state.checkpoints?.planIdentity === before.identity)
|
|
126
|
+
.sort((a, b) => b.state.updatedAt.localeCompare(a.state.updatedAt))[0]?.state.checkpoints;
|
|
127
|
+
const now = this.deps.now();
|
|
128
|
+
const state = {
|
|
129
|
+
...(current.state ?? disabledAutopilot(sessionId, now)),
|
|
130
|
+
requestedEnabled: true,
|
|
131
|
+
state: 'monitoring',
|
|
132
|
+
stopReason: null,
|
|
133
|
+
blocking: undefined,
|
|
134
|
+
planIdentity: current.identity,
|
|
135
|
+
planFingerprint: fingerprint,
|
|
136
|
+
generation: generation + 1,
|
|
137
|
+
lastControlId: null,
|
|
138
|
+
nextEvaluationAt: null,
|
|
139
|
+
consecutiveNoProgress: 0,
|
|
140
|
+
supervision: startSupervisionProtocol(fingerprint),
|
|
141
|
+
...(history
|
|
142
|
+
? {
|
|
143
|
+
checkpoints: {
|
|
144
|
+
...history,
|
|
145
|
+
pendingTurnId: history.pendingTurnId ? turnId : null,
|
|
146
|
+
checkpointHandoffFailed: false,
|
|
147
|
+
rootContinuationFromTurnId: undefined,
|
|
148
|
+
},
|
|
149
|
+
}
|
|
150
|
+
: {}),
|
|
151
|
+
executor: source
|
|
152
|
+
? {
|
|
153
|
+
...source,
|
|
154
|
+
l1State: current.plan.steps[index].state,
|
|
155
|
+
outcome: 'failed',
|
|
156
|
+
blocking: undefined,
|
|
157
|
+
ownedProcesses: [],
|
|
158
|
+
commands: [],
|
|
159
|
+
continuationCount: 0,
|
|
160
|
+
resumeFailures: 0,
|
|
161
|
+
assignment: executorAssignment(source, 'unavailable'),
|
|
162
|
+
replacement: {
|
|
163
|
+
...identity,
|
|
164
|
+
planIdentity: current.identity,
|
|
165
|
+
planFingerprint: fingerprint,
|
|
166
|
+
previous: executorAssignment(source, 'unavailable'),
|
|
167
|
+
reason: 'userDirectedTakeover',
|
|
168
|
+
evidence: 'explicit-user-takeover',
|
|
169
|
+
},
|
|
170
|
+
}
|
|
171
|
+
: undefined,
|
|
172
|
+
updatedAt: now,
|
|
173
|
+
};
|
|
174
|
+
const previousSessionIds = previous.map((p) => p.session.id);
|
|
175
|
+
if (!this.deps.store.complete(claim, state, [
|
|
176
|
+
{
|
|
177
|
+
sessionId,
|
|
178
|
+
type: 'autopilot.supervisor-taken-over',
|
|
179
|
+
occurredAt: now,
|
|
180
|
+
payload: {
|
|
181
|
+
previousSessionIds,
|
|
182
|
+
canonicalTaskName,
|
|
183
|
+
taskName: identity.taskName,
|
|
184
|
+
generation: identity.generation,
|
|
185
|
+
authority: 'explicit-user-takeover',
|
|
186
|
+
},
|
|
187
|
+
},
|
|
188
|
+
], { threadId, turnId }))
|
|
189
|
+
return { accepted: false, code: 'TAKEOVER_CONTEXT_CHANGED' };
|
|
190
|
+
// Publication cannot undo committed ownership or mint another generation.
|
|
191
|
+
// The durable outbox and normal activity reconciliation can retry refresh.
|
|
192
|
+
try {
|
|
193
|
+
this.deps.changed(sessionId);
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
/* committed takeover remains accepted */
|
|
197
|
+
}
|
|
198
|
+
return {
|
|
199
|
+
accepted: true,
|
|
200
|
+
alreadyOwner: false,
|
|
201
|
+
identity,
|
|
202
|
+
previousSessionIds,
|
|
203
|
+
boundaryFinalRequired: Boolean(history?.pendingTurnId),
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
}
|
|
@@ -42,10 +42,10 @@ export function autopilotSnapshot(state, retryLimit, facts = {
|
|
|
42
42
|
Number.isFinite(evaluationAt) &&
|
|
43
43
|
evaluationAt > Date.parse(facts.observedAt);
|
|
44
44
|
const rootWorking = facts.activeTurn;
|
|
45
|
-
//
|
|
46
|
-
//
|
|
47
|
-
//
|
|
48
|
-
const liveContinuation = parkedWait || scheduled || rootWorking || facts.executorActive
|
|
45
|
+
// A reconciliation is an attempt to restore evidence, not a continuation.
|
|
46
|
+
// Actual work, an armed control, or an owned wait remain live evidence even
|
|
47
|
+
// when the durable transition is old.
|
|
48
|
+
const liveContinuation = parkedWait || scheduled || rootWorking || facts.executorActive;
|
|
49
49
|
const healthy = state.requestedEnabled &&
|
|
50
50
|
!state.checkpoints?.checkpointHandoffFailed &&
|
|
51
51
|
facts.planMatches &&
|
|
@@ -66,7 +66,7 @@ export function autopilotSnapshot(state, retryLimit, facts = {
|
|
|
66
66
|
? 'waitingForAgentEvent'
|
|
67
67
|
: healthy && scheduled
|
|
68
68
|
? 'continuationScheduled'
|
|
69
|
-
: healthy &&
|
|
69
|
+
: facts.reconciling || (healthy && supervision === 'probeRequired')
|
|
70
70
|
? 'checkingState'
|
|
71
71
|
: healthy && rootWorking
|
|
72
72
|
? 'rootWorking'
|
|
@@ -193,7 +193,11 @@ export function parsePersistedSupervisedLifecycle(value) {
|
|
|
193
193
|
? parseExecutorAssignment(replacementPreviousValue)
|
|
194
194
|
: undefined;
|
|
195
195
|
const replacementReason = replacementValue &&
|
|
196
|
-
stringValue(replacementValue.reason, [
|
|
196
|
+
stringValue(replacementValue.reason, [
|
|
197
|
+
'explicitExecutorRejection',
|
|
198
|
+
'humanPermissionGranted',
|
|
199
|
+
'userDirectedTakeover',
|
|
200
|
+
]);
|
|
197
201
|
const replacementEvidence = replacementValue && boundedText(replacementValue.evidence);
|
|
198
202
|
if (!canonicalPosition ||
|
|
199
203
|
!canonicalTaskName ||
|
|
@@ -13,6 +13,13 @@ export class WriterAcquisitionError extends Error {
|
|
|
13
13
|
}
|
|
14
14
|
export function writerAcquisitionProblem(kind) {
|
|
15
15
|
switch (kind) {
|
|
16
|
+
case 'supervisorReplaced':
|
|
17
|
+
return {
|
|
18
|
+
status: 409,
|
|
19
|
+
code: 'SESSION_SUPERVISOR_REPLACED',
|
|
20
|
+
retryable: false,
|
|
21
|
+
detail: 'Another session took over this plan. Continue there, or direct a new session to take over.',
|
|
22
|
+
};
|
|
16
23
|
case 'writerBusy':
|
|
17
24
|
return {
|
|
18
25
|
status: 409,
|
|
@@ -28,7 +28,7 @@ export class CodexCapabilities {
|
|
|
28
28
|
const serenaPath = input.skills.find((skill) => skill.name === 'gestalt:serena')?.path;
|
|
29
29
|
const state = {
|
|
30
30
|
repositories: new RepositoryReadiness(input.cwd),
|
|
31
|
-
deadline: Math.max(input.deadline, serena.ready ? serena.deadline : input.deadline),
|
|
31
|
+
deadline: Math.max(input.deadline, xerj.ready ? xerj.deadline : input.deadline, serena.ready ? serena.deadline : input.deadline),
|
|
32
32
|
get ready() {
|
|
33
33
|
return xerj.ready || serena.ready;
|
|
34
34
|
},
|
|
@@ -17,6 +17,7 @@ import { gestaltOrgPlanHealthDynamicTool } from '../../../shared/contracts/org-p
|
|
|
17
17
|
import { gestaltTestRunnerDynamicTool } from '../../../shared/contracts/host-tests.js';
|
|
18
18
|
import { gestaltAutopilotWaitLeaseDynamicTool } from '../../../shared/contracts/autopilot-wait-lease.js';
|
|
19
19
|
import { gestaltAgentCapacityRecoveryDynamicTool } from '../../../shared/contracts/agent-capacity-recovery.js';
|
|
20
|
+
import { gestaltOrgPlanTakeoverDynamicTool } from '../../../shared/contracts/org-plan-takeover.js';
|
|
20
21
|
import { gestaltManagedPlaywrightDynamicTool } from '../../../shared/contracts/managed-playwright.js';
|
|
21
22
|
import { countDiffLines } from '../../../shared/contracts/file-change.js';
|
|
22
23
|
import { threadPlanName } from './thread-plan-name.js';
|
|
@@ -472,6 +473,135 @@ export class CodexSessionRuntime {
|
|
|
472
473
|
});
|
|
473
474
|
return true;
|
|
474
475
|
}
|
|
476
|
+
/** Stops the previous root's actor tree without transferring its native collaboration namespace. */
|
|
477
|
+
async quiesceForTakeover(session, recordedProcesses = [], executor) {
|
|
478
|
+
let expired = false;
|
|
479
|
+
let timer;
|
|
480
|
+
try {
|
|
481
|
+
return await Promise.race([
|
|
482
|
+
this.quiesceTakeoverActors(session, recordedProcesses, executor, () => !expired),
|
|
483
|
+
new Promise((resolve) => {
|
|
484
|
+
timer = setTimeout(() => {
|
|
485
|
+
expired = true;
|
|
486
|
+
this.stop(session.id);
|
|
487
|
+
resolve(false);
|
|
488
|
+
}, 30_000);
|
|
489
|
+
}),
|
|
490
|
+
]);
|
|
491
|
+
}
|
|
492
|
+
finally {
|
|
493
|
+
if (timer)
|
|
494
|
+
clearTimeout(timer);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
async quiesceTakeoverActors(session, recordedProcesses, executor, allowed) {
|
|
498
|
+
const writer = await this.ensureWriter(session, new Date().toISOString());
|
|
499
|
+
if (!allowed()) {
|
|
500
|
+
await this.release(session.id);
|
|
501
|
+
return false;
|
|
502
|
+
}
|
|
503
|
+
if (writer.replacementCreated || writer.session.threadId !== session.threadId)
|
|
504
|
+
return false;
|
|
505
|
+
const resource = this.sessions.get(session.id);
|
|
506
|
+
const topology = await this.readExecutorTopology(writer.session);
|
|
507
|
+
if (!resource || !allowed() || topology.kind !== 'observed')
|
|
508
|
+
return false;
|
|
509
|
+
const current = () => allowed() &&
|
|
510
|
+
this.sessions.get(session.id) === resource &&
|
|
511
|
+
resource.active &&
|
|
512
|
+
resource.threadId === session.threadId;
|
|
513
|
+
const threads = [
|
|
514
|
+
{
|
|
515
|
+
id: topology.rootThreadId,
|
|
516
|
+
status: topology.rootActive ? 'active' : 'idle',
|
|
517
|
+
taskPath: '/root',
|
|
518
|
+
qualified: true,
|
|
519
|
+
},
|
|
520
|
+
...topology.children,
|
|
521
|
+
...(executor
|
|
522
|
+
? [
|
|
523
|
+
{
|
|
524
|
+
id: executor.threadId,
|
|
525
|
+
taskPath: executor.taskPath,
|
|
526
|
+
status: 'unknown',
|
|
527
|
+
qualified: true,
|
|
528
|
+
},
|
|
529
|
+
]
|
|
530
|
+
: []),
|
|
531
|
+
];
|
|
532
|
+
const seen = new Set();
|
|
533
|
+
for (let index = 0; index < threads.length; index++) {
|
|
534
|
+
if (!current())
|
|
535
|
+
return false;
|
|
536
|
+
const thread = { ...threads[index] };
|
|
537
|
+
if (seen.has(thread.id))
|
|
538
|
+
continue;
|
|
539
|
+
if (seen.size >= 64)
|
|
540
|
+
return false;
|
|
541
|
+
seen.add(thread.id);
|
|
542
|
+
if (index > 0)
|
|
543
|
+
threads.push(...(await this.listDirectChildrenFromProcess(resource.process, thread.id, () => this.sessions.get(session.id) === resource &&
|
|
544
|
+
resource.active &&
|
|
545
|
+
resource.threadId === session.threadId)));
|
|
546
|
+
if (thread.qualified === false)
|
|
547
|
+
return false;
|
|
548
|
+
if (thread.status === 'unknown') {
|
|
549
|
+
const metadata = await resource.process.rpc.request('thread/read', {
|
|
550
|
+
threadId: thread.id,
|
|
551
|
+
includeTurns: false,
|
|
552
|
+
});
|
|
553
|
+
const observed = asRecord(asRecord(metadata)?.thread);
|
|
554
|
+
const status = String(asRecord(observed?.status)?.type);
|
|
555
|
+
if (observed?.id !== thread.id ||
|
|
556
|
+
observed.parentThreadId !== topology.rootThreadId ||
|
|
557
|
+
!['active', 'idle', 'notLoaded'].includes(status))
|
|
558
|
+
return false;
|
|
559
|
+
thread.status = status;
|
|
560
|
+
}
|
|
561
|
+
const processes = await this.inspectChildProcesses(writer.session, thread);
|
|
562
|
+
if (!current())
|
|
563
|
+
return false;
|
|
564
|
+
if (thread.status === 'notLoaded' &&
|
|
565
|
+
recordedProcesses.some((p) => p.ownerThreadId === thread.id && ['running', 'detached-active'].includes(p.state)))
|
|
566
|
+
return false;
|
|
567
|
+
if (thread.status !== 'notLoaded')
|
|
568
|
+
await this.interruptExecutor(writer.session, thread.id);
|
|
569
|
+
for (const process of processes) {
|
|
570
|
+
if (!current())
|
|
571
|
+
return false;
|
|
572
|
+
if (['running', 'detached-active'].includes(process.state) &&
|
|
573
|
+
!(await this.terminateChildProcess(writer.session, thread.id, process.processId, `takeover:${thread.id}:${process.itemId}`, process)))
|
|
574
|
+
return false;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
if (recordedProcesses.some((process) => ['running', 'detached-active'].includes(process.state) &&
|
|
578
|
+
!seen.has(process.ownerThreadId)))
|
|
579
|
+
return false;
|
|
580
|
+
for (const threadId of seen) {
|
|
581
|
+
if (!current())
|
|
582
|
+
return false;
|
|
583
|
+
const result = await resource.process.rpc.request('thread/read', {
|
|
584
|
+
threadId,
|
|
585
|
+
includeTurns: false,
|
|
586
|
+
});
|
|
587
|
+
const thread = asRecord(asRecord(result)?.thread);
|
|
588
|
+
if (thread?.id !== threadId ||
|
|
589
|
+
!['idle', 'notLoaded'].includes(String(asRecord(thread.status)?.type)))
|
|
590
|
+
return false;
|
|
591
|
+
const processes = await this.inspectChildProcesses(writer.session, {
|
|
592
|
+
id: threadId,
|
|
593
|
+
status: String(asRecord(thread.status)?.type),
|
|
594
|
+
qualified: true,
|
|
595
|
+
});
|
|
596
|
+
if (processes.some((p) => ['running', 'detached-active'].includes(p.state)))
|
|
597
|
+
return false;
|
|
598
|
+
}
|
|
599
|
+
if (!current())
|
|
600
|
+
return false;
|
|
601
|
+
resource.beginExplicitShutdown();
|
|
602
|
+
resource.dispose();
|
|
603
|
+
return true;
|
|
604
|
+
}
|
|
475
605
|
async queueTurnInput(session, turnId, text, clientUserMessageId) {
|
|
476
606
|
const resource = this.sessions.get(session.id);
|
|
477
607
|
if (!resource || !session.threadId)
|
|
@@ -1015,6 +1145,7 @@ export class CodexSessionRuntime {
|
|
|
1015
1145
|
gestaltTestRunnerDynamicTool,
|
|
1016
1146
|
gestaltAutopilotWaitLeaseDynamicTool,
|
|
1017
1147
|
gestaltAgentCapacityRecoveryDynamicTool,
|
|
1148
|
+
gestaltOrgPlanTakeoverDynamicTool,
|
|
1018
1149
|
gestaltManagedPlaywrightDynamicTool,
|
|
1019
1150
|
],
|
|
1020
1151
|
});
|
|
@@ -1122,6 +1253,7 @@ export class CodexSessionRuntime {
|
|
|
1122
1253
|
gestaltTestRunnerDynamicTool,
|
|
1123
1254
|
gestaltAutopilotWaitLeaseDynamicTool,
|
|
1124
1255
|
gestaltAgentCapacityRecoveryDynamicTool,
|
|
1256
|
+
gestaltOrgPlanTakeoverDynamicTool,
|
|
1125
1257
|
gestaltManagedPlaywrightDynamicTool,
|
|
1126
1258
|
],
|
|
1127
1259
|
...(session.model ? { model: session.model } : {}),
|
|
@@ -28,6 +28,8 @@ function migrateWorkspaceGitDefaults(database) {
|
|
|
28
28
|
}
|
|
29
29
|
export function migrate(database) {
|
|
30
30
|
database.exec(schema);
|
|
31
|
+
database.exec('CREATE TABLE IF NOT EXISTS org_plan_retired_supervisors (plan_identity TEXT NOT NULL, session_id TEXT NOT NULL, stopped INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(plan_identity, session_id))');
|
|
32
|
+
database.exec('CREATE TABLE IF NOT EXISTS org_plan_takeovers (plan_identity TEXT PRIMARY KEY, session_id TEXT NOT NULL, epoch INTEGER NOT NULL, phase TEXT NOT NULL)');
|
|
31
33
|
database.exec('CREATE TABLE IF NOT EXISTS tool_efficiency (session_id TEXT PRIMARY KEY REFERENCES relay_sessions(id) ON DELETE CASCADE, state_json TEXT NOT NULL)');
|
|
32
34
|
database.exec(`CREATE TABLE IF NOT EXISTS chat_transport_diagnostics (
|
|
33
35
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -0,0 +1,122 @@
|
|
|
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
|
+
/** A durable plan-scoped reservation also fences a superseded supervisor after relay restart. */
|
|
7
|
+
export class SqliteSupervisionTakeoverStore {
|
|
8
|
+
db;
|
|
9
|
+
autopilot;
|
|
10
|
+
constructor(db, autopilot) {
|
|
11
|
+
this.db = db;
|
|
12
|
+
this.autopilot = autopilot;
|
|
13
|
+
}
|
|
14
|
+
owner(planIdentity) {
|
|
15
|
+
const row = this.db
|
|
16
|
+
.prepare('SELECT session_id,epoch,phase FROM org_plan_takeovers WHERE plan_identity=?')
|
|
17
|
+
.get(planIdentity);
|
|
18
|
+
return row
|
|
19
|
+
? { planIdentity, sessionId: row.session_id, epoch: row.epoch, phase: row.phase }
|
|
20
|
+
: null;
|
|
21
|
+
}
|
|
22
|
+
retired(planIdentity, sessionId) {
|
|
23
|
+
return Boolean(this.db
|
|
24
|
+
.prepare('SELECT 1 FROM org_plan_retired_supervisors WHERE plan_identity=? AND session_id=?')
|
|
25
|
+
.get(planIdentity, sessionId));
|
|
26
|
+
}
|
|
27
|
+
stopped(planIdentity, sessionId) {
|
|
28
|
+
return Boolean(this.db
|
|
29
|
+
.prepare('SELECT 1 FROM org_plan_retired_supervisors WHERE plan_identity=? AND session_id=? AND stopped=1')
|
|
30
|
+
.get(planIdentity, sessionId));
|
|
31
|
+
}
|
|
32
|
+
markStopped(claim, sessionId) {
|
|
33
|
+
return (this.db
|
|
34
|
+
.prepare("UPDATE org_plan_retired_supervisors SET stopped=1 WHERE plan_identity=? AND session_id=? AND EXISTS (SELECT 1 FROM org_plan_takeovers WHERE plan_identity=? AND session_id=? AND epoch=? AND phase='stopping')")
|
|
35
|
+
.run(claim.planIdentity, sessionId, claim.planIdentity, claim.sessionId, claim.epoch)
|
|
36
|
+
.changes === 1);
|
|
37
|
+
}
|
|
38
|
+
retire(claim, sessionIds) {
|
|
39
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
40
|
+
try {
|
|
41
|
+
const current = this.owner(claim.planIdentity);
|
|
42
|
+
if (!current ||
|
|
43
|
+
current.sessionId !== claim.sessionId ||
|
|
44
|
+
current.epoch !== claim.epoch ||
|
|
45
|
+
current.phase !== 'stopping') {
|
|
46
|
+
this.db.exec('ROLLBACK');
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
for (const sessionId of sessionIds)
|
|
50
|
+
this.db
|
|
51
|
+
.prepare('INSERT OR IGNORE INTO org_plan_retired_supervisors (plan_identity,session_id) VALUES (?,?)')
|
|
52
|
+
.run(claim.planIdentity, sessionId);
|
|
53
|
+
this.db.exec('COMMIT');
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
this.db.exec('ROLLBACK');
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
claim(planIdentity, sessionId) {
|
|
62
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
63
|
+
try {
|
|
64
|
+
const previous = this.owner(planIdentity);
|
|
65
|
+
if (previous?.phase === 'stopping' && previous.sessionId !== sessionId) {
|
|
66
|
+
const owner = this.db
|
|
67
|
+
.prepare('SELECT state,active_turn_id FROM relay_sessions WHERE id=?')
|
|
68
|
+
.get(previous.sessionId);
|
|
69
|
+
if (owner && (owner.state === 'turnActive' || owner.active_turn_id)) {
|
|
70
|
+
this.db.exec('ROLLBACK');
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const epoch = previous?.sessionId === sessionId ? previous.epoch : (previous?.epoch ?? 0) + 1;
|
|
75
|
+
const phase = previous?.sessionId === sessionId ? previous.phase : 'stopping';
|
|
76
|
+
this.db
|
|
77
|
+
.prepare('INSERT INTO org_plan_takeovers (plan_identity,session_id,epoch,phase) VALUES (?,?,?,?) ON CONFLICT(plan_identity) DO UPDATE SET session_id=excluded.session_id,epoch=excluded.epoch,phase=excluded.phase')
|
|
78
|
+
.run(planIdentity, sessionId, epoch, phase);
|
|
79
|
+
this.db.exec('COMMIT');
|
|
80
|
+
return { planIdentity, sessionId, epoch, phase };
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
this.db.exec('ROLLBACK');
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
complete(claim, state, events, root) {
|
|
88
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
89
|
+
try {
|
|
90
|
+
const current = this.owner(claim.planIdentity);
|
|
91
|
+
const base = this.autopilot.find(state.sessionId);
|
|
92
|
+
const session = this.db
|
|
93
|
+
.prepare('SELECT thread_id,active_turn_id FROM relay_sessions WHERE id=?')
|
|
94
|
+
.get(state.sessionId);
|
|
95
|
+
if (!session ||
|
|
96
|
+
session.thread_id !== root.threadId ||
|
|
97
|
+
session.active_turn_id !== root.turnId ||
|
|
98
|
+
!current ||
|
|
99
|
+
current.sessionId !== claim.sessionId ||
|
|
100
|
+
current.epoch !== claim.epoch ||
|
|
101
|
+
current.phase !== 'stopping' ||
|
|
102
|
+
(base?.generation ?? 0) !== state.generation - 1) {
|
|
103
|
+
this.db.exec('ROLLBACK');
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
this.autopilot.save(state);
|
|
107
|
+
for (const e of events)
|
|
108
|
+
this.db
|
|
109
|
+
.prepare('INSERT INTO autopilot_outbox (session_id,type,payload_json,occurred_at) VALUES (?,?,?,?)')
|
|
110
|
+
.run(e.sessionId, e.type, JSON.stringify(e.payload), e.occurredAt);
|
|
111
|
+
this.db
|
|
112
|
+
.prepare("UPDATE org_plan_takeovers SET phase='ready' WHERE plan_identity=?")
|
|
113
|
+
.run(claim.planIdentity);
|
|
114
|
+
this.db.exec('COMMIT');
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
this.db.exec('ROLLBACK');
|
|
119
|
+
throw error;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -7,6 +7,7 @@ import { readFile } from 'node:fs/promises';
|
|
|
7
7
|
import { ReadinessEvidence } from './readiness-evidence.js';
|
|
8
8
|
export const xerjServerName = 'gestalt-xerj';
|
|
9
9
|
export const xerjTools = ['xerj_search', 'xerj_map', 'xerj_code_search'];
|
|
10
|
+
const connectionTimeoutMs = 5_000;
|
|
10
11
|
/** Ephemeral native thread configuration; no installation or daemon ownership. */
|
|
11
12
|
export class CodexXerj {
|
|
12
13
|
capability;
|
|
@@ -89,6 +90,10 @@ export class CodexXerj {
|
|
|
89
90
|
const guidance = await beforeDeadline(readFile(skill.path, 'utf8'), input.deadline);
|
|
90
91
|
if (guidance.length > 16_384)
|
|
91
92
|
return state;
|
|
93
|
+
// Backend preparation must not leave the native MCP handshake with only
|
|
94
|
+
// a few milliseconds. These are separate, individually bounded phases.
|
|
95
|
+
state.deadline = Date.now() + connectionTimeoutMs;
|
|
96
|
+
state.verificationTimeoutMs = connectionTimeoutMs;
|
|
92
97
|
state.skillsConfig = state.skillsConfig.map((entry) => ({
|
|
93
98
|
...entry,
|
|
94
99
|
enabled: entry.path === skill.path ? true : entry.enabled,
|
|
@@ -106,7 +111,7 @@ export class CodexXerj {
|
|
|
106
111
|
enabled: true,
|
|
107
112
|
required: false,
|
|
108
113
|
startup_readiness: 'connection',
|
|
109
|
-
startup_timeout_ms:
|
|
114
|
+
startup_timeout_ms: connectionTimeoutMs,
|
|
110
115
|
enabled_tools: xerjTools,
|
|
111
116
|
default_tools_approval_mode: 'approve',
|
|
112
117
|
},
|
|
@@ -125,13 +130,17 @@ export class CodexXerj {
|
|
|
125
130
|
async verify(rpc, threadId, state) {
|
|
126
131
|
if (!state.ready)
|
|
127
132
|
return false;
|
|
133
|
+
// thread/start can consume the handshake allowance before this method runs.
|
|
134
|
+
const deadline = state.verificationTimeoutMs
|
|
135
|
+
? Date.now() + state.verificationTimeoutMs
|
|
136
|
+
: state.deadline;
|
|
128
137
|
try {
|
|
129
|
-
while (Date.now() <
|
|
138
|
+
while (Date.now() < deadline) {
|
|
130
139
|
const result = (await beforeDeadline(rpc.request('mcpServerStatus/list', {
|
|
131
140
|
threadId,
|
|
132
141
|
serverName: xerjServerName,
|
|
133
142
|
detail: 'full',
|
|
134
|
-
}),
|
|
143
|
+
}), deadline));
|
|
135
144
|
const server = result.data?.find((entry) => entry.name === xerjServerName);
|
|
136
145
|
if (server?.runtimeStatus === 'connected' &&
|
|
137
146
|
!server.toolsError &&
|
|
@@ -143,7 +152,7 @@ export class CodexXerj {
|
|
|
143
152
|
state.evidence?.connection('unavailable');
|
|
144
153
|
return false;
|
|
145
154
|
}
|
|
146
|
-
await beforeDeadline(new Promise((resolve) => setTimeout(resolve, 25)),
|
|
155
|
+
await beforeDeadline(new Promise((resolve) => setTimeout(resolve, 25)), deadline);
|
|
147
156
|
}
|
|
148
157
|
state.evidence?.connection('unavailable');
|
|
149
158
|
return false;
|
|
@@ -0,0 +1,41 @@
|
|
|
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, randomUUID } from 'node:crypto';
|
|
7
|
+
import { mkdir, rename, rm, writeFile } from 'node:fs/promises';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
/** Classify bounded native prose; never retain it or copy arbitrary native fields. */
|
|
10
|
+
export function xerjIndexDiagnostic(message) {
|
|
11
|
+
const text = typeof message === 'string' ? message.slice(0, 16_384) : '';
|
|
12
|
+
const code = text.includes('refusing ambiguous assignment')
|
|
13
|
+
? 'ambiguous-assignment'
|
|
14
|
+
: /\b(timeout|timed out)\b/i.test(text)
|
|
15
|
+
? 'timeout'
|
|
16
|
+
: /\b(unauthorized|forbidden|authentication)\b/i.test(text)
|
|
17
|
+
? 'authentication'
|
|
18
|
+
: /\b(connection refused|connection reset|unreachable)\b/i.test(text)
|
|
19
|
+
? 'connection'
|
|
20
|
+
: /\b(out of memory|no space left|disk full)\b/i.test(text)
|
|
21
|
+
? 'capacity'
|
|
22
|
+
: 'unknown-warning';
|
|
23
|
+
return {
|
|
24
|
+
id: randomUUID(),
|
|
25
|
+
occurredAt: new Date().toISOString(),
|
|
26
|
+
code,
|
|
27
|
+
messageDigest: text ? createHash('sha256').update(text).digest('hex') : null,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/** One private atomic record per root; repeated warnings cannot grow a log. */
|
|
31
|
+
export async function saveXerjIndexDiagnostic(directory, diagnostic) {
|
|
32
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
33
|
+
const temporary = join(directory, `.gestalt-index-diagnostic.${randomUUID()}.tmp`);
|
|
34
|
+
try {
|
|
35
|
+
await writeFile(temporary, `${JSON.stringify(diagnostic)}\n`, { flag: 'wx', mode: 0o600 });
|
|
36
|
+
await rename(temporary, join(directory, '.gestalt-index-diagnostic.json'));
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
await rm(temporary, { force: true });
|
|
40
|
+
}
|
|
41
|
+
}
|