agl 43.0.3 → 43.0.4

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 (30) hide show
  1. package/changelog.md +11 -0
  2. package/dist_serve/bundle.js +1 -1
  3. package/dist_serve/bundle.js.map +1 -1
  4. package/dist_ts/00_commitinfo_data.js +1 -1
  5. package/dist_ts/classes.flexframedtransport.d.ts +16 -0
  6. package/dist_ts/classes.flexframedtransport.js +35 -20
  7. package/dist_ts/classes.flexservice.d.ts +7 -1
  8. package/dist_ts/classes.flexservice.js +26 -22
  9. package/dist_ts/classes.flexstore.js +4 -1
  10. package/dist_ts/classes.flexsupervisor.d.ts +10 -0
  11. package/dist_ts/classes.flexsupervisor.js +22 -2
  12. package/dist_ts_migration/classes.flexpostharnessmigrationrunner.d.ts +9 -0
  13. package/dist_ts_migration/classes.flexpostharnessmigrationrunner.js +24 -5
  14. package/dist_ts_migration/index.d.ts +1 -0
  15. package/dist_ts_migration/index.js +2 -1
  16. package/dist_ts_migration/v19_flexprojectmanagement.d.ts +3 -0
  17. package/dist_ts_migration/v19_flexprojectmanagement.js +3 -1
  18. package/dist_ts_migration/v43_flexpostharnessmigrationmarkers.d.ts +44 -0
  19. package/dist_ts_migration/v43_flexpostharnessmigrationmarkers.js +146 -0
  20. package/package.json +1 -1
  21. package/ts/00_commitinfo_data.ts +1 -1
  22. package/ts/classes.flexframedtransport.ts +42 -17
  23. package/ts/classes.flexservice.ts +36 -27
  24. package/ts/classes.flexstore.ts +6 -0
  25. package/ts/classes.flexsupervisor.ts +28 -1
  26. package/ts_migration/classes.flexpostharnessmigrationrunner.ts +37 -5
  27. package/ts_migration/index.ts +1 -0
  28. package/ts_migration/v19_flexprojectmanagement.ts +4 -0
  29. package/ts_migration/v43_flexpostharnessmigrationmarkers.ts +109 -0
  30. package/ts_web/00_commitinfo_data.ts +1 -1
