@agimon-ai/doompi-task 0.0.1-alpha.0
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/LICENSE +21 -0
- package/README.md +35 -0
- package/dist/_virtual/_rolldown/runtime.cjs +1 -0
- package/dist/commands.cjs +2 -0
- package/dist/commands.cjs.map +1 -0
- package/dist/commands.d.cts +14 -0
- package/dist/commands.d.cts.map +1 -0
- package/dist/commands.d.mts +14 -0
- package/dist/commands.d.mts.map +1 -0
- package/dist/commands.mjs +2 -0
- package/dist/commands.mjs.map +1 -0
- package/dist/config.cjs +2 -0
- package/dist/config.cjs.map +1 -0
- package/dist/config.d.cts +38 -0
- package/dist/config.d.cts.map +1 -0
- package/dist/config.d.mts +38 -0
- package/dist/config.d.mts.map +1 -0
- package/dist/config.mjs +2 -0
- package/dist/config.mjs.map +1 -0
- package/dist/delegation/manager.cjs +5 -0
- package/dist/delegation/manager.cjs.map +1 -0
- package/dist/delegation/manager.d.cts +189 -0
- package/dist/delegation/manager.d.cts.map +1 -0
- package/dist/delegation/manager.d.mts +189 -0
- package/dist/delegation/manager.d.mts.map +1 -0
- package/dist/delegation/manager.mjs +5 -0
- package/dist/delegation/manager.mjs.map +1 -0
- package/dist/extension.cjs +3 -0
- package/dist/extension.cjs.map +1 -0
- package/dist/extension.d.cts +12 -0
- package/dist/extension.d.cts.map +1 -0
- package/dist/extension.d.mts +12 -0
- package/dist/extension.d.mts.map +1 -0
- package/dist/extension.mjs +3 -0
- package/dist/extension.mjs.map +1 -0
- package/dist/extensions/doom.cjs +2 -0
- package/dist/extensions/doom.cjs.map +1 -0
- package/dist/extensions/doom.d.cts +6 -0
- package/dist/extensions/doom.d.cts.map +1 -0
- package/dist/extensions/doom.d.mts +7 -0
- package/dist/extensions/doom.d.mts.map +1 -0
- package/dist/extensions/doom.mjs +2 -0
- package/dist/extensions/doom.mjs.map +1 -0
- package/dist/extensions/pi.cjs +2 -0
- package/dist/extensions/pi.cjs.map +1 -0
- package/dist/extensions/pi.d.cts +2 -0
- package/dist/extensions/pi.d.mts +2 -0
- package/dist/extensions/pi.mjs +2 -0
- package/dist/extensions/pi.mjs.map +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +15 -0
- package/dist/index.d.mts +15 -0
- package/dist/index.mjs +1 -0
- package/dist/logSinkTelemetry.cjs +2 -0
- package/dist/logSinkTelemetry.cjs.map +1 -0
- package/dist/logSinkTelemetry.d.cts +51 -0
- package/dist/logSinkTelemetry.d.cts.map +1 -0
- package/dist/logSinkTelemetry.d.mts +51 -0
- package/dist/logSinkTelemetry.d.mts.map +1 -0
- package/dist/logSinkTelemetry.mjs +2 -0
- package/dist/logSinkTelemetry.mjs.map +1 -0
- package/dist/store/invariants.cjs +2 -0
- package/dist/store/invariants.cjs.map +1 -0
- package/dist/store/invariants.d.cts +14 -0
- package/dist/store/invariants.d.cts.map +1 -0
- package/dist/store/invariants.d.mts +14 -0
- package/dist/store/invariants.d.mts.map +1 -0
- package/dist/store/invariants.mjs +2 -0
- package/dist/store/invariants.mjs.map +1 -0
- package/dist/store/paths.cjs +2 -0
- package/dist/store/paths.cjs.map +1 -0
- package/dist/store/paths.d.cts +23 -0
- package/dist/store/paths.d.cts.map +1 -0
- package/dist/store/paths.d.mts +23 -0
- package/dist/store/paths.d.mts.map +1 -0
- package/dist/store/paths.mjs +2 -0
- package/dist/store/paths.mjs.map +1 -0
- package/dist/store/processLiveness.cjs +2 -0
- package/dist/store/processLiveness.cjs.map +1 -0
- package/dist/store/processLiveness.d.cts +12 -0
- package/dist/store/processLiveness.d.cts.map +1 -0
- package/dist/store/processLiveness.d.mts +12 -0
- package/dist/store/processLiveness.d.mts.map +1 -0
- package/dist/store/processLiveness.mjs +2 -0
- package/dist/store/processLiveness.mjs.map +1 -0
- package/dist/store/reconcile.cjs +2 -0
- package/dist/store/reconcile.cjs.map +1 -0
- package/dist/store/reconcile.d.cts +34 -0
- package/dist/store/reconcile.d.cts.map +1 -0
- package/dist/store/reconcile.d.mts +34 -0
- package/dist/store/reconcile.d.mts.map +1 -0
- package/dist/store/reconcile.mjs +2 -0
- package/dist/store/reconcile.mjs.map +1 -0
- package/dist/store/reducer.cjs +3 -0
- package/dist/store/reducer.cjs.map +1 -0
- package/dist/store/reducer.d.cts +72 -0
- package/dist/store/reducer.d.cts.map +1 -0
- package/dist/store/reducer.d.mts +72 -0
- package/dist/store/reducer.d.mts.map +1 -0
- package/dist/store/reducer.mjs +3 -0
- package/dist/store/reducer.mjs.map +1 -0
- package/dist/store/taskGraph.cjs +2 -0
- package/dist/store/taskGraph.cjs.map +1 -0
- package/dist/store/taskGraph.d.cts +25 -0
- package/dist/store/taskGraph.d.cts.map +1 -0
- package/dist/store/taskGraph.d.mts +25 -0
- package/dist/store/taskGraph.d.mts.map +1 -0
- package/dist/store/taskGraph.mjs +2 -0
- package/dist/store/taskGraph.mjs.map +1 -0
- package/dist/store/taskStore.cjs +2 -0
- package/dist/store/taskStore.cjs.map +1 -0
- package/dist/store/taskStore.d.cts +77 -0
- package/dist/store/taskStore.d.cts.map +1 -0
- package/dist/store/taskStore.d.mts +77 -0
- package/dist/store/taskStore.d.mts.map +1 -0
- package/dist/store/taskStore.mjs +2 -0
- package/dist/store/taskStore.mjs.map +1 -0
- package/dist/store/types.cjs +2 -0
- package/dist/store/types.cjs.map +1 -0
- package/dist/store/types.d.cts +165 -0
- package/dist/store/types.d.cts.map +1 -0
- package/dist/store/types.d.mts +165 -0
- package/dist/store/types.d.mts.map +1 -0
- package/dist/store/types.mjs +2 -0
- package/dist/store/types.mjs.map +1 -0
- package/dist/tool/promptGuidelines.cjs +2 -0
- package/dist/tool/promptGuidelines.cjs.map +1 -0
- package/dist/tool/promptGuidelines.d.cts +5 -0
- package/dist/tool/promptGuidelines.d.cts.map +1 -0
- package/dist/tool/promptGuidelines.d.mts +5 -0
- package/dist/tool/promptGuidelines.d.mts.map +1 -0
- package/dist/tool/promptGuidelines.mjs +2 -0
- package/dist/tool/promptGuidelines.mjs.map +1 -0
- package/dist/tool/responseEnvelope.cjs +6 -0
- package/dist/tool/responseEnvelope.cjs.map +1 -0
- package/dist/tool/responseEnvelope.d.cts +39 -0
- package/dist/tool/responseEnvelope.d.cts.map +1 -0
- package/dist/tool/responseEnvelope.d.mts +39 -0
- package/dist/tool/responseEnvelope.d.mts.map +1 -0
- package/dist/tool/responseEnvelope.mjs +6 -0
- package/dist/tool/responseEnvelope.mjs.map +1 -0
- package/dist/tool/schema.cjs +2 -0
- package/dist/tool/schema.cjs.map +1 -0
- package/dist/tool/schema.d.cts +86 -0
- package/dist/tool/schema.d.cts.map +1 -0
- package/dist/tool/schema.d.mts +86 -0
- package/dist/tool/schema.d.mts.map +1 -0
- package/dist/tool/schema.mjs +2 -0
- package/dist/tool/schema.mjs.map +1 -0
- package/dist/tool/taskTool.cjs +3 -0
- package/dist/tool/taskTool.cjs.map +1 -0
- package/dist/tool/taskTool.d.cts +17 -0
- package/dist/tool/taskTool.d.cts.map +1 -0
- package/dist/tool/taskTool.d.mts +17 -0
- package/dist/tool/taskTool.d.mts.map +1 -0
- package/dist/tool/taskTool.mjs +3 -0
- package/dist/tool/taskTool.mjs.map +1 -0
- package/dist/tui/format.cjs +4 -0
- package/dist/tui/format.cjs.map +1 -0
- package/dist/tui/format.d.cts +62 -0
- package/dist/tui/format.d.cts.map +1 -0
- package/dist/tui/format.d.mts +62 -0
- package/dist/tui/format.d.mts.map +1 -0
- package/dist/tui/format.mjs +4 -0
- package/dist/tui/format.mjs.map +1 -0
- package/dist/tui/selectors.cjs +2 -0
- package/dist/tui/selectors.cjs.map +1 -0
- package/dist/tui/selectors.d.cts +45 -0
- package/dist/tui/selectors.d.cts.map +1 -0
- package/dist/tui/selectors.d.mts +45 -0
- package/dist/tui/selectors.d.mts.map +1 -0
- package/dist/tui/selectors.mjs +2 -0
- package/dist/tui/selectors.mjs.map +1 -0
- package/dist/tui/taskOverlay.cjs +2 -0
- package/dist/tui/taskOverlay.cjs.map +1 -0
- package/dist/tui/taskOverlay.d.cts +38 -0
- package/dist/tui/taskOverlay.d.cts.map +1 -0
- package/dist/tui/taskOverlay.d.mts +38 -0
- package/dist/tui/taskOverlay.d.mts.map +1 -0
- package/dist/tui/taskOverlay.mjs +2 -0
- package/dist/tui/taskOverlay.mjs.map +1 -0
- package/dist/tui/taskSpace.cjs +5 -0
- package/dist/tui/taskSpace.cjs.map +1 -0
- package/dist/tui/taskSpace.d.cts +61 -0
- package/dist/tui/taskSpace.d.cts.map +1 -0
- package/dist/tui/taskSpace.d.mts +61 -0
- package/dist/tui/taskSpace.d.mts.map +1 -0
- package/dist/tui/taskSpace.mjs +5 -0
- package/dist/tui/taskSpace.mjs.map +1 -0
- package/package.json +185 -0
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { DoomTelemetryOptions } from "@agimon-ai/doompi-telemetry";
|
|
2
|
+
//#region src/logSinkTelemetry.d.ts
|
|
3
|
+
declare const TASK_EVENT: {
|
|
4
|
+
readonly notificationFailed: "doom_task.notification_failed";
|
|
5
|
+
readonly storeReadFailed: "doom_task.store_read_failed";
|
|
6
|
+
readonly storeLockTimeout: "doom_task.store_lock_timeout";
|
|
7
|
+
readonly storeLockBreakFailed: "doom_task.store_lock_break_failed";
|
|
8
|
+
readonly storeWatchFailed: "doom_task.store_watch_failed";
|
|
9
|
+
readonly storeListenerFailed: "doom_task.store_listener_failed";
|
|
10
|
+
readonly storeSweepFailed: "doom_task.store_sweep_failed";
|
|
11
|
+
readonly sessionStartFailed: "doom_task.session_start_failed";
|
|
12
|
+
readonly toolFailed: "doom_task.tool_failed";
|
|
13
|
+
readonly delegationRequestFailed: "doom_task.delegation_request_failed";
|
|
14
|
+
readonly delegationStartFailed: "doom_task.delegation_start_failed";
|
|
15
|
+
readonly delegationResponseFailed: "doom_task.delegation_response_failed";
|
|
16
|
+
readonly delegationSettleFailed: "doom_task.delegation_settle_failed";
|
|
17
|
+
readonly delegationTimedOut: "doom_task.delegation_timed_out";
|
|
18
|
+
readonly delegationOrphaned: "doom_task.delegation_orphaned";
|
|
19
|
+
readonly delegationAssigned: "doom_task.delegation_assigned";
|
|
20
|
+
readonly delegationCompleted: "doom_task.delegation_completed";
|
|
21
|
+
};
|
|
22
|
+
type TaskEventName = (typeof TASK_EVENT)[keyof typeof TASK_EVENT];
|
|
23
|
+
type TaskErrorAttributes = Record<string, string | number | boolean>;
|
|
24
|
+
type TaskErrorSink = (event: TaskEventName, error: unknown, attributes?: TaskErrorAttributes) => void;
|
|
25
|
+
type TaskEventSink = (event: TaskEventName, attributes?: TaskErrorAttributes) => void;
|
|
26
|
+
interface TaskFailureReporter {
|
|
27
|
+
error: TaskErrorSink;
|
|
28
|
+
warn: TaskErrorSink;
|
|
29
|
+
/** Info-level event sink. Required so an unwired reporter fails to compile. */
|
|
30
|
+
event: TaskEventSink;
|
|
31
|
+
}
|
|
32
|
+
interface TaskErrorReporterOptions {
|
|
33
|
+
cwd?: string;
|
|
34
|
+
workspaceRoot?: string;
|
|
35
|
+
env?: NodeJS.ProcessEnv;
|
|
36
|
+
telemetryFactory?: NonNullable<DoomTelemetryOptions['telemetryFactory']>;
|
|
37
|
+
warn?: (message: string) => void;
|
|
38
|
+
}
|
|
39
|
+
interface TaskErrorReporter {
|
|
40
|
+
recordError(event: string, error: unknown, attributes?: TaskErrorAttributes): Promise<void>;
|
|
41
|
+
recordWarning(event: string, error: unknown, attributes?: TaskErrorAttributes): Promise<void>;
|
|
42
|
+
recordEvent(event: string, attributes?: TaskErrorAttributes): Promise<void>;
|
|
43
|
+
recordNotificationError(error: unknown, taskId: number): Promise<void>;
|
|
44
|
+
flush(): Promise<void>;
|
|
45
|
+
shutdown(): Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
declare function createTaskErrorReporter(options?: TaskErrorReporterOptions): TaskErrorReporter;
|
|
48
|
+
declare function toFailureReporter(reporter: TaskErrorReporter): TaskFailureReporter;
|
|
49
|
+
//#endregion
|
|
50
|
+
export { TASK_EVENT, TaskErrorAttributes, TaskErrorReporter, TaskErrorReporterOptions, TaskErrorSink, TaskEventName, TaskEventSink, TaskFailureReporter, createTaskErrorReporter, toFailureReporter };
|
|
51
|
+
//# sourceMappingURL=logSinkTelemetry.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logSinkTelemetry.d.cts","names":[],"sources":["../src/logSinkTelemetry.ts"],"mappings":";;cAMa;;;;;;;;;;;;;;;;;;;KAsBD,wBAAwB,yBAAyB;KACjD,sBAAsB;KACtB,iBAAiB,OAAO,eAAe,gBAAgB,aAAa;KACpE,iBAAiB,OAAO,eAAe,aAAa;UAE/C;EACf,OAAO;EACP,MAAM;;EAEN,OAAO;;UAGQ;EACf;EACA;EACA,MAAM,OAAO;EACb,mBAAmB,YAAY;EAC/B,QAAQ;;UAGO;EACf,YAAY,eAAe,gBAAgB,aAAa,sBAAsB;EAC9E,cAAc,eAAe,gBAAgB,aAAa,sBAAsB;EAChF,YAAY,eAAe,aAAa,sBAAsB;EAC9D,wBAAwB,gBAAgB,iBAAiB;EACzD,SAAS;EACT,YAAY;;iBAGE,wBAAwB,UAAS,2BAAgC;iBA0BjE,kBAAkB,UAAU,oBAAoB"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { DoomTelemetryOptions } from "@agimon-ai/doompi-telemetry";
|
|
2
|
+
//#region src/logSinkTelemetry.d.ts
|
|
3
|
+
declare const TASK_EVENT: {
|
|
4
|
+
readonly notificationFailed: "doom_task.notification_failed";
|
|
5
|
+
readonly storeReadFailed: "doom_task.store_read_failed";
|
|
6
|
+
readonly storeLockTimeout: "doom_task.store_lock_timeout";
|
|
7
|
+
readonly storeLockBreakFailed: "doom_task.store_lock_break_failed";
|
|
8
|
+
readonly storeWatchFailed: "doom_task.store_watch_failed";
|
|
9
|
+
readonly storeListenerFailed: "doom_task.store_listener_failed";
|
|
10
|
+
readonly storeSweepFailed: "doom_task.store_sweep_failed";
|
|
11
|
+
readonly sessionStartFailed: "doom_task.session_start_failed";
|
|
12
|
+
readonly toolFailed: "doom_task.tool_failed";
|
|
13
|
+
readonly delegationRequestFailed: "doom_task.delegation_request_failed";
|
|
14
|
+
readonly delegationStartFailed: "doom_task.delegation_start_failed";
|
|
15
|
+
readonly delegationResponseFailed: "doom_task.delegation_response_failed";
|
|
16
|
+
readonly delegationSettleFailed: "doom_task.delegation_settle_failed";
|
|
17
|
+
readonly delegationTimedOut: "doom_task.delegation_timed_out";
|
|
18
|
+
readonly delegationOrphaned: "doom_task.delegation_orphaned";
|
|
19
|
+
readonly delegationAssigned: "doom_task.delegation_assigned";
|
|
20
|
+
readonly delegationCompleted: "doom_task.delegation_completed";
|
|
21
|
+
};
|
|
22
|
+
type TaskEventName = (typeof TASK_EVENT)[keyof typeof TASK_EVENT];
|
|
23
|
+
type TaskErrorAttributes = Record<string, string | number | boolean>;
|
|
24
|
+
type TaskErrorSink = (event: TaskEventName, error: unknown, attributes?: TaskErrorAttributes) => void;
|
|
25
|
+
type TaskEventSink = (event: TaskEventName, attributes?: TaskErrorAttributes) => void;
|
|
26
|
+
interface TaskFailureReporter {
|
|
27
|
+
error: TaskErrorSink;
|
|
28
|
+
warn: TaskErrorSink;
|
|
29
|
+
/** Info-level event sink. Required so an unwired reporter fails to compile. */
|
|
30
|
+
event: TaskEventSink;
|
|
31
|
+
}
|
|
32
|
+
interface TaskErrorReporterOptions {
|
|
33
|
+
cwd?: string;
|
|
34
|
+
workspaceRoot?: string;
|
|
35
|
+
env?: NodeJS.ProcessEnv;
|
|
36
|
+
telemetryFactory?: NonNullable<DoomTelemetryOptions['telemetryFactory']>;
|
|
37
|
+
warn?: (message: string) => void;
|
|
38
|
+
}
|
|
39
|
+
interface TaskErrorReporter {
|
|
40
|
+
recordError(event: string, error: unknown, attributes?: TaskErrorAttributes): Promise<void>;
|
|
41
|
+
recordWarning(event: string, error: unknown, attributes?: TaskErrorAttributes): Promise<void>;
|
|
42
|
+
recordEvent(event: string, attributes?: TaskErrorAttributes): Promise<void>;
|
|
43
|
+
recordNotificationError(error: unknown, taskId: number): Promise<void>;
|
|
44
|
+
flush(): Promise<void>;
|
|
45
|
+
shutdown(): Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
declare function createTaskErrorReporter(options?: TaskErrorReporterOptions): TaskErrorReporter;
|
|
48
|
+
declare function toFailureReporter(reporter: TaskErrorReporter): TaskFailureReporter;
|
|
49
|
+
//#endregion
|
|
50
|
+
export { TASK_EVENT, TaskErrorAttributes, TaskErrorReporter, TaskErrorReporterOptions, TaskErrorSink, TaskEventName, TaskEventSink, TaskFailureReporter, createTaskErrorReporter, toFailureReporter };
|
|
51
|
+
//# sourceMappingURL=logSinkTelemetry.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logSinkTelemetry.d.mts","names":[],"sources":["../src/logSinkTelemetry.ts"],"mappings":";;cAMa;;;;;;;;;;;;;;;;;;;KAsBD,wBAAwB,yBAAyB;KACjD,sBAAsB;KACtB,iBAAiB,OAAO,eAAe,gBAAgB,aAAa;KACpE,iBAAiB,OAAO,eAAe,aAAa;UAE/C;EACf,OAAO;EACP,MAAM;;EAEN,OAAO;;UAGQ;EACf;EACA;EACA,MAAM,OAAO;EACb,mBAAmB,YAAY;EAC/B,QAAQ;;UAGO;EACf,YAAY,eAAe,gBAAgB,aAAa,sBAAsB;EAC9E,cAAc,eAAe,gBAAgB,aAAa,sBAAsB;EAChF,YAAY,eAAe,aAAa,sBAAsB;EAC9D,wBAAwB,gBAAgB,iBAAiB;EACzD,SAAS;EACT,YAAY;;iBAGE,wBAAwB,UAAS,2BAAgC;iBA0BjE,kBAAkB,UAAU,oBAAoB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createDoomTelemetry as e}from"@agimon-ai/doompi-telemetry";const t={notificationFailed:`doom_task.notification_failed`,storeReadFailed:`doom_task.store_read_failed`,storeLockTimeout:`doom_task.store_lock_timeout`,storeLockBreakFailed:`doom_task.store_lock_break_failed`,storeWatchFailed:`doom_task.store_watch_failed`,storeListenerFailed:`doom_task.store_listener_failed`,storeSweepFailed:`doom_task.store_sweep_failed`,sessionStartFailed:`doom_task.session_start_failed`,toolFailed:`doom_task.tool_failed`,delegationRequestFailed:`doom_task.delegation_request_failed`,delegationStartFailed:`doom_task.delegation_start_failed`,delegationResponseFailed:`doom_task.delegation_response_failed`,delegationSettleFailed:`doom_task.delegation_settle_failed`,delegationTimedOut:`doom_task.delegation_timed_out`,delegationOrphaned:`doom_task.delegation_orphaned`,delegationAssigned:`doom_task.delegation_assigned`,delegationCompleted:`doom_task.delegation_completed`};function n(n={}){let r=e({serviceName:`doom-task`,packageName:`@agimon-ai/doompi-task`,cwd:n.cwd,workspaceRoot:n.workspaceRoot,env:n.env,telemetryFactory:n.telemetryFactory,warn:n.warn,enableLogs:!0,enableTraces:!0});return{recordError:(e,t,n)=>r.recordError(e,t,n),recordWarning:(e,t,n)=>r.recordWarning(e,t,n),recordEvent:(e,t)=>r.recordEvent(e,t),recordNotificationError:(e,n)=>r.recordError(t.notificationFailed,e,{"task.id":n,"task.operation":`completion_notification`}),flush:()=>r.flush(),shutdown:()=>r.shutdown()}}function r(e){return{error:(t,n,r)=>void e.recordError(t,n,r),warn:(t,n,r)=>void e.recordWarning(t,n,r),event:(t,n)=>void e.recordEvent(t,n)}}export{t as TASK_EVENT,n as createTaskErrorReporter,r as toFailureReporter};
|
|
2
|
+
//# sourceMappingURL=logSinkTelemetry.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logSinkTelemetry.mjs","names":[],"sources":["../src/logSinkTelemetry.ts"],"sourcesContent":["import { createDoomTelemetry, type DoomTelemetry, type DoomTelemetryOptions } from '@agimon-ai/doompi-telemetry';\n\nconst SERVICE_NAME = 'doom-task';\nconst PACKAGE_NAME = '@agimon-ai/doompi-task';\nconst NOTIFICATION_OPERATION = 'completion_notification';\n\nexport const TASK_EVENT = {\n notificationFailed: 'doom_task.notification_failed',\n storeReadFailed: 'doom_task.store_read_failed',\n storeLockTimeout: 'doom_task.store_lock_timeout',\n storeLockBreakFailed: 'doom_task.store_lock_break_failed',\n storeWatchFailed: 'doom_task.store_watch_failed',\n storeListenerFailed: 'doom_task.store_listener_failed',\n storeSweepFailed: 'doom_task.store_sweep_failed',\n sessionStartFailed: 'doom_task.session_start_failed',\n toolFailed: 'doom_task.tool_failed',\n delegationRequestFailed: 'doom_task.delegation_request_failed',\n delegationStartFailed: 'doom_task.delegation_start_failed',\n delegationResponseFailed: 'doom_task.delegation_response_failed',\n delegationSettleFailed: 'doom_task.delegation_settle_failed',\n delegationTimedOut: 'doom_task.delegation_timed_out',\n delegationOrphaned: 'doom_task.delegation_orphaned',\n // Info-level lifecycle events. These are the measurement pair: the shape of\n // the brief that went out, and the cost of the run it produced.\n delegationAssigned: 'doom_task.delegation_assigned',\n delegationCompleted: 'doom_task.delegation_completed',\n} as const;\n\nexport type TaskEventName = (typeof TASK_EVENT)[keyof typeof TASK_EVENT];\nexport type TaskErrorAttributes = Record<string, string | number | boolean>;\nexport type TaskErrorSink = (event: TaskEventName, error: unknown, attributes?: TaskErrorAttributes) => void;\nexport type TaskEventSink = (event: TaskEventName, attributes?: TaskErrorAttributes) => void;\n\nexport interface TaskFailureReporter {\n error: TaskErrorSink;\n warn: TaskErrorSink;\n /** Info-level event sink. Required so an unwired reporter fails to compile. */\n event: TaskEventSink;\n}\n\nexport interface TaskErrorReporterOptions {\n cwd?: string;\n workspaceRoot?: string;\n env?: NodeJS.ProcessEnv;\n telemetryFactory?: NonNullable<DoomTelemetryOptions['telemetryFactory']>;\n warn?: (message: string) => void;\n}\n\nexport interface TaskErrorReporter {\n recordError(event: string, error: unknown, attributes?: TaskErrorAttributes): Promise<void>;\n recordWarning(event: string, error: unknown, attributes?: TaskErrorAttributes): Promise<void>;\n recordEvent(event: string, attributes?: TaskErrorAttributes): Promise<void>;\n recordNotificationError(error: unknown, taskId: number): Promise<void>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport function createTaskErrorReporter(options: TaskErrorReporterOptions = {}): TaskErrorReporter {\n const telemetry: DoomTelemetry = createDoomTelemetry({\n serviceName: SERVICE_NAME,\n packageName: PACKAGE_NAME,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: options.env,\n telemetryFactory: options.telemetryFactory,\n warn: options.warn,\n enableLogs: true,\n enableTraces: true,\n });\n return {\n recordError: (event, error, attributes) => telemetry.recordError(event, error, attributes),\n recordWarning: (event, error, attributes) => telemetry.recordWarning(event, error, attributes),\n recordEvent: (event, attributes) => telemetry.recordEvent(event, attributes),\n recordNotificationError: (error, taskId) =>\n telemetry.recordError(TASK_EVENT.notificationFailed, error, {\n 'task.id': taskId,\n 'task.operation': NOTIFICATION_OPERATION,\n }),\n flush: () => telemetry.flush(),\n shutdown: () => telemetry.shutdown(),\n };\n}\n\nexport function toFailureReporter(reporter: TaskErrorReporter): TaskFailureReporter {\n return {\n error: (event, error, attributes) => void reporter.recordError(event, error, attributes),\n warn: (event, error, attributes) => void reporter.recordWarning(event, error, attributes),\n event: (event, attributes) => void reporter.recordEvent(event, attributes),\n };\n}\n"],"mappings":"kEAEA,MAIa,EAAa,CACxB,mBAAoB,gCACpB,gBAAiB,8BACjB,iBAAkB,+BAClB,qBAAsB,oCACtB,iBAAkB,+BAClB,oBAAqB,kCACrB,iBAAkB,+BAClB,mBAAoB,iCACpB,WAAY,wBACZ,wBAAyB,sCACzB,sBAAuB,oCACvB,yBAA0B,uCAC1B,uBAAwB,qCACxB,mBAAoB,iCACpB,mBAAoB,gCAGpB,mBAAoB,gCACpB,oBAAqB,gCACvB,EA+BA,SAAgB,EAAwB,EAAoC,CAAC,EAAsB,CACjG,IAAM,EAA2B,EAAoB,CACnD,YAAa,YACb,YAAa,yBACb,IAAK,EAAQ,IACb,cAAe,EAAQ,cACvB,IAAK,EAAQ,IACb,iBAAkB,EAAQ,iBAC1B,KAAM,EAAQ,KACd,WAAY,GACZ,aAAc,EAChB,CAAC,EACD,MAAO,CACL,aAAc,EAAO,EAAO,IAAe,EAAU,YAAY,EAAO,EAAO,CAAU,EACzF,eAAgB,EAAO,EAAO,IAAe,EAAU,cAAc,EAAO,EAAO,CAAU,EAC7F,aAAc,EAAO,IAAe,EAAU,YAAY,EAAO,CAAU,EAC3E,yBAA0B,EAAO,IAC/B,EAAU,YAAY,EAAW,mBAAoB,EAAO,CAC1D,UAAW,EACX,iBAAkB,yBACpB,CAAC,EACH,UAAa,EAAU,MAAM,EAC7B,aAAgB,EAAU,SAAS,CACrC,CACF,CAEA,SAAgB,EAAkB,EAAkD,CAClF,MAAO,CACL,OAAQ,EAAO,EAAO,IAAe,KAAK,EAAS,YAAY,EAAO,EAAO,CAAU,EACvF,MAAO,EAAO,EAAO,IAAe,KAAK,EAAS,cAAc,EAAO,EAAO,CAAU,EACxF,OAAQ,EAAO,IAAe,KAAK,EAAS,YAAY,EAAO,CAAU,CAC3E,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e={pending:new Set([`in_progress`,`completed`,`failed`,`deleted`]),in_progress:new Set([`pending`,`completed`,`failed`,`deleted`]),failed:new Set([`pending`,`in_progress`,`completed`,`deleted`]),completed:new Set([`deleted`]),deleted:new Set};function t(t,n){return t===n||e[t].has(n)}exports.VALID_TRANSITIONS=e,exports.isTransitionValid=t;
|
|
2
|
+
//# sourceMappingURL=invariants.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"invariants.cjs","names":[],"sources":["../../src/store/invariants.ts"],"sourcesContent":["import type { TaskStatus } from './types.ts';\n\n/**\n * Allowed forward transitions per source status.\n *\n * `failed` is recoverable (a delegation can be retried) so it may return to\n * pending or in_progress. `completed` is one-way to `deleted`; `deleted` is a\n * terminal tombstone.\n */\nexport const VALID_TRANSITIONS: Record<TaskStatus, ReadonlySet<TaskStatus>> = {\n pending: new Set<TaskStatus>(['in_progress', 'completed', 'failed', 'deleted']),\n in_progress: new Set<TaskStatus>(['pending', 'completed', 'failed', 'deleted']),\n failed: new Set<TaskStatus>(['pending', 'in_progress', 'completed', 'deleted']),\n completed: new Set<TaskStatus>(['deleted']),\n deleted: new Set<TaskStatus>(),\n};\n\nexport function isTransitionValid(from: TaskStatus, to: TaskStatus): boolean {\n if (from === to) return true;\n return VALID_TRANSITIONS[from].has(to);\n}\n"],"mappings":"mEASA,MAAa,EAAiE,CAC5E,QAAS,IAAI,IAAgB,CAAC,cAAe,YAAa,SAAU,SAAS,CAAC,EAC9E,YAAa,IAAI,IAAgB,CAAC,UAAW,YAAa,SAAU,SAAS,CAAC,EAC9E,OAAQ,IAAI,IAAgB,CAAC,UAAW,cAAe,YAAa,SAAS,CAAC,EAC9E,UAAW,IAAI,IAAgB,CAAC,SAAS,CAAC,EAC1C,QAAS,IAAI,GACf,EAEA,SAAgB,EAAkB,EAAkB,EAAyB,CAE3E,OADI,IAAS,GACN,EAAkB,EAAK,CAAC,IAAI,CAAE,CACvC"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { TaskStatus } from "./types.cjs";
|
|
2
|
+
//#region src/store/invariants.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Allowed forward transitions per source status.
|
|
5
|
+
*
|
|
6
|
+
* `failed` is recoverable (a delegation can be retried) so it may return to
|
|
7
|
+
* pending or in_progress. `completed` is one-way to `deleted`; `deleted` is a
|
|
8
|
+
* terminal tombstone.
|
|
9
|
+
*/
|
|
10
|
+
declare const VALID_TRANSITIONS: Record<TaskStatus, ReadonlySet<TaskStatus>>;
|
|
11
|
+
declare function isTransitionValid(from: TaskStatus, to: TaskStatus): boolean;
|
|
12
|
+
//#endregion
|
|
13
|
+
export { VALID_TRANSITIONS, isTransitionValid };
|
|
14
|
+
//# sourceMappingURL=invariants.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"invariants.d.cts","names":[],"sources":["../../src/store/invariants.ts"],"mappings":";;;;;;;;;cASa,mBAAmB,OAAO,YAAY,YAAY;iBAQ/C,kBAAkB,MAAM,YAAY,IAAI"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { TaskStatus } from "./types.mjs";
|
|
2
|
+
//#region src/store/invariants.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Allowed forward transitions per source status.
|
|
5
|
+
*
|
|
6
|
+
* `failed` is recoverable (a delegation can be retried) so it may return to
|
|
7
|
+
* pending or in_progress. `completed` is one-way to `deleted`; `deleted` is a
|
|
8
|
+
* terminal tombstone.
|
|
9
|
+
*/
|
|
10
|
+
declare const VALID_TRANSITIONS: Record<TaskStatus, ReadonlySet<TaskStatus>>;
|
|
11
|
+
declare function isTransitionValid(from: TaskStatus, to: TaskStatus): boolean;
|
|
12
|
+
//#endregion
|
|
13
|
+
export { VALID_TRANSITIONS, isTransitionValid };
|
|
14
|
+
//# sourceMappingURL=invariants.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"invariants.d.mts","names":[],"sources":["../../src/store/invariants.ts"],"mappings":";;;;;;;;;cASa,mBAAmB,OAAO,YAAY,YAAY;iBAQ/C,kBAAkB,MAAM,YAAY,IAAI"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e={pending:new Set([`in_progress`,`completed`,`failed`,`deleted`]),in_progress:new Set([`pending`,`completed`,`failed`,`deleted`]),failed:new Set([`pending`,`in_progress`,`completed`,`deleted`]),completed:new Set([`deleted`]),deleted:new Set};function t(t,n){return t===n||e[t].has(n)}export{e as VALID_TRANSITIONS,t as isTransitionValid};
|
|
2
|
+
//# sourceMappingURL=invariants.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"invariants.mjs","names":[],"sources":["../../src/store/invariants.ts"],"sourcesContent":["import type { TaskStatus } from './types.ts';\n\n/**\n * Allowed forward transitions per source status.\n *\n * `failed` is recoverable (a delegation can be retried) so it may return to\n * pending or in_progress. `completed` is one-way to `deleted`; `deleted` is a\n * terminal tombstone.\n */\nexport const VALID_TRANSITIONS: Record<TaskStatus, ReadonlySet<TaskStatus>> = {\n pending: new Set<TaskStatus>(['in_progress', 'completed', 'failed', 'deleted']),\n in_progress: new Set<TaskStatus>(['pending', 'completed', 'failed', 'deleted']),\n failed: new Set<TaskStatus>(['pending', 'in_progress', 'completed', 'deleted']),\n completed: new Set<TaskStatus>(['deleted']),\n deleted: new Set<TaskStatus>(),\n};\n\nexport function isTransitionValid(from: TaskStatus, to: TaskStatus): boolean {\n if (from === to) return true;\n return VALID_TRANSITIONS[from].has(to);\n}\n"],"mappings":"AASA,MAAa,EAAiE,CAC5E,QAAS,IAAI,IAAgB,CAAC,cAAe,YAAa,SAAU,SAAS,CAAC,EAC9E,YAAa,IAAI,IAAgB,CAAC,UAAW,YAAa,SAAU,SAAS,CAAC,EAC9E,OAAQ,IAAI,IAAgB,CAAC,UAAW,cAAe,YAAa,SAAS,CAAC,EAC9E,UAAW,IAAI,IAAgB,CAAC,SAAS,CAAC,EAC1C,QAAS,IAAI,GACf,EAEA,SAAgB,EAAkB,EAAkB,EAAyB,CAE3E,OADI,IAAS,GACN,EAAkB,EAAK,CAAC,IAAI,CAAE,CACvC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../_virtual/_rolldown/runtime.cjs");let t=require("node:path");t=e.__toESM(t,1);let n=require("node:os");n=e.__toESM(n,1);let r=require("node:child_process"),i=require("node:fs");i=e.__toESM(i,1);let a=require("@agimon-ai/doompi-extension-contracts/child-process");const o=`DOOM_TASK_STORE`,s=`doom-task`,c=`tasks.json`,l=`utf8`;function u(e,t){try{let n=(0,r.execFileSync)(`git`,e,{cwd:t,encoding:l,stdio:[`ignore`,`pipe`,`ignore`]}).trim();return n.length>0?n:void 0}catch{return}}function d(e){let r=e.PI_CODING_AGENT_DIR?.trim();return r===`~`?n.default.homedir():r?.startsWith(`~/`)?t.default.join(n.default.homedir(),r.slice(2)):r?t.default.resolve(r):t.default.join(n.default.homedir(),`.pi`,`agent`)}function f(e,n){let r=t.default.relative(t.default.resolve(e),t.default.resolve(n));return r===``||!r.startsWith(`..`)&&!t.default.isAbsolute(r)}function p(e,t=process.env){if(!t[a.SUBAGENT_CHILD_ENV])return e;let n=t[a.SUBAGENT_PARENT_SESSION_ENV]?.trim();if(!n)throw Error(`${a.SUBAGENT_PARENT_SESSION_ENV} is required in a subagent child`);return n}function m(e=process.cwd(),n=process.env,r=`standalone`){let i=n[o]?.trim();if(i)return t.default.resolve(i);let a=r.trim();if(!a)throw Error(`doom-task session id cannot be blank`);return t.default.join(d(n),s,a,c)}function h(e=process.env){return!!e[o]?.trim()}function g(e=process.cwd()){let n=u([`rev-parse`,`--path-format=absolute`,`--git-common-dir`],e);return n?t.default.join(n,s):void 0}function _(e,n=process.cwd()){let r={removed:[],errors:[]},a=g(n);if(!a||t.default.basename(a)!==s||f(a,e))return r;try{if(!i.default.existsSync(a))return r;i.default.rmSync(a,{recursive:!0,force:!0}),r.removed.push(a)}catch(e){r.errors.push(`Could not remove legacy task store ${a}: ${String(e)}`)}return r}function v(e,n,r=Date.now()){let a={removed:[],errors:[]},o=t.default.dirname(e),s=t.default.dirname(o),u;try{u=i.default.readdirSync(s)}catch(e){return e.code===`ENOENT`||a.errors.push(`Could not read task store directory ${s}: ${String(e)}`),a}for(let e of u){let u=t.default.join(s,e),d=t.default.join(u,c);if(!(u===o||!i.default.existsSync(d)))try{if(i.default.existsSync(y(d))||(JSON.parse(i.default.readFileSync(d,l)),r-i.default.statSync(d).mtimeMs<=n))continue;i.default.rmSync(u,{recursive:!0,force:!0}),a.removed.push(u)}catch(e){a.errors.push(`Could not sweep task store ${d}: ${String(e)}`)}}return a}function y(e){return`${e}.lock`}function b(e,t=process.pid){return`${e}.tmp.${t}`}exports.STORE_PATH_ENV=o,exports.hasStorePathOverride=h,exports.lockPathFor=y,exports.removeLegacyStoreDirectory=_,exports.resolveLegacyStoreDirectory=g,exports.resolveSessionKey=p,exports.resolveStorePath=m,exports.sweepStoreFiles=v,exports.tempPathFor=b;
|
|
2
|
+
//# sourceMappingURL=paths.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paths.cjs","names":["execFileSync","os","path","SUBAGENT_CHILD_ENV","SUBAGENT_PARENT_SESSION_ENV","fs"],"sources":["../../src/store/paths.ts"],"sourcesContent":["import { execFileSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from '@agimon-ai/doompi-extension-contracts/child-process';\n\nexport const STORE_PATH_ENV = 'DOOM_TASK_STORE';\n\nconst STORE_DIR_NAME = 'doom-task';\nconst STORE_FILE_NAME = 'tasks.json';\nconst DEFAULT_CONFIG_DIR_NAME = '.pi';\nconst AGENT_DIR_NAME = 'agent';\nconst PI_CODING_AGENT_DIR_ENV = 'PI_CODING_AGENT_DIR';\nconst HOME_ALIAS = '~';\nconst HOME_ALIAS_PREFIX = '~/';\nconst FILE_ENCODING = 'utf8';\nconst NOT_FOUND_ERROR_CODE = 'ENOENT';\n\nfunction git(args: string[], cwd: string): string | undefined {\n try {\n const output = execFileSync('git', args, {\n cwd,\n encoding: FILE_ENCODING,\n stdio: ['ignore', 'pipe', 'ignore'],\n });\n const trimmed = output.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction resolveAgentDirectory(env: NodeJS.ProcessEnv): string {\n const configured = env[PI_CODING_AGENT_DIR_ENV]?.trim();\n if (configured === HOME_ALIAS) return os.homedir();\n if (configured?.startsWith(HOME_ALIAS_PREFIX)) {\n return path.join(os.homedir(), configured.slice(HOME_ALIAS_PREFIX.length));\n }\n return configured ? path.resolve(configured) : path.join(os.homedir(), DEFAULT_CONFIG_DIR_NAME, AGENT_DIR_NAME);\n}\n\nfunction isWithin(root: string, candidate: string): boolean {\n const relative = path.relative(path.resolve(root), path.resolve(candidate));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\n/** Resolve the tree root without relying on extension startup order. */\nexport function resolveSessionKey(rootSessionId: string, env: NodeJS.ProcessEnv = process.env): string {\n if (!env[SUBAGENT_CHILD_ENV]) return rootSessionId;\n const parentSessionId = env[SUBAGENT_PARENT_SESSION_ENV]?.trim();\n if (!parentSessionId) throw new Error(`${SUBAGENT_PARENT_SESSION_ENV} is required in a subagent child`);\n return parentSessionId;\n}\n\n/** Resolve one root session tree to a task document under the Pi agent directory. */\nexport function resolveStorePath(\n _cwd: string = process.cwd(),\n env: NodeJS.ProcessEnv = process.env,\n sessionKey: string = 'standalone',\n): string {\n const override = env[STORE_PATH_ENV]?.trim();\n if (override) return path.resolve(override);\n\n const trimmedSessionKey = sessionKey.trim();\n if (!trimmedSessionKey) throw new Error('doom-task session id cannot be blank');\n return path.join(resolveAgentDirectory(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);\n}\n\n/** Whether a deliberate unscoped task-store override is active. */\nexport function hasStorePathOverride(env: NodeJS.ProcessEnv = process.env): boolean {\n return Boolean(env[STORE_PATH_ENV]?.trim());\n}\n\n/** Exact legacy Git-directory store, if the current working tree has one. */\nexport function resolveLegacyStoreDirectory(cwd: string = process.cwd()): string | undefined {\n const commonDirectory = git(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport interface StoreSweepResult {\n removed: string[];\n errors: string[];\n}\n\n/** Remove only the validated legacy Git store unless it contains the active override. */\nexport function removeLegacyStoreDirectory(currentStorePath: string, cwd: string = process.cwd()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = resolveLegacyStoreDirectory(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n if (!fs.existsSync(target)) return result;\n fs.rmSync(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n return result;\n}\n\n/** Delete expired sibling session stores while preserving active or unreadable stores. */\nexport function sweepStoreFiles(currentStorePath: string, ttlMs: number, now: number = Date.now()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = fs.readdirSync(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory || !fs.existsSync(candidate)) continue;\n try {\n if (fs.existsSync(lockPathFor(candidate))) continue;\n JSON.parse(fs.readFileSync(candidate, FILE_ENCODING));\n if (now - fs.statSync(candidate).mtimeMs <= ttlMs) continue;\n fs.rmSync(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport function lockPathFor(storePath: string): string {\n return `${storePath}.lock`;\n}\n\nexport function tempPathFor(storePath: string, pid: number = process.pid): string {\n return `${storePath}.tmp.${pid}`;\n}\n"],"mappings":"6VAMA,MAAa,EAAiB,kBAExB,EAAiB,YACjB,EAAkB,aAMlB,EAAgB,OAGtB,SAAS,EAAI,EAAgB,EAAiC,CAC5D,GAAI,CAMF,IAAM,GAAA,EALSA,EAAAA,aAAAA,CAAa,MAAO,EAAM,CACvC,MACA,SAAU,EACV,MAAO,CAAC,SAAU,OAAQ,QAAQ,CACpC,CACqB,CAAC,CAAC,KAAK,EAC5B,OAAO,EAAQ,OAAS,EAAI,E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Ae,EACzD,SAAqB,GAA2B,CAACG,EAAAA,QAAG,WAAW,CAAS,GAC5E,GAAI,CAGF,GAFIA,EAAAA,QAAG,WAAW,EAAY,CAAS,CAAC,IACxC,KAAK,MAAMA,EAAAA,QAAG,aAAa,EAAW,CAAa,CAAC,EAChD,EAAMA,EAAAA,QAAG,SAAS,CAAS,CAAC,CAAC,SAAW,GAAO,SACnD,EAAA,QAAG,OAAO,EAAkB,CAAE,UAAW,GAAM,MAAO,EAAK,CAAC,EAC5D,EAAO,QAAQ,KAAK,CAAgB,CACtC,OAAS,EAAO,CACd,EAAO,OAAO,KAAK,8BAA8B,EAAU,IAAI,OAAO,CAAK,GAAG,CAChF,CACF,CACA,OAAO,CACT,CAEA,SAAgB,EAAY,EAA2B,CACrD,MAAO,GAAG,EAAU,MACtB,CAEA,SAAgB,EAAY,EAAmB,EAAc,QAAQ,IAAa,CAChF,MAAO,GAAG,EAAU,OAAO,GAC7B"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
//#region src/store/paths.d.ts
|
|
2
|
+
declare const STORE_PATH_ENV = "DOOM_TASK_STORE";
|
|
3
|
+
/** Resolve the tree root without relying on extension startup order. */
|
|
4
|
+
declare function resolveSessionKey(rootSessionId: string, env?: NodeJS.ProcessEnv): string;
|
|
5
|
+
/** Resolve one root session tree to a task document under the Pi agent directory. */
|
|
6
|
+
declare function resolveStorePath(_cwd?: string, env?: NodeJS.ProcessEnv, sessionKey?: string): string;
|
|
7
|
+
/** Whether a deliberate unscoped task-store override is active. */
|
|
8
|
+
declare function hasStorePathOverride(env?: NodeJS.ProcessEnv): boolean;
|
|
9
|
+
/** Exact legacy Git-directory store, if the current working tree has one. */
|
|
10
|
+
declare function resolveLegacyStoreDirectory(cwd?: string): string | undefined;
|
|
11
|
+
interface StoreSweepResult {
|
|
12
|
+
removed: string[];
|
|
13
|
+
errors: string[];
|
|
14
|
+
}
|
|
15
|
+
/** Remove only the validated legacy Git store unless it contains the active override. */
|
|
16
|
+
declare function removeLegacyStoreDirectory(currentStorePath: string, cwd?: string): StoreSweepResult;
|
|
17
|
+
/** Delete expired sibling session stores while preserving active or unreadable stores. */
|
|
18
|
+
declare function sweepStoreFiles(currentStorePath: string, ttlMs: number, now?: number): StoreSweepResult;
|
|
19
|
+
declare function lockPathFor(storePath: string): string;
|
|
20
|
+
declare function tempPathFor(storePath: string, pid?: number): string;
|
|
21
|
+
//#endregion
|
|
22
|
+
export { STORE_PATH_ENV, StoreSweepResult, hasStorePathOverride, lockPathFor, removeLegacyStoreDirectory, resolveLegacyStoreDirectory, resolveSessionKey, resolveStorePath, sweepStoreFiles, tempPathFor };
|
|
23
|
+
//# sourceMappingURL=paths.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paths.d.cts","names":[],"sources":["../../src/store/paths.ts"],"mappings":";cAMa;;iBAyCG,kBAAkB,uBAAuB,MAAK,OAAO;;iBAQrD,iBACd,eACA,MAAK,OAAO,YACZ;;iBAWc,qBAAqB,MAAK,OAAO;;iBAKjC,4BAA4B;UAK3B;EACf;EACA;;;iBAIc,2BAA2B,0BAA0B,eAA8B;;iBAgBnF,gBAAgB,0BAA0B,eAAe,eAA2B;iBA8BpF,YAAY;iBAIZ,YAAY,mBAAmB"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
//#region src/store/paths.d.ts
|
|
2
|
+
declare const STORE_PATH_ENV = "DOOM_TASK_STORE";
|
|
3
|
+
/** Resolve the tree root without relying on extension startup order. */
|
|
4
|
+
declare function resolveSessionKey(rootSessionId: string, env?: NodeJS.ProcessEnv): string;
|
|
5
|
+
/** Resolve one root session tree to a task document under the Pi agent directory. */
|
|
6
|
+
declare function resolveStorePath(_cwd?: string, env?: NodeJS.ProcessEnv, sessionKey?: string): string;
|
|
7
|
+
/** Whether a deliberate unscoped task-store override is active. */
|
|
8
|
+
declare function hasStorePathOverride(env?: NodeJS.ProcessEnv): boolean;
|
|
9
|
+
/** Exact legacy Git-directory store, if the current working tree has one. */
|
|
10
|
+
declare function resolveLegacyStoreDirectory(cwd?: string): string | undefined;
|
|
11
|
+
interface StoreSweepResult {
|
|
12
|
+
removed: string[];
|
|
13
|
+
errors: string[];
|
|
14
|
+
}
|
|
15
|
+
/** Remove only the validated legacy Git store unless it contains the active override. */
|
|
16
|
+
declare function removeLegacyStoreDirectory(currentStorePath: string, cwd?: string): StoreSweepResult;
|
|
17
|
+
/** Delete expired sibling session stores while preserving active or unreadable stores. */
|
|
18
|
+
declare function sweepStoreFiles(currentStorePath: string, ttlMs: number, now?: number): StoreSweepResult;
|
|
19
|
+
declare function lockPathFor(storePath: string): string;
|
|
20
|
+
declare function tempPathFor(storePath: string, pid?: number): string;
|
|
21
|
+
//#endregion
|
|
22
|
+
export { STORE_PATH_ENV, StoreSweepResult, hasStorePathOverride, lockPathFor, removeLegacyStoreDirectory, resolveLegacyStoreDirectory, resolveSessionKey, resolveStorePath, sweepStoreFiles, tempPathFor };
|
|
23
|
+
//# sourceMappingURL=paths.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paths.d.mts","names":[],"sources":["../../src/store/paths.ts"],"mappings":";cAMa;;iBAyCG,kBAAkB,uBAAuB,MAAK,OAAO;;iBAQrD,iBACd,eACA,MAAK,OAAO,YACZ;;iBAWc,qBAAqB,MAAK,OAAO;;iBAKjC,4BAA4B;UAK3B;EACf;EACA;;;iBAIc,2BAA2B,0BAA0B,eAA8B;;iBAgBnF,gBAAgB,0BAA0B,eAAe,eAA2B;iBA8BpF,YAAY;iBAIZ,YAAY,mBAAmB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import e from"node:path";import t from"node:os";import{execFileSync as n}from"node:child_process";import r from"node:fs";import{SUBAGENT_CHILD_ENV as i,SUBAGENT_PARENT_SESSION_ENV as a}from"@agimon-ai/doompi-extension-contracts/child-process";const o=`DOOM_TASK_STORE`,s=`doom-task`,c=`tasks.json`,l=`utf8`;function u(e,t){try{let r=n(`git`,e,{cwd:t,encoding:l,stdio:[`ignore`,`pipe`,`ignore`]}).trim();return r.length>0?r:void 0}catch{return}}function d(n){let r=n.PI_CODING_AGENT_DIR?.trim();return r===`~`?t.homedir():r?.startsWith(`~/`)?e.join(t.homedir(),r.slice(2)):r?e.resolve(r):e.join(t.homedir(),`.pi`,`agent`)}function f(t,n){let r=e.relative(e.resolve(t),e.resolve(n));return r===``||!r.startsWith(`..`)&&!e.isAbsolute(r)}function p(e,t=process.env){if(!t[i])return e;let n=t[a]?.trim();if(!n)throw Error(`${a} is required in a subagent child`);return n}function m(t=process.cwd(),n=process.env,r=`standalone`){let i=n[o]?.trim();if(i)return e.resolve(i);let a=r.trim();if(!a)throw Error(`doom-task session id cannot be blank`);return e.join(d(n),s,a,c)}function h(e=process.env){return!!e[o]?.trim()}function g(t=process.cwd()){let n=u([`rev-parse`,`--path-format=absolute`,`--git-common-dir`],t);return n?e.join(n,s):void 0}function _(t,n=process.cwd()){let i={removed:[],errors:[]},a=g(n);if(!a||e.basename(a)!==s||f(a,t))return i;try{if(!r.existsSync(a))return i;r.rmSync(a,{recursive:!0,force:!0}),i.removed.push(a)}catch(e){i.errors.push(`Could not remove legacy task store ${a}: ${String(e)}`)}return i}function v(t,n,i=Date.now()){let a={removed:[],errors:[]},o=e.dirname(t),s=e.dirname(o),u;try{u=r.readdirSync(s)}catch(e){return e.code===`ENOENT`||a.errors.push(`Could not read task store directory ${s}: ${String(e)}`),a}for(let t of u){let u=e.join(s,t),d=e.join(u,c);if(!(u===o||!r.existsSync(d)))try{if(r.existsSync(y(d))||(JSON.parse(r.readFileSync(d,l)),i-r.statSync(d).mtimeMs<=n))continue;r.rmSync(u,{recursive:!0,force:!0}),a.removed.push(u)}catch(e){a.errors.push(`Could not sweep task store ${d}: ${String(e)}`)}}return a}function y(e){return`${e}.lock`}function b(e,t=process.pid){return`${e}.tmp.${t}`}export{o as STORE_PATH_ENV,h as hasStorePathOverride,y as lockPathFor,_ as removeLegacyStoreDirectory,g as resolveLegacyStoreDirectory,p as resolveSessionKey,m as resolveStorePath,v as sweepStoreFiles,b as tempPathFor};
|
|
2
|
+
//# sourceMappingURL=paths.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paths.mjs","names":[],"sources":["../../src/store/paths.ts"],"sourcesContent":["import { execFileSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from '@agimon-ai/doompi-extension-contracts/child-process';\n\nexport const STORE_PATH_ENV = 'DOOM_TASK_STORE';\n\nconst STORE_DIR_NAME = 'doom-task';\nconst STORE_FILE_NAME = 'tasks.json';\nconst DEFAULT_CONFIG_DIR_NAME = '.pi';\nconst AGENT_DIR_NAME = 'agent';\nconst PI_CODING_AGENT_DIR_ENV = 'PI_CODING_AGENT_DIR';\nconst HOME_ALIAS = '~';\nconst HOME_ALIAS_PREFIX = '~/';\nconst FILE_ENCODING = 'utf8';\nconst NOT_FOUND_ERROR_CODE = 'ENOENT';\n\nfunction git(args: string[], cwd: string): string | undefined {\n try {\n const output = execFileSync('git', args, {\n cwd,\n encoding: FILE_ENCODING,\n stdio: ['ignore', 'pipe', 'ignore'],\n });\n const trimmed = output.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction resolveAgentDirectory(env: NodeJS.ProcessEnv): string {\n const configured = env[PI_CODING_AGENT_DIR_ENV]?.trim();\n if (configured === HOME_ALIAS) return os.homedir();\n if (configured?.startsWith(HOME_ALIAS_PREFIX)) {\n return path.join(os.homedir(), configured.slice(HOME_ALIAS_PREFIX.length));\n }\n return configured ? path.resolve(configured) : path.join(os.homedir(), DEFAULT_CONFIG_DIR_NAME, AGENT_DIR_NAME);\n}\n\nfunction isWithin(root: string, candidate: string): boolean {\n const relative = path.relative(path.resolve(root), path.resolve(candidate));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\n/** Resolve the tree root without relying on extension startup order. */\nexport function resolveSessionKey(rootSessionId: string, env: NodeJS.ProcessEnv = process.env): string {\n if (!env[SUBAGENT_CHILD_ENV]) return rootSessionId;\n const parentSessionId = env[SUBAGENT_PARENT_SESSION_ENV]?.trim();\n if (!parentSessionId) throw new Error(`${SUBAGENT_PARENT_SESSION_ENV} is required in a subagent child`);\n return parentSessionId;\n}\n\n/** Resolve one root session tree to a task document under the Pi agent directory. */\nexport function resolveStorePath(\n _cwd: string = process.cwd(),\n env: NodeJS.ProcessEnv = process.env,\n sessionKey: string = 'standalone',\n): string {\n const override = env[STORE_PATH_ENV]?.trim();\n if (override) return path.resolve(override);\n\n const trimmedSessionKey = sessionKey.trim();\n if (!trimmedSessionKey) throw new Error('doom-task session id cannot be blank');\n return path.join(resolveAgentDirectory(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);\n}\n\n/** Whether a deliberate unscoped task-store override is active. */\nexport function hasStorePathOverride(env: NodeJS.ProcessEnv = process.env): boolean {\n return Boolean(env[STORE_PATH_ENV]?.trim());\n}\n\n/** Exact legacy Git-directory store, if the current working tree has one. */\nexport function resolveLegacyStoreDirectory(cwd: string = process.cwd()): string | undefined {\n const commonDirectory = git(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport interface StoreSweepResult {\n removed: string[];\n errors: string[];\n}\n\n/** Remove only the validated legacy Git store unless it contains the active override. */\nexport function removeLegacyStoreDirectory(currentStorePath: string, cwd: string = process.cwd()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = resolveLegacyStoreDirectory(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n if (!fs.existsSync(target)) return result;\n fs.rmSync(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n return result;\n}\n\n/** Delete expired sibling session stores while preserving active or unreadable stores. */\nexport function sweepStoreFiles(currentStorePath: string, ttlMs: number, now: number = Date.now()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = fs.readdirSync(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory || !fs.existsSync(candidate)) continue;\n try {\n if (fs.existsSync(lockPathFor(candidate))) continue;\n JSON.parse(fs.readFileSync(candidate, FILE_ENCODING));\n if (now - fs.statSync(candidate).mtimeMs <= ttlMs) continue;\n fs.rmSync(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport function lockPathFor(storePath: string): string {\n return `${storePath}.lock`;\n}\n\nexport function tempPathFor(storePath: string, pid: number = process.pid): string {\n return `${storePath}.tmp.${pid}`;\n}\n"],"mappings":"mPAMA,MAAa,EAAiB,kBAExB,EAAiB,YACjB,EAAkB,aAMlB,EAAgB,OAGtB,SAAS,EAAI,EAAgB,EAAiC,CAC5D,GAAI,CAMF,IAAM,EALS,EAAa,MAAO,EAAM,CACvC,MACA,SAAU,EACV,MAAO,CAAC,SAAU,OAAQ,QAAQ,CACpC,CACqB,CAAC,CAAC,KAAK,EAC5B,OAAO,EAAQ,OAAS,EAAI,EAAU,IAAA,EACxC,MAAQ,CACN,MACF,CACF,CAEA,SAAS,EAAsB,EAAgC,CAC7D,IAAM,EAAa,EAAI,qBAA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AAgB,CACtC,OAAS,EAAO,CACd,EAAO,OAAO,KAAK,8BAA8B,EAAU,IAAI,OAAO,CAAK,GAAG,CAChF,CACF,CACA,OAAO,CACT,CAEA,SAAgB,EAAY,EAA2B,CACrD,MAAO,GAAG,EAAU,MACtB,CAEA,SAAgB,EAAY,EAAmB,EAAc,QAAQ,IAAa,CAChF,MAAO,GAAG,EAAU,OAAO,GAC7B"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"processLiveness.cjs","names":[],"sources":["../../src/store/processLiveness.ts"],"sourcesContent":["/**\n * Is a process still running?\n *\n * Signal 0 performs the permission and existence check without delivering a\n * signal. EPERM means the process exists but belongs to another user, which\n * still counts as alive.\n */\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n"],"mappings":"mEAOA,SAAgB,EAAe,EAAsB,CACnD,GAAI,CAEF,OADA,QAAQ,KAAK,EAAK,CAAC,EACZ,EACT,OAAS,EAAO,CACd,OAAQ,EAAgC,OAAS,OACnD,CACF"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
//#region src/store/processLiveness.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Is a process still running?
|
|
4
|
+
*
|
|
5
|
+
* Signal 0 performs the permission and existence check without delivering a
|
|
6
|
+
* signal. EPERM means the process exists but belongs to another user, which
|
|
7
|
+
* still counts as alive.
|
|
8
|
+
*/
|
|
9
|
+
declare function isProcessAlive(pid: number): boolean;
|
|
10
|
+
//#endregion
|
|
11
|
+
export { isProcessAlive };
|
|
12
|
+
//# sourceMappingURL=processLiveness.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"processLiveness.d.cts","names":[],"sources":["../../src/store/processLiveness.ts"],"mappings":";;;;;;;;iBAOgB,eAAe"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
//#region src/store/processLiveness.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Is a process still running?
|
|
4
|
+
*
|
|
5
|
+
* Signal 0 performs the permission and existence check without delivering a
|
|
6
|
+
* signal. EPERM means the process exists but belongs to another user, which
|
|
7
|
+
* still counts as alive.
|
|
8
|
+
*/
|
|
9
|
+
declare function isProcessAlive(pid: number): boolean;
|
|
10
|
+
//#endregion
|
|
11
|
+
export { isProcessAlive };
|
|
12
|
+
//# sourceMappingURL=processLiveness.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"processLiveness.d.mts","names":[],"sources":["../../src/store/processLiveness.ts"],"mappings":";;;;;;;;iBAOgB,eAAe"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"processLiveness.mjs","names":[],"sources":["../../src/store/processLiveness.ts"],"sourcesContent":["/**\n * Is a process still running?\n *\n * Signal 0 performs the permission and existence check without delivering a\n * signal. EPERM means the process exists but belongs to another user, which\n * still counts as alive.\n */\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n"],"mappings":"AAOA,SAAgB,EAAe,EAAsB,CACnD,GAAI,CAEF,OADA,QAAQ,KAAK,EAAK,CAAC,EACZ,EACT,OAAS,EAAO,CACd,OAAQ,EAAgC,OAAS,OACnD,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./processLiveness.cjs"),t=require("./types.cjs"),n=`Delegation orphaned by harness restart`,r=`Delegation orphaned by session restart`;function i(i,a=new Date().toISOString(),o=e.isProcessAlive,s){let c=[],l=i.tasks.map(e=>{if(!t.isDelegationActive(e))return e;let i=e.delegation?.pid;if(i===void 0)return e;let l=s!==void 0&&i===s.pid&&!s.liveRequestIds.has(e.delegation.requestId);if(!l&&o(i))return e;let u={...e,status:`pending`,updatedAt:a,delegation:{...e.delegation,state:`failed`,endedAt:a,result:{status:`failed`,error:l?r:n}}};return c.push(u),u});return c.length===0?{document:i,orphaned:c}:{document:{...i,tasks:l},orphaned:c}}exports.ERR_ORPHANED_BY_RESTART=n,exports.ERR_ORPHANED_BY_SESSION=r,exports.reconcileOrphanedDelegations=i;
|
|
2
|
+
//# sourceMappingURL=reconcile.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reconcile.cjs","names":["isProcessAlive","isDelegationActive"],"sources":["../../src/store/reconcile.ts"],"sourcesContent":["import { isProcessAlive } from './processLiveness.ts';\nimport { isDelegationActive, type Task, type TaskDocument } from './types.ts';\n\nexport const ERR_ORPHANED_BY_RESTART = 'Delegation orphaned by harness restart';\nexport const ERR_ORPHANED_BY_SESSION = 'Delegation orphaned by session restart';\n\nexport interface ReconcileResult {\n document: TaskDocument;\n orphaned: Task[];\n}\n\n/** The delegations this process can still settle, used to spot its own leftovers. */\nexport interface ReconcileSelf {\n pid: number;\n liveRequestIds: ReadonlySet<string>;\n}\n\n/**\n * Recover tasks that no longer have anyone able to finish them.\n *\n * A subagent run dies with the harness that spawned it, but the store file\n * outlives both, so a crash leaves tasks stuck in `in_progress` forever. Two\n * kinds of delegation qualify as dead:\n *\n * - the owning pid is gone, so nothing is left to report a result;\n * - the owning pid is *this* process, yet the request is absent from the live\n * set. Settling requires an in-memory record, so an in-process session\n * restart (which clears that map without writing to the store) leaves rows\n * nothing can ever resolve. Checking pid liveness alone misses these, because\n * the pid is our own and very much alive.\n *\n * Delegations owned by a different, still-running pid belong to a parallel\n * session and are left untouched.\n */\nexport function reconcileOrphanedDelegations(\n document: TaskDocument,\n now: string = new Date().toISOString(),\n isAlive: (pid: number) => boolean = isProcessAlive,\n self?: ReconcileSelf,\n): ReconcileResult {\n const orphaned: Task[] = [];\n\n const tasks = document.tasks.map((task) => {\n if (!isDelegationActive(task)) return task;\n const pid = task.delegation?.pid;\n if (pid === undefined) return task;\n\n const ownedByThisSession = self !== undefined && pid === self.pid;\n const abandonedHere = ownedByThisSession && !self.liveRequestIds.has(task.delegation!.requestId);\n if (!abandonedHere && isAlive(pid)) return task;\n\n const recovered: Task = {\n ...task,\n status: 'pending',\n updatedAt: now,\n delegation: {\n ...task.delegation!,\n state: 'failed',\n endedAt: now,\n result: {\n status: 'failed',\n error: abandonedHere ? ERR_ORPHANED_BY_SESSION : ERR_ORPHANED_BY_RESTART,\n },\n },\n };\n orphaned.push(recovered);\n return recovered;\n });\n\n if (orphaned.length === 0) return { document, orphaned };\n return { document: { ...document, tasks }, orphaned };\n}\n"],"mappings":"qIAGa,EAA0B,yCAC1B,EAA0B,yCA8BvC,SAAgB,EACd,EACA,EAAc,IAAI,KAAK,CAAA,CAAE,YAAY,EACrC,EAAoCA,EAAAA,eACpC,EACiB,CACjB,IAAM,EAAmB,CAAC,EAEpB,EAAQ,EAAS,MAAM,IAAK,GAAS,CACzC,GAAI,CAACC,EAAAA,mBAAmB,CAAI,EAAG,OAAO,EACtC,IAAM,EAAM,EAAK,YAAY,IAC7B,GAAI,IAAQ,IAAA,GAAW,OAAO,EAG9B,IAAM,EADqB,IAAS,IAAA,IAAa,IAAQ,EAAK,KAClB,CAAC,EAAK,eAAe,IAAI,EAAK,WAAY,SAAS,EAC/F,GAAI,CAAC,GAAiB,EAAQ,CAAG,EAAG,OAAO,EAE3C,IAAM,EAAkB,CACtB,GAAG,EACH,OAAQ,UACR,UAAW,EACX,WAAY,CACV,GAAG,EAAK,WACR,MAAO,SACP,QAAS,EACT,OAAQ,CACN,OAAQ,SACR,MAAO,EAAgB,EAA0B,CACnD,CACF,CACF,EAEA,OADA,EAAS,KAAK,CAAS,EAChB,CACT,CAAC,EAGD,OADI,EAAS,SAAW,EAAU,CAAE,WAAU,UAAS,EAChD,CAAE,SAAU,CAAE,GAAG,EAAU,OAAM,EAAG,UAAS,CACtD"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { Task, TaskDocument } from "./types.cjs";
|
|
2
|
+
//#region src/store/reconcile.d.ts
|
|
3
|
+
declare const ERR_ORPHANED_BY_RESTART = "Delegation orphaned by harness restart";
|
|
4
|
+
declare const ERR_ORPHANED_BY_SESSION = "Delegation orphaned by session restart";
|
|
5
|
+
interface ReconcileResult {
|
|
6
|
+
document: TaskDocument;
|
|
7
|
+
orphaned: Task[];
|
|
8
|
+
}
|
|
9
|
+
/** The delegations this process can still settle, used to spot its own leftovers. */
|
|
10
|
+
interface ReconcileSelf {
|
|
11
|
+
pid: number;
|
|
12
|
+
liveRequestIds: ReadonlySet<string>;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Recover tasks that no longer have anyone able to finish them.
|
|
16
|
+
*
|
|
17
|
+
* A subagent run dies with the harness that spawned it, but the store file
|
|
18
|
+
* outlives both, so a crash leaves tasks stuck in `in_progress` forever. Two
|
|
19
|
+
* kinds of delegation qualify as dead:
|
|
20
|
+
*
|
|
21
|
+
* - the owning pid is gone, so nothing is left to report a result;
|
|
22
|
+
* - the owning pid is *this* process, yet the request is absent from the live
|
|
23
|
+
* set. Settling requires an in-memory record, so an in-process session
|
|
24
|
+
* restart (which clears that map without writing to the store) leaves rows
|
|
25
|
+
* nothing can ever resolve. Checking pid liveness alone misses these, because
|
|
26
|
+
* the pid is our own and very much alive.
|
|
27
|
+
*
|
|
28
|
+
* Delegations owned by a different, still-running pid belong to a parallel
|
|
29
|
+
* session and are left untouched.
|
|
30
|
+
*/
|
|
31
|
+
declare function reconcileOrphanedDelegations(document: TaskDocument, now?: string, isAlive?: (pid: number) => boolean, self?: ReconcileSelf): ReconcileResult;
|
|
32
|
+
//#endregion
|
|
33
|
+
export { ERR_ORPHANED_BY_RESTART, ERR_ORPHANED_BY_SESSION, ReconcileResult, ReconcileSelf, reconcileOrphanedDelegations };
|
|
34
|
+
//# sourceMappingURL=reconcile.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reconcile.d.cts","names":[],"sources":["../../src/store/reconcile.ts"],"mappings":";;cAGa;cACA;UAEI;EACf,UAAU;EACV,UAAU;;;UAIK;EACf;EACA,gBAAgB;;;;;;;;;;;;;;;;;;;iBAoBF,6BACd,UAAU,cACV,cACA,WAAU,yBACV,OAAO,gBACN"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { Task, TaskDocument } from "./types.mjs";
|
|
2
|
+
//#region src/store/reconcile.d.ts
|
|
3
|
+
declare const ERR_ORPHANED_BY_RESTART = "Delegation orphaned by harness restart";
|
|
4
|
+
declare const ERR_ORPHANED_BY_SESSION = "Delegation orphaned by session restart";
|
|
5
|
+
interface ReconcileResult {
|
|
6
|
+
document: TaskDocument;
|
|
7
|
+
orphaned: Task[];
|
|
8
|
+
}
|
|
9
|
+
/** The delegations this process can still settle, used to spot its own leftovers. */
|
|
10
|
+
interface ReconcileSelf {
|
|
11
|
+
pid: number;
|
|
12
|
+
liveRequestIds: ReadonlySet<string>;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Recover tasks that no longer have anyone able to finish them.
|
|
16
|
+
*
|
|
17
|
+
* A subagent run dies with the harness that spawned it, but the store file
|
|
18
|
+
* outlives both, so a crash leaves tasks stuck in `in_progress` forever. Two
|
|
19
|
+
* kinds of delegation qualify as dead:
|
|
20
|
+
*
|
|
21
|
+
* - the owning pid is gone, so nothing is left to report a result;
|
|
22
|
+
* - the owning pid is *this* process, yet the request is absent from the live
|
|
23
|
+
* set. Settling requires an in-memory record, so an in-process session
|
|
24
|
+
* restart (which clears that map without writing to the store) leaves rows
|
|
25
|
+
* nothing can ever resolve. Checking pid liveness alone misses these, because
|
|
26
|
+
* the pid is our own and very much alive.
|
|
27
|
+
*
|
|
28
|
+
* Delegations owned by a different, still-running pid belong to a parallel
|
|
29
|
+
* session and are left untouched.
|
|
30
|
+
*/
|
|
31
|
+
declare function reconcileOrphanedDelegations(document: TaskDocument, now?: string, isAlive?: (pid: number) => boolean, self?: ReconcileSelf): ReconcileResult;
|
|
32
|
+
//#endregion
|
|
33
|
+
export { ERR_ORPHANED_BY_RESTART, ERR_ORPHANED_BY_SESSION, ReconcileResult, ReconcileSelf, reconcileOrphanedDelegations };
|
|
34
|
+
//# sourceMappingURL=reconcile.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reconcile.d.mts","names":[],"sources":["../../src/store/reconcile.ts"],"mappings":";;cAGa;cACA;UAEI;EACf,UAAU;EACV,UAAU;;;UAIK;EACf;EACA,gBAAgB;;;;;;;;;;;;;;;;;;;iBAoBF,6BACd,UAAU,cACV,cACA,WAAU,yBACV,OAAO,gBACN"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{isProcessAlive as e}from"./processLiveness.mjs";import{isDelegationActive as t}from"./types.mjs";const n=`Delegation orphaned by harness restart`,r=`Delegation orphaned by session restart`;function i(i,a=new Date().toISOString(),o=e,s){let c=[],l=i.tasks.map(e=>{if(!t(e))return e;let i=e.delegation?.pid;if(i===void 0)return e;let l=s!==void 0&&i===s.pid&&!s.liveRequestIds.has(e.delegation.requestId);if(!l&&o(i))return e;let u={...e,status:`pending`,updatedAt:a,delegation:{...e.delegation,state:`failed`,endedAt:a,result:{status:`failed`,error:l?r:n}}};return c.push(u),u});return c.length===0?{document:i,orphaned:c}:{document:{...i,tasks:l},orphaned:c}}export{n as ERR_ORPHANED_BY_RESTART,r as ERR_ORPHANED_BY_SESSION,i as reconcileOrphanedDelegations};
|
|
2
|
+
//# sourceMappingURL=reconcile.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reconcile.mjs","names":[],"sources":["../../src/store/reconcile.ts"],"sourcesContent":["import { isProcessAlive } from './processLiveness.ts';\nimport { isDelegationActive, type Task, type TaskDocument } from './types.ts';\n\nexport const ERR_ORPHANED_BY_RESTART = 'Delegation orphaned by harness restart';\nexport const ERR_ORPHANED_BY_SESSION = 'Delegation orphaned by session restart';\n\nexport interface ReconcileResult {\n document: TaskDocument;\n orphaned: Task[];\n}\n\n/** The delegations this process can still settle, used to spot its own leftovers. */\nexport interface ReconcileSelf {\n pid: number;\n liveRequestIds: ReadonlySet<string>;\n}\n\n/**\n * Recover tasks that no longer have anyone able to finish them.\n *\n * A subagent run dies with the harness that spawned it, but the store file\n * outlives both, so a crash leaves tasks stuck in `in_progress` forever. Two\n * kinds of delegation qualify as dead:\n *\n * - the owning pid is gone, so nothing is left to report a result;\n * - the owning pid is *this* process, yet the request is absent from the live\n * set. Settling requires an in-memory record, so an in-process session\n * restart (which clears that map without writing to the store) leaves rows\n * nothing can ever resolve. Checking pid liveness alone misses these, because\n * the pid is our own and very much alive.\n *\n * Delegations owned by a different, still-running pid belong to a parallel\n * session and are left untouched.\n */\nexport function reconcileOrphanedDelegations(\n document: TaskDocument,\n now: string = new Date().toISOString(),\n isAlive: (pid: number) => boolean = isProcessAlive,\n self?: ReconcileSelf,\n): ReconcileResult {\n const orphaned: Task[] = [];\n\n const tasks = document.tasks.map((task) => {\n if (!isDelegationActive(task)) return task;\n const pid = task.delegation?.pid;\n if (pid === undefined) return task;\n\n const ownedByThisSession = self !== undefined && pid === self.pid;\n const abandonedHere = ownedByThisSession && !self.liveRequestIds.has(task.delegation!.requestId);\n if (!abandonedHere && isAlive(pid)) return task;\n\n const recovered: Task = {\n ...task,\n status: 'pending',\n updatedAt: now,\n delegation: {\n ...task.delegation!,\n state: 'failed',\n endedAt: now,\n result: {\n status: 'failed',\n error: abandonedHere ? ERR_ORPHANED_BY_SESSION : ERR_ORPHANED_BY_RESTART,\n },\n },\n };\n orphaned.push(recovered);\n return recovered;\n });\n\n if (orphaned.length === 0) return { document, orphaned };\n return { document: { ...document, tasks }, orphaned };\n}\n"],"mappings":"wGAGA,MAAa,EAA0B,yCAC1B,EAA0B,yCA8BvC,SAAgB,EACd,EACA,EAAc,IAAI,KAAK,CAAA,CAAE,YAAY,EACrC,EAAoC,EACpC,EACiB,CACjB,IAAM,EAAmB,CAAC,EAEpB,EAAQ,EAAS,MAAM,IAAK,GAAS,CACzC,GAAI,CAAC,EAAmB,CAAI,EAAG,OAAO,EACtC,IAAM,EAAM,EAAK,YAAY,IAC7B,GAAI,IAAQ,IAAA,GAAW,OAAO,EAG9B,IAAM,EADqB,IAAS,IAAA,IAAa,IAAQ,EAAK,KAClB,CAAC,EAAK,eAAe,IAAI,EAAK,WAAY,SAAS,EAC/F,GAAI,CAAC,GAAiB,EAAQ,CAAG,EAAG,OAAO,EAE3C,IAAM,EAAkB,CACtB,GAAG,EACH,OAAQ,UACR,UAAW,EACX,WAAY,CACV,GAAG,EAAK,WACR,MAAO,SACP,QAAS,EACT,OAAQ,CACN,OAAQ,SACR,MAAO,EAAgB,EAA0B,CACnD,CACF,CACF,EAEA,OADA,EAAS,KAAK,CAAS,EAChB,CACT,CAAC,EAGD,OADI,EAAS,SAAW,EAAU,CAAE,WAAU,UAAS,EAChD,CAAE,SAAU,CAAE,GAAG,EAAU,OAAM,EAAG,UAAS,CACtD"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./types.cjs"),t=require("./taskGraph.cjs"),n=require("./invariants.cjs"),r=/^[A-Za-z][A-Za-z0-9_-]{0,31}$/;function i(e){switch(e.kind){case`error`:case`list`:case`get`:return!1;case`upsert`:return e.applied>0;case`delete`:case`clear`:return!0}}function a(e){return e.items.filter(e=>e.kind===`failed`).map(e=>`item[${e.index}]: ${e.message}`).join(`
|
|
2
|
+
`)}function o(e){return e.kind===`upsert`?e.items[0]:void 0}function s(e,t){return{document:e,op:{kind:`error`,message:t}}}function c(e,t){let n=e??[],r=t??[];return n.length===r.length&&n.every((e,t)=>e===r[t])}function l(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function u(e,t){return e.subject!==t.subject||e.status!==t.status||e.description!==t.description||e.activeForm!==t.activeForm||e.owner!==t.owner||!c(e.blockedBy,t.blockedBy)||!l(e.metadata,t.metadata)}function d(e,t,n=e.nextId){return{...e,tasks:t,nextId:n}}function f(e,t){let n={...e};for(let[e,r]of Object.entries(t))r===null?delete n[e]:n[e]=r;return Object.keys(n).length?n:void 0}function p(e,t){if(t.subject!==void 0&&(e.subject=t.subject),t.description!==void 0&&(e.description=t.description),t.activeForm!==void 0&&(e.activeForm=t.activeForm),t.owner!==void 0&&(e.owner=t.owner),t.metadata!==void 0){let n=f(e.metadata,t.metadata);n===void 0?delete e.metadata:e.metadata=n}}function m(e,t,n){if(typeof n==`number`)return{ok:!0,id:n};if(!r.test(n))return{ok:!1,message:`${t}: "${n}" is not a valid ref; pass an existing task id as a number`};let i=e.refIds.get(n);if(i!==void 0)return{ok:!0,id:i};let a=e.failedRefs.get(n);return a===void 0?{ok:!1,message:`${t}: unknown ref "${n}" — a ref must be declared by an earlier entry in the same call`}:{ok:!1,message:`${t}: ref "${n}" refers to item[${a}], which failed`}}function h(e){return{ok:!1,message:e}}function g(e,t){if(t.ref!==void 0){if(t.id!==void 0)return`ref is only valid when creating a task; drop the id, or drop the ref`;if(!r.test(t.ref))return`ref "${t.ref}" is invalid: a ref must start with a letter and contain only letters, digits, - or _`;if(e.refIds.get(t.ref)!==void 0||e.failedRefs.has(t.ref))return`duplicate ref "${t.ref}": it was already declared by an earlier entry`}}function _(e,t,n,r){if(t.subject===void 0)return h(`subject is required when the entry has no id`);if(!t.subject.trim())return h(`subject must not be blank`);if(t.addBlockedBy!==void 0||t.removeBlockedBy!==void 0)return h(`addBlockedBy / removeBlockedBy are only for an entry with an id; a new task uses blockedBy`);if(t.status===`deleted`)return h(`cannot create a task with status deleted; create it, then use action delete`);let i=[];for(let n of t.blockedBy??[]){let t=m(e,`blockedBy`,n);if(!t.ok)return h(t.message);let r=e.tasks.find(e=>e.id===t.id);if(!r)return h(`blockedBy: #${t.id} not found`);if(r.status===`deleted`)return h(`blockedBy: #${t.id} is deleted`);i.includes(t.id)||i.push(t.id)}let a={id:e.nextId,subject:t.subject,status:t.status??`pending`,createdAt:r,updatedAt:r};return p(a,t),i.length&&(a.blockedBy=i),e.nextId+=1,e.tasks.push(a),t.ref&&e.refIds.set(t.ref,a.id),{ok:!0,outcome:{index:n,kind:`created`,id:a.id,subject:a.subject,status:a.status,...t.ref?{ref:t.ref}:{},...i.length?{blockedBy:i}:{}}}}function v(e,r,i,a){let o=r.id,s=e.tasks.findIndex(e=>e.id===o);if(s===-1)return h(`#${o} not found`);if(r.blockedBy!==void 0)return h(`blockedBy is only for a new entry; use addBlockedBy / removeBlockedBy on an entry that has an id`);if(!(r.subject!==void 0||r.description!==void 0||r.activeForm!==void 0||r.status!==void 0||r.owner!==void 0||r.metadata!==void 0||r.addBlockedBy?.length||r.removeBlockedBy?.length))return h(`nothing to change: provide at least one of subject, description, activeForm, status, owner, metadata, addBlockedBy, or removeBlockedBy`);let c=e.tasks[s];if(r.subject!==void 0&&!r.subject.trim())return h(`subject must not be blank`);let l=c.status;if(r.status!==void 0){if(!n.isTransitionValid(c.status,r.status))return h(`illegal transition ${c.status} -> ${r.status}`);l=r.status}let d=c.blockedBy?[...c.blockedBy]:[];for(let t of r.removeBlockedBy??[]){let n=m(e,`removeBlockedBy`,t);if(!n.ok)return h(n.message);d=d.filter(e=>e!==n.id)}for(let t of r.addBlockedBy??[]){let n=m(e,`addBlockedBy`,t);if(!n.ok)return h(n.message);if(n.id===o)return h(`cannot block #${o} on itself`);let r=e.tasks.find(e=>e.id===n.id);if(!r)return h(`addBlockedBy: #${n.id} not found`);if(r.status===`deleted`)return h(`addBlockedBy: #${n.id} is deleted`);d.includes(n.id)||d.push(n.id)}let f={...c,status:l};p(f,r),d.length?f.blockedBy=d:delete f.blockedBy;let g=[...e.tasks];if(g[s]=f,r.addBlockedBy?.length&&t.detectCycle(g,o,d))return h(`addBlockedBy would create a cycle in the blockedBy graph`);let _=u(c,f);return _&&(f.updatedAt=a),e.tasks=g,{ok:!0,outcome:_?{index:i,kind:`updated`,id:o,fromStatus:c.status,toStatus:l}:{index:i,kind:`unchanged`,id:o,status:l}}}function y(e,t,n){let i={tasks:[...e.tasks],nextId:e.nextId,refIds:new Map,failedRefs:new Map},a=[],o=0;for(let[e,s]of t.entries()){let t=g(i,s),c=t?h(t):s.id===void 0?_(i,s,e,n):v(i,s,e,n);if(c.ok){a.push(c.outcome),o+=1;continue}s.ref&&r.test(s.ref)&&!i.refIds.has(s.ref)&&i.failedRefs.set(s.ref,e),a.push({index:e,kind:`failed`,message:c.message,...s.id===void 0?{}:{id:s.id},...s.ref?{ref:s.ref}:{}})}return{document:o>0?d(e,i.tasks,i.nextId):e,op:{kind:`upsert`,items:a,applied:o,failed:a.length-o}}}function b(t,n,r,i=new Date().toISOString()){switch(n){case`upsert`:{let e=r.tasks;return!Array.isArray(e)||e.length===0?s(t,`upsert requires a non-empty tasks array, e.g. {"action":"upsert","tasks":[{"subject":"Write tests"}]}`):e.length>100?s(t,`upsert accepts at most 100 entries per call (received ${e.length})`):y(t,e,i)}case`list`:return{document:t,op:{kind:`list`,includeDeleted:r.includeDeleted===!0,...r.status===void 0?{}:{statusFilter:r.status}}};case`get`:{if(r.id===void 0)return s(t,`id required for get`);let e=t.tasks.find(e=>e.id===r.id);return e?{document:t,op:{kind:`get`,task:e}}:s(t,`#${r.id} not found`)}case`delete`:{if(r.id===void 0)return s(t,`id required for delete`);let n=t.tasks.findIndex(e=>e.id===r.id);if(n===-1)return s(t,`#${r.id} not found`);let a=t.tasks[n];if(a.status===`deleted`)return s(t,`#${a.id} is already deleted`);if(e.isDelegationActive(a))return s(t,`#${a.id} has a running delegation — cancel it before deleting`);let o=[...t.tasks];return o[n]={...a,status:e.DELETED_STATUS,updatedAt:i},{document:d(t,o),op:{kind:`delete`,id:a.id,subject:a.subject}}}case`clear`:{let n=t.tasks.filter(e.isDelegationActive);if(n.length>0)return s(t,`cannot clear while delegations are running (${n.map(e=>`#${e.id}`).join(`, `)}) — cancel them first`);let r=t.tasks.length;return{document:d(t,[],1),op:{kind:`clear`,count:r}}}}}exports.MAX_UPSERT_ITEMS=100,exports.REF_PATTERN=r,exports.applyTaskMutation=b,exports.formatUpsertFailure=a,exports.isCommittingOp=i,exports.singleItemOutcome=o;
|
|
3
|
+
//# sourceMappingURL=reducer.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reducer.cjs","names":["isTransitionValid","detectCycle","isDelegationActive","DELETED_STATUS"],"sources":["../../src/store/reducer.ts"],"sourcesContent":["import { isTransitionValid } from './invariants.ts';\nimport { detectCycle } from './taskGraph.ts';\nimport {\n DELETED_STATUS,\n type DepToken,\n isDelegationActive,\n type Task,\n type TaskAction,\n type TaskDocument,\n type TaskItemMutation,\n type TaskMutationParams,\n type TaskStatus,\n type UpsertItemOutcome,\n} from './types.ts';\n\n/** Bounds the work one call can do, and with it the size of one committed write. */\nexport const MAX_UPSERT_ITEMS = 100;\n\n/**\n * A ref must start with a letter, which makes it structurally unconfusable with\n * a stringified id. That is why resolving a dependency token is just a `typeof`\n * check with no coercion heuristics.\n */\nexport const REF_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;\n\n/**\n * Reducer outcome. Closed tagged union: adding an action requires extending\n * this union and the response formatter, which the compiler enforces.\n *\n * `upsert` carries one outcome per request item. It is returned even when every\n * item failed — `error` is reserved for whole-call faults — so the tool layer\n * still has the per-item messages to report.\n */\nexport type Op =\n | { kind: 'upsert'; items: UpsertItemOutcome[]; applied: number; failed: number }\n | { kind: 'delete'; id: number; subject: string }\n | { kind: 'list'; statusFilter?: TaskStatus; includeDeleted: boolean }\n | { kind: 'get'; task: Task }\n | { kind: 'clear'; count: number }\n | { kind: 'error'; message: string };\n\nexport interface ApplyResult {\n document: TaskDocument;\n op: Op;\n}\n\n/** Actions the reducer owns. `assign`/`cancel` are handled by the delegation manager. */\nexport type ReducerAction = Exclude<TaskAction, 'assign' | 'cancel'>;\n\n/**\n * Does this op represent state that must reach disk?\n *\n * The exhaustive switch is the point: a future `Op` variant cannot be added\n * without declaring its persistence intent, so nothing silently starts or stops\n * bumping `rev`.\n */\nexport function isCommittingOp(op: Op): boolean {\n switch (op.kind) {\n case 'error':\n case 'list':\n case 'get':\n return false;\n case 'upsert':\n return op.applied > 0;\n case 'delete':\n case 'clear':\n return true;\n }\n}\n\n/** Joined per-item failures, for the thrown error when an upsert applied nothing. */\nexport function formatUpsertFailure(op: Extract<Op, { kind: 'upsert' }>): string {\n return op.items\n .filter((item) => item.kind === 'failed')\n .map((item) => `item[${item.index}]: ${item.message}`)\n .join('\\n');\n}\n\n/** The single item's outcome, for callers that only ever send a batch of one. */\nexport function singleItemOutcome(op: Op): UpsertItemOutcome | undefined {\n return op.kind === 'upsert' ? op.items[0] : undefined;\n}\n\nfunction errorResult(document: TaskDocument, message: string): ApplyResult {\n return { document, op: { kind: 'error', message } };\n}\n\nfunction sameNumberList(a: number[] | undefined, b: number[] | undefined): boolean {\n const x = a ?? [];\n const y = b ?? [];\n return x.length === y.length && x.every((value, index) => value === y[index]);\n}\n\nfunction sameRecord(a: Record<string, unknown> | undefined, b: Record<string, unknown> | undefined): boolean {\n return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);\n}\n\n/**\n * Did this update change anything? A no-effect update (status re-set to its\n * current value, fields re-sent unchanged) reports \"No change\" rather than\n * \"Updated #N\" — without the distinction a model can loop re-issuing the same\n * call believing it never landed.\n */\nfunction taskChanged(before: Task, after: Task): boolean {\n return (\n before.subject !== after.subject ||\n before.status !== after.status ||\n before.description !== after.description ||\n before.activeForm !== after.activeForm ||\n before.owner !== after.owner ||\n !sameNumberList(before.blockedBy, after.blockedBy) ||\n !sameRecord(before.metadata, after.metadata)\n );\n}\n\nfunction withTasks(document: TaskDocument, tasks: Task[], nextId = document.nextId): TaskDocument {\n return { ...document, tasks, nextId };\n}\n\n/** Merge incoming metadata over a base; a `null` value deletes its key. */\nfunction mergeMetadata(\n base: Record<string, unknown> | undefined,\n incoming: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const merged: Record<string, unknown> = { ...base };\n for (const [key, value] of Object.entries(incoming)) {\n if (value === null) delete merged[key];\n else merged[key] = value;\n }\n return Object.keys(merged).length ? merged : undefined;\n}\n\n/** Copy the optional scalar fields an item may set onto a task, in place. */\nfunction assignScalars(target: Task, item: TaskItemMutation): void {\n if (item.subject !== undefined) target.subject = item.subject;\n if (item.description !== undefined) target.description = item.description;\n if (item.activeForm !== undefined) target.activeForm = item.activeForm;\n if (item.owner !== undefined) target.owner = item.owner;\n if (item.metadata !== undefined) {\n const merged = mergeMetadata(target.metadata, item.metadata);\n if (merged === undefined) delete target.metadata;\n else target.metadata = merged;\n }\n}\n\n/**\n * Working state threaded item to item, so entry N observes every effect of\n * entries 1..N-1. `refIds` and `failedRefs` are what make the cascade work:\n * refs resolve backward only, so an entry that names a failed sibling is always\n * processed after the failure that killed it.\n */\ninterface UpsertContext {\n tasks: Task[];\n nextId: number;\n refIds: Map<string, number>;\n failedRefs: Map<string, number>;\n}\n\ntype Resolved = { ok: true; id: number } | { ok: false; message: string };\n\nfunction resolveDep(context: UpsertContext, field: string, token: DepToken): Resolved {\n if (typeof token === 'number') return { ok: true, id: token };\n if (!REF_PATTERN.test(token)) {\n return { ok: false, message: `${field}: \"${token}\" is not a valid ref; pass an existing task id as a number` };\n }\n const id = context.refIds.get(token);\n if (id !== undefined) return { ok: true, id };\n const failedAt = context.failedRefs.get(token);\n if (failedAt !== undefined) {\n return { ok: false, message: `${field}: ref \"${token}\" refers to item[${failedAt}], which failed` };\n }\n return {\n ok: false,\n message: `${field}: unknown ref \"${token}\" — a ref must be declared by an earlier entry in the same call`,\n };\n}\n\ntype ItemResult = { ok: true; outcome: UpsertItemOutcome } | { ok: false; message: string };\n\nfunction fail(message: string): ItemResult {\n return { ok: false, message };\n}\n\n/** Structural checks that apply to every entry, whichever kind it is. */\nfunction checkShape(context: UpsertContext, item: TaskItemMutation): string | undefined {\n if (item.ref !== undefined) {\n if (item.id !== undefined) return 'ref is only valid when creating a task; drop the id, or drop the ref';\n if (!REF_PATTERN.test(item.ref)) {\n return `ref \"${item.ref}\" is invalid: a ref must start with a letter and contain only letters, digits, - or _`;\n }\n const owner = context.refIds.get(item.ref) !== undefined || context.failedRefs.has(item.ref);\n if (owner) return `duplicate ref \"${item.ref}\": it was already declared by an earlier entry`;\n }\n return undefined;\n}\n\nfunction applyCreateItem(context: UpsertContext, item: TaskItemMutation, index: number, now: string): ItemResult {\n if (item.subject === undefined) return fail('subject is required when the entry has no id');\n if (!item.subject.trim()) return fail('subject must not be blank');\n if (item.addBlockedBy !== undefined || item.removeBlockedBy !== undefined) {\n return fail('addBlockedBy / removeBlockedBy are only for an entry with an id; a new task uses blockedBy');\n }\n // A task created as a tombstone is invisible to every view and can never\n // leave `deleted`, so it would be a write-only black hole.\n if (item.status === DELETED_STATUS) {\n return fail('cannot create a task with status deleted; create it, then use action delete');\n }\n\n const blockedBy: number[] = [];\n for (const token of item.blockedBy ?? []) {\n const resolved = resolveDep(context, 'blockedBy', token);\n if (!resolved.ok) return fail(resolved.message);\n const dep = context.tasks.find((task) => task.id === resolved.id);\n if (!dep) return fail(`blockedBy: #${resolved.id} not found`);\n if (dep.status === DELETED_STATUS) return fail(`blockedBy: #${resolved.id} is deleted`);\n if (!blockedBy.includes(resolved.id)) blockedBy.push(resolved.id);\n }\n\n // No cycle check is needed: the id is freshly allocated, so nothing already\n // in the document can point at it yet.\n const created: Task = {\n id: context.nextId,\n subject: item.subject,\n status: item.status ?? 'pending',\n createdAt: now,\n updatedAt: now,\n };\n assignScalars(created, item);\n if (blockedBy.length) created.blockedBy = blockedBy;\n\n context.nextId += 1;\n context.tasks.push(created);\n if (item.ref) context.refIds.set(item.ref, created.id);\n\n return {\n ok: true,\n outcome: {\n index,\n kind: 'created',\n id: created.id,\n subject: created.subject,\n status: created.status,\n ...(item.ref ? { ref: item.ref } : {}),\n ...(blockedBy.length ? { blockedBy } : {}),\n },\n };\n}\n\nfunction applyUpdateItem(context: UpsertContext, item: TaskItemMutation, index: number, now: string): ItemResult {\n const id = item.id as number;\n const at = context.tasks.findIndex((task) => task.id === id);\n if (at === -1) return fail(`#${id} not found`);\n if (item.blockedBy !== undefined) {\n return fail('blockedBy is only for a new entry; use addBlockedBy / removeBlockedBy on an entry that has an id');\n }\n\n const hasMutation =\n item.subject !== undefined ||\n item.description !== undefined ||\n item.activeForm !== undefined ||\n item.status !== undefined ||\n item.owner !== undefined ||\n item.metadata !== undefined ||\n Boolean(item.addBlockedBy?.length) ||\n Boolean(item.removeBlockedBy?.length);\n if (!hasMutation) {\n return fail(\n 'nothing to change: provide at least one of subject, description, activeForm, status, owner, metadata, addBlockedBy, or removeBlockedBy',\n );\n }\n\n const current = context.tasks[at];\n\n // The Task Space overlay commits free text from an inline editor, so a blank\n // subject reaches the reducer as a real update rather than as a missing\n // field. Persisting it would leave an unidentifiable row.\n if (item.subject !== undefined && !item.subject.trim()) return fail('subject must not be blank');\n\n let newStatus = current.status;\n if (item.status !== undefined) {\n if (!isTransitionValid(current.status, item.status)) {\n return fail(`illegal transition ${current.status} -> ${item.status}`);\n }\n newStatus = item.status;\n }\n\n let newBlockedBy = current.blockedBy ? [...current.blockedBy] : [];\n for (const token of item.removeBlockedBy ?? []) {\n const resolved = resolveDep(context, 'removeBlockedBy', token);\n if (!resolved.ok) return fail(resolved.message);\n // Removing an id that is not there is a well-defined no-op, so unlike the\n // add path this deliberately skips the existence check.\n newBlockedBy = newBlockedBy.filter((dep) => dep !== resolved.id);\n }\n for (const token of item.addBlockedBy ?? []) {\n const resolved = resolveDep(context, 'addBlockedBy', token);\n if (!resolved.ok) return fail(resolved.message);\n if (resolved.id === id) return fail(`cannot block #${id} on itself`);\n const dep = context.tasks.find((task) => task.id === resolved.id);\n if (!dep) return fail(`addBlockedBy: #${resolved.id} not found`);\n if (dep.status === DELETED_STATUS) return fail(`addBlockedBy: #${resolved.id} is deleted`);\n if (!newBlockedBy.includes(resolved.id)) newBlockedBy.push(resolved.id);\n }\n\n const updated: Task = { ...current, status: newStatus };\n assignScalars(updated, item);\n if (newBlockedBy.length) updated.blockedBy = newBlockedBy;\n else delete updated.blockedBy;\n\n // The candidate is written before the check because `detectCycle` unions the\n // node's stored edges with the ones passed in: checking against the old array\n // would resurrect an edge `removeBlockedBy` just stripped and reject a\n // remove+add that legitimately breaks a cycle.\n const candidate = [...context.tasks];\n candidate[at] = updated;\n if (item.addBlockedBy?.length && detectCycle(candidate, id, newBlockedBy)) {\n return fail('addBlockedBy would create a cycle in the blockedBy graph');\n }\n\n const changed = taskChanged(current, updated);\n if (changed) updated.updatedAt = now;\n context.tasks = candidate;\n\n return {\n ok: true,\n outcome: changed\n ? { index, kind: 'updated', id, fromStatus: current.status, toStatus: newStatus }\n : { index, kind: 'unchanged', id, status: newStatus },\n };\n}\n\n/**\n * Apply every entry in request order, threading the document.\n *\n * Each entry lands completely or not at all: a create whose dependencies fail\n * is not kept dependency-free, because handing back an unblocked task the\n * caller asked to be blocked is a lie it may immediately act on.\n */\nfunction applyUpsert(document: TaskDocument, items: TaskItemMutation[], now: string): ApplyResult {\n const context: UpsertContext = {\n tasks: [...document.tasks],\n nextId: document.nextId,\n refIds: new Map(),\n failedRefs: new Map(),\n };\n const outcomes: UpsertItemOutcome[] = [];\n let applied = 0;\n\n for (const [index, item] of items.entries()) {\n const shapeError = checkShape(context, item);\n const result = shapeError\n ? fail(shapeError)\n : item.id === undefined\n ? applyCreateItem(context, item, index, now)\n : applyUpdateItem(context, item, index, now);\n\n if (result.ok) {\n outcomes.push(result.outcome);\n applied += 1;\n continue;\n }\n // A ref whose owner failed must not read as a typo to the entries that\n // depend on it, so the dead ref is recorded rather than left unknown.\n if (item.ref && REF_PATTERN.test(item.ref) && !context.refIds.has(item.ref)) {\n context.failedRefs.set(item.ref, index);\n }\n outcomes.push({\n index,\n kind: 'failed',\n message: result.message,\n ...(item.id === undefined ? {} : { id: item.id }),\n ...(item.ref ? { ref: item.ref } : {}),\n });\n }\n\n return {\n // Nothing applied means nothing to write: returning the original object by\n // reference keeps the caller's write-skip path identical to a hard error.\n document: applied > 0 ? withTasks(document, context.tasks, context.nextId) : document,\n op: { kind: 'upsert', items: outcomes, applied, failed: outcomes.length - applied },\n };\n}\n\n/**\n * Pure reducer: (document, action, params) -> (document, op).\n *\n * All validation is in-line: structural guards plus state-aware checks\n * (transition legality, dangling or deleted blockedBy, self-block, cycles,\n * in-flight delegations). The caller owns persistence and formatting.\n */\nexport function applyTaskMutation(\n document: TaskDocument,\n action: ReducerAction,\n params: TaskMutationParams,\n now: string = new Date().toISOString(),\n): ApplyResult {\n switch (action) {\n case 'upsert': {\n const items = params.tasks;\n if (!Array.isArray(items) || items.length === 0) {\n return errorResult(\n document,\n 'upsert requires a non-empty tasks array, e.g. {\"action\":\"upsert\",\"tasks\":[{\"subject\":\"Write tests\"}]}',\n );\n }\n if (items.length > MAX_UPSERT_ITEMS) {\n return errorResult(\n document,\n `upsert accepts at most ${MAX_UPSERT_ITEMS} entries per call (received ${items.length})`,\n );\n }\n return applyUpsert(document, items, now);\n }\n\n case 'list': {\n return {\n document,\n op: {\n kind: 'list',\n includeDeleted: params.includeDeleted === true,\n ...(params.status !== undefined ? { statusFilter: params.status } : {}),\n },\n };\n }\n\n case 'get': {\n if (params.id === undefined) return errorResult(document, 'id required for get');\n const task = document.tasks.find((candidate) => candidate.id === params.id);\n if (!task) return errorResult(document, `#${params.id} not found`);\n return { document, op: { kind: 'get', task } };\n }\n\n case 'delete': {\n if (params.id === undefined) return errorResult(document, 'id required for delete');\n const index = document.tasks.findIndex((task) => task.id === params.id);\n if (index === -1) return errorResult(document, `#${params.id} not found`);\n const current = document.tasks[index];\n if (current.status === DELETED_STATUS) return errorResult(document, `#${current.id} is already deleted`);\n if (isDelegationActive(current)) {\n return errorResult(document, `#${current.id} has a running delegation — cancel it before deleting`);\n }\n\n const tasks = [...document.tasks];\n tasks[index] = { ...current, status: DELETED_STATUS, updatedAt: now };\n return {\n document: withTasks(document, tasks),\n op: { kind: 'delete', id: current.id, subject: current.subject },\n };\n }\n\n case 'clear': {\n const active = document.tasks.filter(isDelegationActive);\n if (active.length > 0) {\n const ids = active.map((task) => `#${task.id}`).join(', ');\n return errorResult(document, `cannot clear while delegations are running (${ids}) — cancel them first`);\n }\n const count = document.tasks.length;\n return {\n document: withTasks(document, [], 1),\n op: { kind: 'clear', count },\n };\n }\n }\n}\n"],"mappings":"6JAuBa,EAAc,gCAiC3B,SAAgB,EAAe,EAAiB,CAC9C,OAAQ,EAAG,KAAX,CACE,IAAK,QACL,IAAK,OACL,IAAK,MACH,MAAO,GACT,IAAK,SACH,OAAO,EAAG,QAAU,EACtB,IAAK,SACL,IAAK,QACH,MAAO,EACX,CACF,CAGA,SAAgB,EAAoB,EAA6C,CAC/E,OAAO,EAAG,MACP,OAAQ,GAAS,EAAK,OAAS,QAAQ,CAAC,CACxC,IAAK,GAAS,QAAQ,EAAK,MAAM,KAAK,EAAK,SAAS,CAAC,CACrD,KAAK;CAAI,CACd,CAGA,SAAgB,EAAkB,EAAuC,CACvE,OAAO,EAAG,OAAS,SAAW,EAAG,MAAM,GAAK,IAAA,EAC9C,CAEA,SAAS,EAAY,EAAwB,EAA8B,CACzE,MAAO,CAAE,WAAU,GAAI,CAAE,KAAM,QAAS,SAAQ,CAAE,CACpD,CAEA,SAAS,EAAe,EAAyB,EAAkC,CACjF,IAAM,EAAI,GAAK,CAAC,EACV,EAAI,GAAK,CAAC,EAChB,OAAO,EAAE,SAAW,EAAE,QAAU,EAAE,OAAO,EAAO,IAAU,IAAU,EAAE,EAAM,CAC9E,CAEA,SAAS,EAAW,EAAwC,EAAiD,CAC3G,OAAO,KAAK,UAAU,GAAK,IAAI,IAAM,KAAK,UAAU,GAAK,IAAI,CAC/D,CAQA,SAAS,EAAY,EAAc,EAAsB,CACvD,OACE,EAAO,UAAY,EAAM,SACzB,EAAO,SAAW,EAAM,QACxB,EAAO,cAAgB,EAAM,aAC7B,EAAO,aAAe,EAAM,YAC5B,EAAO,QAAU,EAAM,OACvB,CAAC,EAAe,EAAO,UAAW,EAAM,SAAS,GACjD,CAAC,EAAW,EAA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