pi-better-server 0.7.3 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/runtime/background-tools.ts +146 -6
- package/src/runtime/background.ts +2 -2
- package/src/runtime/catalog.ts +30 -1
- package/src/runtime/ci-recovery.ts +172 -0
- package/src/runtime/domain/assignment-inbox.mjs +4 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -1
- package/src/runtime/domain/assignment-observation.mjs +1 -0
- package/src/runtime/domain/background/supervisor/identity.mjs +5 -0
- package/src/runtime/domain/background/supervisor/supervisor.mjs +3 -4
- package/src/runtime/domain/background-service/ci-observation.domain.mjs +134 -0
- package/src/runtime/domain/background-service/ci-observation.ts +118 -0
- package/src/runtime/domain/background-service/managed-client.domain.mjs +6 -2
- package/src/runtime/domain/background-service/managed-client.ts +6 -2
- package/src/runtime/domain/background-service/managed-frontend.domain.mjs +47 -7
- package/src/runtime/domain/background-service/managed-frontend.ts +36 -6
- package/src/runtime/domain/background-service/observed-waits.domain.mjs +36 -7
- package/src/runtime/domain/background-service/observed-waits.ts +33 -6
- package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +3 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +1 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +0 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +6 -4
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +7 -4
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +5 -12
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +5 -11
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +53 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +54 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +3 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +5 -5
- package/src/runtime/domain/background-service/supervisor/generated/identity.mjs +5 -0
- package/src/runtime/domain/background-service/supervisor/identity.domain.mjs +5 -0
- package/src/runtime/domain/background-service/supervisor/identity.ts +6 -0
- package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +3 -4
- package/src/runtime/domain/background-service/supervisor/supervisor.ts +3 -4
- package/src/runtime/domain/catalog/catalog-schema.d.mts +6 -0
- package/src/runtime/domain/catalog/catalog-schema.mjs +1 -0
- package/src/runtime/domain/catalog/roles/role.supervisor.md +16 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +0 -2
- package/src/runtime/domain/coordinator/src/discovery.mjs +6 -4
- package/src/runtime/domain/coordinator/src/operations.mjs +5 -12
- package/src/runtime/domain/coordinator/src/schema.mjs +53 -1
- package/src/runtime/domain/coordinator/src/store.mjs +3 -3
- package/src/runtime/domain/subagents/catalog-schema.domain.mjs +1 -0
- package/src/runtime/domain/subagents/catalog-schema.ts +1 -0
- package/src/runtime/domain/subagents/cleanup.domain.mjs +7 -10
- package/src/runtime/domain/subagents/cleanup.ts +6 -8
- package/src/runtime/domain/subagents/package.json +1 -1
- package/src/runtime/domain/subagents/registry.domain.mjs +9 -7
- package/src/runtime/domain/subagents/registry.ts +11 -6
- package/src/runtime/domain/subagents/retained-result.domain.mjs +3 -3
- package/src/runtime/domain/subagents/retained-result.ts +2 -3
- package/src/runtime/domain/subagents/roles/role.supervisor.md +16 -0
- package/src/runtime/domain/subagents/shared-catalog.domain.mjs +14 -2
- package/src/runtime/domain/subagents/shared-catalog.ts +14 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +3 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +1 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +0 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +6 -4
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +7 -4
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +5 -12
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +5 -11
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +53 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +54 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +3 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +5 -5
- package/src/runtime/domain/subagents/supervisor-client.mjs +36 -0
- package/src/runtime/domain/subagents/worker-waits.domain.mjs +3 -4
- package/src/runtime/domain/subagents/worker-waits.ts +3 -3
- package/src/runtime/domain/subagents/workspace-files.domain.mjs +19 -5
- package/src/runtime/domain/subagents/workspace-files.ts +27 -5
- package/src/runtime/queries.ts +17 -3
- package/src/runtime/query-executor.ts +46 -3
- package/src/runtime/query-worker.mjs +6 -1
- package/src/runtime/read-model.ts +14 -5
- package/src/runtime/result-supervision.ts +16 -5
- package/src/runtime/shared-read-diagnosis.ts +29 -0
- package/src/runtime/supervisor-admission.ts +42 -0
- package/src/runtime/supervisor-decisions.ts +60 -0
- package/src/server.ts +9 -8
- package/src/version.ts +1 -1
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
---
|
|
2
|
+
schema: pi-agent/v1
|
|
3
|
+
kind: role
|
|
4
|
+
id: role.supervisor
|
|
5
|
+
name: Supervisor
|
|
6
|
+
description: Diagnoses blocked or stalled Outcomes and reviews scope drift using evidence supplied for the affected owner.
|
|
7
|
+
defaults:
|
|
8
|
+
model: openai/gpt-6.1-sol
|
|
9
|
+
effort: medium
|
|
10
|
+
tier: balanced
|
|
11
|
+
---
|
|
12
|
+
Start from the current Outcome, acceptance criteria and evidence supplied for this owner. Cite the observations that support your diagnosis. If one fact would distinguish plausible causes, request the smallest authorized read-only check.
|
|
13
|
+
|
|
14
|
+
For a blocker, propose a recovery action, its prerequisites and a check of the original operation. If a CI watcher exits while its remote run is active, suggest resuming observation by the original run ID. For a stall, identify the last change to an acceptance criterion and test why progress stopped. For scope drift, identify necessary investigations and which planned steps the owner can prune.
|
|
15
|
+
|
|
16
|
+
Return the next action and its expected observable result to the execution owner. Consult prior interventions and approvals when supplied. Repeat a recommendation only when the evidence changes what the owner needs to do. Do not restart builds, wake sessions, grant approvals, or change an Outcome. The daemon controls delivery and the execution owner controls recovery.
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
// Generated canonical coordinator. Do not edit directly.
|
|
2
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
-
import { bumpChangeRevision } from "./discovery.mjs";
|
|
4
3
|
import { StoreError } from "./errors.mjs";
|
|
5
4
|
import { columnText, getRow, getRows, run } from "./sqlite.mjs";
|
|
6
5
|
import { requireWait, readPins } from "./rows.mjs";
|
|
@@ -108,7 +107,6 @@ export function recordAssignmentOutcome(ctx, input) {
|
|
|
108
107
|
for (const e of retained)
|
|
109
108
|
run(ctx, `INSERT OR IGNORE INTO evidence_pins (pin_id, wait_id, generation, operation_id, terminal_revision, kind, ref, summary, detail_lost, bytes, pinned_at) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)`, `pin_${randomUUID()}`, eventId, e.operationId, e.terminalRevision, e.kind, e.ref, e.summary ?? null, e.detailLost ? 1 : 0, e.bytes ?? null, at);
|
|
110
109
|
run(ctx, `INSERT INTO outbox_events (event_id, event_type, operation_id, terminal_revision, wait_id, generation, recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id, state, created_at) VALUES (?, 'assignment-outcome', ?, ?, ?, 1, ?, ?, ?, ?, ?, 'pending', ?)`, eventId, assignmentId, revision, eventId, recipient.kind, recipient.sessionId, recipient.workspace, recipient.branchId ?? null, recipient.goalId ?? null, at);
|
|
111
|
-
bumpChangeRevision(ctx);
|
|
112
110
|
return record;
|
|
113
111
|
});
|
|
114
112
|
}
|
|
@@ -33,13 +33,15 @@ export function readDiscoveryClaim(ctx, scope) {
|
|
|
33
33
|
return readClaim(ctx, requireId("scope", scope));
|
|
34
34
|
}
|
|
35
35
|
/** Read scope transfer and its discovery claim from one SQLite snapshot. */
|
|
36
|
-
export function readDiscoveryState(ctx, scope) {
|
|
36
|
+
export function readDiscoveryState(ctx, scope, hostId) {
|
|
37
37
|
scope = requireId("scope", scope);
|
|
38
38
|
const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed,
|
|
39
39
|
EXISTS(SELECT 1 FROM operations INDEXED BY operations_assignment_cleanup
|
|
40
|
-
WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks
|
|
41
|
-
|
|
42
|
-
|
|
40
|
+
WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks,
|
|
41
|
+
EXISTS(SELECT 1 FROM assignment_cleanup_pending WHERE supervision_host_id = ?) AS cleanup_pending
|
|
42
|
+
FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, hostId === undefined ? null : requireId("hostId", hostId), scope);
|
|
43
|
+
return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1,
|
|
44
|
+
...(hostId === undefined ? {} : { cleanupPending: Number(row.cleanup_pending) === 1 }) };
|
|
43
45
|
}
|
|
44
46
|
export function tryClaimDiscovery(ctx, input) {
|
|
45
47
|
const scope = requireId("scope", input.scope);
|
|
@@ -312,24 +312,17 @@ export function listOperations(ctx, filter = {}) {
|
|
|
312
312
|
return getRows(ctx, `SELECT *, EXISTS(SELECT 1 FROM coordinator_state s WHERE s.key = 'result-supervision-v1:' || operations.operation_id) AS result_managed FROM operations ${where} ORDER BY created_at, operation_id`, ...params)
|
|
313
313
|
.map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
|
|
314
314
|
}
|
|
315
|
-
export function listAssignmentCleanupOperations(ctx, limit, afterOperationId) {
|
|
315
|
+
export function listAssignmentCleanupOperations(ctx, limit, afterOperationId, hostId) {
|
|
316
316
|
const requested = requireCounter("limit", limit);
|
|
317
317
|
if (requested === 0)
|
|
318
318
|
throw new StoreError("validation", "Invalid limit: must be at least 1");
|
|
319
319
|
const cursor = afterOperationId === undefined ? "" : requireId("afterOperationId", afterOperationId);
|
|
320
|
-
|
|
320
|
+
const params = hostId === undefined ? [] : [requireId("hostId", hostId)];
|
|
321
321
|
return getRows(ctx, `SELECT op.*, EXISTS(SELECT 1 FROM coordinator_state s
|
|
322
322
|
WHERE s.key = 'result-supervision-v1:' || op.operation_id) AS result_managed
|
|
323
|
-
FROM operations op
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
WHERE op.assignment_attempt_id IS NOT NULL AND op.operation_id > ?
|
|
327
|
-
AND (op.terminal_revision = 0 OR op.terminal_outcome = 'lost'
|
|
328
|
-
OR EXISTS (SELECT 1 FROM operation_evidence e WHERE e.operation_id = op.operation_id
|
|
329
|
-
AND e.terminal_revision = op.terminal_revision AND e.kind = 'terminal-record'
|
|
330
|
-
AND e.summary LIKE '%groupCleanup=unproven%'))
|
|
331
|
-
AND NOT EXISTS (SELECT 1 FROM coordinator_state s WHERE s.key = 'assignment-cleanup-verified:' || op.operation_id)
|
|
332
|
-
ORDER BY op.operation_id LIMIT ?`, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
|
|
323
|
+
FROM assignment_cleanup_pending p CROSS JOIN operations op ON op.operation_id = p.operation_id
|
|
324
|
+
WHERE ${hostId === undefined ? "" : "p.supervision_host_id = ? AND "}p.operation_id > ?
|
|
325
|
+
ORDER BY p.operation_id LIMIT ?`, ...params, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
|
|
333
326
|
.map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
|
|
334
327
|
}
|
|
335
328
|
/** Running operations assigned to one supervising host, using the phase/host index. */
|
|
@@ -67,6 +67,42 @@ const EXPIRY_INDEXES = [
|
|
|
67
67
|
const ASSIGNMENT_CLEANUP_INDEX = `CREATE INDEX IF NOT EXISTS operations_assignment_cleanup
|
|
68
68
|
ON operations (operation_id, assignment_attempt_id)
|
|
69
69
|
WHERE assignment_attempt_id IS NOT NULL`;
|
|
70
|
+
// Terminal evidence is written before the operation's terminal revision in the same transaction.
|
|
71
|
+
function needsAssignmentCleanup(row) {
|
|
72
|
+
return `(${row}.terminal_revision = 0 OR ${row}.terminal_outcome = 'lost' OR EXISTS (
|
|
73
|
+
SELECT 1 FROM operation_evidence e WHERE e.operation_id = ${row}.operation_id
|
|
74
|
+
AND e.terminal_revision = ${row}.terminal_revision AND e.kind = 'terminal-record'
|
|
75
|
+
AND e.summary LIKE '%groupCleanup=unproven%'))`;
|
|
76
|
+
}
|
|
77
|
+
const CLEANUP_FOR_ASSIGNMENT = `SELECT op.operation_id, op.supervision_host_id
|
|
78
|
+
FROM assignment_attempts a JOIN operations op ON op.assignment_attempt_id = a.attempt_id
|
|
79
|
+
WHERE a.assignment_id = NEW.assignment_id AND ${needsAssignmentCleanup("op")}`;
|
|
80
|
+
// Triggers also cover older processes that still have an open coordinator connection.
|
|
81
|
+
const PENDING_CLEANUP_DDL = [
|
|
82
|
+
`CREATE TABLE IF NOT EXISTS assignment_cleanup_pending (
|
|
83
|
+
operation_id TEXT PRIMARY KEY REFERENCES operations(operation_id),
|
|
84
|
+
supervision_host_id TEXT
|
|
85
|
+
) WITHOUT ROWID`,
|
|
86
|
+
`CREATE INDEX assignment_cleanup_host ON assignment_cleanup_pending(supervision_host_id, operation_id)`,
|
|
87
|
+
`CREATE INDEX assignment_attempts_by_assignment ON assignment_attempts(assignment_id, attempt_id)`,
|
|
88
|
+
`CREATE INDEX operations_by_assignment_attempt ON operations(assignment_attempt_id)
|
|
89
|
+
WHERE assignment_attempt_id IS NOT NULL`,
|
|
90
|
+
`CREATE TRIGGER assignment_cleanup_enqueue AFTER INSERT ON assignment_outcomes BEGIN
|
|
91
|
+
INSERT INTO assignment_cleanup_pending ${CLEANUP_FOR_ASSIGNMENT};
|
|
92
|
+
END`,
|
|
93
|
+
`CREATE TRIGGER assignment_cleanup_terminal AFTER UPDATE OF terminal_revision ON operations
|
|
94
|
+
WHEN NEW.assignment_attempt_id IS NOT NULL AND NEW.terminal_revision > 0 AND NOT ${needsAssignmentCleanup("NEW")} BEGIN
|
|
95
|
+
DELETE FROM assignment_cleanup_pending WHERE operation_id = NEW.operation_id;
|
|
96
|
+
END`,
|
|
97
|
+
`CREATE TRIGGER assignment_cleanup_transfer AFTER UPDATE OF supervision_host_id ON operations
|
|
98
|
+
WHEN NEW.assignment_attempt_id IS NOT NULL AND NEW.supervision_host_id IS NOT OLD.supervision_host_id BEGIN
|
|
99
|
+
UPDATE assignment_cleanup_pending SET supervision_host_id = NEW.supervision_host_id WHERE operation_id = NEW.operation_id;
|
|
100
|
+
END`,
|
|
101
|
+
`CREATE TRIGGER assignment_cleanup_verified AFTER INSERT ON coordinator_state
|
|
102
|
+
WHEN NEW.key GLOB 'assignment-cleanup-verified:*' BEGIN
|
|
103
|
+
DELETE FROM assignment_cleanup_pending WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1);
|
|
104
|
+
END`,
|
|
105
|
+
];
|
|
70
106
|
const DDL = [
|
|
71
107
|
`CREATE TABLE task_cancellation_authorities (
|
|
72
108
|
credential_hash TEXT PRIMARY KEY,
|
|
@@ -288,6 +324,7 @@ const DDL = [
|
|
|
288
324
|
PRIMARY KEY (wait_id, generation)
|
|
289
325
|
)`,
|
|
290
326
|
RESULT_ADMISSION_FENCE,
|
|
327
|
+
...PENDING_CLEANUP_DDL,
|
|
291
328
|
];
|
|
292
329
|
const SCHEMA_VERSION_KEY = "schema_version";
|
|
293
330
|
function existingTables(ctx) {
|
|
@@ -358,14 +395,29 @@ function ensureAssignmentCleanupSchema(ctx) {
|
|
|
358
395
|
for (const statement of EXPIRY_INDEXES)
|
|
359
396
|
ctx.db.exec(statement);
|
|
360
397
|
const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
|
|
361
|
-
|
|
398
|
+
const hasPending = () => !!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'assignment_cleanup_pending'");
|
|
399
|
+
if (hasPending())
|
|
362
400
|
return;
|
|
363
401
|
ctx.transaction(() => {
|
|
402
|
+
if (hasPending())
|
|
403
|
+
return;
|
|
364
404
|
ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
|
|
365
405
|
// Legacy writers leave the nullable provenance unset.
|
|
366
406
|
if (!hasColumn())
|
|
367
407
|
ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
|
|
368
408
|
ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
|
|
409
|
+
for (const statement of PENDING_CLEANUP_DDL)
|
|
410
|
+
ctx.db.exec(statement);
|
|
411
|
+
if (process.platform === "win32") {
|
|
412
|
+
// Earlier Windows writers mistook an unsupported group probe for proof of exit.
|
|
413
|
+
ctx.db.exec("DELETE FROM coordinator_state WHERE key GLOB 'assignment-cleanup-verified:*'");
|
|
414
|
+
}
|
|
415
|
+
ctx.db.exec(`INSERT INTO assignment_cleanup_pending
|
|
416
|
+
SELECT op.operation_id, op.supervision_host_id FROM operations op
|
|
417
|
+
JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
|
|
418
|
+
JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
|
|
419
|
+
WHERE ${needsAssignmentCleanup("op")} AND NOT EXISTS (SELECT 1 FROM coordinator_state
|
|
420
|
+
WHERE key = 'assignment-cleanup-verified:' || op.operation_id)`);
|
|
369
421
|
});
|
|
370
422
|
}
|
|
371
423
|
/**
|
|
@@ -117,9 +117,9 @@ export function openStore(options) {
|
|
|
117
117
|
alive();
|
|
118
118
|
return readOperationRecords(ctx, filter);
|
|
119
119
|
},
|
|
120
|
-
listAssignmentCleanupOperations(limit, afterOperationId) {
|
|
120
|
+
listAssignmentCleanupOperations(limit, afterOperationId, hostId) {
|
|
121
121
|
alive();
|
|
122
|
-
return readAssignmentCleanupOperations(ctx, limit, afterOperationId);
|
|
122
|
+
return readAssignmentCleanupOperations(ctx, limit, afterOperationId, hostId);
|
|
123
123
|
},
|
|
124
124
|
verifyAssignmentCleanup(operationId, launchToken, terminalRevision) {
|
|
125
125
|
alive();
|
|
@@ -139,7 +139,7 @@ export function openStore(options) {
|
|
|
139
139
|
alive();
|
|
140
140
|
return readOperationEvidence(ctx, requireId("operationId", operationId), terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision));
|
|
141
141
|
},
|
|
142
|
-
readDiscoveryState(scope) { alive(); return readDiscoveryState(ctx, scope); },
|
|
142
|
+
readDiscoveryState(scope, hostId) { alive(); return readDiscoveryState(ctx, scope, hostId); },
|
|
143
143
|
readDiscoveryClaim(scope) {
|
|
144
144
|
alive();
|
|
145
145
|
return readClaim(ctx, scope);
|
|
@@ -71,6 +71,7 @@ export const APPROVED_ROLE_DEFAULTS = [
|
|
|
71
71
|
{ id: "role.developer", name: "Developer", model: "openai/gpt-6.1-sol", effort: "high", tier: "balanced" },
|
|
72
72
|
{ id: "role.reviewer", name: "Reviewer", model: "openai/gpt-6-astra", effort: "medium", tier: "frontier" },
|
|
73
73
|
{ id: "role.architect", name: "Architect", model: "openai/gpt-6-astra", effort: "high", tier: "frontier" },
|
|
74
|
+
{ id: "role.supervisor", name: "Supervisor", model: "openai/gpt-6.1-sol", effort: "medium", tier: "balanced" },
|
|
74
75
|
{ id: "role.writer", name: "Writer", model: "openai/gpt-6.1-terra", effort: "medium", tier: undefined },
|
|
75
76
|
];
|
|
76
77
|
export const DiagnosticCodes = {
|
|
@@ -85,6 +85,7 @@ export const APPROVED_ROLE_DEFAULTS = [
|
|
|
85
85
|
{ id: "role.developer", name: "Developer", model: "openai/gpt-6.1-sol", effort: "high", tier: "balanced" },
|
|
86
86
|
{ id: "role.reviewer", name: "Reviewer", model: "openai/gpt-6-astra", effort: "medium", tier: "frontier" },
|
|
87
87
|
{ id: "role.architect", name: "Architect", model: "openai/gpt-6-astra", effort: "high", tier: "frontier" },
|
|
88
|
+
{ id: "role.supervisor", name: "Supervisor", model: "openai/gpt-6.1-sol", effort: "medium", tier: "balanced" },
|
|
88
89
|
{ id: "role.writer", name: "Writer", model: "openai/gpt-6.1-terra", effort: "medium", tier: undefined },
|
|
89
90
|
] as const;
|
|
90
91
|
|
|
@@ -768,24 +768,21 @@ export function enforceRegistrySizeCapOnce(options = {}) {
|
|
|
768
768
|
};
|
|
769
769
|
const bytesById = new Map(entries.map((entry) => [entry.id, entry.bytes]));
|
|
770
770
|
const removed = [];
|
|
771
|
-
let
|
|
771
|
+
let reclaimedBytes = 0;
|
|
772
772
|
for (const id of plan.remove) {
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
retainedBytes += bytesById.get(id) ?? 0;
|
|
773
|
+
if (removeSizeCappedRun(id, scope, errors) !== "removed")
|
|
774
|
+
continue;
|
|
775
|
+
removed.push(id);
|
|
776
|
+
reclaimedBytes += bytesById.get(id) ?? 0;
|
|
778
777
|
}
|
|
779
|
-
|
|
780
|
-
// the shortfall it reports stay honest.
|
|
781
|
-
const keptBytes = plan.keptBytes + retainedBytes;
|
|
778
|
+
const keptBytes = totalBytes - reclaimedBytes;
|
|
782
779
|
try {
|
|
783
780
|
writeCleanupState({ ...state, lastSizeSweepAt: options.now ?? Date.now() });
|
|
784
781
|
}
|
|
785
782
|
catch (err) {
|
|
786
783
|
errors.push(`${cleanupStatePath()}: ${err instanceof Error ? err.message : String(err)}`);
|
|
787
784
|
}
|
|
788
|
-
return {
|
|
785
|
+
return { ran: true, remove: plan.remove, removed, reclaimedBytes, keptBytes, overBudget: keptBytes > maxBytes, errors };
|
|
789
786
|
}
|
|
790
787
|
/**
|
|
791
788
|
* Remove one planned size-cap candidate, serialized with its conversation.
|
|
@@ -969,15 +969,13 @@ export function enforceRegistrySizeCapOnce(options: SizeCapOptions = {}): SizeCa
|
|
|
969
969
|
};
|
|
970
970
|
const bytesById = new Map(entries.map((entry) => [entry.id, entry.bytes]));
|
|
971
971
|
const removed: string[] = [];
|
|
972
|
-
let
|
|
972
|
+
let reclaimedBytes = 0;
|
|
973
973
|
for (const id of plan.remove) {
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
974
|
+
if (removeSizeCappedRun(id, scope, errors) !== "removed") continue;
|
|
975
|
+
removed.push(id);
|
|
976
|
+
reclaimedBytes += bytesById.get(id) ?? 0;
|
|
977
977
|
}
|
|
978
|
-
|
|
979
|
-
// the shortfall it reports stay honest.
|
|
980
|
-
const keptBytes = plan.keptBytes + retainedBytes;
|
|
978
|
+
const keptBytes = totalBytes - reclaimedBytes;
|
|
981
979
|
|
|
982
980
|
try {
|
|
983
981
|
writeCleanupState({ ...state, lastSizeSweepAt: options.now ?? Date.now() });
|
|
@@ -985,7 +983,7 @@ export function enforceRegistrySizeCapOnce(options: SizeCapOptions = {}): SizeCa
|
|
|
985
983
|
errors.push(`${cleanupStatePath()}: ${err instanceof Error ? err.message : String(err)}`);
|
|
986
984
|
}
|
|
987
985
|
|
|
988
|
-
return {
|
|
986
|
+
return { ran: true, remove: plan.remove, removed, reclaimedBytes, keptBytes, overBudget: keptBytes > maxBytes, errors };
|
|
989
987
|
}
|
|
990
988
|
|
|
991
989
|
/**
|
|
@@ -184,24 +184,26 @@ export function listParkRecordCandidates(metas = listMetas()) {
|
|
|
184
184
|
|| (volatileIds.has(meta.id) && existsSync(parkRecordPath(meta.id))));
|
|
185
185
|
}
|
|
186
186
|
/** Read recovery sidecars in batches so a large registry does not block socket replies. */
|
|
187
|
-
export async function* scanParkRecords(metas = listMetas()) {
|
|
187
|
+
export async function* scanParkRecords(metas = listMetas(), include) {
|
|
188
188
|
const runs = join(baseDir(), "runs");
|
|
189
|
-
const volatileIds =
|
|
189
|
+
const volatileIds = await readdir(runs).then(ids => new Set(ids), (error) => error.code === "ENOENT" ? new Set() : undefined);
|
|
190
190
|
const batchSize = 32;
|
|
191
191
|
for (let offset = 0; offset < metas.length; offset += batchSize) {
|
|
192
192
|
const batch = await Promise.all(metas.slice(offset, offset + batchSize).map(async (meta) => {
|
|
193
|
-
if (
|
|
193
|
+
if (meta.park && include && !include(meta.park))
|
|
194
|
+
return;
|
|
195
|
+
if (volatileIds && !volatileIds.has(meta.id))
|
|
196
|
+
return meta.park ? { meta, record: meta.park } : undefined;
|
|
197
|
+
if (!volatileIds && !meta.park)
|
|
194
198
|
return;
|
|
195
199
|
try {
|
|
196
200
|
const record = parseParkRecord(JSON.parse(await readFile(join(runs, meta.id, "park.json"), "utf-8")));
|
|
197
|
-
if (record)
|
|
201
|
+
if (record && (!include || include(record)))
|
|
198
202
|
return { meta, record };
|
|
199
203
|
}
|
|
200
204
|
catch (error) {
|
|
201
205
|
if (error.code === "ENOENT" && meta.park) {
|
|
202
|
-
|
|
203
|
-
if (record)
|
|
204
|
-
return { meta, record };
|
|
206
|
+
return { meta, record: meta.park };
|
|
205
207
|
}
|
|
206
208
|
}
|
|
207
209
|
}));
|
|
@@ -544,20 +544,25 @@ export function listParkRecordCandidates(metas: readonly RunMeta[] = listMetas()
|
|
|
544
544
|
}
|
|
545
545
|
|
|
546
546
|
/** Read recovery sidecars in batches so a large registry does not block socket replies. */
|
|
547
|
-
export async function* scanParkRecords(
|
|
547
|
+
export async function* scanParkRecords(
|
|
548
|
+
metas: readonly RunMeta[] = listMetas(),
|
|
549
|
+
include?: (record: ParkRecord) => boolean,
|
|
550
|
+
): AsyncGenerator<{ meta: RunMeta; record: ParkRecord }> {
|
|
548
551
|
const runs = join(baseDir(), "runs");
|
|
549
|
-
const volatileIds =
|
|
552
|
+
const volatileIds = await readdir(runs).then(ids => new Set(ids),
|
|
553
|
+
(error: NodeJS.ErrnoException) => error.code === "ENOENT" ? new Set<string>() : undefined);
|
|
550
554
|
const batchSize = 32;
|
|
551
555
|
for (let offset = 0; offset < metas.length; offset += batchSize) {
|
|
552
556
|
const batch = await Promise.all(metas.slice(offset, offset + batchSize).map(async (meta) => {
|
|
553
|
-
if (
|
|
557
|
+
if (meta.park && include && !include(meta.park)) return;
|
|
558
|
+
if (volatileIds && !volatileIds.has(meta.id)) return meta.park ? { meta, record: meta.park } : undefined;
|
|
559
|
+
if (!volatileIds && !meta.park) return;
|
|
554
560
|
try {
|
|
555
561
|
const record = parseParkRecord(JSON.parse(await readFile(join(runs, meta.id, "park.json"), "utf-8")));
|
|
556
|
-
if (record) return { meta, record };
|
|
562
|
+
if (record && (!include || include(record))) return { meta, record };
|
|
557
563
|
} catch (error) {
|
|
558
564
|
if ((error as NodeJS.ErrnoException).code === "ENOENT" && meta.park) {
|
|
559
|
-
|
|
560
|
-
if (record) return { meta, record };
|
|
565
|
+
return { meta, record: meta.park };
|
|
561
566
|
}
|
|
562
567
|
}
|
|
563
568
|
}));
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Generated fixed launch domain from packages/pi-better-subagents/retained-result.ts. Do not edit directly.
|
|
2
|
-
import { copyFileSync,
|
|
2
|
+
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync, } from "node:fs";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
|
-
import { snapshotTree, verifyTree } from "./workspace-files.domain.mjs";
|
|
4
|
+
import { copyTree, snapshotTree, verifyTree } from "./workspace-files.domain.mjs";
|
|
5
5
|
import { resultDir } from "./session-store.domain.mjs";
|
|
6
6
|
// Published only while retiring a quiescent attempt. A result record can answer reads,
|
|
7
7
|
// but cannot authorize admission, revive a writer or make a failed attempt resumable.
|
|
@@ -26,7 +26,7 @@ export function retainResult(meta, logPath, scratch) {
|
|
|
26
26
|
if (scratch && existsSync(scratch)) {
|
|
27
27
|
const files = snapshotTree(scratch);
|
|
28
28
|
if (files.some((entry) => entry.name !== ".sandbox-anchor")) {
|
|
29
|
-
|
|
29
|
+
copyTree(scratch, join(temp, "scratch"), files);
|
|
30
30
|
verifyTree(join(temp, "scratch"), files);
|
|
31
31
|
verifyTree(scratch, files);
|
|
32
32
|
savedScratch = join(dir, "scratch");
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import {
|
|
2
2
|
copyFileSync,
|
|
3
|
-
cpSync,
|
|
4
3
|
existsSync,
|
|
5
4
|
mkdirSync,
|
|
6
5
|
mkdtempSync,
|
|
@@ -10,7 +9,7 @@ import {
|
|
|
10
9
|
writeFileSync,
|
|
11
10
|
} from "node:fs";
|
|
12
11
|
import { dirname, join } from "node:path";
|
|
13
|
-
import { snapshotTree, verifyTree } from "./workspace-files.ts";
|
|
12
|
+
import { copyTree, snapshotTree, verifyTree } from "./workspace-files.ts";
|
|
14
13
|
import type { RunMeta } from "./registry.ts";
|
|
15
14
|
import { resultDir } from "./session-store.ts";
|
|
16
15
|
|
|
@@ -35,7 +34,7 @@ export function retainResult(meta: RunMeta, logPath: string, scratch?: string):
|
|
|
35
34
|
if (scratch && existsSync(scratch)) {
|
|
36
35
|
const files = snapshotTree(scratch);
|
|
37
36
|
if (files.some((entry) => entry.name !== ".sandbox-anchor")) {
|
|
38
|
-
|
|
37
|
+
copyTree(scratch, join(temp, "scratch"), files);
|
|
39
38
|
verifyTree(join(temp, "scratch"), files);
|
|
40
39
|
verifyTree(scratch, files);
|
|
41
40
|
savedScratch = join(dir, "scratch");
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
---
|
|
2
|
+
schema: pi-agent/v1
|
|
3
|
+
kind: role
|
|
4
|
+
id: role.supervisor
|
|
5
|
+
name: Supervisor
|
|
6
|
+
description: Diagnoses blocked or stalled Outcomes and reviews scope drift using evidence supplied for the affected owner.
|
|
7
|
+
defaults:
|
|
8
|
+
model: openai/gpt-6.1-sol
|
|
9
|
+
effort: medium
|
|
10
|
+
tier: balanced
|
|
11
|
+
---
|
|
12
|
+
Start from the current Outcome, acceptance criteria and evidence supplied for this owner. Cite the observations that support your diagnosis. If one fact would distinguish plausible causes, request the smallest authorized read-only check.
|
|
13
|
+
|
|
14
|
+
For a blocker, propose a recovery action, its prerequisites and a check of the original operation. If a CI watcher exits while its remote run is active, suggest resuming observation by the original run ID. For a stall, identify the last change to an acceptance criterion and test why progress stopped. For scope drift, identify necessary investigations and which planned steps the owner can prune.
|
|
15
|
+
|
|
16
|
+
Return the next action and its expected observable result to the execution owner. Consult prior interventions and approvals when supplied. Repeat a recommendation only when the evidence changes what the owner needs to do. Do not restart builds, wake sessions, grant approvals, or change an Outcome. The daemon controls delivery and the execution owner controls recovery.
|
|
@@ -5,7 +5,7 @@ import { connectWorkClient } from "./shared-work-client.mjs";
|
|
|
5
5
|
import { catalogSnapshotFromWire, defaultUserRoot } from "./catalog-store.domain.mjs";
|
|
6
6
|
import { catalogHostAuthority } from "./catalog-host-admission.domain.mjs";
|
|
7
7
|
/** Short-lived catalog connection. No transcript or permission authority travels here. */
|
|
8
|
-
export async function openSharedCatalog(cwd, userRoot = defaultUserRoot(), sessionId = "catalog", projectAccess, signal) {
|
|
8
|
+
export async function openSharedCatalog(cwd, userRoot = defaultUserRoot(), sessionId = "catalog", projectAccess, signal, hostAuthority = catalogHostAuthority) {
|
|
9
9
|
signal?.throwIfAborted();
|
|
10
10
|
const agentDir = realpathSync(userRoot);
|
|
11
11
|
let registration;
|
|
@@ -22,7 +22,7 @@ export async function openSharedCatalog(cwd, userRoot = defaultUserRoot(), sessi
|
|
|
22
22
|
throw new Error("Invalid canonical runtime registration");
|
|
23
23
|
const client = await connectCatalogClient(agentDir, registration.serverDir, undefined, signal);
|
|
24
24
|
const register = async (setupSignal) => {
|
|
25
|
-
const authority = await
|
|
25
|
+
const authority = await hostAuthority(agentDir, cwd, join(registration.serverDir, "pi-server.sock"));
|
|
26
26
|
setupSignal?.throwIfAborted();
|
|
27
27
|
await client.request("runtime_register_catalog", { cwd, sessionId: authority?.sessionId ?? sessionId, authority, projectAccess: projectAccess === false ? "deny" : undefined });
|
|
28
28
|
};
|
|
@@ -39,6 +39,18 @@ export async function openSharedCatalog(cwd, userRoot = defaultUserRoot(), sessi
|
|
|
39
39
|
const wire = await client.request("runtime_get_catalog", { overlay });
|
|
40
40
|
return catalogSnapshotFromWire(wire);
|
|
41
41
|
},
|
|
42
|
+
async decision(action, scope, token, answer) {
|
|
43
|
+
await register();
|
|
44
|
+
return client.request("runtime_supervisor_review", { action, scope, token, answer });
|
|
45
|
+
},
|
|
46
|
+
async sharedReadDiagnosis(verifiedIncident) {
|
|
47
|
+
await register();
|
|
48
|
+
return client.request("runtime_supervisor_review", { action: "read-health", verifiedIncident });
|
|
49
|
+
},
|
|
50
|
+
async review(scenario, action, token) {
|
|
51
|
+
await register();
|
|
52
|
+
return client.request("runtime_supervisor_review", { scenario, action, token });
|
|
53
|
+
},
|
|
42
54
|
async edit(edit) { await register(); return client.request("runtime_edit_catalog", edit); },
|
|
43
55
|
async scopedAgents(scope) { await register(); return client.request("runtime_get_catalog_scope", { scope }); },
|
|
44
56
|
async subscribe(changed) {
|
|
@@ -6,7 +6,7 @@ import type { AgentSessionOverrides } from "./agent-session-settings.ts";
|
|
|
6
6
|
import { catalogHostAuthority } from "./catalog-host-admission.ts";
|
|
7
7
|
|
|
8
8
|
/** Short-lived catalog connection. No transcript or permission authority travels here. */
|
|
9
|
-
export async function openSharedCatalog(cwd: string, userRoot = defaultUserRoot(), sessionId = "catalog", projectAccess?: boolean, signal?: AbortSignal) {
|
|
9
|
+
export async function openSharedCatalog(cwd: string, userRoot = defaultUserRoot(), sessionId = "catalog", projectAccess?: boolean, signal?: AbortSignal, hostAuthority = catalogHostAuthority) {
|
|
10
10
|
signal?.throwIfAborted();
|
|
11
11
|
const agentDir = realpathSync(userRoot);
|
|
12
12
|
let registration;
|
|
@@ -19,7 +19,7 @@ export async function openSharedCatalog(cwd: string, userRoot = defaultUserRoot(
|
|
|
19
19
|
if (registration.version !== 1 || registration.agentDir !== agentDir) throw new Error("Invalid canonical runtime registration");
|
|
20
20
|
const client = await connectCatalogClient(agentDir, registration.serverDir, undefined, signal);
|
|
21
21
|
const register = async (setupSignal?: AbortSignal) => {
|
|
22
|
-
const authority = await
|
|
22
|
+
const authority = await hostAuthority(agentDir, cwd, join(registration.serverDir, "pi-server.sock"));
|
|
23
23
|
setupSignal?.throwIfAborted();
|
|
24
24
|
await client.request("runtime_register_catalog", { cwd, sessionId: authority?.sessionId ?? sessionId, authority, projectAccess: projectAccess === false ? "deny" : undefined });
|
|
25
25
|
};
|
|
@@ -32,6 +32,18 @@ export async function openSharedCatalog(cwd: string, userRoot = defaultUserRoot(
|
|
|
32
32
|
const wire = await client.request("runtime_get_catalog", { overlay });
|
|
33
33
|
return catalogSnapshotFromWire(wire);
|
|
34
34
|
},
|
|
35
|
+
async decision(action: string, scope: Record<string, string>, token?: string, answer?: string) {
|
|
36
|
+
await register();
|
|
37
|
+
return client.request("runtime_supervisor_review", { action, scope, token, answer });
|
|
38
|
+
},
|
|
39
|
+
async sharedReadDiagnosis(verifiedIncident?: string): Promise<{ status: string; incident?: { id: string; recommendation: string } }> {
|
|
40
|
+
await register();
|
|
41
|
+
return client.request("runtime_supervisor_review", { action: "read-health", verifiedIncident });
|
|
42
|
+
},
|
|
43
|
+
async review(scenario: string, action: "begin" | "finish" | "release", token?: string): Promise<{ status: string; token?: string }> {
|
|
44
|
+
await register();
|
|
45
|
+
return client.request("runtime_supervisor_review", { scenario, action, token });
|
|
46
|
+
},
|
|
35
47
|
async edit(edit: Record<string, unknown>) { await register(); return client.request("runtime_edit_catalog", edit); },
|
|
36
48
|
async scopedAgents(scope: "user" | "project") { await register(); return client.request("runtime_get_catalog_scope", { scope }); },
|
|
37
49
|
async subscribe(changed: (snapshot: CatalogSnapshot | undefined) => void) {
|
|
@@ -129,6 +129,9 @@ export class AssignmentInbox {
|
|
|
129
129
|
throw error;
|
|
130
130
|
}
|
|
131
131
|
}
|
|
132
|
+
get hasPendingChanges() {
|
|
133
|
+
return Boolean(this.more || this.db.prepare(`SELECT 1 FROM ${this.prefix}pending LIMIT 1`).get());
|
|
134
|
+
}
|
|
132
135
|
get metrics() {
|
|
133
136
|
const pending = this.db.prepare(`SELECT count(*) AS pending, min(since) AS oldestPendingAt FROM ${this.prefix}pending`).get();
|
|
134
137
|
return { ...this.db.prepare(`SELECT * FROM ${this.prefix}position`).get(),
|
package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs
CHANGED
|
@@ -102,6 +102,7 @@ export function createAssignmentReader(path, inboxPath = ":memory:", derivedConn
|
|
|
102
102
|
this.revision(); return db; },
|
|
103
103
|
changes() { this.revision(); return inbox.receive(db, identity); },
|
|
104
104
|
acknowledgeChanges(batch, complete) { inbox.acknowledge(batch, complete); },
|
|
105
|
+
get hasPendingChanges() { return inbox.hasPendingChanges; },
|
|
105
106
|
get changeMetrics() { return inbox.metrics; },
|
|
106
107
|
get snapshotActive() { return snapshot; },
|
|
107
108
|
beginSnapshot() {
|
package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
// Generated fixed launch domain from packages/pi-better-subagents/shared-operation-coordinator/src/assignment-outcomes.ts. Do not edit directly.
|
|
2
2
|
// Generated from packages/operation-coordinator/src/assignment-outcomes.ts. Do not edit directly.
|
|
3
3
|
import { createHash, randomUUID } from "node:crypto";
|
|
4
|
-
import { bumpChangeRevision } from "./discovery.domain.mjs";
|
|
5
4
|
import { StoreError } from "./errors.domain.mjs";
|
|
6
5
|
import { columnText, getRow, getRows, run } from "./sqlite.domain.mjs";
|
|
7
6
|
import { requireWait, readPins } from "./rows.domain.mjs";
|
|
@@ -109,7 +108,6 @@ export function recordAssignmentOutcome(ctx, input) {
|
|
|
109
108
|
for (const e of retained)
|
|
110
109
|
run(ctx, `INSERT OR IGNORE INTO evidence_pins (pin_id, wait_id, generation, operation_id, terminal_revision, kind, ref, summary, detail_lost, bytes, pinned_at) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)`, `pin_${randomUUID()}`, eventId, e.operationId, e.terminalRevision, e.kind, e.ref, e.summary ?? null, e.detailLost ? 1 : 0, e.bytes ?? null, at);
|
|
111
110
|
run(ctx, `INSERT INTO outbox_events (event_id, event_type, operation_id, terminal_revision, wait_id, generation, recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id, state, created_at) VALUES (?, 'assignment-outcome', ?, ?, ?, 1, ?, ?, ?, ?, ?, 'pending', ?)`, eventId, assignmentId, revision, eventId, recipient.kind, recipient.sessionId, recipient.workspace, recipient.branchId ?? null, recipient.goalId ?? null, at);
|
|
112
|
-
bumpChangeRevision(ctx);
|
|
113
111
|
return record;
|
|
114
112
|
});
|
|
115
113
|
}
|
package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
// Generated from packages/operation-coordinator/src/assignment-outcomes.ts. Do not edit directly.
|
|
2
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
-
import { bumpChangeRevision } from "./discovery.ts";
|
|
4
3
|
import { StoreError } from "./errors.ts";
|
|
5
4
|
import { columnText, getRow, getRows, run, type StoreContext } from "./sqlite.ts";
|
|
6
5
|
import { requireWait, readPins } from "./rows.ts";
|
|
@@ -121,7 +120,6 @@ export function recordAssignmentOutcome(ctx: StoreContext, input: AssignmentOutc
|
|
|
121
120
|
}
|
|
122
121
|
for (const e of retained) run(ctx, `INSERT OR IGNORE INTO evidence_pins (pin_id, wait_id, generation, operation_id, terminal_revision, kind, ref, summary, detail_lost, bytes, pinned_at) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)`, `pin_${randomUUID()}`, eventId, e.operationId, e.terminalRevision, e.kind, e.ref, e.summary ?? null, e.detailLost ? 1 : 0, e.bytes ?? null, at);
|
|
123
122
|
run(ctx, `INSERT INTO outbox_events (event_id, event_type, operation_id, terminal_revision, wait_id, generation, recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id, state, created_at) VALUES (?, 'assignment-outcome', ?, ?, ?, 1, ?, ?, ?, ?, ?, 'pending', ?)`, eventId, assignmentId, revision, eventId, recipient.kind, recipient.sessionId, recipient.workspace, recipient.branchId ?? null, recipient.goalId ?? null, at);
|
|
124
|
-
bumpChangeRevision(ctx);
|
|
125
123
|
return record;
|
|
126
124
|
});
|
|
127
125
|
}
|
|
@@ -34,13 +34,15 @@ export function readDiscoveryClaim(ctx, scope) {
|
|
|
34
34
|
return readClaim(ctx, requireId("scope", scope));
|
|
35
35
|
}
|
|
36
36
|
/** Read scope transfer and its discovery claim from one SQLite snapshot. */
|
|
37
|
-
export function readDiscoveryState(ctx, scope) {
|
|
37
|
+
export function readDiscoveryState(ctx, scope, hostId) {
|
|
38
38
|
scope = requireId("scope", scope);
|
|
39
39
|
const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed,
|
|
40
40
|
EXISTS(SELECT 1 FROM operations INDEXED BY operations_assignment_cleanup
|
|
41
|
-
WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks
|
|
42
|
-
|
|
43
|
-
|
|
41
|
+
WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks,
|
|
42
|
+
EXISTS(SELECT 1 FROM assignment_cleanup_pending WHERE supervision_host_id = ?) AS cleanup_pending
|
|
43
|
+
FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, hostId === undefined ? null : requireId("hostId", hostId), scope);
|
|
44
|
+
return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1,
|
|
45
|
+
...(hostId === undefined ? {} : { cleanupPending: Number(row.cleanup_pending) === 1 }) };
|
|
44
46
|
}
|
|
45
47
|
export function tryClaimDiscovery(ctx, input) {
|
|
46
48
|
const scope = requireId("scope", input.scope);
|
|
@@ -49,13 +49,16 @@ export function readDiscoveryClaim(ctx: StoreContext, scope: unknown): Discovery
|
|
|
49
49
|
}
|
|
50
50
|
|
|
51
51
|
/** Read scope transfer and its discovery claim from one SQLite snapshot. */
|
|
52
|
-
export function readDiscoveryState(ctx: StoreContext, scope: string): { managed: boolean; claim: DiscoveryClaimRecord | null; hasAssignmentTasks: boolean } {
|
|
52
|
+
export function readDiscoveryState(ctx: StoreContext, scope: string, hostId?: string): { managed: boolean; claim: DiscoveryClaimRecord | null; hasAssignmentTasks: boolean; cleanupPending?: boolean } {
|
|
53
53
|
scope = requireId("scope", scope);
|
|
54
54
|
const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed,
|
|
55
55
|
EXISTS(SELECT 1 FROM operations INDEXED BY operations_assignment_cleanup
|
|
56
|
-
WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks
|
|
57
|
-
|
|
58
|
-
|
|
56
|
+
WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks,
|
|
57
|
+
EXISTS(SELECT 1 FROM assignment_cleanup_pending WHERE supervision_host_id = ?) AS cleanup_pending
|
|
58
|
+
FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope,
|
|
59
|
+
hostId === undefined ? null : requireId("hostId", hostId), scope)!;
|
|
60
|
+
return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1,
|
|
61
|
+
...(hostId === undefined ? {} : { cleanupPending: Number(row.cleanup_pending) === 1 }) };
|
|
59
62
|
}
|
|
60
63
|
|
|
61
64
|
export function tryClaimDiscovery(
|