Skip to content

Commit a81a644

Browse files
committed
fix(workboard): enforce fail-closed completion gates
1 parent d4794c9 commit a81a644

10 files changed

Lines changed: 492 additions & 40 deletions

File tree

‎extensions/workboard/src/gateway.test.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -642,7 +642,15 @@ describe("workboard gateway methods", () => {
642642

643643
const completeRespond = vi.fn();
644644
await methods.get("workboard.cards.complete")?.handler({
645-
params: { id: cardId, summary: "Operator closed it." },
645+
params: {
646+
id: cardId,
647+
summary: "Operator closed it.",
648+
proof: {
649+
status: "passed",
650+
command: "pnpm test extensions/workboard/src/gateway.test.ts",
651+
note: "Gateway lifecycle test passed.",
652+
},
653+
},
646654
respond: completeRespond,
647655
} as never);
648656
expect(completeRespond.mock.calls[0]?.[1]).toMatchObject({

‎extensions/workboard/src/store-card-helpers.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
type WorkboardExecution,
1212
type WorkboardMetadata,
1313
type WorkboardNotification,
14+
type WorkboardProof,
1415
type WorkboardRunAttempt,
1516
type WorkboardStatus,
1617
} from "@openclaw/workboard-contract";
@@ -50,6 +51,22 @@ export function cardRunId(card: WorkboardCard): string | undefined {
5051
return card.runId ?? card.execution?.runId;
5152
}
5253

54+
export function isStructuredPassedProof(proof: WorkboardProof | undefined): boolean {
55+
if (proof?.status !== "passed") {
56+
return false;
57+
}
58+
const source = proof.command?.trim() || proof.url?.trim();
59+
const note = proof.note?.trim();
60+
return Boolean(source && note && !/^(?:ok|done|complete|verified)$/i.test(note));
61+
}
62+
63+
export function pullRequestUrls(card: WorkboardCard): string[] {
64+
const urls = [card.sourceUrl, ...(card.metadata?.links ?? []).map((link) => link.url)].filter(
65+
(url): url is string => Boolean(url),
66+
);
67+
return urls.filter((url) => /github\.com\/[^/]+\/[^/]+\/pull\/\d+(?:[/?#]|$)/i.test(url));
68+
}
69+
5370
function executionAttemptStatus(execution: WorkboardExecution): WorkboardAttemptStatus {
5471
if (execution.status === "running") {
5572
return "running";

‎extensions/workboard/src/store-core.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,19 @@ import { normalizeAutomationPatch, normalizeCardAutomation } from "./store-autom
1818
import {
1919
assertCanMutateClaimedCard,
2020
cardBoardId,
21+
cardChildIds,
2122
cardParentIds,
2223
compareCards,
2324
isActiveDependencyTarget,
2425
isDependencyPromotableStatus,
26+
isStructuredPassedProof,
2527
lifecycleStatusSourceUpdatedAtFromPatch,
2628
removeUndefinedCardFields,
2729
shouldSkipPersistedLifecycleStatusUpdate,
2830
syncExecutionAttemptMetadata,
2931
updateEvent,
3032
appendEvent,
33+
pullRequestUrls,
3134
} from "./store-card-helpers.js";
3235
import { WorkboardChangeTracker } from "./store-change-tracker.js";
3336
import { MAX_CARD_COMMENTS, MAX_CARD_WORKER_LOGS, POSITION_STEP } from "./store-constants.js";
@@ -433,6 +436,9 @@ export class WorkboardCoreStore {
433436
...(completedAt ? { completedAt } : {}),
434437
...(!metadataIsEmpty(syncedMetadata) ? { metadata: syncedMetadata } : {}),
435438
};
439+
if (card.status === "done") {
440+
await this.assertDoneTransitionAllowed(undefined, card);
441+
}
436442
await this.store.register(card.id, { version: 1, card });
437443
try {
438444
for (const parent of parentCards) {
@@ -650,6 +656,7 @@ export class WorkboardCoreStore {
650656
throw new Error("card dependencies are not done.");
651657
}
652658
if (next.status === "done") {
659+
await this.assertDoneTransitionAllowed(existing, next);
653660
return;
654661
}
655662
const scheduledAt = next.metadata?.automation?.scheduledAt;
@@ -658,6 +665,61 @@ export class WorkboardCoreStore {
658665
}
659666
}
660667

668+
private async assertDoneTransitionAllowed(
669+
existing: WorkboardCard | undefined,
670+
next: WorkboardCard,
671+
): Promise<void> {
672+
const proof = next.metadata?.proof?.findLast(isStructuredPassedProof);
673+
if (!proof) {
674+
throw new Error(
675+
"done gate: a passed structured proof with an exact command or URL and result note is required.",
676+
);
677+
}
678+
if (next.metadata?.workflowState === "decomposed") {
679+
throw new Error(
680+
"done gate: a decomposed/planning card must remain open until execution is complete.",
681+
);
682+
}
683+
const cardsById = new Map((await this.list()).map((card) => [card.id, card]));
684+
if (existing) {
685+
cardsById.set(existing.id, next);
686+
}
687+
for (const parentId of cardParentIds(next)) {
688+
if (cardsById.get(parentId)?.status !== "done") {
689+
throw new Error(`done gate: dependency ${parentId} is not done.`);
690+
}
691+
}
692+
for (const childId of cardChildIds(next)) {
693+
const child = cardsById.get(childId);
694+
if (!child) {
695+
throw new Error(`done gate: required child ${childId} is missing.`);
696+
}
697+
if (child.status !== "done" && (next.metadata?.completionWaiver?.trim().length ?? 0) < 12) {
698+
throw new Error(`done gate: required child ${childId} is ${child.status}, not done.`);
699+
}
700+
}
701+
for (const link of next.metadata?.links ?? []) {
702+
if (link.type !== "blocked_by") {
703+
continue;
704+
}
705+
const blocker = link.targetCardId ? cardsById.get(link.targetCardId) : undefined;
706+
if (!blocker || blocker.status !== "done") {
707+
throw new Error(
708+
`done gate: unresolved blocker ${link.targetCardId ?? link.url ?? "(unknown)"}.`,
709+
);
710+
}
711+
}
712+
if (pullRequestUrls(next).length > 0) {
713+
const note = proof.note?.toLowerCase() ?? "";
714+
const hasCommit = /\b[0-9a-f]{7,40}\b/i.test(proof.note ?? "");
715+
if (!/\bmerged\b/.test(note) || !/\breview(?:ed)?\b/.test(note) || !hasCommit) {
716+
throw new Error(
717+
"done gate: a pull request remains in review until merged exact-head/review proof includes the commit SHA.",
718+
);
719+
}
720+
}
721+
}
722+
661723
async delete(id: string): Promise<{ deleted: boolean }> {
662724
return await this.enqueueMutation(async () => await this.deleteDirect(id));
663725
}

‎extensions/workboard/src/store-inputs.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ export type WorkboardCompleteInput = {
113113
proofId?: unknown;
114114
artifacts?: unknown;
115115
createdCardIds?: unknown;
116+
completionWaiver?: unknown;
116117
};
117118
export type WorkboardBlockInput = {
118119
ownerId?: unknown;
@@ -170,6 +171,8 @@ export type WorkboardDecomposeInput = {
170171
summary?: unknown;
171172
children?: unknown;
172173
completeParent?: unknown;
174+
proof?: unknown;
175+
completionWaiver?: unknown;
173176
};
174177
export type WorkboardNotificationSubscribeInput = {
175178
boardId?: unknown;

‎extensions/workboard/src/store-normalizers.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1037,6 +1037,8 @@ export function normalizeMetadata(
10371037
const hasArchivedAt = Object.hasOwn(record, "archivedAt");
10381038
const hasStale = Object.hasOwn(record, "stale");
10391039
const hasLifecycleStatusSourceUpdatedAt = Object.hasOwn(record, "lifecycleStatusSourceUpdatedAt");
1040+
const hasWorkflowState = Object.hasOwn(record, "workflowState");
1041+
const hasCompletionWaiver = Object.hasOwn(record, "completionWaiver");
10401042
const links = Array.isArray(record.links)
10411043
? record.links.map(normalizeLink).filter((link): link is WorkboardLink => link !== null)
10421044
: undefined;
@@ -1140,6 +1142,14 @@ export function normalizeMetadata(
11401142
typeof record.failureCount === "number" && Number.isFinite(record.failureCount)
11411143
? Math.max(0, Math.trunc(record.failureCount))
11421144
: fallback.failureCount,
1145+
workflowState: hasWorkflowState
1146+
? record.workflowState === "planned" || record.workflowState === "decomposed"
1147+
? record.workflowState
1148+
: undefined
1149+
: fallback.workflowState,
1150+
completionWaiver: hasCompletionWaiver
1151+
? normalizeBoundedString(record.completionWaiver, undefined, 2000, "completion waiver")
1152+
: fallback.completionWaiver,
11431153
};
11441154
return trimMetadataToBudget(normalized, options);
11451155
}
@@ -1257,6 +1267,8 @@ export function removeUndefinedMetadataFields(metadata: WorkboardMetadata): Work
12571267
"stale",
12581268
"lifecycleStatusSourceUpdatedAt",
12591269
"failureCount",
1270+
"workflowState",
1271+
"completionWaiver",
12601272
] as const) {
12611273
const value = next[key];
12621274
if (

‎extensions/workboard/src/store-workflow.ts‎

Lines changed: 47 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,12 @@ export class WorkboardWorkflowStore extends WorkboardPromoteStore {
244244
}
245245
}
246246
const summary = normalizeBoundedString(input.summary, undefined, 2000, "summary");
247+
const completionWaiver = normalizeBoundedString(
248+
input.completionWaiver,
249+
undefined,
250+
2000,
251+
"completion waiver",
252+
);
247253
const proofInput =
248254
input.proof && typeof input.proof === "object" && !Array.isArray(input.proof)
249255
? (input.proof as WorkboardProofInput)
@@ -286,6 +292,8 @@ export class WorkboardWorkflowStore extends WorkboardPromoteStore {
286292
claim: undefined,
287293
attempts: closeRunningAttempts(metadata.attempts, now, "succeeded"),
288294
failureCount: 0,
295+
workflowState: undefined,
296+
...(completionWaiver ? { completionWaiver } : {}),
289297
automation: normalizeAutomation(
290298
{
291299
...metadata.automation,
@@ -545,22 +553,34 @@ export class WorkboardWorkflowStore extends WorkboardPromoteStore {
545553
const existingCardIds = new Set((await this.list()).map((card) => card.id));
546554
const children: WorkboardCard[] = [];
547555
const reusedChildSnapshots = new Map<string, WorkboardCard>();
556+
const childIdempotencyKeys = new Set<string>();
548557
try {
549558
for (const rawChild of childrenInput) {
550559
if (!rawChild || typeof rawChild !== "object" || Array.isArray(rawChild)) {
551560
throw new Error("children must be objects.");
552561
}
553562
const child = rawChild as WorkboardDecomposeChildInput;
563+
const childIdempotencyKey = normalizeBoundedString(
564+
child.idempotencyKey ??
565+
deriveChildIdempotencyKey(parentAutomation?.idempotencyKey, children.length + 1),
566+
undefined,
567+
160,
568+
"idempotency key",
569+
);
570+
if (childIdempotencyKey) {
571+
if (childIdempotencyKeys.has(childIdempotencyKey)) {
572+
throw new Error(`duplicate child idempotency key: ${childIdempotencyKey}`);
573+
}
574+
childIdempotencyKeys.add(childIdempotencyKey);
575+
}
554576
const created = await this.createDirect(
555577
{
556578
...child,
557579
parents: [parent.id],
558580
boardId: child.boardId ?? parentAutomation?.boardId,
559581
tenant: child.tenant ?? parentAutomation?.tenant,
560582
createdByCardId: parent.id,
561-
idempotencyKey:
562-
child.idempotencyKey ??
563-
deriveChildIdempotencyKey(parentAutomation?.idempotencyKey, children.length + 1),
583+
idempotencyKey: childIdempotencyKey,
564584
},
565585
scope === null ? undefined : scope,
566586
);
@@ -579,11 +599,22 @@ export class WorkboardWorkflowStore extends WorkboardPromoteStore {
579599
);
580600
}
581601
const summary = normalizeBoundedString(input.summary, undefined, 2000, "decompose summary");
582-
const completeParent = input.completeParent !== false;
602+
const completionWaiver = normalizeBoundedString(
603+
input.completionWaiver,
604+
undefined,
605+
2000,
606+
"completion waiver",
607+
);
608+
const completeParent = input.completeParent === true;
583609
const updatedParent = completeParent
584610
? await this.completeDirect(
585611
parent.id,
586-
{ summary, createdCardIds: children.map((child) => child.id) },
612+
{
613+
summary,
614+
proof: input.proof,
615+
createdCardIds: children.map((child) => child.id),
616+
...(completionWaiver ? { completionWaiver } : {}),
617+
},
587618
scope,
588619
)
589620
: await (async () => {
@@ -597,6 +628,7 @@ export class WorkboardWorkflowStore extends WorkboardPromoteStore {
597628
: latestParent.status,
598629
metadata: {
599630
...latestParent.metadata,
631+
workflowState: "decomposed",
600632
automation: normalizeAutomation(
601633
{
602634
...latestParent.metadata?.automation,
@@ -605,6 +637,16 @@ export class WorkboardWorkflowStore extends WorkboardPromoteStore {
605637
},
606638
latestParent.metadata?.automation,
607639
),
640+
notifications: [
641+
...(latestParent.metadata?.notifications ?? []),
642+
{
643+
id: randomUUID(),
644+
kind: "decomposed",
645+
createdAt: Date.now(),
646+
sequence: this.nextNotificationSequence(Date.now()),
647+
message: capText(summary, 240) ?? "Workboard card decomposed.",
648+
} satisfies WorkboardNotification,
649+
].slice(-MAX_CARD_NOTIFICATIONS),
608650
},
609651
},
610652
{ enforceStatusHolds: true },

0 commit comments

Comments
 (0)