@@ -0,0 +1,146 @@
1
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
2
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
3
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
4
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
5
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
6
+ var _, done = false;
7
+ for (var i = decorators.length - 1; i >= 0; i--) {
8
+ var context = {};
9
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
10
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
11
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
12
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
13
+ if (kind === "accessor") {
14
+ if (result === void 0) continue;
15
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
16
+ if (_ = accept(result.get)) descriptor.get = _;
17
+ if (_ = accept(result.set)) descriptor.set = _;
18
+ if (_ = accept(result.init)) initializers.unshift(_);
19
+ }
20
+ else if (_ = accept(result)) {
21
+ if (kind === "field") initializers.unshift(_);
22
+ else descriptor[key] = _;
23
+ }
24
+ }
25
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
26
+ done = true;
27
+ };
28
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
29
+ var useValue = arguments.length > 2;
30
+ for (var i = 0; i < initializers.length; i++) {
31
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
32
+ }
33
+ return useValue ? value : void 0;
34
+ };
35
+ import * as plugins from './plugins.js';
36
+ const markerSchema = plugins.z.object({
37
+ id: plugins.z.string().regex(/^flex-post-harness-migration:[0-9a-f]{64}$/u),
38
+ controllerId: plugins.z.string().min(1).max(512),
39
+ storageKey: plugins.z.string().min(1).max(512),
40
+ migration: plugins.z.string().regex(/^v[0-9]+_[a-z0-9]+$/u),
41
+ completedAt: plugins.z.iso.datetime(),
42
+ }).strict();
43
+ export const flexPostHarnessMigrationMarkerId = (controllerIdArg, storageKeyArg, migrationArg) => `flex-post-harness-migration:${plugins.crypto.createHash('sha256')
44
+ .update(controllerIdArg, 'utf8')
45
+ .update('\0', 'utf8')
46
+ .update(storageKeyArg, 'utf8')
47
+ .update('\0', 'utf8')
48
+ .update(migrationArg, 'utf8')
49
+ .digest('hex')}`;
50
+ /**
51
+ * One record per post-harness migration and storage key, written once the migration walked every
52
+ * session of that key: a key with a marker is never walked again, by any later Flex child. A walk
53
+ * that failed or was aborted records nothing, so the next registration walks the key again.
54
+ */
55
+ let FlexPostHarnessMigrationMarkerModel = (() => {
56
+ let _classDecorators = [plugins.nosqldb.managed({ collectionName: 'flex_post_harness_migrations' }), plugins.nosqldb.exactPersistence({ assertDocument: (input) => { markerSchema.parse(input); } })];
57
+ let _classDescriptor;
58
+ let _classExtraInitializers = [];
59
+ let _classThis;
60
+ let _classSuper = plugins.nosqldb.SmartDataDbDoc;
61
+ let _id_decorators;
62
+ let _id_initializers = [];
63
+ let _id_extraInitializers = [];
64
+ let _controllerId_decorators;
65
+ let _controllerId_initializers = [];
66
+ let _controllerId_extraInitializers = [];
67
+ let _storageKey_decorators;
68
+ let _storageKey_initializers = [];
69
+ let _storageKey_extraInitializers = [];
70
+ let _migration_decorators;
71
+ let _migration_initializers = [];
72
+ let _migration_extraInitializers = [];
73
+ let _completedAt_decorators;
74
+ let _completedAt_initializers = [];
75
+ let _completedAt_extraInitializers = [];
76
+ var FlexPostHarnessMigrationMarkerModel = class extends _classSuper {
77
+ static { _classThis = this; }
78
+ static {
79
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
80
+ _id_decorators = [plugins.nosqldb.unI()];
81
+ _controllerId_decorators = [plugins.nosqldb.svDb()];
82
+ _storageKey_decorators = [plugins.nosqldb.svDb()];
83
+ _migration_decorators = [plugins.nosqldb.svDb()];
84
+ _completedAt_decorators = [plugins.nosqldb.svDb()];
85
+ __esDecorate(null, null, _id_decorators, { kind: "field", name: "id", static: false, private: false, access: { has: obj => "id" in obj, get: obj => obj.id, set: (obj, value) => { obj.id = value; } }, metadata: _metadata }, _id_initializers, _id_extraInitializers);
86
+ __esDecorate(null, null, _controllerId_decorators, { kind: "field", name: "controllerId", static: false, private: false, access: { has: obj => "controllerId" in obj, get: obj => obj.controllerId, set: (obj, value) => { obj.controllerId = value; } }, metadata: _metadata }, _controllerId_initializers, _controllerId_extraInitializers);
87
+ __esDecorate(null, null, _storageKey_decorators, { kind: "field", name: "storageKey", static: false, private: false, access: { has: obj => "storageKey" in obj, get: obj => obj.storageKey, set: (obj, value) => { obj.storageKey = value; } }, metadata: _metadata }, _storageKey_initializers, _storageKey_extraInitializers);
88
+ __esDecorate(null, null, _migration_decorators, { kind: "field", name: "migration", static: false, private: false, access: { has: obj => "migration" in obj, get: obj => obj.migration, set: (obj, value) => { obj.migration = value; } }, metadata: _metadata }, _migration_initializers, _migration_extraInitializers);
89
+ __esDecorate(null, null, _completedAt_decorators, { kind: "field", name: "completedAt", static: false, private: false, access: { has: obj => "completedAt" in obj, get: obj => obj.completedAt, set: (obj, value) => { obj.completedAt = value; } }, metadata: _metadata }, _completedAt_initializers, _completedAt_extraInitializers);
90
+ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
91
+ FlexPostHarnessMigrationMarkerModel = _classThis = _classDescriptor.value;
92
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
93
+ __runInitializers(_classThis, _classExtraInitializers);
94
+ }
95
+ id = __runInitializers(this, _id_initializers, void 0);
96
+ controllerId = (__runInitializers(this, _id_extraInitializers), __runInitializers(this, _controllerId_initializers, void 0));
97
+ storageKey = (__runInitializers(this, _controllerId_extraInitializers), __runInitializers(this, _storageKey_initializers, void 0));
98
+ migration = (__runInitializers(this, _storageKey_extraInitializers), __runInitializers(this, _migration_initializers, void 0));
99
+ completedAt = (__runInitializers(this, _migration_extraInitializers), __runInitializers(this, _completedAt_initializers, void 0));
100
+ constructor() {
101
+ super(...arguments);
102
+ __runInitializers(this, _completedAt_extraInitializers);
103
+ }
104
+ };
105
+ return FlexPostHarnessMigrationMarkerModel = _classThis;
106
+ })();
107
+ export { FlexPostHarnessMigrationMarkerModel };
108
+ export const registerFlexPostHarnessMigrationMarkerModel = (managerArg) => {
109
+ plugins.nosqldb.setDefaultManagerForDoc(managerArg, FlexPostHarnessMigrationMarkerModel);
110
+ };
111
+ export const initFlexPostHarnessMigrationMarkerModel = async () => {
112
+ await FlexPostHarnessMigrationMarkerModel.exact.prepare();
113
+ };
114
+ /** The markers of one controller, in its Flex database's `flex_post_harness_migrations`. */
115
+ export class FlexPostHarnessMigrationMarkers {
116
+ controllerId;
117
+ constructor(controllerId) {
118
+ this.controllerId = controllerId;
119
+ }
120
+ async completed(storageKeyArg, migrationArg) {
121
+ const id = flexPostHarnessMigrationMarkerId(this.controllerId, storageKeyArg, migrationArg);
122
+ const stored = await FlexPostHarnessMigrationMarkerModel.exact.findStoredOne({ id });
123
+ if (!stored)
124
+ return false;
125
+ const marker = FlexPostHarnessMigrationMarkerModel.exact.toPersisted(stored);
126
+ if (marker.controllerId !== this.controllerId
127
+ || marker.storageKey !== storageKeyArg
128
+ || marker.migration !== migrationArg)
129
+ throw new Error('The Flex post-harness migration marker names another migration.');
130
+ return true;
131
+ }
132
+ async record(storageKeyArg, migrationArg) {
133
+ const inserted = await FlexPostHarnessMigrationMarkerModel.exact.insert({
134
+ id: flexPostHarnessMigrationMarkerId(this.controllerId, storageKeyArg, migrationArg),
135
+ controllerId: this.controllerId,
136
+ storageKey: storageKeyArg,
137
+ migration: migrationArg,
138
+ completedAt: new Date().toISOString(),
139
+ });
140
+ // A conflict is a marker with the same id recorded earlier, with its own completion time.
141
+ if (inserted.status === 'conflict' && !await this.completed(storageKeyArg, migrationArg)) {
142
+ throw new Error('The Flex post-harness migration marker could not be recorded.');
143
+ }
144
+ }
145
+ }
146
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidjQzX2ZsZXhwb3N0aGFybmVzc21pZ3JhdGlvbm1hcmtlcnMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi90c19taWdyYXRpb24vdjQzX2ZsZXhwb3N0aGFybmVzc21pZ3JhdGlvbm1hcmtlcnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztBQUFBLE9BQU8sS0FBSyxPQUFPLE1BQU0sY0FBYyxDQUFDO0FBZ0J4QyxNQUFNLFlBQVksR0FBRyxPQUFPLENBQUMsQ0FBQyxDQUFDLE1BQU0sQ0FBQztJQUNwQyxFQUFFLEVBQUUsT0FBTyxDQUFDLENBQUMsQ0FBQyxNQUFNLEVBQUUsQ0FBQyxLQUFLLENBQUMsNkNBQTZDLENBQUM7SUFDM0UsWUFBWSxFQUFFLE9BQU8sQ0FBQyxDQUFDLENBQUMsTUFBTSxFQUFFLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxDQUFDLEdBQUcsQ0FBQyxHQUFHLENBQUM7SUFDaEQsVUFBVSxFQUFFLE9BQU8sQ0FBQyxDQUFDLENBQUMsTUFBTSxFQUFFLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxDQUFDLEdBQUcsQ0FBQyxHQUFHLENBQUM7SUFDOUMsU0FBUyxFQUFFLE9BQU8sQ0FBQyxDQUFDLENBQUMsTUFBTSxFQUFFLENBQUMsS0FBSyxDQUFDLHNCQUFzQixDQUFDO0lBQzNELFdBQVcsRUFBRSxPQUFPLENBQUMsQ0FBQyxDQUFDLEdBQUcsQ0FB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USxDQUFDLE1BQU0sS0FBSyxVQUFVLElBQUksQ0FBQyxNQUFNLElBQUksQ0FBQyxTQUFTLENBQUMsYUFBYSxFQUFFLFlBQVksQ0FBQyxFQUFFLENBQUM7WUFDekYsTUFBTSxJQUFJLEtBQUssQ0FBQywrREFBK0QsQ0FBQyxDQUFDO1FBQ25GLENBQUM7SUFDSCxDQUFDO0NBQ0YifQ==
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agl",
3
- "version": "43.0.3",
3
+ "version": "43.0.4",
4
4
  "controllerUpgradeManagementVersion": 2,
