@mastra/factory 0.12.1-alpha.1 → 0.13.0-alpha.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/README.md +10 -0
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +64 -8
- package/dist/factory.js.map +1 -1
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +26 -2
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/routes/attention-providers.d.ts +17 -0
- package/dist/routes/attention-providers.d.ts.map +1 -1
- package/dist/routes/attention-providers.js +128 -2
- package/dist/routes/attention-providers.js.map +1 -1
- package/dist/routes/attention.d.ts.map +1 -1
- package/dist/routes/attention.js +11 -4
- package/dist/routes/attention.js.map +1 -1
- package/dist/routes/supervisor.d.ts +23 -0
- package/dist/routes/supervisor.d.ts.map +1 -0
- package/dist/routes/supervisor.js +34 -0
- package/dist/routes/supervisor.js.map +1 -0
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +5 -0
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/defaults.d.ts.map +1 -1
- package/dist/rules/defaults.js +4 -2
- package/dist/rules/defaults.js.map +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +49 -21
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/terminal-cleanup.d.ts +3 -1
- package/dist/rules/terminal-cleanup.d.ts.map +1 -1
- package/dist/rules/terminal-cleanup.js +5 -0
- package/dist/rules/terminal-cleanup.js.map +1 -1
- package/dist/rules/transition-service.d.ts +1 -0
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +2 -1
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/rules/types.d.ts +5 -0
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +36 -1
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +144 -2
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/supervisor/health-worker.d.ts +17 -0
- package/dist/supervisor/health-worker.d.ts.map +1 -0
- package/dist/supervisor/health-worker.js +72 -0
- package/dist/supervisor/health-worker.js.map +1 -0
- package/dist/supervisor/health.d.ts +81 -0
- package/dist/supervisor/health.d.ts.map +1 -0
- package/dist/supervisor/health.js +245 -0
- package/dist/supervisor/health.js.map +1 -0
- package/dist/supervisor/instructions.d.ts +6 -0
- package/dist/supervisor/instructions.d.ts.map +1 -0
- package/dist/supervisor/instructions.js +64 -0
- package/dist/supervisor/instructions.js.map +1 -0
- package/dist/supervisor/read-tools.d.ts +41 -0
- package/dist/supervisor/read-tools.d.ts.map +1 -0
- package/dist/supervisor/read-tools.js +338 -0
- package/dist/supervisor/read-tools.js.map +1 -0
- package/dist/supervisor/session.d.ts +38 -0
- package/dist/supervisor/session.d.ts.map +1 -0
- package/dist/supervisor/session.js +63 -0
- package/dist/supervisor/session.js.map +1 -0
- package/dist/supervisor/write-tools.d.ts +26 -0
- package/dist/supervisor/write-tools.d.ts.map +1 -0
- package/dist/supervisor/write-tools.js +227 -0
- package/dist/supervisor/write-tools.js.map +1 -0
- package/dist/workspace.d.ts +3 -0
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +13 -3
- package/dist/workspace.js.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { MastraWorker } from '@mastra/core/worker';
|
|
2
|
+
import type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';
|
|
3
|
+
import type { WorkItemsStorage } from '../storage/domains/work-items/base.js';
|
|
4
|
+
export declare const DEFAULT_SUPERVISOR_HEALTH_INTERVAL_MS: number;
|
|
5
|
+
export declare class FactorySupervisorHealthWorker extends MastraWorker {
|
|
6
|
+
#private;
|
|
7
|
+
readonly name = "factory-supervisor-health";
|
|
8
|
+
constructor(input: {
|
|
9
|
+
projects: FactoryProjectsStorage;
|
|
10
|
+
workItems: WorkItemsStorage;
|
|
11
|
+
intervalMs?: number;
|
|
12
|
+
});
|
|
13
|
+
start(): Promise<void>;
|
|
14
|
+
stop(): Promise<void>;
|
|
15
|
+
get isRunning(): boolean;
|
|
16
|
+
}
|
|
17
|
+
//# sourceMappingURL=health-worker.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"health-worker.d.ts","sourceRoot":"","sources":["../../src/supervisor/health-worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAEnD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAG9E,eAAO,MAAM,qCAAqC,QAAa,CAAC;AAEhE,qBAAa,6BAA8B,SAAQ,YAAY;;IAC7D,QAAQ,CAAC,IAAI,+BAA+B;gBAShC,KAAK,EAAE;QAAE,QAAQ,EAAE,sBAAsB,CAAC;QAAC,SAAS,EAAE,gBAAgB,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE;IAOnG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAOtB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAO3B,IAAI,SAAS,IAAI,OAAO,CAEvB;CA2CF"}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { runFactoryHealthCheck } from "./health.js";
|
|
2
|
+
import { MastraWorker } from "@mastra/core/worker";
|
|
3
|
+
//#region src/supervisor/health-worker.ts
|
|
4
|
+
const DEFAULT_SUPERVISOR_HEALTH_INTERVAL_MS = 5 * 6e4;
|
|
5
|
+
var FactorySupervisorHealthWorker = class extends MastraWorker {
|
|
6
|
+
name = "factory-supervisor-health";
|
|
7
|
+
#projects;
|
|
8
|
+
#workItems;
|
|
9
|
+
#intervalMs;
|
|
10
|
+
#running = false;
|
|
11
|
+
#timer;
|
|
12
|
+
#inFlight;
|
|
13
|
+
constructor(input) {
|
|
14
|
+
super();
|
|
15
|
+
this.#projects = input.projects;
|
|
16
|
+
this.#workItems = input.workItems;
|
|
17
|
+
this.#intervalMs = input.intervalMs ?? 3e5;
|
|
18
|
+
}
|
|
19
|
+
async start() {
|
|
20
|
+
if (this.#running) return;
|
|
21
|
+
if (!this.deps) throw new Error("FactorySupervisorHealthWorker: call init() before start()");
|
|
22
|
+
this.#running = true;
|
|
23
|
+
this.#schedule(0);
|
|
24
|
+
}
|
|
25
|
+
async stop() {
|
|
26
|
+
this.#running = false;
|
|
27
|
+
if (this.#timer) clearTimeout(this.#timer);
|
|
28
|
+
this.#timer = void 0;
|
|
29
|
+
await this.#inFlight;
|
|
30
|
+
}
|
|
31
|
+
get isRunning() {
|
|
32
|
+
return this.#running;
|
|
33
|
+
}
|
|
34
|
+
#schedule(delayMs) {
|
|
35
|
+
if (!this.#running) return;
|
|
36
|
+
this.#timer = setTimeout(() => {
|
|
37
|
+
this.#timer = void 0;
|
|
38
|
+
this.#inFlight = this.#tick().catch((error) => this.deps?.logger.error("Factory supervisor health sweep failed", { error })).finally(() => {
|
|
39
|
+
this.#inFlight = void 0;
|
|
40
|
+
this.#schedule(this.#intervalMs);
|
|
41
|
+
});
|
|
42
|
+
}, delayMs);
|
|
43
|
+
this.#timer.unref?.();
|
|
44
|
+
}
|
|
45
|
+
async #tick() {
|
|
46
|
+
const now = /* @__PURE__ */ new Date();
|
|
47
|
+
const projects = await this.#projects.listAll();
|
|
48
|
+
const concurrency = 4;
|
|
49
|
+
let nextIndex = 0;
|
|
50
|
+
const failure = (await Promise.allSettled(Array.from({ length: Math.min(concurrency, projects.length) }, async () => {
|
|
51
|
+
while (nextIndex < projects.length) {
|
|
52
|
+
const project = projects[nextIndex++];
|
|
53
|
+
if (!project) return;
|
|
54
|
+
const report = await runFactoryHealthCheck(this.#workItems, {
|
|
55
|
+
orgId: project.orgId,
|
|
56
|
+
factoryProjectId: project.id
|
|
57
|
+
}, { now });
|
|
58
|
+
await this.#workItems.syncSupervisorFindings({
|
|
59
|
+
orgId: project.orgId,
|
|
60
|
+
factoryProjectId: project.id,
|
|
61
|
+
findings: report.findings,
|
|
62
|
+
now
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}))).find((result) => result.status === "rejected");
|
|
66
|
+
if (failure) throw failure.reason;
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
//#endregion
|
|
70
|
+
export { DEFAULT_SUPERVISOR_HEALTH_INTERVAL_MS, FactorySupervisorHealthWorker };
|
|
71
|
+
|
|
72
|
+
//# sourceMappingURL=health-worker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"health-worker.js","names":["#projects","#workItems","#intervalMs","#running","#schedule","#timer","#inFlight","#tick"],"sources":["../../src/supervisor/health-worker.ts"],"sourcesContent":["import { MastraWorker } from '@mastra/core/worker';\n\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { runFactoryHealthCheck } from './health.js';\n\nexport const DEFAULT_SUPERVISOR_HEALTH_INTERVAL_MS = 5 * 60_000;\n\nexport class FactorySupervisorHealthWorker extends MastraWorker {\n readonly name = 'factory-supervisor-health';\n\n readonly #projects: FactoryProjectsStorage;\n readonly #workItems: WorkItemsStorage;\n readonly #intervalMs: number;\n #running = false;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #inFlight: Promise<void> | undefined;\n\n constructor(input: { projects: FactoryProjectsStorage; workItems: WorkItemsStorage; intervalMs?: number }) {\n super();\n this.#projects = input.projects;\n this.#workItems = input.workItems;\n this.#intervalMs = input.intervalMs ?? DEFAULT_SUPERVISOR_HEALTH_INTERVAL_MS;\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (!this.deps) throw new Error('FactorySupervisorHealthWorker: call init() before start()');\n this.#running = true;\n this.#schedule(0);\n }\n\n async stop(): Promise<void> {\n this.#running = false;\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n await this.#inFlight;\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n #schedule(delayMs: number): void {\n if (!this.#running) return;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n this.#inFlight = this.#tick()\n .catch(error => this.deps?.logger.error('Factory supervisor health sweep failed', { error }))\n .finally(() => {\n this.#inFlight = undefined;\n this.#schedule(this.#intervalMs);\n });\n }, delayMs);\n this.#timer.unref?.();\n }\n\n async #tick(): Promise<void> {\n const now = new Date();\n const projects = await this.#projects.listAll();\n const concurrency = 4;\n let nextIndex = 0;\n const results = await Promise.allSettled(\n Array.from({ length: Math.min(concurrency, projects.length) }, async () => {\n while (nextIndex < projects.length) {\n const project = projects[nextIndex++];\n if (!project) return;\n const report = await runFactoryHealthCheck(\n this.#workItems,\n { orgId: project.orgId, factoryProjectId: project.id },\n { now },\n );\n await this.#workItems.syncSupervisorFindings({\n orgId: project.orgId,\n factoryProjectId: project.id,\n findings: report.findings,\n now,\n });\n }\n }),\n );\n const failure = results.find((result): result is PromiseRejectedResult => result.status === 'rejected');\n if (failure) throw failure.reason;\n }\n}\n"],"mappings":";;;AAMA,MAAa,wCAAwC,IAAI;AAEzD,IAAa,gCAAb,cAAmD,aAAa;CAC9D,OAAgB;CAEhB;CACA;CACA;CACA,WAAW;CACX;CACA;CAEA,YAAY,OAA+F;EACzG,MAAM;EACN,KAAKA,YAAY,MAAM;EACvB,KAAKC,aAAa,MAAM;EACxB,KAAKC,cAAc,MAAM,cAAA;CAC3B;CAEA,MAAM,QAAuB;EAC3B,IAAI,KAAKC,UAAU;EACnB,IAAI,CAAC,KAAK,MAAM,MAAM,IAAI,MAAM,2DAA2D;EAC3F,KAAKA,WAAW;EAChB,KAAKC,UAAU,CAAC;CAClB;CAEA,MAAM,OAAsB;EAC1B,KAAKD,WAAW;EAChB,IAAI,KAAKE,QAAQ,aAAa,KAAKA,MAAM;EACzC,KAAKA,SAAS,KAAA;EACd,MAAM,KAAKC;CACb;CAEA,IAAI,YAAqB;EACvB,OAAO,KAAKH;CACd;CAEA,UAAU,SAAuB;EAC/B,IAAI,CAAC,KAAKA,UAAU;EACpB,KAAKE,SAAS,iBAAiB;GAC7B,KAAKA,SAAS,KAAA;GACd,KAAKC,YAAY,KAAKC,MAAM,CAAC,CAC1B,OAAM,UAAS,KAAK,MAAM,OAAO,MAAM,0CAA0C,EAAE,MAAM,CAAC,CAAC,CAAC,CAC5F,cAAc;IACb,KAAKD,YAAY,KAAA;IACjB,KAAKF,UAAU,KAAKF,WAAW;GACjC,CAAC;EACL,GAAG,OAAO;EACV,KAAKG,OAAO,QAAQ;CACtB;CAEA,MAAME,QAAuB;EAC3B,MAAM,sBAAM,IAAI,KAAK;EACrB,MAAM,WAAW,MAAM,KAAKP,UAAU,QAAQ;EAC9C,MAAM,cAAc;EACpB,IAAI,YAAY;EAoBhB,MAAM,WAAU,MAnBM,QAAQ,WAC5B,MAAM,KAAK,EAAE,QAAQ,KAAK,IAAI,aAAa,SAAS,MAAM,EAAE,GAAG,YAAY;GACzE,OAAO,YAAY,SAAS,QAAQ;IAClC,MAAM,UAAU,SAAS;IACzB,IAAI,CAAC,SAAS;IACd,MAAM,SAAS,MAAM,sBACnB,KAAKC,YACL;KAAE,OAAO,QAAQ;KAAO,kBAAkB,QAAQ;IAAG,GACrD,EAAE,IAAI,CACR;IACA,MAAM,KAAKA,WAAW,uBAAuB;KAC3C,OAAO,QAAQ;KACf,kBAAkB,QAAQ;KAC1B,UAAU,OAAO;KACjB;IACF,CAAC;GACH;EACF,CAAC,CACH,EAAA,CACwB,MAAM,WAA4C,OAAO,WAAW,UAAU;EACtG,IAAI,SAAS,MAAM,QAAQ;CAC7B;AACF"}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic Factory health check.
|
|
3
|
+
*
|
|
4
|
+
* Every finding is computed from storage rows alone — no model, no controller —
|
|
5
|
+
* so the supervisor agent explains findings rather than inventing them, and the
|
|
6
|
+
* same list can be rendered by the UI or polled by a timer. Each finding names
|
|
7
|
+
* the row it came from and the standard repair a person (or the supervisor's
|
|
8
|
+
* write tools) would apply.
|
|
9
|
+
*/
|
|
10
|
+
import type { FactoryDeferredDecisionRecord, FactoryPendingStartRecord, FactoryRunBindingRecord, WorkItemRow, WorkItemsStorage } from '../storage/domains/work-items/base.js';
|
|
11
|
+
export type FactoryHealthFindingKind = 'decision-failed' | 'decision-stuck' | 'start-stalled' | 'seat-orphaned' | 'seat-missing' | 'proposal-waiting' | 'held-waiting' | 'label-drift';
|
|
12
|
+
export type FactoryHealthRepair = {
|
|
13
|
+
action: 'retry-decision';
|
|
14
|
+
decisionId: string;
|
|
15
|
+
} | {
|
|
16
|
+
action: 'dismiss-decision';
|
|
17
|
+
decisionId: string;
|
|
18
|
+
} | {
|
|
19
|
+
action: 'resolve-proposal';
|
|
20
|
+
decisionId: string;
|
|
21
|
+
} | {
|
|
22
|
+
action: 'revoke-binding';
|
|
23
|
+
bindingId: string;
|
|
24
|
+
} | {
|
|
25
|
+
action: 'accept-work-item';
|
|
26
|
+
workItemId: string;
|
|
27
|
+
} | {
|
|
28
|
+
action: 'start-run';
|
|
29
|
+
workItemId: string;
|
|
30
|
+
role: string;
|
|
31
|
+
} | {
|
|
32
|
+
action: 'reconcile-labels';
|
|
33
|
+
workItemId: string;
|
|
34
|
+
};
|
|
35
|
+
export interface FactoryHealthFinding {
|
|
36
|
+
kind: FactoryHealthFindingKind;
|
|
37
|
+
/** Stable per (kind, subject) so the UI and attention inbox can dedupe. */
|
|
38
|
+
id: string;
|
|
39
|
+
workItemId: string | null;
|
|
40
|
+
/** Card number as shown on the board, when the row carries one. */
|
|
41
|
+
workItemNumber: number | null;
|
|
42
|
+
title: string;
|
|
43
|
+
/** One sentence of grounded evidence: ids, timestamps, error text. */
|
|
44
|
+
evidence: string;
|
|
45
|
+
/** How long the condition has held, in ms, when it is age-based. */
|
|
46
|
+
ageMs: number | null;
|
|
47
|
+
suggestedRepair: FactoryHealthRepair | null;
|
|
48
|
+
}
|
|
49
|
+
export interface FactoryHealthReport {
|
|
50
|
+
checkedAt: string;
|
|
51
|
+
findings: FactoryHealthFinding[];
|
|
52
|
+
counts: Record<FactoryHealthFindingKind, number>;
|
|
53
|
+
}
|
|
54
|
+
export interface FactoryHealthThresholds {
|
|
55
|
+
/** A retry/pending decision whose `availableAt` is this far in the past never got picked up. */
|
|
56
|
+
stuckDecisionMs: number;
|
|
57
|
+
/** A lease this far past its expiry belongs to a worker that died mid-dispatch. */
|
|
58
|
+
expiredLeaseMs: number;
|
|
59
|
+
/** A pending start this old is not "booting", it is stalled. */
|
|
60
|
+
stalledStartMs: number;
|
|
61
|
+
/** Proposals and held cards older than this are worth nudging a person about. */
|
|
62
|
+
waitingOnPersonMs: number;
|
|
63
|
+
}
|
|
64
|
+
export declare const DEFAULT_HEALTH_THRESHOLDS: FactoryHealthThresholds;
|
|
65
|
+
interface HealthInputs {
|
|
66
|
+
items: WorkItemRow[];
|
|
67
|
+
decisions: FactoryDeferredDecisionRecord[];
|
|
68
|
+
bindings: FactoryRunBindingRecord[];
|
|
69
|
+
pendingStarts: FactoryPendingStartRecord[];
|
|
70
|
+
}
|
|
71
|
+
/** Pure: findings from rows. Exported so tests can feed fixtures directly. */
|
|
72
|
+
export declare function computeFactoryHealth(inputs: HealthInputs, now: Date, thresholds?: FactoryHealthThresholds): FactoryHealthReport;
|
|
73
|
+
export declare function runFactoryHealthCheck(workItems: WorkItemsStorage, scope: {
|
|
74
|
+
orgId: string;
|
|
75
|
+
factoryProjectId: string;
|
|
76
|
+
}, options?: {
|
|
77
|
+
now?: Date;
|
|
78
|
+
thresholds?: FactoryHealthThresholds;
|
|
79
|
+
}): Promise<FactoryHealthReport>;
|
|
80
|
+
export {};
|
|
81
|
+
//# sourceMappingURL=health.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"health.d.ts","sourceRo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rB,eAAe,EAAE,mBAAmB,GAAG,IAAI,CAAC;CAC7C;AAED,MAAM,WAAW,mBAAmB;IAClC,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,oBAAoB,EAAE,CAAC;IACjC,MAAM,EAAE,MAAM,CAAC,wBAAwB,EAAE,MAAM,CAAC,CAAC;CAClD;AAED,MAAM,WAAW,uBAAuB;IACtC,gGAAgG;IAChG,eAAe,EAAE,MAAM,CAAC;IACxB,mFAAmF;IACnF,cAAc,EAAE,MAAM,CAAC;IACvB,gEAAgE;IAChE,cAAc,EAAE,MAAM,CAAC;IACvB,iFAAiF;IACjF,iBAAiB,EAAE,MAAM,CAAC;CAC3B;AAED,eAAO,MAAM,yBAAyB,EAAE,uBAKvC,CAAC;AAqDF,UAAU,YAAY;IACpB,KAAK,EAAE,WAAW,EAAE,CAAC;IACrB,SAAS,EAAE,6BAA6B,EAAE,CAAC;IAC3C,QAAQ,EAAE,uBAAuB,EAAE,CAAC;IACpC,aAAa,EAAE,yBAAyB,EAAE,CAAC;CAC5C;AAED,8EAA8E;AAC9E,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,YAAY,EACpB,GAAG,EAAE,IAAI,EACT,UAAU,GAAE,uBAAmD,GAC9D,mBAAmB,CA2JrB;AAED,wBAAsB,qBAAqB,CACzC,SAAS,EAAE,gBAAgB,EAC3B,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,gBAAgB,EAAE,MAAM,CAAA;CAAE,EAClD,OAAO,GAAE;IAAE,GAAG,CAAC,EAAE,IAAI,CAAC;IAAC,UAAU,CAAC,EAAE,uBAAuB,CAAA;CAAO,GACjE,OAAO,CAAC,mBAAmB,CAAC,CAY9B"}
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { NEEDS_APPROVAL_LABEL } from "../integrations/github/acceptance-labels.js";
|
|
2
|
+
import { FACTORY_ROLE_STAGES, factoryRuleStage, isTerminalFactoryRuleStage } from "../rules/types.js";
|
|
3
|
+
//#region src/supervisor/health.ts
|
|
4
|
+
/**
|
|
5
|
+
* Deterministic Factory health check.
|
|
6
|
+
*
|
|
7
|
+
* Every finding is computed from storage rows alone — no model, no controller —
|
|
8
|
+
* so the supervisor agent explains findings rather than inventing them, and the
|
|
9
|
+
* same list can be rendered by the UI or polled by a timer. Each finding names
|
|
10
|
+
* the row it came from and the standard repair a person (or the supervisor's
|
|
11
|
+
* write tools) would apply.
|
|
12
|
+
*/
|
|
13
|
+
const DEFAULT_HEALTH_THRESHOLDS = {
|
|
14
|
+
stuckDecisionMs: 10 * 6e4,
|
|
15
|
+
expiredLeaseMs: 5 * 6e4,
|
|
16
|
+
stalledStartMs: 10 * 6e4,
|
|
17
|
+
waitingOnPersonMs: 1440 * 6e4
|
|
18
|
+
};
|
|
19
|
+
const FINDING_KINDS = [
|
|
20
|
+
"decision-failed",
|
|
21
|
+
"decision-stuck",
|
|
22
|
+
"start-stalled",
|
|
23
|
+
"seat-orphaned",
|
|
24
|
+
"seat-missing",
|
|
25
|
+
"proposal-waiting",
|
|
26
|
+
"held-waiting",
|
|
27
|
+
"label-drift"
|
|
28
|
+
];
|
|
29
|
+
const IN_FLIGHT_DECISION_STATUSES = /* @__PURE__ */ new Set([
|
|
30
|
+
"pending",
|
|
31
|
+
"retry",
|
|
32
|
+
"leased",
|
|
33
|
+
"proposed"
|
|
34
|
+
]);
|
|
35
|
+
/** Working lane → the role whose seat carries a card through it. */
|
|
36
|
+
const ROLE_FOR_LANE = new Map(Object.entries(FACTORY_ROLE_STAGES).map(([role, lane]) => [lane, role]));
|
|
37
|
+
function itemNumber(item) {
|
|
38
|
+
const number = item?.metadata?.number ?? item?.metadata?.githubIssueNumber ?? item?.metadata?.githubPullRequestNumber;
|
|
39
|
+
return typeof number === "number" ? number : null;
|
|
40
|
+
}
|
|
41
|
+
function itemLabels(item) {
|
|
42
|
+
const labels = item.metadata?.labels;
|
|
43
|
+
return Array.isArray(labels) ? labels.filter((label) => typeof label === "string") : [];
|
|
44
|
+
}
|
|
45
|
+
function decisionType(decision) {
|
|
46
|
+
const type = decision.decision.type;
|
|
47
|
+
return typeof type === "string" ? type : "decision";
|
|
48
|
+
}
|
|
49
|
+
function decisionRole(decision) {
|
|
50
|
+
const role = decision.decision.role;
|
|
51
|
+
return typeof role === "string" ? role : null;
|
|
52
|
+
}
|
|
53
|
+
function describeDecision(decision) {
|
|
54
|
+
const role = decisionRole(decision);
|
|
55
|
+
return role ? `${decisionType(decision)} (${role})` : decisionType(decision);
|
|
56
|
+
}
|
|
57
|
+
function truncate(text, max = 200) {
|
|
58
|
+
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
|
59
|
+
}
|
|
60
|
+
function stageEnteredAt(item) {
|
|
61
|
+
const open = [...item.stageHistory].reverse().find((entry) => !entry.exitedAt);
|
|
62
|
+
const at = open ? Date.parse(open.enteredAt) : NaN;
|
|
63
|
+
return Number.isFinite(at) ? new Date(at) : null;
|
|
64
|
+
}
|
|
65
|
+
/** Pure: findings from rows. Exported so tests can feed fixtures directly. */
|
|
66
|
+
function computeFactoryHealth(inputs, now, thresholds = DEFAULT_HEALTH_THRESHOLDS) {
|
|
67
|
+
const itemsById = new Map(inputs.items.map((item) => [item.id, item]));
|
|
68
|
+
const findings = [];
|
|
69
|
+
const subject = (workItemId) => {
|
|
70
|
+
const item = workItemId ? itemsById.get(workItemId) : void 0;
|
|
71
|
+
return {
|
|
72
|
+
workItemId,
|
|
73
|
+
workItemNumber: itemNumber(item),
|
|
74
|
+
title: item?.title ?? ""
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
for (const decision of inputs.decisions) {
|
|
78
|
+
const base = subject(decision.workItemId);
|
|
79
|
+
if (decision.status === "failed") {
|
|
80
|
+
findings.push({
|
|
81
|
+
kind: "decision-failed",
|
|
82
|
+
id: `decision-failed:${decision.id}`,
|
|
83
|
+
...base,
|
|
84
|
+
evidence: `Decision ${decision.id} (${describeDecision(decision)}) failed after ${decision.attempts} attempt(s) at ${decision.updatedAt.toISOString()}${decision.failureCode ? ` [${decision.failureCode}]` : ""}: ${truncate(decision.lastError ?? "no error recorded")}`,
|
|
85
|
+
ageMs: now.getTime() - decision.updatedAt.getTime(),
|
|
86
|
+
suggestedRepair: {
|
|
87
|
+
action: "retry-decision",
|
|
88
|
+
decisionId: decision.id
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
if (decision.status === "retry" || decision.status === "pending") {
|
|
94
|
+
const overdue = now.getTime() - decision.availableAt.getTime();
|
|
95
|
+
if (overdue > thresholds.stuckDecisionMs) findings.push({
|
|
96
|
+
kind: "decision-stuck",
|
|
97
|
+
id: `decision-stuck:${decision.id}`,
|
|
98
|
+
...base,
|
|
99
|
+
evidence: `Decision ${decision.id} (${describeDecision(decision)}) has been ${decision.status} since ${decision.availableAt.toISOString()} with ${decision.attempts} attempt(s) and was never leased; is the dispatcher running?`,
|
|
100
|
+
ageMs: overdue,
|
|
101
|
+
suggestedRepair: null
|
|
102
|
+
});
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (decision.status === "leased" && decision.leaseExpiresAt) {
|
|
106
|
+
const expired = now.getTime() - decision.leaseExpiresAt.getTime();
|
|
107
|
+
if (expired > thresholds.expiredLeaseMs) findings.push({
|
|
108
|
+
kind: "decision-stuck",
|
|
109
|
+
id: `decision-stuck:${decision.id}`,
|
|
110
|
+
...base,
|
|
111
|
+
evidence: `Decision ${decision.id} (${describeDecision(decision)}) is still leased by ${decision.leaseOwner ?? "unknown"} though the lease expired at ${decision.leaseExpiresAt.toISOString()}; the worker likely died mid-dispatch.`,
|
|
112
|
+
ageMs: expired,
|
|
113
|
+
suggestedRepair: null
|
|
114
|
+
});
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (decision.status === "proposed") {
|
|
118
|
+
const waiting = now.getTime() - decision.createdAt.getTime();
|
|
119
|
+
if (waiting > thresholds.waitingOnPersonMs) findings.push({
|
|
120
|
+
kind: "proposal-waiting",
|
|
121
|
+
id: `proposal-waiting:${decision.id}`,
|
|
122
|
+
...base,
|
|
123
|
+
evidence: `Proposed run ${decision.id} (${describeDecision(decision)}) has waited for a person since ${decision.createdAt.toISOString()}.`,
|
|
124
|
+
ageMs: waiting,
|
|
125
|
+
suggestedRepair: {
|
|
126
|
+
action: "resolve-proposal",
|
|
127
|
+
decisionId: decision.id
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const bindingsById = new Map(inputs.bindings.map((binding) => [binding.id, binding]));
|
|
133
|
+
for (const start of inputs.pendingStarts) {
|
|
134
|
+
if (start.status === "sent") continue;
|
|
135
|
+
const binding = bindingsById.get(start.bindingId);
|
|
136
|
+
const base = subject(binding?.workItemId ?? null);
|
|
137
|
+
const age = now.getTime() - start.createdAt.getTime();
|
|
138
|
+
if (start.status === "failed" || age > thresholds.stalledStartMs) findings.push({
|
|
139
|
+
kind: "start-stalled",
|
|
140
|
+
id: `start-stalled:${start.id}`,
|
|
141
|
+
...base,
|
|
142
|
+
evidence: `Pending start ${start.id}${binding ? ` for the ${binding.role} seat` : ""} is ${start.status} since ${start.createdAt.toISOString()} after ${start.attempts} attempt(s)${start.lastError ? `: ${truncate(start.lastError)}` : "."}`,
|
|
143
|
+
ageMs: age,
|
|
144
|
+
suggestedRepair: binding ? {
|
|
145
|
+
action: "revoke-binding",
|
|
146
|
+
bindingId: binding.id
|
|
147
|
+
} : null
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
const activeSeatsByItem = /* @__PURE__ */ new Map();
|
|
151
|
+
for (const binding of inputs.bindings) {
|
|
152
|
+
if (binding.status !== "active") continue;
|
|
153
|
+
const item = itemsById.get(binding.workItemId);
|
|
154
|
+
const stage = item ? factoryRuleStage(item.stages) : void 0;
|
|
155
|
+
if (!item || !stage || isTerminalFactoryRuleStage([stage])) {
|
|
156
|
+
findings.push({
|
|
157
|
+
kind: "seat-orphaned",
|
|
158
|
+
id: `seat-orphaned:${binding.id}`,
|
|
159
|
+
...subject(item ? item.id : null),
|
|
160
|
+
evidence: item ? `Binding ${binding.id} (${binding.role}) is still active though the card is in ${stage ?? item.stages.join("+")}.` : `Binding ${binding.id} (${binding.role}) is active for work item ${binding.workItemId}, which no longer exists.`,
|
|
161
|
+
ageMs: now.getTime() - binding.createdAt.getTime(),
|
|
162
|
+
suggestedRepair: {
|
|
163
|
+
action: "revoke-binding",
|
|
164
|
+
bindingId: binding.id
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
const seats = activeSeatsByItem.get(item.id) ?? [];
|
|
170
|
+
seats.push(binding);
|
|
171
|
+
activeSeatsByItem.set(item.id, seats);
|
|
172
|
+
}
|
|
173
|
+
const inFlightByItem = new Set(inputs.decisions.filter((d) => d.workItemId && IN_FLIGHT_DECISION_STATUSES.has(d.status)).map((d) => d.workItemId));
|
|
174
|
+
for (const item of inputs.items) {
|
|
175
|
+
const stage = factoryRuleStage(item.stages);
|
|
176
|
+
if (!stage || stage === "intake" || isTerminalFactoryRuleStage([stage])) continue;
|
|
177
|
+
const base = subject(item.id);
|
|
178
|
+
const enteredAt = stageEnteredAt(item);
|
|
179
|
+
const inStageMs = enteredAt ? now.getTime() - enteredAt.getTime() : null;
|
|
180
|
+
if (stage === "triage" && item.triageType !== null && item.triageType !== "bug" && !item.acceptedAt) {
|
|
181
|
+
if (inStageMs !== null && inStageMs > thresholds.waitingOnPersonMs) findings.push({
|
|
182
|
+
kind: "held-waiting",
|
|
183
|
+
id: `held-waiting:${item.id}`,
|
|
184
|
+
...base,
|
|
185
|
+
evidence: `Triaged as "${item.triageType}" and waiting for a maintainer's decision since ${enteredAt.toISOString()}.`,
|
|
186
|
+
ageMs: inStageMs,
|
|
187
|
+
suggestedRepair: {
|
|
188
|
+
action: "accept-work-item",
|
|
189
|
+
workItemId: item.id
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
} else if (!activeSeatsByItem.has(item.id) && !inFlightByItem.has(item.id)) {
|
|
193
|
+
const role = ROLE_FOR_LANE.get(stage);
|
|
194
|
+
findings.push({
|
|
195
|
+
kind: "seat-missing",
|
|
196
|
+
id: `seat-missing:${item.id}`,
|
|
197
|
+
...base,
|
|
198
|
+
evidence: `In ${stage} since ${enteredAt?.toISOString() ?? "unknown"} with no active seat and no decision in flight; nothing will move it.`,
|
|
199
|
+
ageMs: inStageMs,
|
|
200
|
+
suggestedRepair: role ? {
|
|
201
|
+
action: "start-run",
|
|
202
|
+
workItemId: item.id,
|
|
203
|
+
role
|
|
204
|
+
} : null
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
if (item.acceptedAt && itemLabels(item).includes("status: needs approval")) findings.push({
|
|
208
|
+
kind: "label-drift",
|
|
209
|
+
id: `label-drift:${item.id}`,
|
|
210
|
+
...base,
|
|
211
|
+
evidence: `Accepted at ${item.acceptedAt.toISOString()} but the last observed labels still include "${NEEDS_APPROVAL_LABEL}".`,
|
|
212
|
+
ageMs: now.getTime() - item.acceptedAt.getTime(),
|
|
213
|
+
suggestedRepair: {
|
|
214
|
+
action: "reconcile-labels",
|
|
215
|
+
workItemId: item.id
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
findings.sort((a, b) => (b.ageMs ?? 0) - (a.ageMs ?? 0));
|
|
220
|
+
const counts = Object.fromEntries(FINDING_KINDS.map((kind) => [kind, 0]));
|
|
221
|
+
for (const finding of findings) counts[finding.kind] += 1;
|
|
222
|
+
return {
|
|
223
|
+
checkedAt: now.toISOString(),
|
|
224
|
+
findings,
|
|
225
|
+
counts
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
async function runFactoryHealthCheck(workItems, scope, options = {}) {
|
|
229
|
+
const [items, decisions, bindings, pendingStarts] = await Promise.all([
|
|
230
|
+
workItems.list(scope),
|
|
231
|
+
workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId),
|
|
232
|
+
workItems.listRunBindings(scope.orgId, scope.factoryProjectId),
|
|
233
|
+
workItems.listPendingStarts(scope.orgId, scope.factoryProjectId)
|
|
234
|
+
]);
|
|
235
|
+
return computeFactoryHealth({
|
|
236
|
+
items,
|
|
237
|
+
decisions,
|
|
238
|
+
bindings,
|
|
239
|
+
pendingStarts
|
|
240
|
+
}, options.now ?? /* @__PURE__ */ new Date(), options.thresholds);
|
|
241
|
+
}
|
|
242
|
+
//#endregion
|
|
243
|
+
export { DEFAULT_HEALTH_THRESHOLDS, computeFactoryHealth, runFactoryHealthCheck };
|
|
244
|
+
|
|
245
|
+
//# sourceMappingURL=health.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"health.js","names":[],"sources":["../../src/supervisor/health.ts"],"sourcesContent":["/**\n * Deterministic Factory health check.\n *\n * Every finding is computed from storage rows alone — no model, no controller —\n * so the supervisor agent explains findings rather than inventing them, and the\n * same list can be rendered by the UI or polled by a timer. Each finding names\n * the row it came from and the standard repair a person (or the supervisor's\n * write tools) would apply.\n */\n\nimport { NEEDS_APPROVAL_LABEL } from '../integrations/github/acceptance-labels.js';\nimport { FACTORY_ROLE_STAGES, factoryRuleStage, isTerminalFactoryRuleStage } from '../rules/types.js';\nimport type {\n FactoryDeferredDecisionRecord,\n FactoryPendingStartRecord,\n FactoryRunBindingRecord,\n WorkItemRow,\n WorkItemsStorage,\n} from '../storage/domains/work-items/base.js';\n\nexport type FactoryHealthFindingKind =\n | 'decision-failed'\n | 'decision-stuck'\n | 'start-stalled'\n | 'seat-orphaned'\n | 'seat-missing'\n | 'proposal-waiting'\n | 'held-waiting'\n | 'label-drift';\n\nexport type FactoryHealthRepair =\n | { action: 'retry-decision'; decisionId: string }\n | { action: 'dismiss-decision'; decisionId: string }\n | { action: 'resolve-proposal'; decisionId: string }\n | { action: 'revoke-binding'; bindingId: string }\n | { action: 'accept-work-item'; workItemId: string }\n | { action: 'start-run'; workItemId: string; role: string }\n | { action: 'reconcile-labels'; workItemId: string };\n\nexport interface FactoryHealthFinding {\n kind: FactoryHealthFindingKind;\n /** Stable per (kind, subject) so the UI and attention inbox can dedupe. */\n id: string;\n workItemId: string | null;\n /** Card number as shown on the board, when the row carries one. */\n workItemNumber: number | null;\n title: string;\n /** One sentence of grounded evidence: ids, timestamps, error text. */\n evidence: string;\n /** How long the condition has held, in ms, when it is age-based. */\n ageMs: number | null;\n suggestedRepair: FactoryHealthRepair | null;\n}\n\nexport interface FactoryHealthReport {\n checkedAt: string;\n findings: FactoryHealthFinding[];\n counts: Record<FactoryHealthFindingKind, number>;\n}\n\nexport interface FactoryHealthThresholds {\n /** A retry/pending decision whose `availableAt` is this far in the past never got picked up. */\n stuckDecisionMs: number;\n /** A lease this far past its expiry belongs to a worker that died mid-dispatch. */\n expiredLeaseMs: number;\n /** A pending start this old is not \"booting\", it is stalled. */\n stalledStartMs: number;\n /** Proposals and held cards older than this are worth nudging a person about. */\n waitingOnPersonMs: number;\n}\n\nexport const DEFAULT_HEALTH_THRESHOLDS: FactoryHealthThresholds = {\n stuckDecisionMs: 10 * 60_000,\n expiredLeaseMs: 5 * 60_000,\n stalledStartMs: 10 * 60_000,\n waitingOnPersonMs: 24 * 60 * 60_000,\n};\n\nconst FINDING_KINDS: FactoryHealthFindingKind[] = [\n 'decision-failed',\n 'decision-stuck',\n 'start-stalled',\n 'seat-orphaned',\n 'seat-missing',\n 'proposal-waiting',\n 'held-waiting',\n 'label-drift',\n];\n\nconst IN_FLIGHT_DECISION_STATUSES = new Set(['pending', 'retry', 'leased', 'proposed']);\n\n/** Working lane → the role whose seat carries a card through it. */\nconst ROLE_FOR_LANE = new Map<string, string>(Object.entries(FACTORY_ROLE_STAGES).map(([role, lane]) => [lane, role]));\n\nfunction itemNumber(item: WorkItemRow | undefined): number | null {\n const number = item?.metadata?.number ?? item?.metadata?.githubIssueNumber ?? item?.metadata?.githubPullRequestNumber;\n return typeof number === 'number' ? number : null;\n}\n\nfunction itemLabels(item: WorkItemRow): string[] {\n const labels = item.metadata?.labels;\n return Array.isArray(labels) ? labels.filter((label): label is string => typeof label === 'string') : [];\n}\n\nfunction decisionType(decision: FactoryDeferredDecisionRecord): string {\n const type = decision.decision.type;\n return typeof type === 'string' ? type : 'decision';\n}\n\nfunction decisionRole(decision: FactoryDeferredDecisionRecord): string | null {\n const role = decision.decision.role;\n return typeof role === 'string' ? role : null;\n}\n\nfunction describeDecision(decision: FactoryDeferredDecisionRecord): string {\n const role = decisionRole(decision);\n return role ? `${decisionType(decision)} (${role})` : decisionType(decision);\n}\n\nfunction truncate(text: string, max = 200): string {\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n\nfunction stageEnteredAt(item: WorkItemRow): Date | null {\n const open = [...item.stageHistory].reverse().find(entry => !entry.exitedAt);\n const at = open ? Date.parse(open.enteredAt) : Number.NaN;\n return Number.isFinite(at) ? new Date(at) : null;\n}\n\ninterface HealthInputs {\n items: WorkItemRow[];\n decisions: FactoryDeferredDecisionRecord[];\n bindings: FactoryRunBindingRecord[];\n pendingStarts: FactoryPendingStartRecord[];\n}\n\n/** Pure: findings from rows. Exported so tests can feed fixtures directly. */\nexport function computeFactoryHealth(\n inputs: HealthInputs,\n now: Date,\n thresholds: FactoryHealthThresholds = DEFAULT_HEALTH_THRESHOLDS,\n): FactoryHealthReport {\n const itemsById = new Map(inputs.items.map(item => [item.id, item]));\n const findings: FactoryHealthFinding[] = [];\n const subject = (workItemId: string | null) => {\n const item = workItemId ? itemsById.get(workItemId) : undefined;\n return { workItemId, workItemNumber: itemNumber(item), title: item?.title ?? '' };\n };\n\n for (const decision of inputs.decisions) {\n const base = subject(decision.workItemId);\n if (decision.status === 'failed') {\n findings.push({\n kind: 'decision-failed',\n id: `decision-failed:${decision.id}`,\n ...base,\n evidence: `Decision ${decision.id} (${describeDecision(decision)}) failed after ${decision.attempts} attempt(s) at ${decision.updatedAt.toISOString()}${decision.failureCode ? ` [${decision.failureCode}]` : ''}: ${truncate(decision.lastError ?? 'no error recorded')}`,\n ageMs: now.getTime() - decision.updatedAt.getTime(),\n suggestedRepair: { action: 'retry-decision', decisionId: decision.id },\n });\n continue;\n }\n if (decision.status === 'retry' || decision.status === 'pending') {\n const overdue = now.getTime() - decision.availableAt.getTime();\n if (overdue > thresholds.stuckDecisionMs) {\n findings.push({\n kind: 'decision-stuck',\n id: `decision-stuck:${decision.id}`,\n ...base,\n evidence: `Decision ${decision.id} (${describeDecision(decision)}) has been ${decision.status} since ${decision.availableAt.toISOString()} with ${decision.attempts} attempt(s) and was never leased; is the dispatcher running?`,\n ageMs: overdue,\n suggestedRepair: null,\n });\n }\n continue;\n }\n if (decision.status === 'leased' && decision.leaseExpiresAt) {\n const expired = now.getTime() - decision.leaseExpiresAt.getTime();\n if (expired > thresholds.expiredLeaseMs) {\n findings.push({\n kind: 'decision-stuck',\n id: `decision-stuck:${decision.id}`,\n ...base,\n evidence: `Decision ${decision.id} (${describeDecision(decision)}) is still leased by ${decision.leaseOwner ?? 'unknown'} though the lease expired at ${decision.leaseExpiresAt.toISOString()}; the worker likely died mid-dispatch.`,\n ageMs: expired,\n suggestedRepair: null,\n });\n }\n continue;\n }\n if (decision.status === 'proposed') {\n const waiting = now.getTime() - decision.createdAt.getTime();\n if (waiting > thresholds.waitingOnPersonMs) {\n findings.push({\n kind: 'proposal-waiting',\n id: `proposal-waiting:${decision.id}`,\n ...base,\n evidence: `Proposed run ${decision.id} (${describeDecision(decision)}) has waited for a person since ${decision.createdAt.toISOString()}.`,\n ageMs: waiting,\n suggestedRepair: { action: 'resolve-proposal', decisionId: decision.id },\n });\n }\n }\n }\n\n const bindingsById = new Map(inputs.bindings.map(binding => [binding.id, binding]));\n for (const start of inputs.pendingStarts) {\n if (start.status === 'sent') continue;\n const binding = bindingsById.get(start.bindingId);\n const base = subject(binding?.workItemId ?? null);\n const age = now.getTime() - start.createdAt.getTime();\n if (start.status === 'failed' || age > thresholds.stalledStartMs) {\n findings.push({\n kind: 'start-stalled',\n id: `start-stalled:${start.id}`,\n ...base,\n evidence: `Pending start ${start.id}${binding ? ` for the ${binding.role} seat` : ''} is ${start.status} since ${start.createdAt.toISOString()} after ${start.attempts} attempt(s)${start.lastError ? `: ${truncate(start.lastError)}` : '.'}`,\n ageMs: age,\n suggestedRepair: binding ? { action: 'revoke-binding', bindingId: binding.id } : null,\n });\n }\n }\n\n const activeSeatsByItem = new Map<string, FactoryRunBindingRecord[]>();\n for (const binding of inputs.bindings) {\n if (binding.status !== 'active') continue;\n const item = itemsById.get(binding.workItemId);\n const stage = item ? factoryRuleStage(item.stages) : undefined;\n if (!item || !stage || isTerminalFactoryRuleStage([stage])) {\n findings.push({\n kind: 'seat-orphaned',\n id: `seat-orphaned:${binding.id}`,\n ...subject(item ? item.id : null),\n evidence: item\n ? `Binding ${binding.id} (${binding.role}) is still active though the card is in ${stage ?? item.stages.join('+')}.`\n : `Binding ${binding.id} (${binding.role}) is active for work item ${binding.workItemId}, which no longer exists.`,\n ageMs: now.getTime() - binding.createdAt.getTime(),\n suggestedRepair: { action: 'revoke-binding', bindingId: binding.id },\n });\n continue;\n }\n const seats = activeSeatsByItem.get(item.id) ?? [];\n seats.push(binding);\n activeSeatsByItem.set(item.id, seats);\n }\n\n const inFlightByItem = new Set(\n inputs.decisions.filter(d => d.workItemId && IN_FLIGHT_DECISION_STATUSES.has(d.status)).map(d => d.workItemId!),\n );\n for (const item of inputs.items) {\n const stage = factoryRuleStage(item.stages);\n if (!stage || stage === 'intake' || isTerminalFactoryRuleStage([stage])) continue;\n const base = subject(item.id);\n const enteredAt = stageEnteredAt(item);\n const inStageMs = enteredAt ? now.getTime() - enteredAt.getTime() : null;\n\n const held = stage === 'triage' && item.triageType !== null && item.triageType !== 'bug' && !item.acceptedAt;\n if (held) {\n if (inStageMs !== null && inStageMs > thresholds.waitingOnPersonMs) {\n findings.push({\n kind: 'held-waiting',\n id: `held-waiting:${item.id}`,\n ...base,\n evidence: `Triaged as \"${item.triageType}\" and waiting for a maintainer's decision since ${enteredAt!.toISOString()}.`,\n ageMs: inStageMs,\n suggestedRepair: { action: 'accept-work-item', workItemId: item.id },\n });\n }\n } else if (!activeSeatsByItem.has(item.id) && !inFlightByItem.has(item.id)) {\n const role = ROLE_FOR_LANE.get(stage);\n findings.push({\n kind: 'seat-missing',\n id: `seat-missing:${item.id}`,\n ...base,\n evidence: `In ${stage} since ${enteredAt?.toISOString() ?? 'unknown'} with no active seat and no decision in flight; nothing will move it.`,\n ageMs: inStageMs,\n suggestedRepair: role ? { action: 'start-run', workItemId: item.id, role } : null,\n });\n }\n\n if (item.acceptedAt && itemLabels(item).includes(NEEDS_APPROVAL_LABEL)) {\n findings.push({\n kind: 'label-drift',\n id: `label-drift:${item.id}`,\n ...base,\n evidence: `Accepted at ${item.acceptedAt.toISOString()} but the last observed labels still include \"${NEEDS_APPROVAL_LABEL}\".`,\n ageMs: now.getTime() - item.acceptedAt.getTime(),\n suggestedRepair: { action: 'reconcile-labels', workItemId: item.id },\n });\n }\n }\n\n findings.sort((a, b) => (b.ageMs ?? 0) - (a.ageMs ?? 0));\n const counts = Object.fromEntries(FINDING_KINDS.map(kind => [kind, 0])) as Record<FactoryHealthFindingKind, number>;\n for (const finding of findings) counts[finding.kind] += 1;\n return { checkedAt: now.toISOString(), findings, counts };\n}\n\nexport async function runFactoryHealthCheck(\n workItems: WorkItemsStorage,\n scope: { orgId: string; factoryProjectId: string },\n options: { now?: Date; thresholds?: FactoryHealthThresholds } = {},\n): Promise<FactoryHealthReport> {\n const [items, decisions, bindings, pendingStarts] = await Promise.all([\n workItems.list(scope),\n workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId),\n workItems.listRunBindings(scope.orgId, scope.factoryProjectId),\n workItems.listPendingStarts(scope.orgId, scope.factoryProjectId),\n ]);\n return computeFactoryHealth(\n { items, decisions, bindings, pendingStarts },\n options.now ?? new Date(),\n options.thresholds,\n );\n}\n"],"mappings":";;;;;;;;;;;;AAuEA,MAAa,4BAAqD;CAChE,iBAAiB,KAAK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,SAAS,EAAE;CACvD,MAAM,SAAS,OAAO,YAAY,cAAc,KAAI,SAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;CACtE,KAAK,MAAM,WAAW,UAAU,OAAO,QAAQ,SAAS;CACxD,OAAO;EAAE,WAAW,IAAI,YAAY;EAAG;EAAU;CAAO;AAC1D;AAEA,eAAsB,sBACpB,WACA,OACA,UAAgE,CAAC,GACnC;CAC9B,MAAM,CAAC,OAAO,WAAW,UAAU,iBAAiB,MAAM,QAAQ,IAAI;EACpE,UAAU,KAAK,KAAK;EACpB,UAAU,sBAAsB,MAAM,OAAO,MAAM,gBAAgB;EACnE,UAAU,gBAAgB,MAAM,OAAO,MAAM,gBAAgB;EAC7D,UAAU,kBAAkB,MAAM,OAAO,MAAM,gBAAgB;CACjE,CAAC;CACD,OAAO,qBACL;EAAE;EAAO;EAAW;EAAU;CAAc,GAC5C,QAAQ,uBAAO,IAAI,KAAK,GACxB,QAAQ,UACV;AACF"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The supervisor's playbook. Lives in code (not a workspace skill) because
|
|
3
|
+
* the supervisor session has no checkout to load skills from.
|
|
4
|
+
*/
|
|
5
|
+
export declare const SUPERVISOR_INSTRUCTIONS = "# Factory supervisor\n\nYou supervise one Software Factory: a pipeline of cards (work items) that move\nintake \u2192 triage \u2192 planning \u2192 execute \u2192 review \u2192 done|canceled. Four agent roles\n(triage, plan, work, review) each hold a *seat* (run binding) on a card while\nthey act on it; every role on a card shares one session thread. Typed rules\nemit *decisions* (invoke a skill, send a message, sync a linked card, \u2026) that a\ndispatcher executes with retries; a decision that exhausts its retries is\n*failed* and shows the card red. Some decisions are *proposals* parked for a\nperson to approve. Non-bug cards are *held* in triage until a maintainer\naccepts them.\n\nYou have no repository and no sandbox. Everything you know comes from the\n`factory_*` tools, which read the Factory's own records.\n\n## How to answer\n\n- Ground every claim in a tool result. Quote ids (card number, decision id,\n seat id, thread id) and timestamps so the person can click through. Never\n guess at a cause the records do not show.\n- Start with `factory_health_check` for \"what's wrong / what needs me\", and\n `factory_inspect_work_item` for questions about one card. Use\n `factory_read_session` only when the records don't explain a card and the\n worker's own transcript might.\n- Lead with the answer, then the evidence, then the standard repair. Keep it\n short; the person will ask for more.\n- Group like with like: several cards failing with the same code and error at\n the same time are one incident, not several.\n\n## Reading the records\n\n- `decision-failed` \u2014 the dispatcher gave up. If the cause was transient\n (a restart, a fixed bug, a rate limit), a retry will succeed. If the card\n has already moved on past the role the decision was for, the decision is\n moot and should be dismissed, not retried.\n- `decision-stuck` \u2014 retry/pending past its backoff, or a lease that\n expired: the dispatcher is not picking it up. Usually a stalled process.\n- `seat-missing` \u2014 a card sits in a working lane with nobody bound to it\n and nothing in flight; it will not progress until a run is started.\n- `seat-orphaned` \u2014 a seat is active on a card that already finished or\n left that role's lane; a lifecycle bug left it behind.\n- `start-stalled` \u2014 a run was asked for but the kickoff never landed.\n- `proposal-waiting` / `held-waiting` \u2014 a person is the blocker. Say so\n plainly and name what they need to decide.\n- `label-drift` \u2014 the GitHub labels disagree with the card's accepted\n state; reconcile its acceptance labels after confirming the repair.\n\n## Repairs\n\nWrite tools require confirmation and are recorded against the person who\nasked. Use the repair suggested by the health finding: retry or dismiss a\ndecision, accept a held card, approve or dismiss a proposal, revoke an\norphaned seat, signal a worker, or reconcile stale acceptance labels. Never\nclaim a repair happened unless a tool result says it did.\n";
|
|
6
|
+
//# sourceMappingURL=instructions.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"instructions.d.ts","sourceRoot":"","sources":["../../src/supervisor/instructions.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,eAAO,MAAM,uBAAuB,08FAsDnC,CAAC"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
//#region src/supervisor/instructions.ts
|
|
2
|
+
/**
|
|
3
|
+
* The supervisor's playbook. Lives in code (not a workspace skill) because
|
|
4
|
+
* the supervisor session has no checkout to load skills from.
|
|
5
|
+
*/
|
|
6
|
+
const SUPERVISOR_INSTRUCTIONS = `# Factory supervisor
|
|
7
|
+
|
|
8
|
+
You supervise one Software Factory: a pipeline of cards (work items) that move
|
|
9
|
+
intake → triage → planning → execute → review → done|canceled. Four agent roles
|
|
10
|
+
(triage, plan, work, review) each hold a *seat* (run binding) on a card while
|
|
11
|
+
they act on it; every role on a card shares one session thread. Typed rules
|
|
12
|
+
emit *decisions* (invoke a skill, send a message, sync a linked card, …) that a
|
|
13
|
+
dispatcher executes with retries; a decision that exhausts its retries is
|
|
14
|
+
*failed* and shows the card red. Some decisions are *proposals* parked for a
|
|
15
|
+
person to approve. Non-bug cards are *held* in triage until a maintainer
|
|
16
|
+
accepts them.
|
|
17
|
+
|
|
18
|
+
You have no repository and no sandbox. Everything you know comes from the
|
|
19
|
+
\`factory_*\` tools, which read the Factory's own records.
|
|
20
|
+
|
|
21
|
+
## How to answer
|
|
22
|
+
|
|
23
|
+
- Ground every claim in a tool result. Quote ids (card number, decision id,
|
|
24
|
+
seat id, thread id) and timestamps so the person can click through. Never
|
|
25
|
+
guess at a cause the records do not show.
|
|
26
|
+
- Start with \`factory_health_check\` for "what's wrong / what needs me", and
|
|
27
|
+
\`factory_inspect_work_item\` for questions about one card. Use
|
|
28
|
+
\`factory_read_session\` only when the records don't explain a card and the
|
|
29
|
+
worker's own transcript might.
|
|
30
|
+
- Lead with the answer, then the evidence, then the standard repair. Keep it
|
|
31
|
+
short; the person will ask for more.
|
|
32
|
+
- Group like with like: several cards failing with the same code and error at
|
|
33
|
+
the same time are one incident, not several.
|
|
34
|
+
|
|
35
|
+
## Reading the records
|
|
36
|
+
|
|
37
|
+
- \`decision-failed\` — the dispatcher gave up. If the cause was transient
|
|
38
|
+
(a restart, a fixed bug, a rate limit), a retry will succeed. If the card
|
|
39
|
+
has already moved on past the role the decision was for, the decision is
|
|
40
|
+
moot and should be dismissed, not retried.
|
|
41
|
+
- \`decision-stuck\` — retry/pending past its backoff, or a lease that
|
|
42
|
+
expired: the dispatcher is not picking it up. Usually a stalled process.
|
|
43
|
+
- \`seat-missing\` — a card sits in a working lane with nobody bound to it
|
|
44
|
+
and nothing in flight; it will not progress until a run is started.
|
|
45
|
+
- \`seat-orphaned\` — a seat is active on a card that already finished or
|
|
46
|
+
left that role's lane; a lifecycle bug left it behind.
|
|
47
|
+
- \`start-stalled\` — a run was asked for but the kickoff never landed.
|
|
48
|
+
- \`proposal-waiting\` / \`held-waiting\` — a person is the blocker. Say so
|
|
49
|
+
plainly and name what they need to decide.
|
|
50
|
+
- \`label-drift\` — the GitHub labels disagree with the card's accepted
|
|
51
|
+
state; reconcile its acceptance labels after confirming the repair.
|
|
52
|
+
|
|
53
|
+
## Repairs
|
|
54
|
+
|
|
55
|
+
Write tools require confirmation and are recorded against the person who
|
|
56
|
+
asked. Use the repair suggested by the health finding: retry or dismiss a
|
|
57
|
+
decision, accept a held card, approve or dismiss a proposal, revoke an
|
|
58
|
+
orphaned seat, signal a worker, or reconcile stale acceptance labels. Never
|
|
59
|
+
claim a repair happened unless a tool result says it did.
|
|
60
|
+
`;
|
|
61
|
+
//#endregion
|
|
62
|
+
export { SUPERVISOR_INSTRUCTIONS };
|
|
63
|
+
|
|
64
|
+
//# sourceMappingURL=instructions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"instructions.js","names":[],"sources":["../../src/supervisor/instructions.ts"],"sourcesContent":["/**\n * The supervisor's playbook. Lives in code (not a workspace skill) because\n * the supervisor session has no checkout to load skills from.\n */\nexport const SUPERVISOR_INSTRUCTIONS = `# Factory supervisor\n\nYou supervise one Software Factory: a pipeline of cards (work items) that move\nintake → triage → planning → execute → review → done|canceled. Four agent roles\n(triage, plan, work, review) each hold a *seat* (run binding) on a card while\nthey act on it; every role on a card shares one session thread. Typed rules\nemit *decisions* (invoke a skill, send a message, sync a linked card, …) that a\ndispatcher executes with retries; a decision that exhausts its retries is\n*failed* and shows the card red. Some decisions are *proposals* parked for a\nperson to approve. Non-bug cards are *held* in triage until a maintainer\naccepts them.\n\nYou have no repository and no sandbox. Everything you know comes from the\n\\`factory_*\\` tools, which read the Factory's own records.\n\n## How to answer\n\n- Ground every claim in a tool result. Quote ids (card number, decision id,\n seat id, thread id) and timestamps so the person can click through. Never\n guess at a cause the records do not show.\n- Start with \\`factory_health_check\\` for \"what's wrong / what needs me\", and\n \\`factory_inspect_work_item\\` for questions about one card. Use\n \\`factory_read_session\\` only when the records don't explain a card and the\n worker's own transcript might.\n- Lead with the answer, then the evidence, then the standard repair. Keep it\n short; the person will ask for more.\n- Group like with like: several cards failing with the same code and error at\n the same time are one incident, not several.\n\n## Reading the records\n\n- \\`decision-failed\\` — the dispatcher gave up. If the cause was transient\n (a restart, a fixed bug, a rate limit), a retry will succeed. If the card\n has already moved on past the role the decision was for, the decision is\n moot and should be dismissed, not retried.\n- \\`decision-stuck\\` — retry/pending past its backoff, or a lease that\n expired: the dispatcher is not picking it up. Usually a stalled process.\n- \\`seat-missing\\` — a card sits in a working lane with nobody bound to it\n and nothing in flight; it will not progress until a run is started.\n- \\`seat-orphaned\\` — a seat is active on a card that already finished or\n left that role's lane; a lifecycle bug left it behind.\n- \\`start-stalled\\` — a run was asked for but the kickoff never landed.\n- \\`proposal-waiting\\` / \\`held-waiting\\` — a person is the blocker. Say so\n plainly and name what they need to decide.\n- \\`label-drift\\` — the GitHub labels disagree with the card's accepted\n state; reconcile its acceptance labels after confirming the repair.\n\n## Repairs\n\nWrite tools require confirmation and are recorded against the person who\nasked. Use the repair suggested by the health finding: retry or dismiss a\ndecision, accept a held card, approve or dismiss a proposal, revoke an\norphaned seat, signal a worker, or reconcile stale acceptance labels. Never\nclaim a repair happened unless a tool result says it did.\n`;\n"],"mappings":";;;;;AAIA,MAAa,0BAA0B"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Supervisor read surface. Every tool is bounded (hard row caps, truncated
|
|
3
|
+
* text) and answers with ids a person can click on the board, so the model
|
|
4
|
+
* can explain a card's state without ever touching the database itself.
|
|
5
|
+
*/
|
|
6
|
+
import type { MastraDBMessage } from '@mastra/core/agent/message-list';
|
|
7
|
+
import type { IntegrationTools } from '../integrations/base.js';
|
|
8
|
+
import type { AuditStorage } from '../storage/domains/audit/base.js';
|
|
9
|
+
import type { WorkItemCommentsStorage } from '../storage/domains/comments/base.js';
|
|
10
|
+
import type { WorkItemsStorage } from '../storage/domains/work-items/base.js';
|
|
11
|
+
import type { FactoryHealthThresholds } from './health.js';
|
|
12
|
+
export interface SupervisorScope {
|
|
13
|
+
orgId: string;
|
|
14
|
+
factoryProjectId: string;
|
|
15
|
+
}
|
|
16
|
+
export interface SupervisorMessageReader {
|
|
17
|
+
listMessages(input: {
|
|
18
|
+
threadId: string;
|
|
19
|
+
resourceId?: string;
|
|
20
|
+
page: number;
|
|
21
|
+
perPage: number;
|
|
22
|
+
orderBy: {
|
|
23
|
+
field: 'createdAt';
|
|
24
|
+
direction: 'ASC' | 'DESC';
|
|
25
|
+
};
|
|
26
|
+
}): Promise<{
|
|
27
|
+
messages: MastraDBMessage[];
|
|
28
|
+
hasMore: boolean;
|
|
29
|
+
}>;
|
|
30
|
+
}
|
|
31
|
+
export interface SupervisorReadDependencies {
|
|
32
|
+
scope: SupervisorScope;
|
|
33
|
+
workItems: WorkItemsStorage;
|
|
34
|
+
comments: WorkItemCommentsStorage;
|
|
35
|
+
audit: AuditStorage;
|
|
36
|
+
messageReader?: SupervisorMessageReader;
|
|
37
|
+
healthThresholds?: FactoryHealthThresholds;
|
|
38
|
+
now?: () => Date;
|
|
39
|
+
}
|
|
40
|
+
export declare function createFactorySupervisorReadTools(deps: SupervisorReadDependencies): IntegrationTools;
|
|
41
|
+
//# sourceMappingURL=read-tools.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"read-tools.d.ts","sourceRoot":"","sources":["../../src/supervisor/read-tools.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KA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