pi-better-server 0.7.1 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/runtime/background-tools.ts +2 -1
- package/src/runtime/domain/background/registry.mjs +3 -0
- package/src/runtime/domain/background/shared-operation-coordinator/src/task-lifetime.mjs +6 -0
- package/src/runtime/domain/background/terminal-publication.mjs +5 -2
- package/src/runtime/domain/background-service/managed-authority.domain.mjs +13 -0
- package/src/runtime/domain/background-service/managed-authority.ts +16 -0
- package/src/runtime/domain/background-service/managed-client.domain.mjs +2 -2
- package/src/runtime/domain/background-service/managed-client.ts +2 -2
- package/src/runtime/domain/background-service/observed-waits.domain.mjs +8 -4
- package/src/runtime/domain/background-service/observed-waits.ts +8 -4
- package/src/runtime/domain/background-service/registry.domain.mjs +3 -0
- package/src/runtime/domain/background-service/registry.ts +2 -0
- package/src/runtime/domain/background-service/runtime.domain.mjs +3 -2
- package/src/runtime/domain/background-service/runtime.ts +3 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/expiry.domain.mjs +44 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/expiry.ts +44 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +8 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +8 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +3 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +5 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-lifetime.domain.mjs +7 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-lifetime.ts +7 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.domain.mjs +22 -13
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.ts +40 -32
- package/src/runtime/domain/background-service/shared-sandbox-diagnostics.domain.mjs +12 -19
- package/src/runtime/domain/background-service/shared-sandbox-diagnostics.ts +12 -16
- package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
- package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +12 -7
- package/src/runtime/domain/background-service/supervisor/generated/task-lifetime.mjs +9 -0
- package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +12 -7
- package/src/runtime/domain/background-service/supervisor/runner.ts +12 -7
- package/src/runtime/domain/background-service/supervisor/types.ts +1 -1
- package/src/runtime/domain/background-service/tools.domain.mjs +3 -2
- package/src/runtime/domain/background-service/tools.ts +3 -2
- package/src/runtime/domain/coordinator/src/expiry.mjs +43 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +8 -1
- package/src/runtime/domain/coordinator/src/store.mjs +3 -0
- package/src/runtime/domain/coordinator/src/task-lifetime.mjs +6 -0
- package/src/runtime/domain/coordinator/src/waits.mjs +22 -13
- package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.domain.mjs +12 -19
- package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.ts +12 -16
- package/src/runtime/domain/subagents/README.md +2 -2
- package/src/runtime/domain/subagents/cleanup.domain.mjs +5 -2
- package/src/runtime/domain/subagents/cleanup.ts +4 -1
- package/src/runtime/domain/subagents/index.domain.mjs +41 -27
- package/src/runtime/domain/subagents/index.ts +39 -25
- package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +28 -2
- package/src/runtime/domain/subagents/managed-launch-host.ts +26 -2
- package/src/runtime/domain/subagents/managed-launch-port.ts +2 -0
- package/src/runtime/domain/subagents/package.json +1 -1
- package/src/runtime/domain/subagents/registry-cleanup-worker.mjs +24 -0
- package/src/runtime/domain/subagents/registry.domain.mjs +33 -7
- package/src/runtime/domain/subagents/registry.ts +18 -4
- package/src/runtime/domain/subagents/settings-page.domain.mjs +10 -10
- package/src/runtime/domain/subagents/settings-page.ts +10 -10
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/expiry.domain.mjs +44 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/expiry.ts +44 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +8 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +8 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +3 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +5 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-lifetime.domain.mjs +7 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-lifetime.ts +7 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.domain.mjs +22 -13
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.ts +40 -32
- package/src/runtime/domain/subagents/shared-sandbox-diagnostics.domain.mjs +12 -19
- package/src/runtime/domain/subagents/shared-sandbox-diagnostics.ts +12 -16
- package/src/runtime/domain/subagents/stop.domain.mjs +7 -5
- package/src/runtime/domain/subagents/stop.ts +7 -5
- package/src/runtime/domain/subagents/timing.domain.mjs +7 -3
- package/src/runtime/domain/subagents/timing.ts +11 -4
- package/src/runtime/domain/subagents/workspace-files.domain.mjs +6 -6
- package/src/runtime/domain/subagents/workspace-files.ts +6 -6
- package/src/runtime/task-expiry.ts +52 -0
- package/src/server.ts +4 -0
- package/src/version.ts +1 -1
|
@@ -10,7 +10,7 @@ import extension from "./index.domain.mjs";
|
|
|
10
10
|
import { bindRuntimeOutcomeStore } from "./assignment-outcomes.domain.mjs";
|
|
11
11
|
import { catalogSnapshotFromWire } from "./catalog-store.domain.mjs";
|
|
12
12
|
import { openLaunchJournal, launchDigest } from "./managed-launch-journal.mjs";
|
|
13
|
-
import { baseDir, nextRunId, processStartToken, listMetas, writeMeta, listActiveMetasForParent, effectiveStatus, readMeta, readParkRecord, updateParkRecord } from "./registry.domain.mjs";
|
|
13
|
+
import { baseDir, nextRunId, processStartToken, listMetas, notifyRunRemoved, writeMeta, listActiveMetasForParent, effectiveStatus, readMeta, readParkRecord, updateParkRecord } from "./registry.domain.mjs";
|
|
14
14
|
import { recoverLaunchMetadata } from "./managed-launch-recovery.domain.mjs";
|
|
15
15
|
import { assertSubagentHandoff } from "./managed-launch-ownership.domain.mjs";
|
|
16
16
|
import { createOwnerCapacityGates } from "./capacity.mjs";
|
|
@@ -42,6 +42,7 @@ export class ManagedSubagentHost {
|
|
|
42
42
|
closeJournal;
|
|
43
43
|
epoch;
|
|
44
44
|
pending = 0;
|
|
45
|
+
registryCleanup;
|
|
45
46
|
requestSequence = 0;
|
|
46
47
|
requestRecords = new Map();
|
|
47
48
|
foldRecord;
|
|
@@ -196,7 +197,8 @@ export class ManagedSubagentHost {
|
|
|
196
197
|
}
|
|
197
198
|
capacityFor = createOwnerCapacityGates(({ pid, start }) => listActiveMetasForParent(pid).filter(meta => meta.spawnPidStartTime === start && effectiveStatus(meta) === "running").length
|
|
198
199
|
+ this.journal.unresolvedAttempts().filter((attempt) => attempt.capacityOwner?.pid === pid && attempt.capacityOwner?.start === start && !readMeta(attempt.id)).length);
|
|
199
|
-
get
|
|
200
|
+
get cleaningRegistry() { return this.registryCleanup !== undefined; }
|
|
201
|
+
get busy() { return this.pending > 0 || Boolean(this.failureResponse) || this.cleaningRegistry; }
|
|
200
202
|
status() {
|
|
201
203
|
return { owner: "server", instanceId: this.instance, runtimeEpoch: this.epoch,
|
|
202
204
|
lifecycle: { ...this.lifecycleMetrics, activeDeadlines: this.healthDue.size },
|
|
@@ -339,10 +341,33 @@ export class ManagedSubagentHost {
|
|
|
339
341
|
process.kill(record.pid, 0);
|
|
340
342
|
return record;
|
|
341
343
|
}
|
|
344
|
+
scheduleRegistryCleanup = (config, onRemoved) => {
|
|
345
|
+
if (this.registryCleanup)
|
|
346
|
+
return;
|
|
347
|
+
this.registryCleanup = new Promise((resolve, reject) => {
|
|
348
|
+
const worker = new Worker(new URL("./registry-cleanup-worker.mjs", import.meta.url), {
|
|
349
|
+
workerData: { root: this.root, config },
|
|
350
|
+
execArgv: import.meta.url.endsWith(".domain.mjs") ? [] : ["--import", import.meta.resolve("tsx")],
|
|
351
|
+
});
|
|
352
|
+
worker.on("message", (id) => {
|
|
353
|
+
notifyRunRemoved(id);
|
|
354
|
+
onRemoved(id);
|
|
355
|
+
});
|
|
356
|
+
worker.once("error", reject);
|
|
357
|
+
worker.once("exit", code => {
|
|
358
|
+
if (code === 0)
|
|
359
|
+
resolve();
|
|
360
|
+
else
|
|
361
|
+
reject(new Error(`Registry cleanup worker exited with code ${code}`));
|
|
362
|
+
});
|
|
363
|
+
}).catch(error => console.error("[pi-better-subagents] Registry cleanup failed:", error))
|
|
364
|
+
.finally(() => { this.registryCleanup = undefined; });
|
|
365
|
+
};
|
|
342
366
|
initialize() {
|
|
343
367
|
return this.initializing ??= (async () => {
|
|
344
368
|
const host = this;
|
|
345
369
|
const port = {
|
|
370
|
+
scheduleRegistryCleanup: this.scheduleRegistryCleanup,
|
|
346
371
|
observeHealth: reconcile => host.observeHealth(reconcile),
|
|
347
372
|
activeProviders: () => host.current.activeProviders ?? {},
|
|
348
373
|
backgroundTools: () => host.current.background?.available === true ? host.current.background.tools : [],
|
|
@@ -598,6 +623,7 @@ export class ManagedSubagentHost {
|
|
|
598
623
|
this.healthClose?.();
|
|
599
624
|
Atomics.store(this.foldRevocation, 0, 1);
|
|
600
625
|
await this.tail.catch(() => undefined);
|
|
626
|
+
await this.registryCleanup;
|
|
601
627
|
await this.failureWorker?.terminate();
|
|
602
628
|
this.failureWorker = undefined;
|
|
603
629
|
if (failureFoldRevocations.get(this.root) === this.foldRevocation)
|
|
@@ -9,7 +9,7 @@ import extension from "./index.ts";
|
|
|
9
9
|
import { bindRuntimeOutcomeStore } from "./assignment-outcomes.ts";
|
|
10
10
|
import { catalogSnapshotFromWire } from "./catalog-store.ts";
|
|
11
11
|
import { openLaunchJournal, launchDigest } from "./managed-launch-journal.mjs";
|
|
12
|
-
import { baseDir, nextRunId, processStartToken, listMetas, writeMeta, listActiveMetasForParent, effectiveStatus, readMeta, readParkRecord, updateParkRecord } from "./registry.ts";
|
|
12
|
+
import { baseDir, nextRunId, processStartToken, listMetas, notifyRunRemoved, writeMeta, listActiveMetasForParent, effectiveStatus, readMeta, readParkRecord, updateParkRecord } from "./registry.ts";
|
|
13
13
|
import { recoverLaunchMetadata } from "./managed-launch-recovery.ts";
|
|
14
14
|
import { assertSubagentHandoff } from "./managed-launch-ownership.ts";
|
|
15
15
|
import { createOwnerCapacityGates } from "./capacity.mjs";
|
|
@@ -37,6 +37,7 @@ export class ManagedSubagentHost {
|
|
|
37
37
|
private closeJournal: () => void;
|
|
38
38
|
private epoch: number;
|
|
39
39
|
private pending = 0;
|
|
40
|
+
private registryCleanup?: Promise<void>;
|
|
40
41
|
private requestSequence = 0;
|
|
41
42
|
private requestRecords = new Map<number, any>();
|
|
42
43
|
private foldRecord?: { kind: string; ids: readonly string[]; lastProgressAt: number; nextDeadline: number; recovery: string };
|
|
@@ -151,7 +152,8 @@ export class ManagedSubagentHost {
|
|
|
151
152
|
private capacityFor = createOwnerCapacityGates(({ pid, start }: { pid: number; start: string }) =>
|
|
152
153
|
listActiveMetasForParent(pid).filter(meta => meta.spawnPidStartTime === start && effectiveStatus(meta) === "running").length
|
|
153
154
|
+ this.journal.unresolvedAttempts().filter((attempt: any) => attempt.capacityOwner?.pid === pid && attempt.capacityOwner?.start === start && !readMeta(attempt.id)).length);
|
|
154
|
-
get
|
|
155
|
+
get cleaningRegistry() { return this.registryCleanup !== undefined; }
|
|
156
|
+
get busy() { return this.pending > 0 || Boolean(this.failureResponse) || this.cleaningRegistry; }
|
|
155
157
|
status() {
|
|
156
158
|
return { owner: "server", instanceId: this.instance, runtimeEpoch: this.epoch,
|
|
157
159
|
lifecycle: { ...this.lifecycleMetrics, activeDeadlines: this.healthDue.size },
|
|
@@ -260,10 +262,31 @@ export class ManagedSubagentHost {
|
|
|
260
262
|
process.kill(record.pid, 0);
|
|
261
263
|
return record;
|
|
262
264
|
}
|
|
265
|
+
private scheduleRegistryCleanup: ManagedLaunchPort["scheduleRegistryCleanup"] = (config, onRemoved) => {
|
|
266
|
+
if (this.registryCleanup) return;
|
|
267
|
+
this.registryCleanup = new Promise<void>((resolve, reject) => {
|
|
268
|
+
const worker = new Worker(new URL("./registry-cleanup-worker.mjs", import.meta.url), {
|
|
269
|
+
workerData: { root: this.root, config },
|
|
270
|
+
execArgv: import.meta.url.endsWith(".domain.mjs") ? [] : ["--import", import.meta.resolve("tsx")],
|
|
271
|
+
});
|
|
272
|
+
worker.on("message", (id: string) => {
|
|
273
|
+
notifyRunRemoved(id);
|
|
274
|
+
onRemoved(id);
|
|
275
|
+
});
|
|
276
|
+
worker.once("error", reject);
|
|
277
|
+
worker.once("exit", code => {
|
|
278
|
+
if (code === 0) resolve();
|
|
279
|
+
else reject(new Error(`Registry cleanup worker exited with code ${code}`));
|
|
280
|
+
});
|
|
281
|
+
}).catch(error => console.error("[pi-better-subagents] Registry cleanup failed:", error))
|
|
282
|
+
.finally(() => { this.registryCleanup = undefined; });
|
|
283
|
+
};
|
|
284
|
+
|
|
263
285
|
private initialize() {
|
|
264
286
|
return this.initializing ??= (async () => {
|
|
265
287
|
const host = this;
|
|
266
288
|
const port: ManagedLaunchPort = {
|
|
289
|
+
scheduleRegistryCleanup: this.scheduleRegistryCleanup,
|
|
267
290
|
observeHealth: reconcile => host.observeHealth(reconcile),
|
|
268
291
|
activeProviders: () => host.current.activeProviders ?? {},
|
|
269
292
|
backgroundTools: () => host.current.background?.available === true ? host.current.background.tools : [],
|
|
@@ -487,6 +510,7 @@ export class ManagedSubagentHost {
|
|
|
487
510
|
this.healthClose?.();
|
|
488
511
|
Atomics.store(this.foldRevocation, 0, 1);
|
|
489
512
|
await this.tail.catch(() => undefined);
|
|
513
|
+
await this.registryCleanup;
|
|
490
514
|
await this.failureWorker?.terminate(); this.failureWorker = undefined;
|
|
491
515
|
if (failureFoldRevocations.get(this.root) === this.foldRevocation) failureFoldRevocations.delete(this.root);
|
|
492
516
|
const session = this.session;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { SubagentConfig } from "./config.ts";
|
|
1
2
|
import type { CatalogHost } from "./catalog-runtime.ts";
|
|
2
3
|
import type { CatalogSnapshot } from "./catalog-store.ts";
|
|
3
4
|
import type { RunMeta } from "./registry.ts";
|
|
@@ -6,6 +7,7 @@ import type { RunMeta } from "./registry.ts";
|
|
|
6
7
|
export interface ManagedLaunchPort {
|
|
7
8
|
observeHealth?(reconcile: (ids: readonly string[]) => void): () => void;
|
|
8
9
|
activeProviders?(): Record<string, string>;
|
|
10
|
+
scheduleRegistryCleanup(config: Pick<SubagentConfig, "cleanupTerminalRunRetentionMs" | "cleanupSessionRetentionMs" | "maxRegistryBytes">, onRemoved: (id: string) => void): void;
|
|
9
11
|
backgroundTools(): readonly string[];
|
|
10
12
|
readonly owner: { pid: number; start?: string };
|
|
11
13
|
readonly identity: { root: string; instance: string; epoch: number };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Generated fixed launch domain from packages/pi-better-subagents/registry-cleanup-worker.mjs. Do not edit directly.
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
4
|
+
import { bindRuntimeOutcomeStore } from "./assignment-outcomes.domain.mjs";
|
|
5
|
+
import { enforceRegistrySizeCapOnce, runDailyCleanupOnce } from "./cleanup.domain.mjs";
|
|
6
|
+
import { onMetaChanged } from "./registry.domain.mjs";
|
|
7
|
+
import { openStore } from "./shared-operation-coordinator/index.domain.mjs";
|
|
8
|
+
const { root, config } = workerData;
|
|
9
|
+
process.env.PI_CODING_AGENT_DIR = root;
|
|
10
|
+
// Reuse one coordinator connection for all assignment and retention checks in this sweep.
|
|
11
|
+
const store = openStore({ path: join(root, "operation-coordinator.sqlite") });
|
|
12
|
+
const unbind = bindRuntimeOutcomeStore(root, store);
|
|
13
|
+
// Cleanup emits a metadata change after each committed removal, including during the daily sweep.
|
|
14
|
+
const off = onMetaChanged(meta => { if (meta)
|
|
15
|
+
parentPort.postMessage(meta.id); });
|
|
16
|
+
try {
|
|
17
|
+
runDailyCleanupOnce({ config });
|
|
18
|
+
enforceRegistrySizeCapOnce({ config });
|
|
19
|
+
}
|
|
20
|
+
finally {
|
|
21
|
+
off();
|
|
22
|
+
unbind();
|
|
23
|
+
store.close();
|
|
24
|
+
}
|
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
// Generated fixed launch domain from packages/pi-better-subagents/registry.ts. Do not edit directly.
|
|
2
2
|
import { reclaimWorkspace } from "./isolated-workspace.domain.mjs";
|
|
3
3
|
import { retainResult } from "./retained-result.domain.mjs";
|
|
4
|
+
/**
|
|
5
|
+
* Run registry — durable metadata for each spawned subagent.
|
|
6
|
+
*
|
|
7
|
+
* The authoritative record for every run is a `meta.json` sidecar on disk, so
|
|
8
|
+
* `list` / `output` / `result` keep working across foreground turns, `/reload`,
|
|
9
|
+
* and even a full pi restart. In-memory state holds only the live exit handlers
|
|
10
|
+
* for runs this process spawned.
|
|
11
|
+
*
|
|
12
|
+
* Catalog launches may attach an optional immutable `catalog` snapshot to that
|
|
13
|
+
* same record. Display-label reservations live under `{baseDir()}/labels`
|
|
14
|
+
* (see catalog-identity.ts). They are not a second registry, and removing a
|
|
15
|
+
* run directory does not delete them.
|
|
16
|
+
*/
|
|
17
|
+
import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.domain.mjs";
|
|
4
18
|
import { assignmentRetainsEvidence } from "./assignment-outcomes.domain.mjs";
|
|
5
19
|
import { processStartToken } from "./process-identity.mjs";
|
|
6
20
|
export { processStartToken } from "./process-identity.mjs";
|
|
@@ -1022,10 +1036,27 @@ export function onMetaChanged(listener) {
|
|
|
1022
1036
|
metaChangedListeners.add(listener);
|
|
1023
1037
|
return () => metaChangedListeners.delete(listener);
|
|
1024
1038
|
}
|
|
1039
|
+
/** Drop volatile state in the process observing a committed cleanup. */
|
|
1040
|
+
export function notifyRunRemoved(id, meta = metaCache.get(id)) {
|
|
1041
|
+
metaCache.delete(id);
|
|
1042
|
+
for (const listener of metaChangedListeners) {
|
|
1043
|
+
try {
|
|
1044
|
+
listener(meta);
|
|
1045
|
+
}
|
|
1046
|
+
catch { /* best effort */ }
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
function restoreTaskDeadline(meta) {
|
|
1050
|
+
if (meta.status !== "running" && meta.status !== "orphaned")
|
|
1051
|
+
return;
|
|
1052
|
+
meta.timing ??= { graceMs: 0 };
|
|
1053
|
+
meta.timing.ceilingAt = taskDeadline(meta.startedAt, meta.timing.ceilingAt);
|
|
1054
|
+
}
|
|
1025
1055
|
export function readMeta(id) {
|
|
1026
1056
|
try {
|
|
1027
1057
|
registryIo.metadataFileReads += 1;
|
|
1028
1058
|
const meta = JSON.parse(readFileSync(metaPathFor(id), "utf-8"));
|
|
1059
|
+
restoreTaskDeadline(meta);
|
|
1029
1060
|
metaCache.set(id, meta);
|
|
1030
1061
|
return meta;
|
|
1031
1062
|
}
|
|
@@ -1069,16 +1100,10 @@ export function removeMetaArtifacts(meta, options = {}) {
|
|
|
1069
1100
|
if (scratch) {
|
|
1070
1101
|
rmSync(scratch, { recursive: true, force: true });
|
|
1071
1102
|
}
|
|
1072
|
-
metaCache.delete(meta.id);
|
|
1073
1103
|
removeIndexEntry(join(baseDir(), "by-parent", String(meta.spawnPid)), meta.id);
|
|
1074
1104
|
removeIndexEntry(join(baseDir(), "by-parent-active", String(meta.spawnPid)), meta.id);
|
|
1075
1105
|
removeIndexEntry(join(baseDir(), "by-origin", originKey(originOf(meta))), meta.id);
|
|
1076
|
-
|
|
1077
|
-
try {
|
|
1078
|
-
listener(meta);
|
|
1079
|
-
}
|
|
1080
|
-
catch { /* best effort */ }
|
|
1081
|
-
}
|
|
1106
|
+
notifyRunRemoved(meta.id, meta);
|
|
1082
1107
|
return true;
|
|
1083
1108
|
}
|
|
1084
1109
|
catch (error) {
|
|
@@ -1329,6 +1354,7 @@ export function inspectRunMeta(id) {
|
|
|
1329
1354
|
metaCache.delete(id);
|
|
1330
1355
|
return { kind: "unreadable", detail: `invalid metadata: ${invalid}` };
|
|
1331
1356
|
}
|
|
1357
|
+
restoreTaskDeadline(meta);
|
|
1332
1358
|
metaCache.set(id, meta);
|
|
1333
1359
|
return { kind: "ok", meta };
|
|
1334
1360
|
}
|
|
@@ -14,6 +14,7 @@ import { retainResult } from "./retained-result.ts";
|
|
|
14
14
|
* run directory does not delete them.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
+
import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.ts";
|
|
17
18
|
import type { RunTiming } from "./timing.ts";
|
|
18
19
|
import { assignmentRetainsEvidence } from "./assignment-outcomes.ts";
|
|
19
20
|
import type { SkillExposureSource } from "./skills.ts";
|
|
@@ -1316,10 +1317,25 @@ export function onMetaChanged(listener: (meta?: RunMeta) => void): () => void {
|
|
|
1316
1317
|
return () => metaChangedListeners.delete(listener);
|
|
1317
1318
|
}
|
|
1318
1319
|
|
|
1320
|
+
/** Drop volatile state in the process observing a committed cleanup. */
|
|
1321
|
+
export function notifyRunRemoved(id: string, meta = metaCache.get(id)): void {
|
|
1322
|
+
metaCache.delete(id);
|
|
1323
|
+
for (const listener of metaChangedListeners) {
|
|
1324
|
+
try { listener(meta); } catch { /* best effort */ }
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
function restoreTaskDeadline(meta: RunMeta): void {
|
|
1329
|
+
if (meta.status !== "running" && meta.status !== "orphaned") return;
|
|
1330
|
+
meta.timing ??= { graceMs: 0 };
|
|
1331
|
+
meta.timing.ceilingAt = taskDeadline(meta.startedAt, meta.timing.ceilingAt);
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1319
1334
|
export function readMeta(id: string): RunMeta | undefined {
|
|
1320
1335
|
try {
|
|
1321
1336
|
registryIo.metadataFileReads += 1;
|
|
1322
1337
|
const meta = JSON.parse(readFileSync(metaPathFor(id), "utf-8")) as RunMeta;
|
|
1338
|
+
restoreTaskDeadline(meta);
|
|
1323
1339
|
metaCache.set(id, meta);
|
|
1324
1340
|
return meta;
|
|
1325
1341
|
} catch (error) {
|
|
@@ -1376,13 +1392,10 @@ export function removeMetaArtifacts(meta: RunMeta, options: RemoveMetaArtifactsO
|
|
|
1376
1392
|
if (scratch) {
|
|
1377
1393
|
rmSync(scratch, { recursive: true, force: true });
|
|
1378
1394
|
}
|
|
1379
|
-
metaCache.delete(meta.id);
|
|
1380
1395
|
removeIndexEntry(join(baseDir(), "by-parent", String(meta.spawnPid)), meta.id);
|
|
1381
1396
|
removeIndexEntry(join(baseDir(), "by-parent-active", String(meta.spawnPid)), meta.id);
|
|
1382
1397
|
removeIndexEntry(join(baseDir(), "by-origin", originKey(originOf(meta))), meta.id);
|
|
1383
|
-
|
|
1384
|
-
try { listener(meta); } catch { /* best effort */ }
|
|
1385
|
-
}
|
|
1398
|
+
notifyRunRemoved(meta.id, meta);
|
|
1386
1399
|
return true;
|
|
1387
1400
|
} catch (error) {
|
|
1388
1401
|
options.errors?.push(meta.cwd + ": " + String(error));
|
|
@@ -1659,6 +1672,7 @@ export function inspectRunMeta(id: string): { kind: "ok"; meta: RunMeta } | { ki
|
|
|
1659
1672
|
metaCache.delete(id);
|
|
1660
1673
|
return { kind: "unreadable", detail: `invalid metadata: ${invalid}` };
|
|
1661
1674
|
}
|
|
1675
|
+
restoreTaskDeadline(meta);
|
|
1662
1676
|
metaCache.set(id, meta);
|
|
1663
1677
|
return { kind: "ok", meta };
|
|
1664
1678
|
}
|
|
@@ -3,7 +3,7 @@ import * as Tui from "@earendil-works/pi-tui";
|
|
|
3
3
|
import { isConcurrencyCap } from "./config.domain.mjs";
|
|
4
4
|
import { DELEGATION_MODES } from "./delegation.domain.mjs";
|
|
5
5
|
import { createSkillPicker } from "./skill-picker.domain.mjs";
|
|
6
|
-
import { isTimingMinutes,
|
|
6
|
+
import { isTimingMinutes, validatedTimingMinutes } from "./timing.domain.mjs";
|
|
7
7
|
const rows = [
|
|
8
8
|
{ kind: "mode", label: "Delegation mode" },
|
|
9
9
|
{ kind: "cap", label: "Concurrent subagents" },
|
|
@@ -22,14 +22,14 @@ const SKILL_MODES = [
|
|
|
22
22
|
{ mode: "none", label: "No skill catalog" },
|
|
23
23
|
{ mode: "explicit", label: "Selected skills" },
|
|
24
24
|
];
|
|
25
|
-
const
|
|
25
|
+
const MAX_TIMEOUT = "24 hours";
|
|
26
26
|
function parseRunTimeout(input) {
|
|
27
27
|
const text = input.trim();
|
|
28
|
-
if (
|
|
28
|
+
if (["no limit", MAX_TIMEOUT].includes(text.toLowerCase()))
|
|
29
29
|
return 0;
|
|
30
30
|
const minutes = Number(text);
|
|
31
|
-
if (!text || !isTimingMinutes(minutes)) {
|
|
32
|
-
throw new Error(
|
|
31
|
+
if (!text || !isTimingMinutes(minutes) || minutes > 1440) {
|
|
32
|
+
throw new Error("Enter 24 hours or a duration up to 1440 minutes.");
|
|
33
33
|
}
|
|
34
34
|
return minutes;
|
|
35
35
|
}
|
|
@@ -51,7 +51,7 @@ function settingValue(kind, s) {
|
|
|
51
51
|
case "mode": return s.mode;
|
|
52
52
|
case "cap": return String(s.maxConcurrent);
|
|
53
53
|
case "workspace": return s.gitWorkspace === "worktree" ? "Worktree" : "Clone";
|
|
54
|
-
case "timeout": return s.maxMinutes === 0 ?
|
|
54
|
+
case "timeout": return s.maxMinutes === 0 || s.maxMinutes >= 1440 ? MAX_TIMEOUT : `${s.maxMinutes} min`;
|
|
55
55
|
case "toolWait": return s.toolWaitMinutes === 0 ? "Off" : `${s.toolWaitMinutes} min`;
|
|
56
56
|
case "stuck": return s.stuckMinutes === 0 ? "Off" : `${s.stuckMinutes} min`;
|
|
57
57
|
case "skills": return skillLabel(s.skillsMode);
|
|
@@ -71,7 +71,7 @@ function description(kind, s) {
|
|
|
71
71
|
case "workspace": return s.gitWorkspace === "worktree"
|
|
72
72
|
? "Create a linked worktree that shares the repository’s Git metadata."
|
|
73
73
|
: "Create a separate local clone for each isolated Git workspace.";
|
|
74
|
-
case "timeout": return "Stop a subagent when its run reaches this limit.
|
|
74
|
+
case "timeout": return "Stop a subagent when its run reaches this limit. The maximum is 24 hours.";
|
|
75
75
|
case "toolWait": return "Notify the parent when a tool call stays open this long. Enter 0 to turn this alert off.";
|
|
76
76
|
case "stuck": return "Notify the parent after this long without progress. Time spent waiting for a tool is excluded. Enter 0 to turn this alert off.";
|
|
77
77
|
case "skills": return "Choose how new subagents discover skills.\n" + skillSource(s);
|
|
@@ -94,7 +94,7 @@ function shortcuts(kind, editing) {
|
|
|
94
94
|
const change = confirm ? `${confirm}/Space` : "Space";
|
|
95
95
|
const verb = kind === "agents" || kind === "choose" ? "open" : kind === "reset" ? "restore" : "change";
|
|
96
96
|
const actions = editing ? [confirm && `${confirm} to apply`]
|
|
97
|
-
: kind === "timeout" ? ["Space for
|
|
97
|
+
: kind === "timeout" ? ["Space for 24 hours", confirm && `${confirm} to edit minutes`]
|
|
98
98
|
: [`${change} to ${verb}`];
|
|
99
99
|
if (!editing)
|
|
100
100
|
actions.push("Ctrl+S to save defaults");
|
|
@@ -187,10 +187,10 @@ export function createSubagentSettingsPage(theme, handlers, requestRender, close
|
|
|
187
187
|
else if (selected.kind === "timeout") {
|
|
188
188
|
if (key === " ") {
|
|
189
189
|
handlers.changeTiming("maxMinutes", 0);
|
|
190
|
-
report("Run timeout set to
|
|
190
|
+
report("Run timeout set to 24 hours.");
|
|
191
191
|
}
|
|
192
192
|
else {
|
|
193
|
-
startEditing(selected, settings.maxMinutes === 0 ?
|
|
193
|
+
startEditing(selected, settings.maxMinutes === 0 || settings.maxMinutes >= 1440 ? MAX_TIMEOUT : String(settings.maxMinutes));
|
|
194
194
|
}
|
|
195
195
|
}
|
|
196
196
|
else if (selected.kind === "skills") {
|
|
@@ -4,7 +4,7 @@ import { isConcurrencyCap } from "./config.ts";
|
|
|
4
4
|
import { DELEGATION_MODES, type DelegationMode } from "./delegation.ts";
|
|
5
5
|
import type { SkillExposureMode } from "./skills.ts";
|
|
6
6
|
import { createSkillPicker, type DiscoveredSkill } from "./skill-picker.ts";
|
|
7
|
-
import { isTimingMinutes,
|
|
7
|
+
import { isTimingMinutes, validatedTimingMinutes } from "./timing.ts";
|
|
8
8
|
|
|
9
9
|
export type TimingSettingKey = "maxMinutes" | "toolWaitMinutes" | "stuckMinutes";
|
|
10
10
|
|
|
@@ -72,14 +72,14 @@ const SKILL_MODES: readonly { mode: SkillExposureMode; label: string }[] = [
|
|
|
72
72
|
{ mode: "explicit", label: "Selected skills" },
|
|
73
73
|
];
|
|
74
74
|
|
|
75
|
-
const
|
|
75
|
+
const MAX_TIMEOUT = "24 hours";
|
|
76
76
|
|
|
77
77
|
function parseRunTimeout(input: string): number {
|
|
78
78
|
const text = input.trim();
|
|
79
|
-
if (
|
|
79
|
+
if (["no limit", MAX_TIMEOUT].includes(text.toLowerCase())) return 0;
|
|
80
80
|
const minutes = Number(text);
|
|
81
|
-
if (!text || !isTimingMinutes(minutes)) {
|
|
82
|
-
throw new Error(
|
|
81
|
+
if (!text || !isTimingMinutes(minutes) || minutes > 1440) {
|
|
82
|
+
throw new Error("Enter 24 hours or a duration up to 1440 minutes.");
|
|
83
83
|
}
|
|
84
84
|
return minutes;
|
|
85
85
|
}
|
|
@@ -103,7 +103,7 @@ function settingValue(kind: Row["kind"], s: SubagentSettingsSnapshot): string {
|
|
|
103
103
|
case "mode": return s.mode;
|
|
104
104
|
case "cap": return String(s.maxConcurrent);
|
|
105
105
|
case "workspace": return s.gitWorkspace === "worktree" ? "Worktree" : "Clone";
|
|
106
|
-
case "timeout": return s.maxMinutes === 0 ?
|
|
106
|
+
case "timeout": return s.maxMinutes === 0 || s.maxMinutes >= 1440 ? MAX_TIMEOUT : `${s.maxMinutes} min`;
|
|
107
107
|
case "toolWait": return s.toolWaitMinutes === 0 ? "Off" : `${s.toolWaitMinutes} min`;
|
|
108
108
|
case "stuck": return s.stuckMinutes === 0 ? "Off" : `${s.stuckMinutes} min`;
|
|
109
109
|
case "skills": return skillLabel(s.skillsMode);
|
|
@@ -124,7 +124,7 @@ function description(kind: Row["kind"], s: SubagentSettingsSnapshot): string {
|
|
|
124
124
|
case "workspace": return s.gitWorkspace === "worktree"
|
|
125
125
|
? "Create a linked worktree that shares the repository’s Git metadata."
|
|
126
126
|
: "Create a separate local clone for each isolated Git workspace.";
|
|
127
|
-
case "timeout": return "Stop a subagent when its run reaches this limit.
|
|
127
|
+
case "timeout": return "Stop a subagent when its run reaches this limit. The maximum is 24 hours.";
|
|
128
128
|
case "toolWait": return "Notify the parent when a tool call stays open this long. Enter 0 to turn this alert off.";
|
|
129
129
|
case "stuck": return "Notify the parent after this long without progress. Time spent waiting for a tool is excluded. Enter 0 to turn this alert off.";
|
|
130
130
|
case "skills": return "Choose how new subagents discover skills.\n" + skillSource(s);
|
|
@@ -147,7 +147,7 @@ function shortcuts(kind: Row["kind"], editing: boolean): string {
|
|
|
147
147
|
const change = confirm ? `${confirm}/Space` : "Space";
|
|
148
148
|
const verb = kind === "agents" || kind === "choose" ? "open" : kind === "reset" ? "restore" : "change";
|
|
149
149
|
const actions = editing ? [confirm && `${confirm} to apply`]
|
|
150
|
-
: kind === "timeout" ? ["Space for
|
|
150
|
+
: kind === "timeout" ? ["Space for 24 hours", confirm && `${confirm} to edit minutes`]
|
|
151
151
|
: [`${change} to ${verb}`];
|
|
152
152
|
if (!editing) actions.push("Ctrl+S to save defaults");
|
|
153
153
|
if (cancel) actions.push(`${cancel} to ${editing ? "cancel" : "go back"}`);
|
|
@@ -244,9 +244,9 @@ export function createSubagentSettingsPage(
|
|
|
244
244
|
} else if (selected.kind === "timeout") {
|
|
245
245
|
if (key === " ") {
|
|
246
246
|
handlers.changeTiming("maxMinutes", 0);
|
|
247
|
-
report("Run timeout set to
|
|
247
|
+
report("Run timeout set to 24 hours.");
|
|
248
248
|
} else {
|
|
249
|
-
startEditing(selected, settings.maxMinutes === 0 ?
|
|
249
|
+
startEditing(selected, settings.maxMinutes === 0 || settings.maxMinutes >= 1440 ? MAX_TIMEOUT : String(settings.maxMinutes));
|
|
250
250
|
}
|
|
251
251
|
} else if (selected.kind === "skills") {
|
|
252
252
|
if (settings.skillsMode === "explicit") rememberedSkillPaths = [...settings.skillsPaths];
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Generated fixed launch domain from packages/pi-better-subagents/shared-operation-coordinator/src/expiry.ts. Do not edit directly.
|
|
2
|
+
// Generated from packages/operation-coordinator/src/expiry.ts. Do not edit directly.
|
|
3
|
+
import { bumpChangeRevision } from "./discovery.domain.mjs";
|
|
4
|
+
import { getOperation } from "./operations.domain.mjs";
|
|
5
|
+
import { columnNumber, columnText, getRows, run } from "./sqlite.domain.mjs";
|
|
6
|
+
import { MAX_TASK_LIFETIME_MS } from "./task-lifetime.domain.mjs";
|
|
7
|
+
import { cancelGeneration } from "./waits.domain.mjs";
|
|
8
|
+
const reason = "24-hour task lifetime exceeded";
|
|
9
|
+
const batch = 8;
|
|
10
|
+
export function overdueOperations(ctx) {
|
|
11
|
+
return getRows(ctx, `SELECT operation_id FROM operations WHERE phase = 'running' AND terminal_revision = 0
|
|
12
|
+
AND created_at <= ? ORDER BY created_at LIMIT ?`, ctx.now() - MAX_TASK_LIFETIME_MS, batch)
|
|
13
|
+
.map(row => getOperation(ctx, columnText(row, "operation_id")))
|
|
14
|
+
.filter(operation => operation.phase === "running");
|
|
15
|
+
}
|
|
16
|
+
export function expireWaits(ctx) {
|
|
17
|
+
const now = ctx.now();
|
|
18
|
+
const cutoff = now - MAX_TASK_LIFETIME_MS;
|
|
19
|
+
const waits = getRows(ctx, `SELECT wait_id, generation FROM waits WHERE phase NOT IN ('consumed', 'cancelled')
|
|
20
|
+
AND dispatch_disarmed = 0 AND created_at <= ? ORDER BY created_at LIMIT ?`, cutoff, batch);
|
|
21
|
+
const claims = getRows(ctx, `SELECT claim_id FROM resume_claims WHERE state IN ('claimed', 'published')
|
|
22
|
+
AND claimed_at <= ? ORDER BY claimed_at LIMIT ?`, cutoff, batch);
|
|
23
|
+
if (!waits.length && !claims.length)
|
|
24
|
+
return 0;
|
|
25
|
+
return ctx.transaction(() => {
|
|
26
|
+
let changed = 0;
|
|
27
|
+
for (const row of waits) {
|
|
28
|
+
const id = columnText(row, "wait_id"), generation = columnNumber(row, "generation");
|
|
29
|
+
if (!ctx.db.prepare(`SELECT 1 FROM waits WHERE wait_id = ? AND generation = ?
|
|
30
|
+
AND phase NOT IN ('consumed', 'cancelled') AND dispatch_disarmed = 0 AND created_at <= ?`).get(id, generation, cutoff))
|
|
31
|
+
continue;
|
|
32
|
+
cancelGeneration(ctx, id, generation, reason);
|
|
33
|
+
changed++;
|
|
34
|
+
}
|
|
35
|
+
// Published claims can outlive consumed waits or a disarmed assignment.
|
|
36
|
+
for (const row of claims) {
|
|
37
|
+
changed += run(ctx, `UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
|
|
38
|
+
WHERE claim_id = ? AND state IN ('claimed', 'published') AND claimed_at <= ?`, now, reason, columnText(row, "claim_id"), cutoff);
|
|
39
|
+
}
|
|
40
|
+
if (changed)
|
|
41
|
+
bumpChangeRevision(ctx);
|
|
42
|
+
return changed;
|
|
43
|
+
});
|
|
44
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Generated from packages/operation-coordinator/src/expiry.ts. Do not edit directly.
|
|
2
|
+
import { bumpChangeRevision } from "./discovery.ts";
|
|
3
|
+
import { getOperation } from "./operations.ts";
|
|
4
|
+
import { columnNumber, columnText, getRows, run, type StoreContext } from "./sqlite.ts";
|
|
5
|
+
import { MAX_TASK_LIFETIME_MS } from "./task-lifetime.ts";
|
|
6
|
+
import { cancelGeneration } from "./waits.ts";
|
|
7
|
+
|
|
8
|
+
const reason = "24-hour task lifetime exceeded";
|
|
9
|
+
const batch = 8;
|
|
10
|
+
|
|
11
|
+
export function overdueOperations(ctx: StoreContext) {
|
|
12
|
+
return getRows(ctx, `SELECT operation_id FROM operations WHERE phase = 'running' AND terminal_revision = 0
|
|
13
|
+
AND created_at <= ? ORDER BY created_at LIMIT ?`, ctx.now() - MAX_TASK_LIFETIME_MS, batch)
|
|
14
|
+
.map(row => getOperation(ctx, columnText(row, "operation_id"))!)
|
|
15
|
+
.filter(operation => operation.phase === "running");
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function expireWaits(ctx: StoreContext): number {
|
|
19
|
+
const now = ctx.now();
|
|
20
|
+
const cutoff = now - MAX_TASK_LIFETIME_MS;
|
|
21
|
+
const waits = getRows(ctx, `SELECT wait_id, generation FROM waits WHERE phase NOT IN ('consumed', 'cancelled')
|
|
22
|
+
AND dispatch_disarmed = 0 AND created_at <= ? ORDER BY created_at LIMIT ?`, cutoff, batch);
|
|
23
|
+
const claims = getRows(ctx, `SELECT claim_id FROM resume_claims WHERE state IN ('claimed', 'published')
|
|
24
|
+
AND claimed_at <= ? ORDER BY claimed_at LIMIT ?`, cutoff, batch);
|
|
25
|
+
if (!waits.length && !claims.length) return 0;
|
|
26
|
+
return ctx.transaction(() => {
|
|
27
|
+
let changed = 0;
|
|
28
|
+
for (const row of waits) {
|
|
29
|
+
const id = columnText(row, "wait_id"), generation = columnNumber(row, "generation");
|
|
30
|
+
if (!ctx.db.prepare(`SELECT 1 FROM waits WHERE wait_id = ? AND generation = ?
|
|
31
|
+
AND phase NOT IN ('consumed', 'cancelled') AND dispatch_disarmed = 0 AND created_at <= ?`).get(id, generation, cutoff)) continue;
|
|
32
|
+
cancelGeneration(ctx, id, generation, reason);
|
|
33
|
+
changed++;
|
|
34
|
+
}
|
|
35
|
+
// Published claims can outlive consumed waits or a disarmed assignment.
|
|
36
|
+
for (const row of claims) {
|
|
37
|
+
changed += run(ctx, `UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
|
|
38
|
+
WHERE claim_id = ? AND state IN ('claimed', 'published') AND claimed_at <= ?`,
|
|
39
|
+
now, reason, columnText(row, "claim_id"), cutoff);
|
|
40
|
+
}
|
|
41
|
+
if (changed) bumpChangeRevision(ctx);
|
|
42
|
+
return changed;
|
|
43
|
+
});
|
|
44
|
+
}
|
|
@@ -60,6 +60,11 @@ const ASSIGNMENT_ATTEMPTS_DDL = `CREATE TABLE IF NOT EXISTS assignment_attempts
|
|
|
60
60
|
assignment_id TEXT NOT NULL REFERENCES assignment_bindings (assignment_id)
|
|
61
61
|
)`;
|
|
62
62
|
const ASSIGNMENT_ATTEMPT_COLUMN = `assignment_attempt_id TEXT REFERENCES assignment_attempts (attempt_id)`;
|
|
63
|
+
const EXPIRY_INDEXES = [
|
|
64
|
+
"CREATE INDEX IF NOT EXISTS operations_expiry ON operations(created_at) WHERE phase = 'running' AND terminal_revision = 0",
|
|
65
|
+
"CREATE INDEX IF NOT EXISTS waits_expiry ON waits(created_at) WHERE phase NOT IN ('consumed', 'cancelled') AND dispatch_disarmed = 0",
|
|
66
|
+
"CREATE INDEX IF NOT EXISTS claims_expiry ON resume_claims(claimed_at) WHERE state IN ('claimed', 'published')",
|
|
67
|
+
];
|
|
63
68
|
const ASSIGNMENT_CLEANUP_INDEX = `CREATE INDEX IF NOT EXISTS operations_assignment_cleanup
|
|
64
69
|
ON operations (operation_id, assignment_attempt_id)
|
|
65
70
|
WHERE assignment_attempt_id IS NOT NULL`;
|
|
@@ -301,7 +306,7 @@ export function ensureSchema(ctx) {
|
|
|
301
306
|
throw new StoreError("schema-version", `The database at this path holds tables (${tables.join(", ")}) but no ${SCHEMA_VERSION_KEY}. It was not written by the operation coordinator; refusing to reuse or clear it.`);
|
|
302
307
|
}
|
|
303
308
|
ctx.transaction(() => {
|
|
304
|
-
for (const statement of DDL)
|
|
309
|
+
for (const statement of [...DDL, ...EXPIRY_INDEXES])
|
|
305
310
|
ctx.db.exec(statement);
|
|
306
311
|
run(ctx, "INSERT INTO schema_meta (key, value) VALUES (?, ?)", SCHEMA_VERSION_KEY, String(SCHEMA_VERSION));
|
|
307
312
|
});
|
|
@@ -351,6 +356,8 @@ export function ensureSchema(ctx) {
|
|
|
351
356
|
ensureAssignmentCleanupSchema(ctx);
|
|
352
357
|
}
|
|
353
358
|
function ensureAssignmentCleanupSchema(ctx) {
|
|
359
|
+
for (const statement of EXPIRY_INDEXES)
|
|
360
|
+
ctx.db.exec(statement);
|
|
354
361
|
const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
|
|
355
362
|
if (hasColumn() && getRow(ctx, "SELECT 1 FROM sqlite_master WHERE name = 'operations_assignment_cleanup'"))
|
|
356
363
|
return;
|
|
@@ -62,6 +62,12 @@ const ASSIGNMENT_ATTEMPTS_DDL = `CREATE TABLE IF NOT EXISTS assignment_attempts
|
|
|
62
62
|
assignment_id TEXT NOT NULL REFERENCES assignment_bindings (assignment_id)
|
|
63
63
|
)`;
|
|
64
64
|
const ASSIGNMENT_ATTEMPT_COLUMN = `assignment_attempt_id TEXT REFERENCES assignment_attempts (attempt_id)`;
|
|
65
|
+
const EXPIRY_INDEXES = [
|
|
66
|
+
"CREATE INDEX IF NOT EXISTS operations_expiry ON operations(created_at) WHERE phase = 'running' AND terminal_revision = 0",
|
|
67
|
+
"CREATE INDEX IF NOT EXISTS waits_expiry ON waits(created_at) WHERE phase NOT IN ('consumed', 'cancelled') AND dispatch_disarmed = 0",
|
|
68
|
+
"CREATE INDEX IF NOT EXISTS claims_expiry ON resume_claims(claimed_at) WHERE state IN ('claimed', 'published')",
|
|
69
|
+
];
|
|
70
|
+
|
|
65
71
|
const ASSIGNMENT_CLEANUP_INDEX = `CREATE INDEX IF NOT EXISTS operations_assignment_cleanup
|
|
66
72
|
ON operations (operation_id, assignment_attempt_id)
|
|
67
73
|
WHERE assignment_attempt_id IS NOT NULL`;
|
|
@@ -313,7 +319,7 @@ export function ensureSchema(ctx: StoreContext): void {
|
|
|
313
319
|
);
|
|
314
320
|
}
|
|
315
321
|
ctx.transaction(() => {
|
|
316
|
-
for (const statement of DDL) ctx.db.exec(statement);
|
|
322
|
+
for (const statement of [...DDL, ...EXPIRY_INDEXES]) ctx.db.exec(statement);
|
|
317
323
|
run(ctx, "INSERT INTO schema_meta (key, value) VALUES (?, ?)", SCHEMA_VERSION_KEY, String(SCHEMA_VERSION));
|
|
318
324
|
});
|
|
319
325
|
return;
|
|
@@ -369,6 +375,7 @@ export function ensureSchema(ctx: StoreContext): void {
|
|
|
369
375
|
}
|
|
370
376
|
|
|
371
377
|
function ensureAssignmentCleanupSchema(ctx: StoreContext): void {
|
|
378
|
+
for (const statement of EXPIRY_INDEXES) ctx.db.exec(statement);
|
|
372
379
|
const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
|
|
373
380
|
if (hasColumn() && getRow(ctx, "SELECT 1 FROM sqlite_master WHERE name = 'operations_assignment_cleanup'")) return;
|
|
374
381
|
ctx.transaction(() => {
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* synchronous and transactional; a refusal throws `StoreError` with a typed code
|
|
9
9
|
* and leaves no partial record.
|
|
10
10
|
*/
|
|
11
|
+
import { expireWaits, overdueOperations } from "./expiry.domain.mjs";
|
|
11
12
|
import { setUpgradeFence } from "./upgrade.domain.mjs";
|
|
12
13
|
import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks } from "./background-parent-callbacks.domain.mjs";
|
|
13
14
|
import { BackgroundRequests } from "./background-requests.domain.mjs";
|
|
@@ -51,6 +52,8 @@ export function openStore(options) {
|
|
|
51
52
|
}
|
|
52
53
|
};
|
|
53
54
|
const store = {
|
|
55
|
+
overdueOperations() { alive(); return overdueOperations(ctx); },
|
|
56
|
+
expireWaits() { alive(); return expireWaits(ctx); },
|
|
54
57
|
subagentLaunchJournal() { alive(); return new SubagentLaunchJournal(ctx, alive); },
|
|
55
58
|
resultScopeManaged(scope) { alive(); return resultScopeManaged(ctx, scope); },
|
|
56
59
|
handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* synchronous and transactional; a refusal throws `StoreError` with a typed code
|
|
8
8
|
* and leaves no partial record.
|
|
9
9
|
*/
|
|
10
|
+
import { expireWaits, overdueOperations } from "./expiry.ts";
|
|
10
11
|
import { setUpgradeFence } from "./upgrade.ts";
|
|
11
12
|
import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks, type ParentCallbackScope, type ParentCallbackPage, type RecentBackgroundTerminalPage } from './background-parent-callbacks.ts';
|
|
12
13
|
import { BackgroundRequests } from "./background-requests.ts";
|
|
@@ -127,6 +128,8 @@ import {
|
|
|
127
128
|
} from "./types.ts";
|
|
128
129
|
|
|
129
130
|
export interface Store {
|
|
131
|
+
overdueOperations(): OperationRecord[];
|
|
132
|
+
expireWaits(): number;
|
|
130
133
|
hasSubagentManagement(): boolean;
|
|
131
134
|
resultSupervisionChanges(after?: Parameters<typeof resultSupervisionChanges>[1]): ReturnType<typeof resultSupervisionChanges>;
|
|
132
135
|
subagentLaunchJournal(): SubagentLaunchJournal;
|
|
@@ -359,6 +362,8 @@ export function openStore(options: StoreOptions): Store {
|
|
|
359
362
|
};
|
|
360
363
|
|
|
361
364
|
const store: Store = {
|
|
365
|
+
overdueOperations() { alive(); return overdueOperations(ctx); },
|
|
366
|
+
expireWaits() { alive(); return expireWaits(ctx); },
|
|
362
367
|
subagentLaunchJournal() { alive(); return new SubagentLaunchJournal(ctx, alive); },
|
|
363
368
|
resultScopeManaged(scope) { alive(); return resultScopeManaged(ctx, scope); },
|
|
364
369
|
handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
|