pi-better-server 0.7.1 → 0.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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 +47 -29
- package/src/runtime/domain/subagents/index.ts +46 -27
- 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/output-payload.domain.mjs +3 -1
- package/src/runtime/domain/subagents/output-payload.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/tools.domain.mjs +3 -2
- package/src/runtime/domain/subagents/tools.ts +3 -2
- package/src/runtime/domain/subagents/workflow-assignment.domain.mjs +25 -0
- package/src/runtime/domain/subagents/workflow-assignment.ts +35 -0
- package/src/runtime/domain/subagents/workspace-files.domain.mjs +6 -6
- package/src/runtime/domain/subagents/workspace-files.ts +6 -6
- package/src/runtime/query-executor.ts +11 -2
- package/src/runtime/task-expiry.ts +52 -0
- package/src/server.ts +4 -0
- package/src/version.ts +1 -1
|
@@ -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); },
|
package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-lifetime.domain.mjs
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Generated fixed launch domain from packages/pi-better-subagents/shared-operation-coordinator/src/task-lifetime.ts. Do not edit directly.
|
|
2
|
+
// Generated from packages/operation-coordinator/src/task-lifetime.ts. Do not edit directly.
|
|
3
|
+
/** Absolute wall-clock limit, including time spent waiting for a runner. */
|
|
4
|
+
export const MAX_TASK_LIFETIME_MS = 24 * 60 * 60 * 1000;
|
|
5
|
+
export function taskDeadline(startedAt, requestedDeadline) {
|
|
6
|
+
return Math.min(startedAt + MAX_TASK_LIFETIME_MS, requestedDeadline ?? Infinity);
|
|
7
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Generated from packages/operation-coordinator/src/task-lifetime.ts. Do not edit directly.
|
|
2
|
+
/** Absolute wall-clock limit, including time spent waiting for a runner. */
|
|
3
|
+
export const MAX_TASK_LIFETIME_MS = 24 * 60 * 60 * 1000;
|
|
4
|
+
|
|
5
|
+
export function taskDeadline(startedAt: number, requestedDeadline?: number): number {
|
|
6
|
+
return Math.min(startedAt + MAX_TASK_LIFETIME_MS, requestedDeadline ?? Infinity);
|
|
7
|
+
}
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* the cancellation epoch it observed. Cancellation invalidates the active resume
|
|
16
16
|
* claim, and a claim whose epoch no longer matches can never publish an attempt.
|
|
17
17
|
*/
|
|
18
|
+
import { taskDeadline } from "./task-lifetime.domain.mjs";
|
|
18
19
|
import { randomUUID } from "node:crypto";
|
|
19
20
|
import { StoreError } from "./errors.domain.mjs";
|
|
20
21
|
import { acknowledgeGenerationOutbox, enqueueReadyGeneration, releaseGenerationPins, voidGenerationOutbox, } from "./outbox.domain.mjs";
|
|
@@ -370,21 +371,25 @@ export function cancelWait(ctx, input) {
|
|
|
370
371
|
throw new StoreError("wait-phase", `Wait ${waitId} generation ${generation} is already ${wait.phase}; cancellation is recorded once and cannot be repeated or replaced.`);
|
|
371
372
|
}
|
|
372
373
|
assertExpectedEpoch(wait, expectedCancelEpoch);
|
|
373
|
-
|
|
374
|
-
run(ctx, "UPDATE waits SET phase = 'cancelled', phase_reason = ?, cancel_epoch = cancel_epoch + 1, updated_at = ? WHERE wait_id = ? AND generation = ?", reason, at, waitId, generation);
|
|
375
|
-
const activeClaimRows = getRows(ctx, "SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')", waitId, generation);
|
|
376
|
-
const invalidatedClaimIds = activeClaimRows.map((row) => columnText(row, "claim_id"));
|
|
377
|
-
run(ctx, `UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
|
|
378
|
-
WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')`, at, reason, waitId, generation);
|
|
379
|
-
const voidedOutboxIds = voidGenerationOutbox(ctx, waitId, generation, reason, at);
|
|
380
|
-
releaseGenerationPins(ctx, waitId, generation, "wait-cancelled", at);
|
|
381
|
-
return {
|
|
382
|
-
wait: requireWait(ctx, waitId, generation),
|
|
383
|
-
invalidatedClaimIds,
|
|
384
|
-
voidedOutboxIds,
|
|
385
|
-
};
|
|
374
|
+
return cancelGeneration(ctx, waitId, generation, reason);
|
|
386
375
|
});
|
|
387
376
|
}
|
|
377
|
+
/** Caller holds the write transaction and has selected a nonterminal generation. */
|
|
378
|
+
export function cancelGeneration(ctx, waitId, generation, reason) {
|
|
379
|
+
const at = ctx.now();
|
|
380
|
+
run(ctx, "UPDATE waits SET phase = 'cancelled', phase_reason = ?, cancel_epoch = cancel_epoch + 1, updated_at = ? WHERE wait_id = ? AND generation = ?", reason, at, waitId, generation);
|
|
381
|
+
const activeClaimRows = getRows(ctx, "SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')", waitId, generation);
|
|
382
|
+
const invalidatedClaimIds = activeClaimRows.map((row) => columnText(row, "claim_id"));
|
|
383
|
+
run(ctx, `UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
|
|
384
|
+
WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')`, at, reason, waitId, generation);
|
|
385
|
+
const voidedOutboxIds = voidGenerationOutbox(ctx, waitId, generation, reason, at);
|
|
386
|
+
releaseGenerationPins(ctx, waitId, generation, "wait-cancelled", at);
|
|
387
|
+
return {
|
|
388
|
+
wait: requireWait(ctx, waitId, generation),
|
|
389
|
+
invalidatedClaimIds,
|
|
390
|
+
voidedOutboxIds,
|
|
391
|
+
};
|
|
392
|
+
}
|
|
388
393
|
// ---- resume claims ------------------------------------------------------
|
|
389
394
|
export function claimResume(ctx, input) {
|
|
390
395
|
const waitId = requireId("waitId", input.waitId);
|
|
@@ -395,6 +400,8 @@ export function claimResume(ctx, input) {
|
|
|
395
400
|
return ctx.transaction(() => {
|
|
396
401
|
assertCurrentGeneration(ctx, waitId, generation);
|
|
397
402
|
const wait = requireWait(ctx, waitId, generation);
|
|
403
|
+
if (ctx.now() >= taskDeadline(wait.createdAt))
|
|
404
|
+
throw new StoreError("wait-phase", "The 24-hour wait lifetime has expired.");
|
|
398
405
|
const active = getRows(ctx, "SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')", waitId, generation)[0];
|
|
399
406
|
if (active) {
|
|
400
407
|
throw new StoreError("concurrent-claim", `Wait ${waitId} generation ${generation} already has an active resume claim (${columnText(active, "claim_id")}). One conversation admits one writer; release or invalidate that claim instead of claiming again.`);
|
|
@@ -439,6 +446,8 @@ export function publishResumeAttempt(ctx, input) {
|
|
|
439
446
|
return ctx.transaction(() => {
|
|
440
447
|
assertCurrentGeneration(ctx, waitId, generation);
|
|
441
448
|
const wait = requireWait(ctx, waitId, generation);
|
|
449
|
+
if (ctx.now() >= taskDeadline(wait.createdAt))
|
|
450
|
+
throw new StoreError("wait-phase", "The 24-hour wait lifetime has expired.");
|
|
442
451
|
const claim = requireClaim(ctx, claimId);
|
|
443
452
|
if (claim.waitId !== waitId || claim.generation !== generation) {
|
|
444
453
|
throw new StoreError("claim-state", `Resume claim ${claimId} belongs to ${claim.waitId} generation ${claim.generation}, not ${waitId} generation ${generation}.`);
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* the cancellation epoch it observed. Cancellation invalidates the active resume
|
|
15
15
|
* claim, and a claim whose epoch no longer matches can never publish an attempt.
|
|
16
16
|
*/
|
|
17
|
+
import { taskDeadline } from "./task-lifetime.ts";
|
|
17
18
|
import { randomUUID } from "node:crypto";
|
|
18
19
|
import { StoreError } from "./errors.ts";
|
|
19
20
|
import {
|
|
@@ -606,41 +607,46 @@ export function cancelWait(ctx: StoreContext, input: CancelWaitInput): CancelWai
|
|
|
606
607
|
);
|
|
607
608
|
}
|
|
608
609
|
assertExpectedEpoch(wait, expectedCancelEpoch);
|
|
609
|
-
|
|
610
|
-
run(
|
|
611
|
-
ctx,
|
|
612
|
-
"UPDATE waits SET phase = 'cancelled', phase_reason = ?, cancel_epoch = cancel_epoch + 1, updated_at = ? WHERE wait_id = ? AND generation = ?",
|
|
613
|
-
reason,
|
|
614
|
-
at,
|
|
615
|
-
waitId,
|
|
616
|
-
generation,
|
|
617
|
-
);
|
|
618
|
-
const activeClaimRows = getRows(
|
|
619
|
-
ctx,
|
|
620
|
-
"SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')",
|
|
621
|
-
waitId,
|
|
622
|
-
generation,
|
|
623
|
-
);
|
|
624
|
-
const invalidatedClaimIds = activeClaimRows.map((row) => columnText(row, "claim_id"));
|
|
625
|
-
run(
|
|
626
|
-
ctx,
|
|
627
|
-
`UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
|
|
628
|
-
WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')`,
|
|
629
|
-
at,
|
|
630
|
-
reason,
|
|
631
|
-
waitId,
|
|
632
|
-
generation,
|
|
633
|
-
);
|
|
634
|
-
const voidedOutboxIds = voidGenerationOutbox(ctx, waitId, generation, reason, at);
|
|
635
|
-
releaseGenerationPins(ctx, waitId, generation, "wait-cancelled", at);
|
|
636
|
-
return {
|
|
637
|
-
wait: requireWait(ctx, waitId, generation),
|
|
638
|
-
invalidatedClaimIds,
|
|
639
|
-
voidedOutboxIds,
|
|
640
|
-
};
|
|
610
|
+
return cancelGeneration(ctx, waitId, generation, reason);
|
|
641
611
|
});
|
|
642
612
|
}
|
|
643
613
|
|
|
614
|
+
/** Caller holds the write transaction and has selected a nonterminal generation. */
|
|
615
|
+
export function cancelGeneration(ctx: StoreContext, waitId: string, generation: number, reason: string): CancelWaitResult {
|
|
616
|
+
const at = ctx.now();
|
|
617
|
+
run(
|
|
618
|
+
ctx,
|
|
619
|
+
"UPDATE waits SET phase = 'cancelled', phase_reason = ?, cancel_epoch = cancel_epoch + 1, updated_at = ? WHERE wait_id = ? AND generation = ?",
|
|
620
|
+
reason,
|
|
621
|
+
at,
|
|
622
|
+
waitId,
|
|
623
|
+
generation,
|
|
624
|
+
);
|
|
625
|
+
const activeClaimRows = getRows(
|
|
626
|
+
ctx,
|
|
627
|
+
"SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')",
|
|
628
|
+
waitId,
|
|
629
|
+
generation,
|
|
630
|
+
);
|
|
631
|
+
const invalidatedClaimIds = activeClaimRows.map((row) => columnText(row, "claim_id"));
|
|
632
|
+
run(
|
|
633
|
+
ctx,
|
|
634
|
+
`UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
|
|
635
|
+
WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')`,
|
|
636
|
+
at,
|
|
637
|
+
reason,
|
|
638
|
+
waitId,
|
|
639
|
+
generation,
|
|
640
|
+
);
|
|
641
|
+
const voidedOutboxIds = voidGenerationOutbox(ctx, waitId, generation, reason, at);
|
|
642
|
+
releaseGenerationPins(ctx, waitId, generation, "wait-cancelled", at);
|
|
643
|
+
return {
|
|
644
|
+
wait: requireWait(ctx, waitId, generation),
|
|
645
|
+
invalidatedClaimIds,
|
|
646
|
+
voidedOutboxIds,
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
|
|
644
650
|
// ---- resume claims ------------------------------------------------------
|
|
645
651
|
|
|
646
652
|
export function claimResume(ctx: StoreContext, input: ClaimResumeInput): ResumeClaimResult {
|
|
@@ -653,6 +659,7 @@ export function claimResume(ctx: StoreContext, input: ClaimResumeInput): ResumeC
|
|
|
653
659
|
return ctx.transaction(() => {
|
|
654
660
|
assertCurrentGeneration(ctx, waitId, generation);
|
|
655
661
|
const wait = requireWait(ctx, waitId, generation);
|
|
662
|
+
if (ctx.now() >= taskDeadline(wait.createdAt)) throw new StoreError("wait-phase", "The 24-hour wait lifetime has expired.");
|
|
656
663
|
const active = getRows(
|
|
657
664
|
ctx,
|
|
658
665
|
"SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')",
|
|
@@ -735,6 +742,7 @@ export function publishResumeAttempt(
|
|
|
735
742
|
return ctx.transaction(() => {
|
|
736
743
|
assertCurrentGeneration(ctx, waitId, generation);
|
|
737
744
|
const wait = requireWait(ctx, waitId, generation);
|
|
745
|
+
if (ctx.now() >= taskDeadline(wait.createdAt)) throw new StoreError("wait-phase", "The 24-hour wait lifetime has expired.");
|
|
738
746
|
const claim = requireClaim(ctx, claimId);
|
|
739
747
|
if (claim.waitId !== waitId || claim.generation !== generation) {
|
|
740
748
|
throw new StoreError(
|
|
@@ -273,7 +273,7 @@ function sameOperation(a, b) {
|
|
|
273
273
|
function load(dir, key) {
|
|
274
274
|
const path = join(dir, "events.jsonl");
|
|
275
275
|
if (!stat(path))
|
|
276
|
-
return { records: [], losses: emptyLosses() };
|
|
276
|
+
return { records: [], losses: emptyLosses(), needsRepair: false };
|
|
277
277
|
chmodSync(path, 0o600);
|
|
278
278
|
const raw = readSafe(path, MAX_BYTES);
|
|
279
279
|
const lines = raw.split("\n");
|
|
@@ -304,7 +304,8 @@ function load(dir, key) {
|
|
|
304
304
|
catch {
|
|
305
305
|
losses.malformed++;
|
|
306
306
|
}
|
|
307
|
-
|
|
307
|
+
const headerMatches = header && header.count === lines.length && header.digest === digest(key, "journal", lines.join("\n"));
|
|
308
|
+
if (header && !headerMatches)
|
|
308
309
|
losses.tampered++;
|
|
309
310
|
const records = [];
|
|
310
311
|
const seen = new Set();
|
|
@@ -340,7 +341,7 @@ function load(dir, key) {
|
|
|
340
341
|
seen.add(record.fingerprint);
|
|
341
342
|
records.push(record);
|
|
342
343
|
}
|
|
343
|
-
return { records, losses };
|
|
344
|
+
return { records, losses, needsRepair: !headerMatches || records.length !== lines.length };
|
|
344
345
|
}
|
|
345
346
|
function encode(journal, key) {
|
|
346
347
|
const lines = journal.records.map(record => JSON.stringify({ ...record, mac: digest(key, "event", JSON.stringify(record)) }));
|
|
@@ -460,31 +461,22 @@ export class SandboxDiagnostics {
|
|
|
460
461
|
return;
|
|
461
462
|
if (input.outcome === "succeeded" && !stat(join(dir, "events.jsonl")))
|
|
462
463
|
return;
|
|
463
|
-
locked(dir, () => {
|
|
464
|
+
const repaired = locked(dir, () => {
|
|
464
465
|
const key = installationKey(dir, input.outcome === "denied");
|
|
465
466
|
const journal = load(dir, key);
|
|
466
|
-
const before = JSON.stringify(journal.losses);
|
|
467
467
|
const pruned = retain(journal, key, now);
|
|
468
468
|
const fingerprint = imported ? digest(key, "relay-event-identity", identity([imported.runIdentity, imported.value.idFingerprint])) :
|
|
469
469
|
digest(key, "event-identity", randomBytes(32).toString("hex"));
|
|
470
470
|
// Signed record identities survive parent reloads and full log rescans.
|
|
471
|
-
|
|
472
|
-
if (pruned || journal.losses.malformed || journal.losses.tampered)
|
|
473
|
-
atomic(join(dir, "events.jsonl"), encode(journal, key));
|
|
474
|
-
if (issues(journal.losses).length)
|
|
475
|
-
this.report(new Error("Diagnostics collection has gaps."));
|
|
476
|
-
return;
|
|
477
|
-
}
|
|
471
|
+
const duplicate = imported && journal.records.some(r => r.fingerprint === fingerprint);
|
|
478
472
|
const operationFingerprint = digest(key, "operation", operation);
|
|
479
473
|
const recovered = new Set(journal.records.flatMap(r => r.recoveryOf ? [r.recoveryOf] : []));
|
|
480
474
|
const prior = [...journal.records].reverse().find(r => r.outcome === "denied" && r.context === this.options.context &&
|
|
481
475
|
r.tool === tool && r.operationFingerprint === operationFingerprint && r.timestamp <= now);
|
|
482
|
-
if (input.outcome === "succeeded" && (!prior || recovered.has(prior.fingerprint))) {
|
|
483
|
-
if (pruned ||
|
|
476
|
+
if (duplicate || (input.outcome === "succeeded" && (!prior || recovered.has(prior.fingerprint)))) {
|
|
477
|
+
if (pruned || journal.needsRepair)
|
|
484
478
|
atomic(join(dir, "events.jsonl"), encode(journal, key));
|
|
485
|
-
|
|
486
|
-
this.report(new Error("Diagnostics collection has gaps."));
|
|
487
|
-
return;
|
|
479
|
+
return journal.needsRepair;
|
|
488
480
|
}
|
|
489
481
|
const backend = imported?.value.backend ?? this.options.backend();
|
|
490
482
|
const version = imported?.value.version ?? this.options.version;
|
|
@@ -505,9 +497,10 @@ export class SandboxDiagnostics {
|
|
|
505
497
|
journal.records.push(record);
|
|
506
498
|
retain(journal, key, now);
|
|
507
499
|
atomic(join(dir, "events.jsonl"), encode(journal, key));
|
|
508
|
-
|
|
509
|
-
this.report(new Error("Diagnostics collection has gaps."));
|
|
500
|
+
return journal.needsRepair;
|
|
510
501
|
});
|
|
502
|
+
if (repaired)
|
|
503
|
+
this.report(new Error("Diagnostics collection has gaps."));
|
|
511
504
|
}
|
|
512
505
|
catch (error) {
|
|
513
506
|
this.report(this.options.relay || imported ? new Error("Diagnostics collection has gaps.") : error);
|
|
@@ -249,9 +249,9 @@ function sameOperation(a: DiagnosticRecord, b: DiagnosticRecord): boolean {
|
|
|
249
249
|
return a.context === b.context && a.tool === b.tool && a.operationFingerprint === b.operationFingerprint;
|
|
250
250
|
}
|
|
251
251
|
interface Journal { records: DiagnosticRecord[]; losses: DiagnosticLosses }
|
|
252
|
-
function load(dir: string, key: Buffer): Journal {
|
|
252
|
+
function load(dir: string, key: Buffer): Journal & { needsRepair: boolean } {
|
|
253
253
|
const path = join(dir, "events.jsonl");
|
|
254
|
-
if (!stat(path)) return { records: [], losses: emptyLosses() };
|
|
254
|
+
if (!stat(path)) return { records: [], losses: emptyLosses(), needsRepair: false };
|
|
255
255
|
chmodSync(path, 0o600);
|
|
256
256
|
const raw = readSafe(path, MAX_BYTES);
|
|
257
257
|
const lines = raw.split("\n");
|
|
@@ -273,7 +273,8 @@ function load(dir: string, key: Buffer): Journal {
|
|
|
273
273
|
} else losses.tampered++;
|
|
274
274
|
} else losses.malformed++;
|
|
275
275
|
} catch { losses.malformed++; }
|
|
276
|
-
|
|
276
|
+
const headerMatches = header && header.count === lines.length && header.digest === digest(key, "journal", lines.join("\n"));
|
|
277
|
+
if (header && !headerMatches) losses.tampered++;
|
|
277
278
|
const records: DiagnosticRecord[] = [];
|
|
278
279
|
const seen = new Set<string>();
|
|
279
280
|
const denied = new Map<string, DiagnosticRecord>();
|
|
@@ -293,7 +294,7 @@ function load(dir: string, key: Buffer): Journal {
|
|
|
293
294
|
seen.add(record.fingerprint);
|
|
294
295
|
records.push(record);
|
|
295
296
|
}
|
|
296
|
-
return { records, losses };
|
|
297
|
+
return { records, losses, needsRepair: !headerMatches || records.length !== lines.length };
|
|
297
298
|
}
|
|
298
299
|
function encode(journal: Journal, key: Buffer): string {
|
|
299
300
|
const lines = journal.records.map(record => JSON.stringify({ ...record, mac: digest(key, "event", JSON.stringify(record)) }));
|
|
@@ -385,27 +386,21 @@ export class SandboxDiagnostics {
|
|
|
385
386
|
const dir = directory(this.options, input.outcome === "denied");
|
|
386
387
|
if (!dir) return;
|
|
387
388
|
if (input.outcome === "succeeded" && !stat(join(dir, "events.jsonl"))) return;
|
|
388
|
-
locked(dir, () => {
|
|
389
|
+
const repaired = locked(dir, () => {
|
|
389
390
|
const key = installationKey(dir, input.outcome === "denied");
|
|
390
391
|
const journal = load(dir, key);
|
|
391
|
-
const before = JSON.stringify(journal.losses);
|
|
392
392
|
const pruned = retain(journal, key, now);
|
|
393
393
|
const fingerprint = imported ? digest(key, "relay-event-identity", identity([imported.runIdentity, imported.value.idFingerprint])) :
|
|
394
394
|
digest(key, "event-identity", randomBytes(32).toString("hex"));
|
|
395
395
|
// Signed record identities survive parent reloads and full log rescans.
|
|
396
|
-
|
|
397
|
-
if (pruned || journal.losses.malformed || journal.losses.tampered) atomic(join(dir, "events.jsonl"), encode(journal, key));
|
|
398
|
-
if (issues(journal.losses).length) this.report(new Error("Diagnostics collection has gaps."));
|
|
399
|
-
return;
|
|
400
|
-
}
|
|
396
|
+
const duplicate = imported && journal.records.some(r => r.fingerprint === fingerprint);
|
|
401
397
|
const operationFingerprint = digest(key, "operation", operation);
|
|
402
398
|
const recovered = new Set(journal.records.flatMap(r => r.recoveryOf ? [r.recoveryOf] : []));
|
|
403
399
|
const prior = [...journal.records].reverse().find(r => r.outcome === "denied" && r.context === this.options.context &&
|
|
404
400
|
r.tool === tool && r.operationFingerprint === operationFingerprint && r.timestamp <= now);
|
|
405
|
-
if (input.outcome === "succeeded" && (!prior || recovered.has(prior.fingerprint))) {
|
|
406
|
-
if (pruned ||
|
|
407
|
-
|
|
408
|
-
return;
|
|
401
|
+
if (duplicate || (input.outcome === "succeeded" && (!prior || recovered.has(prior.fingerprint)))) {
|
|
402
|
+
if (pruned || journal.needsRepair) atomic(join(dir, "events.jsonl"), encode(journal, key));
|
|
403
|
+
return journal.needsRepair;
|
|
409
404
|
}
|
|
410
405
|
const backend = imported?.value.backend ?? this.options.backend();
|
|
411
406
|
const version = imported?.value.version ?? this.options.version;
|
|
@@ -425,8 +420,9 @@ export class SandboxDiagnostics {
|
|
|
425
420
|
journal.records.push(record);
|
|
426
421
|
retain(journal, key, now);
|
|
427
422
|
atomic(join(dir, "events.jsonl"), encode(journal, key));
|
|
428
|
-
|
|
423
|
+
return journal.needsRepair;
|
|
429
424
|
});
|
|
425
|
+
if (repaired) this.report(new Error("Diagnostics collection has gaps."));
|
|
430
426
|
} catch (error) { this.report(this.options.relay || imported ? new Error("Diagnostics collection has gaps.") : error); }
|
|
431
427
|
}
|
|
432
428
|
}
|
|
@@ -27,6 +27,7 @@
|
|
|
27
27
|
* reparented descendants outside that group are out of contract and are
|
|
28
28
|
* never scanned for.
|
|
29
29
|
*/
|
|
30
|
+
import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.domain.mjs";
|
|
30
31
|
import { realProcessProbe } from "./health.domain.mjs";
|
|
31
32
|
import { classifyChildExit } from "./lifecycle.domain.mjs";
|
|
32
33
|
import { parseRunForLifecycle } from "./parse.domain.mjs";
|
|
@@ -74,9 +75,10 @@ function oweTerminalCompletion(meta, now) {
|
|
|
74
75
|
return;
|
|
75
76
|
meta.completionCallbackPendingAt = now;
|
|
76
77
|
}
|
|
77
|
-
function
|
|
78
|
-
meta.
|
|
79
|
-
meta.
|
|
78
|
+
function recordStopped(meta, now) {
|
|
79
|
+
const expired = meta.timing?.stopReason === "ceiling" && now >= (meta.timing.lifetimeAt ?? taskDeadline(meta.startedAt));
|
|
80
|
+
meta.status = expired ? "failed" : "killed";
|
|
81
|
+
meta.lifecycleClassification = expired ? "timed_out" : "killed";
|
|
80
82
|
meta.endedAt = now;
|
|
81
83
|
oweTerminalCompletion(meta, now);
|
|
82
84
|
writeMeta(meta);
|
|
@@ -131,7 +133,7 @@ function cleanupOrphanedRun(meta, probe, now) {
|
|
|
131
133
|
const pgid = relatedProcessGroupId(meta);
|
|
132
134
|
if (pgid !== undefined && probe.groupAlive(pgid)) {
|
|
133
135
|
terminateRelatedWork(meta);
|
|
134
|
-
return
|
|
136
|
+
return recordStopped(meta, now);
|
|
135
137
|
}
|
|
136
138
|
return finalizeOrphanedWithoutProcess(meta, now);
|
|
137
139
|
}
|
|
@@ -175,7 +177,7 @@ export function stopRun(id, deps = {}) {
|
|
|
175
177
|
// Supervised path: same process-group kill + killed write as before.
|
|
176
178
|
// Prefer recorded pgid so running and orphaned share one target rule.
|
|
177
179
|
terminateRelatedWork(meta);
|
|
178
|
-
return
|
|
180
|
+
return recordStopped(meta, now);
|
|
179
181
|
}
|
|
180
182
|
if (status === "orphaned") {
|
|
181
183
|
return cleanupOrphanedRun(meta, probe, now);
|