gestalt-mobile 0.66.3 → 0.67.1

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.
@@ -339,6 +339,10 @@ export class AutopilotCoordinator {
339
339
  const nextProtocol = reportProbe(protocol, report);
340
340
  if (nextProtocol === protocol)
341
341
  return false;
342
+ const ownerTurnId = this.deps.session(sessionId)?.activeTurnId;
343
+ const ownedProtocol = nextProtocol.waitLease && ownerTurnId
344
+ ? { ...nextProtocol, waitLease: { ...nextProtocol.waitLease, turnId: ownerTurnId } }
345
+ : nextProtocol;
342
346
  if (nextProtocol.outcome === 'parked' && nextProtocol.waitLease) {
343
347
  this.parkedSubscriptions.set(sessionId, nextProtocol.waitLease.id);
344
348
  this.activityEventKeys.set(sessionId, this.progressKey(sessionId, false));
@@ -348,7 +352,7 @@ export class AutopilotCoordinator {
348
352
  const now = this.deps.now();
349
353
  this.persist({
350
354
  ...state,
351
- supervision: nextProtocol,
355
+ supervision: ownedProtocol,
352
356
  ...(nextProtocol.outcome === 'attentionRequired'
353
357
  ? {
354
358
  state: 'attentionRequired',
@@ -404,6 +408,10 @@ export class AutopilotCoordinator {
404
408
  const nextProtocol = registerProtocolWait(protocol, { ...report, resumeAt });
405
409
  if (nextProtocol === protocol)
406
410
  return false;
411
+ const ownerTurnId = this.deps.session(sessionId)?.activeTurnId;
412
+ const ownedProtocol = ownerTurnId
413
+ ? { ...nextProtocol, waitLease: { ...nextProtocol.waitLease, turnId: ownerTurnId } }
414
+ : nextProtocol;
407
415
  const cancelled = this.cancelScheduledControl(state, now);
408
416
  this.timers.get(sessionId)?.();
409
417
  this.timers.delete(sessionId);
@@ -417,7 +425,7 @@ export class AutopilotCoordinator {
417
425
  generation: state.generation + (cancelled ? 1 : 0),
418
426
  nextEvaluationAt: null,
419
427
  ...(cancelled ? { lastControlId: null } : {}),
420
- supervision: nextProtocol,
428
+ supervision: ownedProtocol,
421
429
  updatedAt: now,
422
430
  }, cancelled);
423
431
  this.armWaitDeadline(sessionId, report.leaseId, resumeAt);
@@ -817,6 +825,17 @@ export class AutopilotCoordinator {
817
825
  state: 'backoff',
818
826
  nextEvaluationAt: decision.at,
819
827
  lastControlId: scheduledControlId,
828
+ ...(prior.supervision?.diagnosticRecovery
829
+ ? {
830
+ supervision: {
831
+ ...prior.supervision,
832
+ diagnosticRecovery: {
833
+ ...prior.supervision.diagnosticRecovery,
834
+ controlId: scheduledControlId,
835
+ },
836
+ },
837
+ }
838
+ : {}),
820
839
  updatedAt: now,
821
840
  };
822
841
  const control = {
@@ -837,6 +856,9 @@ export class AutopilotCoordinator {
837
856
  type: 'autopilot.continuation-scheduled',
838
857
  payload: {
839
858
  controlId: scheduledControlId,
859
+ ...(next.supervision?.diagnosticRecovery
860
+ ? { ...next.supervision.diagnosticRecovery, disposition: 'executorResumeRecovery' }
861
+ : {}),
840
862
  ...this.wakeAttribution(next),
841
863
  reportId: prior.supervision?.lastReportId ?? null,
842
864
  nextEvaluationAt: decision.at,
@@ -1127,12 +1149,27 @@ export class AutopilotCoordinator {
1127
1149
  }
1128
1150
  if (!finalAllowed) {
1129
1151
  const occurredAt = this.deps.now();
1152
+ const lease = state?.supervision?.waitLease;
1153
+ const currentTurnId = turnId ?? this.deps.session(sessionId)?.activeTurnId;
1154
+ const activeLease = state?.supervision?.outcome === 'parked' &&
1155
+ lease &&
1156
+ (!lease.resumeAt || Date.parse(lease.resumeAt) > Date.parse(occurredAt));
1157
+ const disposition = activeLease && !lease.turnId
1158
+ ? 'unknownWait'
1159
+ : activeLease && currentTurnId && lease.turnId === currentTurnId
1160
+ ? 'acceptedWait'
1161
+ : 'rejectedFinal';
1130
1162
  this.commit({
1131
1163
  events: [
1132
1164
  {
1133
1165
  sessionId,
1134
1166
  type: 'autopilot.final-rejected',
1135
- payload: { reason: 'incompletePlan' },
1167
+ payload: {
1168
+ reason: 'incompletePlan',
1169
+ disposition,
1170
+ ...(currentTurnId ? { turnId: currentTurnId } : {}),
1171
+ ...(disposition === 'acceptedWait' ? { leaseId: lease.id } : {}),
1172
+ },
1136
1173
  occurredAt,
1137
1174
  },
1138
1175
  ],
@@ -1589,6 +1626,7 @@ export class AutopilotCoordinator {
1589
1626
  supervision: {
1590
1627
  ...consumeObsoleteWait(prior.supervision ?? startSupervisionProtocol(this.progressKey(sessionId)), this.progressKey(sessionId)),
1591
1628
  wakeCause: null,
1629
+ diagnosticRecovery: null,
1592
1630
  },
1593
1631
  updatedAt: now,
1594
1632
  }, cancelled);
@@ -1646,6 +1684,13 @@ export class AutopilotCoordinator {
1646
1684
  supervision: {
1647
1685
  ...next.supervision,
1648
1686
  acknowledgedRevision: next.supervision.acknowledgedRevision ?? prior.supervision.acknowledgedRevision,
1687
+ diagnosticRecovery: !next.requestedEnabled ||
1688
+ (control?.status === 'cancelled' &&
1689
+ control.controlId === prior.supervision.diagnosticRecovery?.controlId)
1690
+ ? null
1691
+ : next.supervision.diagnosticRecovery === undefined
1692
+ ? prior.supervision.diagnosticRecovery
1693
+ : next.supervision.diagnosticRecovery,
1649
1694
  wakeCause: !next.requestedEnabled ||
1650
1695
  !prior.requestedEnabled ||
1651
1696
  (next.supervision.waitLease &&
@@ -1667,6 +1712,7 @@ export class AutopilotCoordinator {
1667
1712
  payload: {
1668
1713
  ...this.wakeAttribution(next),
1669
1714
  leaseId: nextLease.id,
1715
+ ...(nextLease.turnId ? { turnId: nextLease.turnId } : {}),
1670
1716
  ...(nextLease.runId ? { runId: nextLease.runId } : {}),
1671
1717
  reportId: next.supervision?.lastReportId,
1672
1718
  resumeAt: nextLease.resumeAt ?? null,
@@ -2787,6 +2833,14 @@ export class AutopilotCoordinator {
2787
2833
  // replayed: app-server acceptance may have happened before a crash.
2788
2834
  if (!command || command.status !== 'scheduled')
2789
2835
  return;
2836
+ const diagnosticAttempt = {
2837
+ requestId: command.commandId,
2838
+ threadId: fence.executorThreadId,
2839
+ generation: fence.executorGeneration,
2840
+ ...(state?.checkpoints?.activeHandoffId
2841
+ ? { traceId: state.checkpoints.activeHandoffId }
2842
+ : {}),
2843
+ };
2790
2844
  let delivered = false;
2791
2845
  this.executorTimers.set(sessionId, this.deps.schedule(() => {
2792
2846
  this.executorTimers.delete(sessionId);
@@ -2862,7 +2916,7 @@ export class AutopilotCoordinator {
2862
2916
  // Only an explicit app-server rejection is safe to retry. A lost
2863
2917
  // response may conceal accepted work, so retain its issued fence.
2864
2918
  if (!explicitExecutorRejection(error)) {
2865
- this.containOperationFailure(sessionId, error, 'executorResume');
2919
+ this.containOperationFailure(sessionId, error, 'executorResume', diagnosticAttempt);
2866
2920
  this.armExecutorRefresh(sessionId, this.deps.policy.executorContinuationMaxMs);
2867
2921
  return;
2868
2922
  }
@@ -2953,6 +3007,8 @@ export class AutopilotCoordinator {
2953
3007
  const occurredAt = this.deps.now();
2954
3008
  const state = this.deps.store.find(sessionId);
2955
3009
  const accepted = status === 'started' && Boolean(turnId);
3010
+ const recovery = state?.supervision?.diagnosticRecovery;
3011
+ const acceptedRecovery = accepted && recovery?.controlId === controlId ? recovery : undefined;
2956
3012
  const acceptanceState = accepted && state
2957
3013
  ? {
2958
3014
  ...state,
@@ -2963,6 +3019,7 @@ export class AutopilotCoordinator {
2963
3019
  controlId,
2964
3020
  turnId: turnId,
2965
3021
  },
3022
+ ...(acceptedRecovery ? { diagnosticRecovery: null } : {}),
2966
3023
  wakeCause: null,
2967
3024
  },
2968
3025
  updatedAt: occurredAt,
@@ -3004,6 +3061,9 @@ export class AutopilotCoordinator {
3004
3061
  ...(state ? this.wakeAttribution(state) : {}),
3005
3062
  trafficClass: accepted ? 'acceptedRootTurn' : 'unconfirmedStart',
3006
3063
  turnId,
3064
+ ...(acceptedRecovery
3065
+ ? { ...acceptedRecovery, disposition: 'executorResumeRecovery' }
3066
+ : {}),
3007
3067
  ...(this.deps.store.find(sessionId)?.checkpoints?.activeHandoffId
3008
3068
  ? { traceId: this.deps.store.find(sessionId).checkpoints.activeHandoffId }
3009
3069
  : {}),
@@ -3398,7 +3458,7 @@ export class AutopilotCoordinator {
3398
3458
  * outbox publication failure must not recursively manufacture another
3399
3459
  * rejected promise before a later journal flush can replay the event.
3400
3460
  */
3401
- containOperationFailure(sessionId, error, operation = 'queuedOperation') {
3461
+ containOperationFailure(sessionId, error, operation = 'queuedOperation', attempt) {
3402
3462
  const code = operationFailureCode(error);
3403
3463
  const rpcCode = operationRpcCode(error);
3404
3464
  try {
@@ -3451,6 +3511,7 @@ export class AutopilotCoordinator {
3451
3511
  waitLease: null,
3452
3512
  retryKey: null,
3453
3513
  safetyPauseReason: null,
3514
+ diagnosticRecovery: attempt ?? null,
3454
3515
  },
3455
3516
  }
3456
3517
  : {}),
@@ -3468,6 +3529,7 @@ export class AutopilotCoordinator {
3468
3529
  kind: operation,
3469
3530
  reason: operationErrorKind(error),
3470
3531
  ...(rpcCode !== undefined ? { rpcCode } : {}),
3532
+ ...(attempt ?? {}),
3471
3533
  },
3472
3534
  occurredAt: now,
3473
3535
  },
@@ -338,8 +338,14 @@ export function parseSupervisionProtocolState(value) {
338
338
  candidate.safetyPauseReason !== 'retryRecurrence' &&
339
339
  candidate.safetyPauseReason !== 'invalidProbeReport')
340
340
  return undefined;
341
+ const diagnosticRecovery = parseDiagnosticRecovery(candidate.diagnosticRecovery);
341
342
  return {
342
343
  ...base,
344
+ ...(candidate.diagnosticRecovery === null
345
+ ? { diagnosticRecovery: null }
346
+ : diagnosticRecovery
347
+ ? { diagnosticRecovery }
348
+ : {}),
343
349
  ...(wakeCause !== undefined ? { wakeCause: parsedWake ?? null } : {}),
344
350
  ...(parsedAcknowledgement ? { acknowledgedRevision: parsedAcknowledgement } : {}),
345
351
  outcome: candidate.outcome,
@@ -391,12 +397,38 @@ function parseWaitLease(value) {
391
397
  return undefined;
392
398
  return {
393
399
  id: candidate.id,
400
+ ...(diagnosticId(candidate.turnId) ? { turnId: candidate.turnId } : {}),
394
401
  probeKey: candidate.probeKey,
395
402
  wakeConditions,
396
403
  ...(typeof resumeAt === 'string' ? { resumeAt } : {}),
397
404
  ...(typeof runId === 'string' ? { runId } : {}),
398
405
  };
399
406
  }
407
+ function diagnosticId(value) {
408
+ return (typeof value === 'string' &&
409
+ value.length > 0 &&
410
+ value.length <= 200 &&
411
+ /^[a-zA-Z0-9_.:@+-]+$/.test(value));
412
+ }
413
+ function parseDiagnosticRecovery(value) {
414
+ if (!value || typeof value !== 'object' || Array.isArray(value))
415
+ return undefined;
416
+ const candidate = value;
417
+ if (!diagnosticId(candidate.requestId) ||
418
+ !diagnosticId(candidate.threadId) ||
419
+ !Number.isSafeInteger(candidate.generation) ||
420
+ Number(candidate.generation) < 1 ||
421
+ (candidate.traceId !== undefined && !diagnosticId(candidate.traceId)) ||
422
+ (candidate.controlId !== undefined && !diagnosticId(candidate.controlId)))
423
+ return undefined;
424
+ return {
425
+ requestId: candidate.requestId,
426
+ threadId: candidate.threadId,
427
+ generation: Number(candidate.generation),
428
+ ...(diagnosticId(candidate.traceId) ? { traceId: candidate.traceId } : {}),
429
+ ...(diagnosticId(candidate.controlId) ? { controlId: candidate.controlId } : {}),
430
+ };
431
+ }
400
432
  function validRunWait(runId, conditions) {
401
433
  return (typeof runId === 'string' &&
402
434
  /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(runId) &&
@@ -32,6 +32,7 @@ const diagnosticFields = new Set([
32
32
  'reason',
33
33
  'code',
34
34
  'rpcCode',
35
+ 'disposition',
35
36
  'providerFailure',
36
37
  'actor',
37
38
  'retryAttempt',
@@ -80,7 +81,10 @@ export function redactDiagnosticPayload(value, depth = 0) {
80
81
  if (!value || typeof value !== 'object')
81
82
  return null;
82
83
  return Object.fromEntries(Object.entries(value)
83
- .filter(([key]) => diagnosticFields.has(key))
84
+ .filter(([key, item]) => diagnosticFields.has(key) &&
85
+ (key !== 'disposition' ||
86
+ (typeof item === 'string' &&
87
+ ['acceptedWait', 'rejectedFinal', 'unknownWait', 'executorResumeRecovery'].includes(item))))
84
88
  .map(([key, item]) => [key, redactDiagnosticPayload(item, depth + 1)]));
85
89
  }
86
90
  function objectPayload(value) {
@@ -100,26 +104,119 @@ function correlation(payload) {
100
104
  return String(payload[key]);
101
105
  return null;
102
106
  }
107
+ function handoffIdentity(payload, key) {
108
+ const value = payload[key];
109
+ return typeof value === 'string' && value && value !== '[redacted]' ? value : null;
110
+ }
111
+ function matchesHandoff(checkpoint, event) {
112
+ let matched = false;
113
+ for (const key of ['traceId', 'handoffId']) {
114
+ const selected = handoffIdentity(checkpoint.payload, key);
115
+ const observed = handoffIdentity(event.payload, key);
116
+ if (selected && observed) {
117
+ if (selected !== observed)
118
+ return false;
119
+ matched = true;
120
+ }
121
+ }
122
+ return matched;
123
+ }
124
+ function conflictsWithHandoff(left, right) {
125
+ return ['traceId', 'handoffId'].some((key) => {
126
+ const a = handoffIdentity(left.payload, key);
127
+ const b = handoffIdentity(right.payload, key);
128
+ return a !== null && b !== null && a !== b;
129
+ });
130
+ }
131
+ function matchesAttempt(failure, event) {
132
+ return (['requestId', 'threadId'].every((key) => {
133
+ const id = handoffIdentity(failure.payload, key);
134
+ return id !== null && id === handoffIdentity(event.payload, key);
135
+ }) &&
136
+ Number.isSafeInteger(failure.payload.generation) &&
137
+ Number(failure.payload.generation) > 0 &&
138
+ failure.payload.generation === event.payload.generation &&
139
+ !conflictsWithHandoff(failure, event));
140
+ }
103
141
  function diagnose(events) {
104
142
  const diagnoses = [];
105
143
  if (!events.length)
106
144
  return ['no control-plane events found for this session'];
107
145
  const checkpointIndex = events.findLastIndex((event) => event.type.endsWith('-checkpointed'));
108
146
  const currentHandoff = checkpointIndex < 0 ? events : events.slice(checkpointIndex);
109
- const types = new Set(currentHandoff.map((event) => event.type));
110
- if ((types.has('org-plan.step-checkpointed') || types.has('org-plan.milestone-checkpointed')) &&
147
+ const checkpoint = checkpointIndex < 0 ? undefined : events[checkpointIndex];
148
+ const hasIdentity = checkpoint && ['traceId', 'handoffId'].some((key) => handoffIdentity(checkpoint.payload, key));
149
+ // Legacy rows retain their chronological diagnostics, but cannot establish
150
+ // matching coverage. A shared turn alone is not a handoff identity.
151
+ if (checkpoint && !hasIdentity)
152
+ diagnoses.push('checkpoint correlation unavailable; matching handoff evidence cannot be established');
153
+ const selected = currentHandoff.filter((event) => !hasIdentity || matchesHandoff(checkpoint, event));
154
+ // A control-only cancellation/outcome can close only the control actually
155
+ // linked by a retained selected schedule/issue event. Conflicting handoff
156
+ // identifiers must not be rescued by a shared control ID.
157
+ const controls = new Set(selected
158
+ .filter((event) => ['autopilot.continuation-scheduled', 'autopilot.control-issued'].includes(event.type))
159
+ .map((event) => handoffIdentity(event.payload, 'controlId'))
160
+ .filter((id) => id !== null));
161
+ const matching = currentHandoff.filter((event) => selected.includes(event) ||
162
+ (checkpoint &&
163
+ !conflictsWithHandoff(checkpoint, event) &&
164
+ ['autopilot.control-cancelled', 'autopilot.turn-started', 'autopilot.turn-failed'].includes(event.type) &&
165
+ controls.has(handoffIdentity(event.payload, 'controlId') ?? '')));
166
+ const types = new Set(matching.map((event) => event.type));
167
+ const closedAfter = (boundary, outcomes) => matching.some((event) => event.sequence > boundary.sequence &&
168
+ outcomes.includes(event.type) &&
169
+ !conflictsWithHandoff(boundary, event) &&
170
+ (!handoffIdentity(boundary.payload, 'controlId') ||
171
+ boundary.payload.controlId === event.payload.controlId));
172
+ const scheduled = matching.findLast((event) => event.type === 'autopilot.continuation-scheduled');
173
+ const issued = matching.findLast((event) => event.type === 'autopilot.control-issued');
174
+ // Terminal supervision closes with a matching report, not another turn.
175
+ const terminalCheckpoint = checkpoint?.type === 'org-plan.terminal-review-checkpointed';
176
+ if (terminalCheckpoint && !types.has('org-plan.terminal-review-reported'))
177
+ diagnoses.push('terminal checkpoint persisted, but no report was observed');
178
+ if (!terminalCheckpoint &&
179
+ (types.has('org-plan.step-checkpointed') || types.has('org-plan.milestone-checkpointed')) &&
111
180
  !types.has('autopilot.continuation-scheduled'))
112
181
  diagnoses.push('checkpoint persisted, but no continuation was scheduled');
113
- if (types.has('autopilot.continuation-scheduled') &&
114
- !types.has('autopilot.control-issued') &&
115
- !types.has('autopilot.executor-resumed'))
182
+ if (scheduled &&
183
+ !closedAfter(scheduled, [
184
+ 'autopilot.control-issued',
185
+ 'autopilot.executor-resumed',
186
+ 'autopilot.control-cancelled',
187
+ ]))
116
188
  diagnoses.push('continuation scheduled, but no control or executor dispatch was observed');
117
- if (types.has('autopilot.control-issued') &&
118
- !types.has('autopilot.turn-started') &&
119
- !types.has('autopilot.turn-failed'))
189
+ if (issued &&
190
+ !closedAfter(issued, [
191
+ 'autopilot.turn-started',
192
+ 'autopilot.turn-failed',
193
+ 'autopilot.control-cancelled',
194
+ ]))
120
195
  diagnoses.push('control issued, but no turn acceptance or failure was observed');
121
196
  if (types.has('org-plan.checkpoint-handoff-failed'))
122
197
  diagnoses.push('checkpoint response handoff failed; inspect the matching trace ID');
198
+ const resumeFailure = matching.findLast((event) => event.type === 'autopilot.operation-failed' && event.payload.kind === 'executorResume');
199
+ if (resumeFailure) {
200
+ diagnoses.push('executor resume failure cause is unknown in retained evidence');
201
+ const recoverySchedule = matching.find((event) => event.sequence > resumeFailure.sequence &&
202
+ event.type === 'autopilot.continuation-scheduled' &&
203
+ event.payload.disposition === 'executorResumeRecovery' &&
204
+ matchesAttempt(resumeFailure, event));
205
+ const recovered = recoverySchedule &&
206
+ matching.some((event) => event.sequence > recoverySchedule.sequence &&
207
+ event.type === 'autopilot.turn-started' &&
208
+ event.payload.disposition === 'executorResumeRecovery' &&
209
+ matchesAttempt(resumeFailure, event) &&
210
+ handoffIdentity(recoverySchedule.payload, 'controlId') !== null &&
211
+ event.payload.controlId === recoverySchedule.payload.controlId);
212
+ diagnoses.push(recovered
213
+ ? 'root continuation observed after executor resume failure; executor outcome remains unconfirmed'
214
+ : 'executor resume failed; no matching root recovery continuation was observed; executor outcome remains unconfirmed');
215
+ }
216
+ if (matching.some((event) => event.type === 'autopilot.final-rejected' &&
217
+ event.payload.reason === 'incompletePlan' &&
218
+ !['acceptedWait', 'rejectedFinal'].includes(String(event.payload.disposition))))
219
+ diagnoses.push('incomplete final disposition is unknown in retained evidence');
123
220
  if (currentHandoff.some((event) => event.type === 'agent.activity.updated'))
124
221
  diagnoses.push('backend agent projection was recorded; browser delivery still requires the client event cursor');
125
222
  return diagnoses;
@@ -197,7 +294,10 @@ export function formatControlPlaneTrace(trace) {
197
294
  ? ` phase=${startup.failure.phase} code=${startup.failure.code} exit=${startup.failure.exitCode ?? 'unavailable'} signal=${startup.failure.signal ?? 'unavailable'} artifact=${startup.failure.artifactDigest ?? 'unavailable'}`
198
295
  : ''}`
199
296
  : '';
200
- lines.push(`${String(event.sequence).padStart(6)} ${event.occurredAt} ${event.type}${correlationLabel}${startupLabel}`);
297
+ const dispositionLabel = typeof event.payload.disposition === 'string'
298
+ ? ` disposition=${event.payload.disposition}`
299
+ : '';
300
+ lines.push(`${String(event.sequence).padStart(6)} ${event.occurredAt} ${event.type}${correlationLabel}${startupLabel}${dispositionLabel}`);
201
301
  }
202
302
  lines.push('', 'Diagnosis:');
203
303
  if (!trace.diagnoses.length)
@@ -3,9 +3,11 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
- import { CodexXerj } from '../retrieval/codex-xerj.js';
6
+ import { beforeDeadline, CodexXerj } from '../retrieval/codex-xerj.js';
7
7
  import { CodexSerena } from './codex-serena.js';
8
8
  import { RepositoryReadiness } from '../retrieval/repository-readiness.js';
9
+ import { withCapabilityInstructions } from './instruction-blocks.js';
10
+ import { prepareStartupGuidance } from './startup-guidance.js';
9
11
  /** The two managed capabilities share lifecycle, but never share availability or approvals. */
10
12
  export class CodexCapabilities {
11
13
  xerj;
@@ -16,17 +18,65 @@ export class CodexCapabilities {
16
18
  this.serena = serena;
17
19
  }
18
20
  async prepare(input) {
21
+ let native = null;
22
+ try {
23
+ const read = (await beforeDeadline(input.rpc.request('config/read', {
24
+ cwd: input.cwd,
25
+ includeLayers: false,
26
+ }), input.deadline));
27
+ native = read.config ?? null;
28
+ }
29
+ catch {
30
+ /* Native fallback remains available without optional guidance. */
31
+ }
32
+ let startup;
33
+ const canComposeInstructions = native !== null || typeof input.config.developer_instructions === 'string';
34
+ let instructions = typeof input.config.developer_instructions === 'string'
35
+ ? input.config.developer_instructions
36
+ : typeof native?.developer_instructions === 'string'
37
+ ? native.developer_instructions
38
+ : '';
39
+ const prepareFreshStartup = async (deadline) => {
40
+ if (!native) {
41
+ startup = { status: 'unavailable', reason: 'native-config-unavailable' };
42
+ return;
43
+ }
44
+ const prepared = await beforeDeadline(prepareStartupGuidance({
45
+ instructions,
46
+ native,
47
+ skills: input.skills,
48
+ skillsConfig: input.skillsConfig,
49
+ }), deadline).catch(() => ({
50
+ instructions,
51
+ startup: { status: 'unavailable', reason: 'invalid-contract' },
52
+ }));
53
+ instructions = prepared.instructions;
54
+ startup = prepared.startup;
55
+ };
56
+ if (input.startup)
57
+ await prepareFreshStartup(input.deadline);
58
+ const preparedInput = {
59
+ ...input,
60
+ nativeConfig: native,
61
+ config: { ...input.config, developer_instructions: instructions },
62
+ };
19
63
  // Connection verification is a separate bounded phase for Serena. A slow
20
64
  // optional XERJ probe must not spend Serena's entire connection allowance.
21
65
  const serenaVerificationMs = Math.max(1, Math.min(5_000, input.deadline - Date.now()));
22
66
  const [xerj, serena] = await Promise.all([
23
- this.xerj.prepare(input),
24
- this.serena.prepare(input),
67
+ this.xerj.prepare(preparedInput),
68
+ this.serena.prepare(preparedInput),
25
69
  ]);
26
70
  if (serena.ready)
27
71
  serena.deadline = Date.now() + serenaVerificationMs;
28
72
  const serenaPath = input.skills.find((skill) => skill.name === 'gestalt:serena')?.path;
29
73
  const state = {
74
+ get startup() {
75
+ return startup;
76
+ },
77
+ // A recognized missing rollout starts a new thread in this same owned
78
+ // runtime. Only the bounded instruction read/composition is repeated.
79
+ prepareFreshStartup: () => prepareFreshStartup(Date.now() + 5_000),
30
80
  repositories: new RepositoryReadiness(input.cwd),
31
81
  get backendPreparation() {
32
82
  return xerj.backendPreparation;
@@ -59,9 +109,12 @@ export class CodexCapabilities {
59
109
  : entry);
60
110
  },
61
111
  get config() {
62
- const xerjInstructions = String(xerj.config.developer_instructions ?? '');
63
- const serenaInstructions = String(serena.config.developer_instructions ?? '');
64
- return {
112
+ let combined = instructions;
113
+ if (xerj.instructionBlock)
114
+ combined = withCapabilityInstructions(combined, 'xerj', xerj.instructionBlock);
115
+ if (serena.instructionBlock)
116
+ combined = withCapabilityInstructions(combined, 'serena', serena.instructionBlock);
117
+ const config = {
65
118
  ...input.config,
66
119
  mcp_servers: {
67
120
  ...xerj.config.mcp_servers,
@@ -73,8 +126,13 @@ export class CodexCapabilities {
73
126
  ...(serena.config.skills?.config ?? []),
74
127
  ],
75
128
  },
76
- developer_instructions: `${xerjInstructions}\n${serenaInstructions.slice(serenaInstructions.indexOf('<gestalt_serena_'))}`,
77
129
  };
130
+ // A failed read does not establish that the native scalar is empty.
131
+ if (canComposeInstructions)
132
+ config.developer_instructions = combined;
133
+ else
134
+ delete config.developer_instructions;
135
+ return config;
78
136
  },
79
137
  // verify already disables only the failed connection; runtime rebinds the composed config.
80
138
  fallback() { },
@@ -6,6 +6,7 @@
6
6
  import { readFile, realpath } from 'node:fs/promises';
7
7
  import { isAbsolute } from 'node:path';
8
8
  import { sessionScratchEnvironmentKeys } from '../scratch/child-environment.js';
9
+ import { withCapabilityInstructions } from './instruction-blocks.js';
9
10
  import { managedPlaywrightRequestSchema } from '../../../shared/contracts/managed-playwright.js';
10
11
  import { profileCapabilitiesSchema } from '../../../shared/contracts/profile-capabilities.js';
11
12
  import { beforeDeadline } from '../retrieval/codex-xerj.js';
@@ -299,6 +300,10 @@ export class CodexPlaywright {
299
300
  };
300
301
  let available = enabled;
301
302
  const state = {
303
+ get startup() {
304
+ return base.startup;
305
+ },
306
+ prepareFreshStartup: base.prepareFreshStartup?.bind(base),
302
307
  get ready() {
303
308
  return base.ready || available;
304
309
  },
@@ -319,8 +324,16 @@ export class CodexPlaywright {
319
324
  return base.skillsConfig.map((entry) => entry.path === skill?.path ? { ...entry, enabled: false } : entry);
320
325
  },
321
326
  get config() {
322
- return {
323
- ...base.config,
327
+ const baseConfig = base.config;
328
+ const instructions = typeof baseConfig.developer_instructions === 'string'
329
+ ? baseConfig.developer_instructions
330
+ : typeof native.developer_instructions === 'string'
331
+ ? native.developer_instructions
332
+ : compatible
333
+ ? ''
334
+ : undefined;
335
+ const config = {
336
+ ...baseConfig,
324
337
  mcp_servers: {
325
338
  ...base.config.mcp_servers,
326
339
  ...mcp,
@@ -341,8 +354,12 @@ export class CodexPlaywright {
341
354
  { name: 'gestalt:playwright', enabled: false },
342
355
  ],
343
356
  },
344
- developer_instructions: `${base.config.developer_instructions ?? ''}\n<gestalt_playwright_unavailable>Browser guidance is inactive until this host verifies connected standard tools. Use gestalt_managed_playwright for session-scoped requests. Installation or a plan declaration never grants consent. Pending activation requires a safe owned-runtime resume.</gestalt_playwright_unavailable>`,
345
357
  };
358
+ if (instructions !== undefined)
359
+ config.developer_instructions = withCapabilityInstructions(instructions, 'playwright', '<gestalt_playwright_unavailable>Browser guidance is inactive until this host verifies connected standard tools. Use gestalt_managed_playwright for session-scoped requests. Installation or a plan declaration never grants consent. Pending activation requires a safe owned-runtime resume.</gestalt_playwright_unavailable>');
360
+ else
361
+ delete config.developer_instructions;
362
+ return config;
346
363
  },
347
364
  // Each verifier already disables only its failed connection. A shared
348
365
  // fallback must not disable a healthy browser after an XERJ/Serena failure.
@@ -8,6 +8,7 @@ import { sessionScratchEnvironmentKeys } from '../scratch/child-environment.js';
8
8
  import { beforeDeadline, } from '../retrieval/codex-xerj.js';
9
9
  import { ManagedSerena, serenaTools } from './managed-serena.js';
10
10
  import { ReadinessEvidence } from '../retrieval/readiness-evidence.js';
11
+ import { withCapabilityInstructions } from './instruction-blocks.js';
11
12
  export const serenaServerName = 'gestalt-serena';
12
13
  // config/read includes unset defaults as null. Thread overrides cannot encode
13
14
  // those as TOML values; retain explicit settings, including tool approvals.
@@ -32,7 +33,9 @@ export class CodexSerena {
32
33
  let native = {};
33
34
  let compatible = false;
34
35
  try {
35
- const read = (await beforeDeadline(input.rpc.request('config/read', { includeLayers: false }), input.deadline));
36
+ const read = input.nativeConfig !== undefined
37
+ ? { config: input.nativeConfig ?? undefined }
38
+ : (await beforeDeadline(input.rpc.request('config/read', { cwd: input.cwd, includeLayers: false }), input.deadline));
36
39
  native = read.config ?? {};
37
40
  compatible = read.config !== undefined;
38
41
  }
@@ -47,7 +50,11 @@ export class CodexSerena {
47
50
  if (args?.[0] === 'serena' && args[1] === 'mcp')
48
51
  mcp[name] = { ...server, enabled: false, required: false };
49
52
  }
50
- const instructions = typeof native.developer_instructions === 'string' ? native.developer_instructions : '';
53
+ const instructions = typeof input.config.developer_instructions === 'string'
54
+ ? input.config.developer_instructions
55
+ : typeof native.developer_instructions === 'string'
56
+ ? native.developer_instructions
57
+ : '';
51
58
  const state = {
52
59
  evidence,
53
60
  get readiness() {
@@ -64,6 +71,8 @@ export class CodexSerena {
64
71
  ...entry,
65
72
  enabled: entry.path === skill?.path ? false : entry.enabled,
66
73
  }));
74
+ state.instructionBlock =
75
+ '<gestalt_serena_unavailable>\nSerena is unavailable in this runtime. Earlier Serena guidance is inactive; use native code tools.\n</gestalt_serena_unavailable>';
67
76
  state.config = {
68
77
  ...input.config,
69
78
  skills: { config: [{ name: 'gestalt:serena', enabled: false }] },
@@ -80,7 +89,7 @@ export class CodexSerena {
80
89
  required: false,
81
90
  },
82
91
  },
83
- developer_instructions: `${instructions}\n<gestalt_serena_unavailable>\nSerena is unavailable in this runtime. Earlier Serena guidance is inactive; use native code tools.\n</gestalt_serena_unavailable>`,
92
+ developer_instructions: withCapabilityInstructions(instructions, 'serena', state.instructionBlock),
84
93
  };
85
94
  },
86
95
  };
@@ -109,6 +118,7 @@ export class CodexSerena {
109
118
  const guidance = await beforeDeadline(readFile(skill.path, 'utf8'), input.deadline);
110
119
  if (guidance.length > 16_384)
111
120
  return state;
121
+ state.instructionBlock = `<gestalt_serena_capability>\nSerena is bound to this workspace. Connection and listed tools do not prove language readiness. Verify usable symbols on a current source file before semantic editing, and usable references before impact claims. Empty results remain unverified; use native current-source tools when permissions or semantic checks are unknown. Native session and child permissions and approvals apply. Plan mode prohibits edits. Do not switch projects or modes.\n${guidance}\n</gestalt_serena_capability>`;
112
122
  state.config = {
113
123
  ...input.config,
114
124
  skills: { config: [{ name: 'gestalt:serena', enabled: true }] },
@@ -130,7 +140,7 @@ export class CodexSerena {
130
140
  startup_timeout_ms: Math.max(1, input.deadline - Date.now()),
131
141
  },
132
142
  },
133
- developer_instructions: `${instructions}\n<gestalt_serena_capability>\nSerena is bound to this workspace. Connection and listed tools do not prove language readiness. Verify usable symbols on a current source file before semantic editing, and usable references before impact claims. Empty results remain unverified; use native current-source tools when permissions or semantic checks are unknown. Native session and child permissions and approvals apply. Plan mode prohibits edits. Do not switch projects or modes.\n${guidance}\n</gestalt_serena_capability>`,
143
+ developer_instructions: withCapabilityInstructions(instructions, 'serena', state.instructionBlock),
134
144
  };
135
145
  state.skillsConfig = [
136
146
  ...input.skillsConfig.filter((entry) => entry.path !== skill.path),
@@ -0,0 +1,17 @@
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
+ /** Replace only complete blocks owned by this capability, preserving all other bytes. */
7
+ export function withCapabilityInstructions(instructions, capability, block) {
8
+ const pattern = new RegExp(`<gestalt_${capability}_(capability|unavailable)>[\\s\\S]*?</gestalt_${capability}_\\1>`, 'gu');
9
+ let replaced = false;
10
+ const result = instructions.replace(pattern, () => {
11
+ if (replaced)
12
+ return '';
13
+ replaced = true;
14
+ return block;
15
+ });
16
+ return replaced ? result : instructions + (instructions ? '\n' : '') + block;
17
+ }