5
5
  "controllerManagementProtocolVersion": 1,
6
6
  "controllerGatewaySourcesVersion": 1,
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: 'agl',
6
- version: '43.0.3',
6
+ version: '43.0.4',
7
7
  description: 'Agent Gateway Layer for OpenCode, FlexHarness, and Codex sessions'
8
8
  }
@@ -16,6 +16,14 @@ type TCloseListener = () => void;
16
16
  export const flexIpcMaximumQueuedFrames = 128;
17
17
  export const flexIpcMaximumQueuedFrameBytes = 64 * 1024 * 1024;
18
18
  const flexIpcCloseDrainTimeoutMs = 2_000;
19
+ const flexIpcMaximumIgnoredStreamErrors = 16;
20
+
21
+ /** A stream error that reached the transport after it closed or failed: recorded, never acted on. */
22
+ export interface IFlexIgnoredStreamError {
23
+ stream: 'readable' | 'writable';
24
+ code?: string;
25
+ timestamp: number;
26
+ }
19
27
 
20
28
  const normalizeMaximumFrameBytes = (valueArg: number | undefined): number => {
21
29
  const selected = valueArg ?? flexIpcMaximumFrameBytes;
@@ -90,6 +98,11 @@ export const encodeFlexFrame = (
90
98
  /**
91
99
  * A single-reader/single-writer JSON transport. The body buffer is allocated
92
100
  * only after the fixed header has passed the configured length limit.
101
+ *
102
+ * Each stream keeps an 'error' listener from construction for as long as it exists: an 'error' event
103
+ * without a listener throws, and a stream outlives the transport's close (a pipe socket keeps reading
104
+ * until its peer is gone, and a peer killed with unread frames resets it). Before close or failure
105
+ * a stream error fails the transport; after it, the listener records the error and ignores it.
93
106
  */
94
107
  export class FlexFramedTransport<TIncoming, TOutgoing> {
95
108
  private readonly readable: plugins.stream.Readable;
@@ -110,6 +123,7 @@ export class FlexFramedTransport<TIncoming, TOutgoing> {
110
123
  private failed = false;
111
124
  private closed = false;
112
125
  private closePromise?: Promise<void>;
126
+ private readonly ignoredStreamErrors: IFlexIgnoredStreamError[] = [];
113
127
 
114
128
  constructor(optionsArg: IFlexFramedTransportOptions<TIncoming, TOutgoing>) {
115
129
  this.readable = optionsArg.readable;
@@ -118,10 +132,10 @@ export class FlexFramedTransport<TIncoming, TOutgoing> {
118
132
  this.validateOutgoing = optionsArg.validateOutgoing;
119
133
  this.maximumFrameBytes = normalizeMaximumFrameBytes(optionsArg.maximumFrameBytes);
120
134
  this.readable.on('data', this.onData);
121
- this.readable.once('error', this.onReadError);
135
+ this.readable.on('error', this.onReadError);
122
136
  this.readable.once('end', this.onReadableClosed);
123
137
  this.readable.once('close', this.onReadableClosed);
124
- this.writable.once('error', this.onWriteError);
138
+ this.writable.on('error', this.onWriteError);
125
139
  this.writable.once('finish', this.onWritableClosed);
126
140
  this.writable.once('close', this.onWritableClosed);
127
141
  }
@@ -141,6 +155,11 @@ export class FlexFramedTransport<TIncoming, TOutgoing> {
141
155
  return () => this.closeListeners.delete(listenerArg);
142
156
  }
143
157
 
158
+ /** The stream errors that arrived after the transport closed or failed, oldest first, the last 16. */
159
+ public getIgnoredStreamErrors(): IFlexIgnoredStreamError[] {
160
+ return this.ignoredStreamErrors.map((entryArg) => ({ ...entryArg }));
161
+ }
162
+
144
163
  /**
145
164
  * Writes one frame after the frames before it. Every refusal before the frame's first byte reaches
146
165
  * the stream throws `FlexIpcNotSentError`; a failure of the write itself may come after bytes went
@@ -189,9 +208,11 @@ export class FlexFramedTransport<TIncoming, TOutgoing> {
189
208
  private async closeTransport(): Promise<void> {
190
209
  this.closed = true;
191
210
  this.detachStreams();
211
+ // Inbound frames are discarded once closed, so the reader goes at once; only the writer drains.
212
+ if (!this.readable.destroyed) this.readable.destroy();
192
213
  let drainTimer: ReturnType<typeof setTimeout> | undefined;
193
- const drainTimeout = new Promise<'timeout'>((resolve) => {
194
- drainTimer = setTimeout(() => resolve('timeout'), flexIpcCloseDrainTimeoutMs);
214
+ const drainTimeout = new Promise<void>((resolve) => {
215
+ drainTimer = setTimeout(resolve, flexIpcCloseDrainTimeoutMs);
195
216
  drainTimer.unref?.();
196
217
  });
197
218
  const gracefulClose = this.writeTail.then(async () => {
@@ -200,20 +221,14 @@ export class FlexFramedTransport<TIncoming, TOutgoing> {
200
221
  this.writable.end(resolve);
201
222
  });
202
223
  }
203
- return 'drained' as const;
204
224
  });
205
- const drainResult = await Promise.race([
225
+ await Promise.race([
206
226
  gracefulClose,
207
227
  drainTimeout,
208
228
  ]);
209
229
  if (drainTimer) clearTimeout(drainTimer);
210
- if (drainResult === 'timeout') {
211
- if (!this.writable.destroyed) this.writable.destroy();
212
- if (!this.readable.destroyed) this.readable.destroy();
213
- this.emitClose();
214
- return;
215
- }
216
- if (!this.readable.destroyed) this.readable.destroy();
230
+ // Drained or not, the writer goes too: a pipe socket ended for writing still reads from its peer.
231
+ if (!this.writable.destroyed) this.writable.destroy();
217
232
  this.emitClose();
218
233
  }
219
234
 
@@ -292,8 +307,19 @@ export class FlexFramedTransport<TIncoming, TOutgoing> {
292
307
  });
293
308
  }
294
309
 
295
- private readonly onReadError = (errorArg: Error): void => this.fail(errorArg);
296
- private readonly onWriteError = (errorArg: Error): void => this.fail(errorArg);
310
+ private readonly onReadError = (errorArg: Error): void => this.handleStreamError('readable', errorArg);
311
+ private readonly onWriteError = (errorArg: Error): void => this.handleStreamError('writable', errorArg);
312
+
313
+ private handleStreamError(streamArg: IFlexIgnoredStreamError['stream'], errorArg: Error): void {
314
+ if (!this.closed && !this.failed) {
315
+ this.fail(errorArg);
316
+ return;
317
+ }
318
+ const code = 'code' in errorArg && typeof errorArg.code === 'string' ? errorArg.code : undefined;
319
+ this.ignoredStreamErrors.push({ stream: streamArg, ...(code ? { code } : {}), timestamp: Date.now() });
320
+ if (this.ignoredStreamErrors.length > flexIpcMaximumIgnoredStreamErrors) this.ignoredStreamErrors.shift();
321
+ }
322
+
297
323
  private readonly onReadableClosed = (): void => {
298
324
  if (this.closed) return;
299
325
  if (this.headerOffset !== 0 || this.body) {
@@ -326,12 +352,11 @@ export class FlexFramedTransport<TIncoming, TOutgoing> {
326
352
  this.emitClose();
327
353
  }
328
354
 
355
+ /** Removes every stream listener but the error listeners, which stay for as long as the streams exist. */
329
356
  private detachStreams(): void {
330
357
  this.readable.removeListener('data', this.onData);
331
- this.readable.removeListener('error', this.onReadError);
332
358
  this.readable.removeListener('end', this.onReadableClosed);
333
359
  this.readable.removeListener('close', this.onReadableClosed);
334
- this.writable.removeListener('error', this.onWriteError);
335
360
  this.writable.removeListener('finish', this.onWritableClosed);
336
361
  this.writable.removeListener('close', this.onWritableClosed);
337
362
  }
@@ -8,6 +8,10 @@ import {
8
8
  import { FlexStore, type IFlexProjectManagementHost } from './classes.flexstore.js';
9
9
  import { FlexPersistenceMigrationRunner } from '../ts_migration/classes.flexmigrationrunner.js';
10
10
  import { FlexPostHarnessMigrationRunner } from '../ts_migration/classes.flexpostharnessmigrationrunner.js';
11
+ import {
12
+ FlexPostHarnessMigrationMarkers,
13
+ type IFlexPostHarnessMigrationMarkers,
14
+ } from '../ts_migration/v43_flexpostharnessmigrationmarkers.js';
11
15
  import {
12
16
  assertCanonicalDirectory,
13
17
  CanonicalDirectoryError,
@@ -718,7 +722,8 @@ export class FlexService {
718
722
  (errorArg, contextArg) => this.projectRunFailure(errorArg, contextArg),
719
723
  );
720
724
  private readonly pendingProjectRegistrations = new Set<string>();
721
- private readonly postHarnessMigratedProjects = new Set<string>();
725
+ /** Which projects' post-harness migrations completed, read by every child generation. */
726
+ private postHarnessMigrationMarkers?: IFlexPostHarnessMigrationMarkers;
722
727
  private readonly pendingProjectRetirements = new Set<string>();
723
728
  private readonly pendingProjectRemovals = new Map<string, IFlexPendingProjectRemoval>();
724
729
  private readonly projectRegistrationMigrationContext =
@@ -958,6 +963,7 @@ export class FlexService {
958
963
  });
959
964
  this.store = store;
960
965
  await store.init();
966
+ this.postHarnessMigrationMarkers = new FlexPostHarnessMigrationMarkers(initArg.controllerId);
961
967
  const activeProjectIds = new Set(this.projects.keys());
962
968
  await new FlexPersistenceMigrationRunner({
963
969
  store,
@@ -5414,16 +5420,7 @@ export class FlexService {
5414
5420
  const current = this.projects.get(projectId);
5415
5421
  if (current) {
5416
5422
  if (!flexProjectDirectoriesEqual(current, projectArg)) throw new FlexServiceError('CONFLICT');
5417
- if (!this.postHarnessMigratedProjects.has(projectId)) {
5418
- await this.projectRegistrationMigrationContext.run(
5419
- { projectId, registrationOperationId: registrationOperationIdArg },
5420
- () => new FlexPostHarnessMigrationRunner({
5421
- harness: harnessArg,
5422
- scopeIds: [projectId],
5423
- }).run(signalArg),
5424
- );
5425
- this.postHarnessMigratedProjects.add(projectId);
5426
- }
5423
+ await this.runPostHarnessMigrations(projectId, registrationOperationIdArg, harnessArg, signalArg);
5427
5424
  return false;
5428
5425
  }
5429
5426
  // Registrations of other projects run concurrently, so a pending one holds its place in the
@@ -5433,7 +5430,7 @@ export class FlexService {
5433
5430
  if (this.projects.size + pendingAdditions >= controllerProjectLimit) {
5434
5431
  throw new FlexServiceError('LIMIT_EXCEEDED');
5435
5432
  }
5436
- if (!this.store) throw new FlexServiceError('NOT_READY');
5433
+ if (!this.store || !this.postHarnessMigrationMarkers) throw new FlexServiceError('NOT_READY');
5437
5434
 
5438
5435
  this.pendingProjectRegistrations.add(projectId);
5439
5436
  const project = structuredClone(projectArg);
@@ -5446,19 +5443,10 @@ export class FlexService {
5446
5443
  signalArg.throwIfAborted();
5447
5444
  this.projects.set(projectId, project);
5448
5445
  temporarilyVisible = true;
5449
- await this.projectRegistrationMigrationContext.run(
5450
- { projectId, registrationOperationId: registrationOperationIdArg },
5451
- () => new FlexPostHarnessMigrationRunner({
5452
- harness: harnessArg,
5453
- scopeIds: [projectId],
5454
- }).run(signalArg),
5455
- );
5456
- this.postHarnessMigratedProjects.add(projectId);
5457
- const sessions = await harnessArg.listSessions(projectId);
5458
- for (const session of sessions) {
5459
- signalArg.throwIfAborted();
5460
- await harnessArg.getSessionReversionInfo(projectId, session.sessionId);
5461
- }
5446
+ // FlexHarness recovers every session's reversion state when it loads the project's namespace,
5447
+ // on the project's first request; reading it adds only a check, which runs when a session is
5448
+ // opened (`session.reversion.info`, sent by `controller.slash.list`). Registration walks none.
5449
+ await this.runPostHarnessMigrations(projectId, registrationOperationIdArg, harnessArg, signalArg);
5462
5450
  signalArg.throwIfAborted();
5463
5451
  return true;
5464
5452
  } catch (errorArg) {
@@ -5471,6 +5459,28 @@ export class FlexService {
5471
5459
  }
5472
5460
  }
5473
5461
 
5462
+ /**
5463
+ * The project's post-harness migrations, each walked only until it completed once for the
5464
+ * project: its persisted marker spares every later child generation the per-session walk.
5465
+ */
5466
+ private async runPostHarnessMigrations(
5467
+ projectIdArg: string,
5468
+ registrationOperationIdArg: string,
5469
+ harnessArg: TFlexHarness<IFlexProjectScope>,
5470
+ signalArg: AbortSignal,
5471
+ ): Promise<void> {
5472
+ const markers = this.postHarnessMigrationMarkers;
5473
+ if (!markers) throw new FlexServiceError('NOT_READY');
5474
+ await this.projectRegistrationMigrationContext.run(
5475
+ { projectId: projectIdArg, registrationOperationId: registrationOperationIdArg },
5476
+ () => new FlexPostHarnessMigrationRunner({
5477
+ harness: harnessArg,
5478
+ markers,
5479
+ scopeIds: [projectIdArg],
5480
+ }).run(signalArg),
5481
+ );
5482
+ }
5483
+
5474
5484
  private async removeProject(
5475
5485
  projectArg: IFlexIdentityBoundProjectRecord,
5476
5486
  removalOperationIdArg: string,
@@ -5524,7 +5534,6 @@ export class FlexService {
5524
5534
  signalArg.throwIfAborted();
5525
5535
  await this.deleteModelChoiceForScope(projectId);
5526
5536
  this.projects.delete(projectId);
5527
- this.postHarnessMigratedProjects.delete(projectId);
5528
5537
  this.deleteProjectUploadGrants(projectId);
5529
5538
  for (const key of this.promptStages.keys()) if (key.startsWith(`${projectId}\0`)) this.promptStages.delete(key);
5530
5539
  for (const [key, event] of this.sessionChangeQueue.entries()) {
@@ -5684,7 +5693,7 @@ export class FlexService {
5684
5693
  this.pendingProjectRegistrations.clear();
5685
5694
  this.pendingProjectRetirements.clear();
5686
5695
  this.pendingProjectRemovals.clear();
5687
- this.postHarnessMigratedProjects.clear();
5696
+ this.postHarnessMigrationMarkers = undefined;
5688
5697
  this.catalogCache.clear();
5689
5698
  this.claudePoolCatalog = undefined;
5690
5699
  this.jobs.clear();
@@ -2,6 +2,10 @@ import * as plugins from './plugins.js';
2
2
  import { FlexOrphanIndexV33Migration } from '../ts_migration/v33_flexorphanindexes.js';
3
3
  import { FlexLegacyPublicationV38Migration } from '../ts_migration/v38_flextranscripts.js';
4
4
  import { FlexPublicHeadPointerV39Migration } from '../ts_migration/v39_flexpublicheadpointers.js';
5
+ import {
6
+ initFlexPostHarnessMigrationMarkerModel,
7
+ registerFlexPostHarnessMigrationMarkerModel,
8
+ } from '../ts_migration/v43_flexpostharnessmigrationmarkers.js';
5
9
  import {
6
10
  FlexDomainHeadModel,
7
11
  FlexHeadModel,
@@ -1288,6 +1292,7 @@ export class FlexStore implements plugins.flexharness.IFlexHarnessStores {
1288
1292
  this.manager = { db: this.database };
1289
1293
  registerFlexPrivateModels(this.manager);
1290
1294
  registerFlexPublicModels(this.manager);
1295
+ registerFlexPostHarnessMigrationMarkerModel(this.manager);
1291
1296
 
1292
1297
  this.scopes = {
1293
1298
  load: (storageKey) => this.loadScope(storageKey),
@@ -1366,6 +1371,7 @@ export class FlexStore implements plugins.flexharness.IFlexHarnessStores {
1366
1371
  await new FlexPublicHeadPointerV39Migration(this.database, this.controllerId).run();
1367
1372
  await initFlexPrivateModels();
1368
1373
  await initFlexPublicModels();
1374
+ await initFlexPostHarnessMigrationMarkerModel();
1369
1375
  this.initialized = true;
1370
1376
  this.queueOrphanMaintenance();
1371
1377
  })();
@@ -70,6 +70,13 @@ export interface IFlexSupervisorLogEntry {
70
70
  truncated: boolean;
71
71
  }
72
72
 
73
+ /** An error of a child's log pipe, or of a started child process, the supervisor recorded and ignored. */
74
+ export interface IFlexSupervisorIgnoredError {
75
+ source: 'stdout' | 'stderr' | 'process';
76
+ code?: string;
77
+ timestamp: number;
78
+ }
79
+
73
80
  export interface IFlexSupervisorOptions {
74
81
  onChildExitObserved?: (exitArg: IFlexSupervisorExit) => void;
75
82
  onChildExit?: (exitArg: IFlexSupervisorExit) => void;
@@ -152,6 +159,7 @@ interface ILogAccumulator {
152
159
  }
153
160
 
154
161
  const supervisorLogEntries = 200;
162
+ const supervisorIgnoredErrorEntries = 16;
155
163
  const supervisorLogLineBytes = 8 * 1024;
156
164
  const supervisorTermTimeoutMs = 5_000;
157
165
  const supervisorKillTimeoutMs = 2_000;
@@ -317,6 +325,7 @@ export class FlexSupervisor {
317
325
  private readonly settledHostRequestIds = new Set<string>();
318
326
  private readonly eventListeners = new Set<(eventArg: TFlexChildEvent) => void>();
319
327
  private readonly logs: IFlexSupervisorLogEntry[] = [];
328
+ private readonly ignoredChildErrors: IFlexSupervisorIgnoredError[] = [];
320
329
  private readonly stdoutAccumulator: ILogAccumulator = {
321
330
  decoder: new TextDecoder(), partial: '', dropping: false,
322
331
  };
@@ -355,6 +364,11 @@ export class FlexSupervisor {
355
364
  return this.logs.map((entry) => ({ ...entry }));
356
365
  }
357
366
 
367
+ /** The child log-pipe and started-process errors the supervisor ignored, oldest first, the last 16. */
368
+ public getIgnoredChildErrors(): IFlexSupervisorIgnoredError[] {
369
+ return this.ignoredChildErrors.map((entry) => ({ ...entry }));
370
+ }
371
+
358
372
  public ownsChildPeer(peerIdArg: string): boolean {
359
373
  return this.browserPeerId !== ''
360
374
  && this.browserPeerId === peerIdArg
@@ -1365,8 +1379,12 @@ export class FlexSupervisor {
1365
1379
  }
1366
1380
 
1367
1381
  private observeChild(childArg: plugins.childProcess.ChildProcess): Promise<IFlexChildLifecycle> {
1382
+ // The log pipes and the process keep their error listeners for as long as they exist: an error
1383
+ // event without a listener throws, and the child's lifecycle never depends on its log pipes.
1368
1384
  childArg.stdout?.on('data', (chunk) => this.consumeLog('stdout', chunk, this.stdoutAccumulator));
1385
+ childArg.stdout?.on('error', (errorArg) => this.recordIgnoredChildError('stdout', errorArg));
1369
1386
  childArg.stderr?.on('data', (chunk) => this.consumeLog('stderr', chunk, this.stderrAccumulator));
1387
+ childArg.stderr?.on('error', (errorArg) => this.recordIgnoredChildError('stderr', errorArg));
1370
1388
  return new Promise((resolve) => {
1371
1389
  let settled = false;
1372
1390
  const finish = (outcomeArg: IFlexChildLifecycle): void => {
@@ -1415,12 +1433,21 @@ export class FlexSupervisor {
1415
1433
  resolve(outcomeArg);
1416
1434
  };
1417
1435
  childArg.once('exit', (code, signal) => finish({ type: 'exit', code, signal }));
1418
- childArg.once('error', (error) => {
1436
+ childArg.on('error', (error) => {
1437
+ // A child without a process ID never started, and its error is its outcome; a started
1438
+ // child's error (a failed signal) leaves its lifecycle to its exit.
1419
1439
  if (!childArg.pid) finish({ type: 'error', error });
1440
+ else this.recordIgnoredChildError('process', error);
1420
1441
  });
1421
1442
  });
1422
1443
  }
1423
1444
 
1445
+ private recordIgnoredChildError(sourceArg: IFlexSupervisorIgnoredError['source'], errorArg: Error): void {
1446
+ const code = 'code' in errorArg && typeof errorArg.code === 'string' ? errorArg.code : undefined;
1447
+ this.ignoredChildErrors.push({ source: sourceArg, ...(code ? { code } : {}), timestamp: Date.now() });
1448
+ if (this.ignoredChildErrors.length > supervisorIgnoredErrorEntries) this.ignoredChildErrors.shift();
1449
+ }
1450
+
1424
1451
  private async reapOrphanedGroup(processGroupIdArg: number): Promise<void> {
1425
1452
  if (!isProcessGroupAlive(processGroupIdArg)) return;
1426
1453
  signalProcessGroup(processGroupIdArg, 'SIGTERM');
@@ -1,22 +1,54 @@
1
1
  import * as plugins from './plugins.js';
2
- import { FlexProjectManagementMigration } from './v19_flexprojectmanagement.js';
2
+ import {
3
+ FlexProjectManagementMigration,
4
+ flexProjectManagementMigrationId,
5
+ } from './v19_flexprojectmanagement.js';
6
+ import type {
7
+ IFlexPostHarnessMigrationMarkers,
8
+ TFlexPostHarnessMigrationId,
9
+ } from './v43_flexpostharnessmigrationmarkers.js';
3
10
 
4
11
  export interface IFlexPostHarnessMigrationRunnerOptions<TScope> {
5
12
  harness: plugins.flexharness.FlexHarness<TScope>;
13
+ /** The storage keys each migration already completed for, which it never walks again. */
14
+ markers: IFlexPostHarnessMigrationMarkers;
6
15
  scopeIds: Iterable<string>;
7
16
  }
8
17
 
18
+ interface IFlexPostHarnessMigration {
19
+ readonly id: TFlexPostHarnessMigrationId;
20
+ run(scopeIdArg: string, signalArg?: AbortSignal): Promise<void>;
21
+ }
22
+
23
+ /**
24
+ * Runs each post-harness migration for every storage key it has not completed for, and records
25
+ * the completion only once the key's walk finished: a failed or aborted walk records nothing.
26
+ */
9
27
  export class FlexPostHarnessMigrationRunner<TScope> {
10
- private readonly migrations: Array<{ run(signalArg?: AbortSignal): Promise<void> }>;
28
+ private readonly markers: IFlexPostHarnessMigrationMarkers;
29
+ private readonly scopeIds: string[];
30
+ private readonly migrations: IFlexPostHarnessMigration[];
11
31
 
12
32
  constructor(optionsArg: IFlexPostHarnessMigrationRunnerOptions<TScope>) {
13
- this.migrations = [new FlexProjectManagementMigration(optionsArg)];
33
+ this.markers = optionsArg.markers;
34
+ this.scopeIds = [...new Set(optionsArg.scopeIds)].sort();
35
+ this.migrations = [{
36
+ id: flexProjectManagementMigrationId,
37
+ run: (scopeIdArg, signalArg) => new FlexProjectManagementMigration({
38
+ harness: optionsArg.harness,
39
+ scopeIds: [scopeIdArg],
40
+ }).run(signalArg),
41
+ }];
14
42
  }
15
43
 
16
44
  public async run(signalArg?: AbortSignal): Promise<void> {
17
45
  for (const migration of this.migrations) {
18
- signalArg?.throwIfAborted();
19
- await migration.run(signalArg);
46
+ for (const scopeId of this.scopeIds) {
47
+ signalArg?.throwIfAborted();
48
+ if (await this.markers.completed(scopeId, migration.id)) continue;
49
+ await migration.run(scopeId, signalArg);
50
+ await this.markers.record(scopeId, migration.id);
51
+ }
20
52
  }
21
53
  }
22
54
  }
@@ -30,3 +30,4 @@ export * from './v39_flexpublicheadpointers.js';
30
30
  export * from './v41_ticketmigrationmarkers.js';
31
31
  export * from './v41_ticketclosedcolumn.js';
32
32
  export * from './v41_ticketlinkrepos.js';
33
+ export * from './v43_flexpostharnessmigrationmarkers.js';
@@ -1,4 +1,8 @@
1
1
  import * as plugins from './plugins.js';
2
+ import type { TFlexPostHarnessMigrationId } from './v43_flexpostharnessmigrationmarkers.js';
3
+
4
+ /** The name its completion is recorded under (`FlexPostHarnessMigrationMarkers`). */
5
+ export const flexProjectManagementMigrationId: TFlexPostHarnessMigrationId = 'v19_flexprojectmanagement';
2
6
 
3
7
  export interface IFlexProjectManagementMigrationOptions<TScope> {
4
8
  harness: plugins.flexharness.FlexHarness<TScope>;