@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,72 @@
|
|
|
1
|
+
import { Task, TaskAction, TaskDocument, TaskMutationParams, TaskStatus, UpsertItemOutcome } from "./types.cjs";
|
|
2
|
+
//#region src/store/reducer.d.ts
|
|
3
|
+
/** Bounds the work one call can do, and with it the size of one committed write. */
|
|
4
|
+
declare const MAX_UPSERT_ITEMS = 100;
|
|
5
|
+
/**
|
|
6
|
+
* A ref must start with a letter, which makes it structurally unconfusable with
|
|
7
|
+
* a stringified id. That is why resolving a dependency token is just a `typeof`
|
|
8
|
+
* check with no coercion heuristics.
|
|
9
|
+
*/
|
|
10
|
+
declare const REF_PATTERN: RegExp;
|
|
11
|
+
/**
|
|
12
|
+
* Reducer outcome. Closed tagged union: adding an action requires extending
|
|
13
|
+
* this union and the response formatter, which the compiler enforces.
|
|
14
|
+
*
|
|
15
|
+
* `upsert` carries one outcome per request item. It is returned even when every
|
|
16
|
+
* item failed — `error` is reserved for whole-call faults — so the tool layer
|
|
17
|
+
* still has the per-item messages to report.
|
|
18
|
+
*/
|
|
19
|
+
type Op = {
|
|
20
|
+
kind: 'upsert';
|
|
21
|
+
items: UpsertItemOutcome[];
|
|
22
|
+
applied: number;
|
|
23
|
+
failed: number;
|
|
24
|
+
} | {
|
|
25
|
+
kind: 'delete';
|
|
26
|
+
id: number;
|
|
27
|
+
subject: string;
|
|
28
|
+
} | {
|
|
29
|
+
kind: 'list';
|
|
30
|
+
statusFilter?: TaskStatus;
|
|
31
|
+
includeDeleted: boolean;
|
|
32
|
+
} | {
|
|
33
|
+
kind: 'get';
|
|
34
|
+
task: Task;
|
|
35
|
+
} | {
|
|
36
|
+
kind: 'clear';
|
|
37
|
+
count: number;
|
|
38
|
+
} | {
|
|
39
|
+
kind: 'error';
|
|
40
|
+
message: string;
|
|
41
|
+
};
|
|
42
|
+
interface ApplyResult {
|
|
43
|
+
document: TaskDocument;
|
|
44
|
+
op: Op;
|
|
45
|
+
}
|
|
46
|
+
/** Actions the reducer owns. `assign`/`cancel` are handled by the delegation manager. */
|
|
47
|
+
type ReducerAction = Exclude<TaskAction, 'assign' | 'cancel'>;
|
|
48
|
+
/**
|
|
49
|
+
* Does this op represent state that must reach disk?
|
|
50
|
+
*
|
|
51
|
+
* The exhaustive switch is the point: a future `Op` variant cannot be added
|
|
52
|
+
* without declaring its persistence intent, so nothing silently starts or stops
|
|
53
|
+
* bumping `rev`.
|
|
54
|
+
*/
|
|
55
|
+
declare function isCommittingOp(op: Op): boolean;
|
|
56
|
+
/** Joined per-item failures, for the thrown error when an upsert applied nothing. */
|
|
57
|
+
declare function formatUpsertFailure(op: Extract<Op, {
|
|
58
|
+
kind: 'upsert';
|
|
59
|
+
}>): string;
|
|
60
|
+
/** The single item's outcome, for callers that only ever send a batch of one. */
|
|
61
|
+
declare function singleItemOutcome(op: Op): UpsertItemOutcome | undefined;
|
|
62
|
+
/**
|
|
63
|
+
* Pure reducer: (document, action, params) -> (document, op).
|
|
64
|
+
*
|
|
65
|
+
* All validation is in-line: structural guards plus state-aware checks
|
|
66
|
+
* (transition legality, dangling or deleted blockedBy, self-block, cycles,
|
|
67
|
+
* in-flight delegations). The caller owns persistence and formatting.
|
|
68
|
+
*/
|
|
69
|
+
declare function applyTaskMutation(document: TaskDocument, action: ReducerAction, params: TaskMutationParams, now?: string): ApplyResult;
|
|
70
|
+
//#endregion
|
|
71
|
+
export { ApplyResult, MAX_UPSERT_ITEMS, Op, REF_PATTERN, ReducerAction, applyTaskMutation, formatUpsertFailure, isCommittingOp, singleItemOutcome };
|
|
72
|
+
//# sourceMappingURL=reducer.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reducer.d.cts","names":[],"sources":["../../src/store/reducer.ts"],"mappings":";;;cAgBa;;;;;;cAOA,aAAW;;;;;;;;;KAUZ;EACN;EAAgB,OAAO;EAAqB;EAAiB;;EAC7D;EAAgB;EAAY;;EAC5B;EAAc,eAAe;EAAY;;EACzC;EAAa,MAAM;;EACnB;EAAe;;EACf;EAAe;;UAEJ;EACf,UAAU;EACV,IAAI;;;KAIM,gBAAgB,QAAQ;;;;;;;;iBASpB,eAAe,IAAI;;iBAenB,oBAAoB,IAAI,QAAQ;EAAM;;;iBAQtC,kBAAkB,IAAI,KAAK;;;;;;;;iBAuT3B,kBACd,UAAU,cACV,QAAQ,eACR,QAAQ,oBACR,eACC"}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { Task, TaskAction, TaskDocument, TaskMutationParams, TaskStatus, UpsertItemOutcome } from "./types.mjs";
|
|
2
|
+
//#region src/store/reducer.d.ts
|
|
3
|
+
/** Bounds the work one call can do, and with it the size of one committed write. */
|
|
4
|
+
declare const MAX_UPSERT_ITEMS = 100;
|
|
5
|
+
/**
|
|
6
|
+
* A ref must start with a letter, which makes it structurally unconfusable with
|
|
7
|
+
* a stringified id. That is why resolving a dependency token is just a `typeof`
|
|
8
|
+
* check with no coercion heuristics.
|
|
9
|
+
*/
|
|
10
|
+
declare const REF_PATTERN: RegExp;
|
|
11
|
+
/**
|
|
12
|
+
* Reducer outcome. Closed tagged union: adding an action requires extending
|
|
13
|
+
* this union and the response formatter, which the compiler enforces.
|
|
14
|
+
*
|
|
15
|
+
* `upsert` carries one outcome per request item. It is returned even when every
|
|
16
|
+
* item failed — `error` is reserved for whole-call faults — so the tool layer
|
|
17
|
+
* still has the per-item messages to report.
|
|
18
|
+
*/
|
|
19
|
+
type Op = {
|
|
20
|
+
kind: 'upsert';
|
|
21
|
+
items: UpsertItemOutcome[];
|
|
22
|
+
applied: number;
|
|
23
|
+
failed: number;
|
|
24
|
+
} | {
|
|
25
|
+
kind: 'delete';
|
|
26
|
+
id: number;
|
|
27
|
+
subject: string;
|
|
28
|
+
} | {
|
|
29
|
+
kind: 'list';
|
|
30
|
+
statusFilter?: TaskStatus;
|
|
31
|
+
includeDeleted: boolean;
|
|
32
|
+
} | {
|
|
33
|
+
kind: 'get';
|
|
34
|
+
task: Task;
|
|
35
|
+
} | {
|
|
36
|
+
kind: 'clear';
|
|
37
|
+
count: number;
|
|
38
|
+
} | {
|
|
39
|
+
kind: 'error';
|
|
40
|
+
message: string;
|
|
41
|
+
};
|
|
42
|
+
interface ApplyResult {
|
|
43
|
+
document: TaskDocument;
|
|
44
|
+
op: Op;
|
|
45
|
+
}
|
|
46
|
+
/** Actions the reducer owns. `assign`/`cancel` are handled by the delegation manager. */
|
|
47
|
+
type ReducerAction = Exclude<TaskAction, 'assign' | 'cancel'>;
|
|
48
|
+
/**
|
|
49
|
+
* Does this op represent state that must reach disk?
|
|
50
|
+
*
|
|
51
|
+
* The exhaustive switch is the point: a future `Op` variant cannot be added
|
|
52
|
+
* without declaring its persistence intent, so nothing silently starts or stops
|
|
53
|
+
* bumping `rev`.
|
|
54
|
+
*/
|
|
55
|
+
declare function isCommittingOp(op: Op): boolean;
|
|
56
|
+
/** Joined per-item failures, for the thrown error when an upsert applied nothing. */
|
|
57
|
+
declare function formatUpsertFailure(op: Extract<Op, {
|
|
58
|
+
kind: 'upsert';
|
|
59
|
+
}>): string;
|
|
60
|
+
/** The single item's outcome, for callers that only ever send a batch of one. */
|
|
61
|
+
declare function singleItemOutcome(op: Op): UpsertItemOutcome | undefined;
|
|
62
|
+
/**
|
|
63
|
+
* Pure reducer: (document, action, params) -> (document, op).
|
|
64
|
+
*
|
|
65
|
+
* All validation is in-line: structural guards plus state-aware checks
|
|
66
|
+
* (transition legality, dangling or deleted blockedBy, self-block, cycles,
|
|
67
|
+
* in-flight delegations). The caller owns persistence and formatting.
|
|
68
|
+
*/
|
|
69
|
+
declare function applyTaskMutation(document: TaskDocument, action: ReducerAction, params: TaskMutationParams, now?: string): ApplyResult;
|
|
70
|
+
//#endregion
|
|
71
|
+
export { ApplyResult, MAX_UPSERT_ITEMS, Op, REF_PATTERN, ReducerAction, applyTaskMutation, formatUpsertFailure, isCommittingOp, singleItemOutcome };
|
|
72
|
+
//# sourceMappingURL=reducer.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reducer.d.mts","names":[],"sources":["../../src/store/reducer.ts"],"mappings":";;;cAgBa;;;;;;cAOA,aAAW;;;;;;;;;KAUZ;EACN;EAAgB,OAAO;EAAqB;EAAiB;;EAC7D;EAAgB;EAAY;;EAC5B;EAAc,eAAe;EAAY;;EACzC;EAAa,MAAM;;EACnB;EAAe;;EACf;EAAe;;UAEJ;EACf,UAAU;EACV,IAAI;;;KAIM,gBAAgB,QAAQ;;;;;;;;iBASpB,eAAe,IAAI;;iBAenB,oBAAoB,IAAI,QAAQ;EAAM;;;iBAQtC,kBAAkB,IAAI,KAAK;;;;;;;;iBAuT3B,kBACd,UAAU,cACV,QAAQ,eACR,QAAQ,oBACR,eACC"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{DELETED_STATUS as e,isDelegationActive as t}from"./types.mjs";import{detectCycle as n}from"./taskGraph.mjs";import{isTransitionValid as r}from"./invariants.mjs";const i=100,a=/^[A-Za-z][A-Za-z0-9_-]{0,31}$/;function o(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 s(e){return e.items.filter(e=>e.kind===`failed`).map(e=>`item[${e.index}]: ${e.message}`).join(`
|
|
2
|
+
`)}function c(e){return e.kind===`upsert`?e.items[0]:void 0}function l(e,t){return{document:e,op:{kind:`error`,message:t}}}function u(e,t){let n=e??[],r=t??[];return n.length===r.length&&n.every((e,t)=>e===r[t])}function d(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function f(e,t){return e.subject!==t.subject||e.status!==t.status||e.description!==t.description||e.activeForm!==t.activeForm||e.owner!==t.owner||!u(e.blockedBy,t.blockedBy)||!d(e.metadata,t.metadata)}function p(e,t,n=e.nextId){return{...e,tasks:t,nextId:n}}function m(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 h(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=m(e.metadata,t.metadata);n===void 0?delete e.metadata:e.metadata=n}}function g(e,t,n){if(typeof n==`number`)return{ok:!0,id:n};if(!a.test(n))return{ok:!1,message:`${t}: "${n}" is not a valid ref; pass an existing task id as a number`};let r=e.refIds.get(n);if(r!==void 0)return{ok:!0,id:r};let i=e.failedRefs.get(n);return i===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[${i}], which failed`}}function _(e){return{ok:!1,message:e}}function v(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(!a.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 y(e,t,n,r){if(t.subject===void 0)return _(`subject is required when the entry has no id`);if(!t.subject.trim())return _(`subject must not be blank`);if(t.addBlockedBy!==void 0||t.removeBlockedBy!==void 0)return _(`addBlockedBy / removeBlockedBy are only for an entry with an id; a new task uses blockedBy`);if(t.status===`deleted`)return _(`cannot create a task with status deleted; create it, then use action delete`);let i=[];for(let n of t.blockedBy??[]){let t=g(e,`blockedBy`,n);if(!t.ok)return _(t.message);let r=e.tasks.find(e=>e.id===t.id);if(!r)return _(`blockedBy: #${t.id} not found`);if(r.status===`deleted`)return _(`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 h(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 b(e,t,i,a){let o=t.id,s=e.tasks.findIndex(e=>e.id===o);if(s===-1)return _(`#${o} not found`);if(t.blockedBy!==void 0)return _(`blockedBy is only for a new entry; use addBlockedBy / removeBlockedBy on an entry that has an id`);if(!(t.subject!==void 0||t.description!==void 0||t.activeForm!==void 0||t.status!==void 0||t.owner!==void 0||t.metadata!==void 0||t.addBlockedBy?.length||t.removeBlockedBy?.length))return _(`nothing to change: provide at least one of subject, description, activeForm, status, owner, metadata, addBlockedBy, or removeBlockedBy`);let c=e.tasks[s];if(t.subject!==void 0&&!t.subject.trim())return _(`subject must not be blank`);let l=c.status;if(t.status!==void 0){if(!r(c.status,t.status))return _(`illegal transition ${c.status} -> ${t.status}`);l=t.status}let u=c.blockedBy?[...c.blockedBy]:[];for(let n of t.removeBlockedBy??[]){let t=g(e,`removeBlockedBy`,n);if(!t.ok)return _(t.message);u=u.filter(e=>e!==t.id)}for(let n of t.addBlockedBy??[]){let t=g(e,`addBlockedBy`,n);if(!t.ok)return _(t.message);if(t.id===o)return _(`cannot block #${o} on itself`);let r=e.tasks.find(e=>e.id===t.id);if(!r)return _(`addBlockedBy: #${t.id} not found`);if(r.status===`deleted`)return _(`addBlockedBy: #${t.id} is deleted`);u.includes(t.id)||u.push(t.id)}let d={...c,status:l};h(d,t),u.length?d.blockedBy=u:delete d.blockedBy;let p=[...e.tasks];if(p[s]=d,t.addBlockedBy?.length&&n(p,o,u))return _(`addBlockedBy would create a cycle in the blockedBy graph`);let m=f(c,d);return m&&(d.updatedAt=a),e.tasks=p,{ok:!0,outcome:m?{index:i,kind:`updated`,id:o,fromStatus:c.status,toStatus:l}:{index:i,kind:`unchanged`,id:o,status:l}}}function x(e,t,n){let r={tasks:[...e.tasks],nextId:e.nextId,refIds:new Map,failedRefs:new Map},i=[],o=0;for(let[e,s]of t.entries()){let t=v(r,s),c=t?_(t):s.id===void 0?y(r,s,e,n):b(r,s,e,n);if(c.ok){i.push(c.outcome),o+=1;continue}s.ref&&a.test(s.ref)&&!r.refIds.has(s.ref)&&r.failedRefs.set(s.ref,e),i.push({index:e,kind:`failed`,message:c.message,...s.id===void 0?{}:{id:s.id},...s.ref?{ref:s.ref}:{}})}return{document:o>0?p(e,r.tasks,r.nextId):e,op:{kind:`upsert`,items:i,applied:o,failed:i.length-o}}}function S(n,r,i,a=new Date().toISOString()){switch(r){case`upsert`:{let e=i.tasks;return!Array.isArray(e)||e.length===0?l(n,`upsert requires a non-empty tasks array, e.g. {"action":"upsert","tasks":[{"subject":"Write tests"}]}`):e.length>100?l(n,`upsert accepts at most 100 entries per call (received ${e.length})`):x(n,e,a)}case`list`:return{document:n,op:{kind:`list`,includeDeleted:i.includeDeleted===!0,...i.status===void 0?{}:{statusFilter:i.status}}};case`get`:{if(i.id===void 0)return l(n,`id required for get`);let e=n.tasks.find(e=>e.id===i.id);return e?{document:n,op:{kind:`get`,task:e}}:l(n,`#${i.id} not found`)}case`delete`:{if(i.id===void 0)return l(n,`id required for delete`);let r=n.tasks.findIndex(e=>e.id===i.id);if(r===-1)return l(n,`#${i.id} not found`);let o=n.tasks[r];if(o.status===`deleted`)return l(n,`#${o.id} is already deleted`);if(t(o))return l(n,`#${o.id} has a running delegation — cancel it before deleting`);let s=[...n.tasks];return s[r]={...o,status:e,updatedAt:a},{document:p(n,s),op:{kind:`delete`,id:o.id,subject:o.subject}}}case`clear`:{let e=n.tasks.filter(t);if(e.length>0)return l(n,`cannot clear while delegations are running (${e.map(e=>`#${e.id}`).join(`, `)}) — cancel them first`);let r=n.tasks.length;return{document:p(n,[],1),op:{kind:`clear`,count:r}}}}}export{i as MAX_UPSERT_ITEMS,a as REF_PATTERN,S as applyTaskMutation,s as formatUpsertFailure,o as isCommittingOp,c as singleItemOutcome};
|
|
3
|
+
//# sourceMappingURL=reducer.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reducer.mjs","names":[],"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":"wKAgBA,MAAa,EAAmB,IAOnB,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,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AG,EAAS,OAAQ,EAAgB,UAAW,CAAI,EAC7D,CACL,SAAU,EAAU,EAAU,CAAK,EACnC,GAAI,CAAE,KAAM,SAAU,GAAI,EAAQ,GAAI,QAAS,EAAQ,OAAQ,CACjE,CACF,CAEA,IAAK,QAAS,CACZ,IAAM,EAAS,EAAS,MAAM,OAAO,CAAkB,EACvD,GAAI,EAAO,OAAS,EAElB,OAAO,EAAY,EAAU,+CADjB,EAAO,IAAK,GAAS,IAAI,EAAK,IAAI,CAAC,CAAC,KAAK,IACyB,EAAE,sBAAsB,EAExG,IAAM,EAAQ,EAAS,MAAM,OAC7B,MAAO,CACL,SAAU,EAAU,EAAU,CAAC,EAAG,CAAC,EACnC,GAAI,CAAE,KAAM,QAAS,OAAM,CAC7B,CACF,CACF,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=`completed`,t=`deleted`;function n(n){let r=n.filter(e=>e.status!==t);return r.length>0&&r.every(t=>t.status===e)}function r(e,t,n){let r=new Map;for(let i of e)i.id===t?r.set(i.id,[...new Set([...i.blockedBy??[],...n])]):r.set(i.id,i.blockedBy?[...i.blockedBy]:[]);let i=new Set,a=new Set,o=e=>{if(i.has(e))return!0;if(a.has(e))return!1;i.add(e);for(let t of r.get(e)??[])if(o(t))return!0;return i.delete(e),a.add(e),!1};for(let e of r.keys())if(o(e))return!0;return!1}function i(e){let t=new Map;for(let n of e)for(let e of n.blockedBy??[]){let r=t.get(e)??[];r.push(n.id),t.set(e,r)}return t}function a(n,r){return(r.blockedBy??[]).filter(r=>{let i=n.find(e=>e.id===r);return i?i.status!==e&&i.status!==t:!1})}function o(e,t){return a(e,t).length>0}exports.deriveBlocks=i,exports.detectCycle=r,exports.isBlocked=o,exports.isTaskListComplete=n,exports.unresolvedBlockers=a;
|
|
2
|
+
//# sourceMappingURL=taskGraph.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"taskGraph.cjs","names":[],"sources":["../../src/store/taskGraph.ts"],"sourcesContent":["import type { Task } from './types.ts';\n\nconst COMPLETED_STATUS: Task['status'] = 'completed';\nconst DELETED_STATUS: Task['status'] = 'deleted';\n\n/** True when a non-empty list has no visible work left to finish. */\nexport function isTaskListComplete(taskList: readonly Task[]): boolean {\n const visible = taskList.filter((task) => task.status !== DELETED_STATUS);\n return visible.length > 0 && visible.every((task) => task.status === COMPLETED_STATUS);\n}\n\n/**\n * Would merging `newBlockedBy` into `taskId`'s dependencies introduce a cycle?\n *\n * Takes the proposed additions explicitly so the reducer can ask the question\n * before mutating anything.\n */\nexport function detectCycle(taskList: readonly Task[], taskId: number, newBlockedBy: readonly number[]): boolean {\n const edges = new Map<number, number[]>();\n for (const task of taskList) {\n if (task.id === taskId) {\n edges.set(task.id, [...new Set([...(task.blockedBy ?? []), ...newBlockedBy])]);\n } else {\n edges.set(task.id, task.blockedBy ? [...task.blockedBy] : []);\n }\n }\n\n const visiting = new Set<number>();\n const visited = new Set<number>();\n const hasCycleFrom = (node: number): boolean => {\n if (visiting.has(node)) return true;\n if (visited.has(node)) return false;\n visiting.add(node);\n for (const next of edges.get(node) ?? []) {\n if (hasCycleFrom(next)) return true;\n }\n visiting.delete(node);\n visited.add(node);\n return false;\n };\n\n for (const node of edges.keys()) {\n if (hasCycleFrom(node)) return true;\n }\n return false;\n}\n\n/** Inverse adjacency: for each task, which tasks list it in their blockedBy. */\nexport function deriveBlocks(taskList: readonly Task[]): Map<number, number[]> {\n const blocks = new Map<number, number[]>();\n for (const task of taskList) {\n for (const dep of task.blockedBy ?? []) {\n const dependents = blocks.get(dep) ?? [];\n dependents.push(task.id);\n blocks.set(dep, dependents);\n }\n }\n return blocks;\n}\n\n/**\n * Blocking dependencies of a task that are not yet resolved.\n *\n * `completed` clears a dependency; `failed` deliberately does not, so a failed\n * delegation keeps its dependents blocked instead of silently releasing work\n * that was never actually finished.\n */\nexport function unresolvedBlockers(taskList: readonly Task[], task: Task): number[] {\n return (task.blockedBy ?? []).filter((dep) => {\n const blocker = taskList.find((candidate) => candidate.id === dep);\n if (!blocker) return false;\n return blocker.status !== COMPLETED_STATUS && blocker.status !== DELETED_STATUS;\n });\n}\n\nexport function isBlocked(taskList: readonly Task[], task: Task): boolean {\n return unresolvedBlockers(taskList, task).length > 0;\n}\n"],"mappings":"mEAEA,MAAM,EAAmC,YACnC,EAAiC,UAGvC,SAAgB,EAAmB,EAAoC,CACrE,IAAM,EAAU,EAAS,OAAQ,GAAS,EAAK,SAAW,CAAc,EACxE,OAAO,EAAQ,OAAS,GAAK,EAAQ,MAAO,GAAS,EAAK,SAAW,CAAgB,CACvF,CAQA,SAAgB,EAAY,EAA2B,EAAgB,EAA0C,CAC/G,IAAM,EAAQ,IAAI,IAClB,IAAK,IAAM,KAAQ,EACb,EAAK,KAAO,EACd,EAAM,IAAI,EAAK,GAAI,CAAC,GAAG,IAAI,IAAI,CAAC,GAAI,EAAK,WAAa,CAAC,EAAI,GAAG,CAAY,CAAC,CAAC,CAAC,EAE7E,EAAM,IAAI,EAAK,GAAI,EAAK,UAAY,CAAC,GAAG,EAAK,SAAS,EAAI,CAAC,CAAC,EAIhE,IAAM,EAAW,IAAI,IACf,EAAU,IAAI,IACd,EAAgB,GAA0B,CAC9C,GAAI,EAAS,IAAI,CAAI,EAAG,MAAO,GAC/B,GAAI,EAAQ,IAAI,CAAI,EAAG,MAAO,GAC9B,EAAS,IAAI,CAAI,EACjB,IAAK,IAAM,KAAQ,EAAM,IAAI,CAAI,GAAK,CAAC,EACrC,GAAI,EAAa,CAAI,EAAG,MAAO,GAIjC,OAFA,EAAS,OAAO,CAAI,EACpB,EAAQ,IAAI,CAAI,EACT,EACT,EAEA,IAAK,IAAM,KAAQ,EAAM,KAAK,EAC5B,GAAI,EAAa,CAAI,EAAG,MAAO,GAEjC,MAAO,EACT,CAGA,SAAgB,EAAa,EAAkD,CAC7E,IAAM,EAAS,IAAI,IACnB,IAAK,IAAM,KAAQ,EACjB,IAAK,IAAM,KAAO,EAAK,WAAa,CAAC,EAAG,CACtC,IAAM,EAAa,EAAO,IAAI,CAAG,GAAK,CAAC,EACvC,EAAW,KAAK,EAAK,EAAE,EACvB,EAAO,IAAI,EAAK,CAAU,CAC5B,CAEF,OAAO,CACT,CASA,SAAgB,EAAmB,EAA2B,EAAsB,CAClF,OAAQ,EAAK,WAAa,CAAC,EAAA,CAAG,OAAQ,GAAQ,CAC5C,IAAM,EAAU,EAAS,KAAM,GAAc,EAAU,KAAO,CAAG,EAEjE,OADK,EACE,EAAQ,SAAW,GAAoB,EAAQ,SAAW,EAD5C,EAEvB,CAAC,CACH,CAEA,SAAgB,EAAU,EAA2B,EAAqB,CACxE,OAAO,EAAmB,EAAU,CAAI,CAAC,CAAC,OAAS,CACrD"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Task } from "./types.cjs";
|
|
2
|
+
//#region src/store/taskGraph.d.ts
|
|
3
|
+
/** True when a non-empty list has no visible work left to finish. */
|
|
4
|
+
declare function isTaskListComplete(taskList: readonly Task[]): boolean;
|
|
5
|
+
/**
|
|
6
|
+
* Would merging `newBlockedBy` into `taskId`'s dependencies introduce a cycle?
|
|
7
|
+
*
|
|
8
|
+
* Takes the proposed additions explicitly so the reducer can ask the question
|
|
9
|
+
* before mutating anything.
|
|
10
|
+
*/
|
|
11
|
+
declare function detectCycle(taskList: readonly Task[], taskId: number, newBlockedBy: readonly number[]): boolean;
|
|
12
|
+
/** Inverse adjacency: for each task, which tasks list it in their blockedBy. */
|
|
13
|
+
declare function deriveBlocks(taskList: readonly Task[]): Map<number, number[]>;
|
|
14
|
+
/**
|
|
15
|
+
* Blocking dependencies of a task that are not yet resolved.
|
|
16
|
+
*
|
|
17
|
+
* `completed` clears a dependency; `failed` deliberately does not, so a failed
|
|
18
|
+
* delegation keeps its dependents blocked instead of silently releasing work
|
|
19
|
+
* that was never actually finished.
|
|
20
|
+
*/
|
|
21
|
+
declare function unresolvedBlockers(taskList: readonly Task[], task: Task): number[];
|
|
22
|
+
declare function isBlocked(taskList: readonly Task[], task: Task): boolean;
|
|
23
|
+
//#endregion
|
|
24
|
+
export { deriveBlocks, detectCycle, isBlocked, isTaskListComplete, unresolvedBlockers };
|
|
25
|
+
//# sourceMappingURL=taskGraph.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"taskGraph.d.cts","names":[],"sources":["../../src/store/taskGraph.ts"],"mappings":";;;iBAMgB,mBAAmB,mBAAmB;;;;;;;iBAWtC,YAAY,mBAAmB,QAAQ,gBAAgB;;iBA+BvD,aAAa,mBAAmB,SAAS;;;;;;;;iBAmBzC,mBAAmB,mBAAmB,QAAQ,MAAM;iBAQpD,UAAU,mBAAmB,QAAQ,MAAM"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Task } from "./types.mjs";
|
|
2
|
+
//#region src/store/taskGraph.d.ts
|
|
3
|
+
/** True when a non-empty list has no visible work left to finish. */
|
|
4
|
+
declare function isTaskListComplete(taskList: readonly Task[]): boolean;
|
|
5
|
+
/**
|
|
6
|
+
* Would merging `newBlockedBy` into `taskId`'s dependencies introduce a cycle?
|
|
7
|
+
*
|
|
8
|
+
* Takes the proposed additions explicitly so the reducer can ask the question
|
|
9
|
+
* before mutating anything.
|
|
10
|
+
*/
|
|
11
|
+
declare function detectCycle(taskList: readonly Task[], taskId: number, newBlockedBy: readonly number[]): boolean;
|
|
12
|
+
/** Inverse adjacency: for each task, which tasks list it in their blockedBy. */
|
|
13
|
+
declare function deriveBlocks(taskList: readonly Task[]): Map<number, number[]>;
|
|
14
|
+
/**
|
|
15
|
+
* Blocking dependencies of a task that are not yet resolved.
|
|
16
|
+
*
|
|
17
|
+
* `completed` clears a dependency; `failed` deliberately does not, so a failed
|
|
18
|
+
* delegation keeps its dependents blocked instead of silently releasing work
|
|
19
|
+
* that was never actually finished.
|
|
20
|
+
*/
|
|
21
|
+
declare function unresolvedBlockers(taskList: readonly Task[], task: Task): number[];
|
|
22
|
+
declare function isBlocked(taskList: readonly Task[], task: Task): boolean;
|
|
23
|
+
//#endregion
|
|
24
|
+
export { deriveBlocks, detectCycle, isBlocked, isTaskListComplete, unresolvedBlockers };
|
|
25
|
+
//# sourceMappingURL=taskGraph.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"taskGraph.d.mts","names":[],"sources":["../../src/store/taskGraph.ts"],"mappings":";;;iBAMgB,mBAAmB,mBAAmB;;;;;;;iBAWtC,YAAY,mBAAmB,QAAQ,gBAAgB;;iBA+BvD,aAAa,mBAAmB,SAAS;;;;;;;;iBAmBzC,mBAAmB,mBAAmB,QAAQ,MAAM;iBAQpD,UAAU,mBAAmB,QAAQ,MAAM"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=`completed`,t=`deleted`;function n(n){let r=n.filter(e=>e.status!==t);return r.length>0&&r.every(t=>t.status===e)}function r(e,t,n){let r=new Map;for(let i of e)i.id===t?r.set(i.id,[...new Set([...i.blockedBy??[],...n])]):r.set(i.id,i.blockedBy?[...i.blockedBy]:[]);let i=new Set,a=new Set,o=e=>{if(i.has(e))return!0;if(a.has(e))return!1;i.add(e);for(let t of r.get(e)??[])if(o(t))return!0;return i.delete(e),a.add(e),!1};for(let e of r.keys())if(o(e))return!0;return!1}function i(e){let t=new Map;for(let n of e)for(let e of n.blockedBy??[]){let r=t.get(e)??[];r.push(n.id),t.set(e,r)}return t}function a(n,r){return(r.blockedBy??[]).filter(r=>{let i=n.find(e=>e.id===r);return i?i.status!==e&&i.status!==t:!1})}function o(e,t){return a(e,t).length>0}export{i as deriveBlocks,r as detectCycle,o as isBlocked,n as isTaskListComplete,a as unresolvedBlockers};
|
|
2
|
+
//# sourceMappingURL=taskGraph.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"taskGraph.mjs","names":[],"sources":["../../src/store/taskGraph.ts"],"sourcesContent":["import type { Task } from './types.ts';\n\nconst COMPLETED_STATUS: Task['status'] = 'completed';\nconst DELETED_STATUS: Task['status'] = 'deleted';\n\n/** True when a non-empty list has no visible work left to finish. */\nexport function isTaskListComplete(taskList: readonly Task[]): boolean {\n const visible = taskList.filter((task) => task.status !== DELETED_STATUS);\n return visible.length > 0 && visible.every((task) => task.status === COMPLETED_STATUS);\n}\n\n/**\n * Would merging `newBlockedBy` into `taskId`'s dependencies introduce a cycle?\n *\n * Takes the proposed additions explicitly so the reducer can ask the question\n * before mutating anything.\n */\nexport function detectCycle(taskList: readonly Task[], taskId: number, newBlockedBy: readonly number[]): boolean {\n const edges = new Map<number, number[]>();\n for (const task of taskList) {\n if (task.id === taskId) {\n edges.set(task.id, [...new Set([...(task.blockedBy ?? []), ...newBlockedBy])]);\n } else {\n edges.set(task.id, task.blockedBy ? [...task.blockedBy] : []);\n }\n }\n\n const visiting = new Set<number>();\n const visited = new Set<number>();\n const hasCycleFrom = (node: number): boolean => {\n if (visiting.has(node)) return true;\n if (visited.has(node)) return false;\n visiting.add(node);\n for (const next of edges.get(node) ?? []) {\n if (hasCycleFrom(next)) return true;\n }\n visiting.delete(node);\n visited.add(node);\n return false;\n };\n\n for (const node of edges.keys()) {\n if (hasCycleFrom(node)) return true;\n }\n return false;\n}\n\n/** Inverse adjacency: for each task, which tasks list it in their blockedBy. */\nexport function deriveBlocks(taskList: readonly Task[]): Map<number, number[]> {\n const blocks = new Map<number, number[]>();\n for (const task of taskList) {\n for (const dep of task.blockedBy ?? []) {\n const dependents = blocks.get(dep) ?? [];\n dependents.push(task.id);\n blocks.set(dep, dependents);\n }\n }\n return blocks;\n}\n\n/**\n * Blocking dependencies of a task that are not yet resolved.\n *\n * `completed` clears a dependency; `failed` deliberately does not, so a failed\n * delegation keeps its dependents blocked instead of silently releasing work\n * that was never actually finished.\n */\nexport function unresolvedBlockers(taskList: readonly Task[], task: Task): number[] {\n return (task.blockedBy ?? []).filter((dep) => {\n const blocker = taskList.find((candidate) => candidate.id === dep);\n if (!blocker) return false;\n return blocker.status !== COMPLETED_STATUS && blocker.status !== DELETED_STATUS;\n });\n}\n\nexport function isBlocked(taskList: readonly Task[], task: Task): boolean {\n return unresolvedBlockers(taskList, task).length > 0;\n}\n"],"mappings":"AAEA,MAAM,EAAmC,YACnC,EAAiC,UAGvC,SAAgB,EAAmB,EAAoC,CACrE,IAAM,EAAU,EAAS,OAAQ,GAAS,EAAK,SAAW,CAAc,EACxE,OAAO,EAAQ,OAAS,GAAK,EAAQ,MAAO,GAAS,EAAK,SAAW,CAAgB,CACvF,CAQA,SAAgB,EAAY,EAA2B,EAAgB,EAA0C,CAC/G,IAAM,EAAQ,IAAI,IAClB,IAAK,IAAM,KAAQ,EACb,EAAK,KAAO,EACd,EAAM,IAAI,EAAK,GAAI,CAAC,GAAG,IAAI,IAAI,CAAC,GAAI,EAAK,WAAa,CAAC,EAAI,GAAG,CAAY,CAAC,CAAC,CAAC,EAE7E,EAAM,IAAI,EAAK,GAAI,EAAK,UAAY,CAAC,GAAG,EAAK,SAAS,EAAI,CAAC,CAAC,EAIhE,IAAM,EAAW,IAAI,IACf,EAAU,IAAI,IACd,EAAgB,GAA0B,CAC9C,GAAI,EAAS,IAAI,CAAI,EAAG,MAAO,GAC/B,GAAI,EAAQ,IAAI,CAAI,EAAG,MAAO,GAC9B,EAAS,IAAI,CAAI,EACjB,IAAK,IAAM,KAAQ,EAAM,IAAI,CAAI,GAAK,CAAC,EACrC,GAAI,EAAa,CAAI,EAAG,MAAO,GAIjC,OAFA,EAAS,OAAO,CAAI,EACpB,EAAQ,IAAI,CAAI,EACT,EACT,EAEA,IAAK,IAAM,KAAQ,EAAM,KAAK,EAC5B,GAAI,EAAa,CAAI,EAAG,MAAO,GAEjC,MAAO,EACT,CAGA,SAAgB,EAAa,EAAkD,CAC7E,IAAM,EAAS,IAAI,IACnB,IAAK,IAAM,KAAQ,EACjB,IAAK,IAAM,KAAO,EAAK,WAAa,CAAC,EAAG,CACtC,IAAM,EAAa,EAAO,IAAI,CAAG,GAAK,CAAC,EACvC,EAAW,KAAK,EAAK,EAAE,EACvB,EAAO,IAAI,EAAK,CAAU,CAC5B,CAEF,OAAO,CACT,CASA,SAAgB,EAAmB,EAA2B,EAAsB,CAClF,OAAQ,EAAK,WAAa,CAAC,EAAA,CAAG,OAAQ,GAAQ,CAC5C,IAAM,EAAU,EAAS,KAAM,GAAc,EAAU,KAAO,CAAG,EAEjE,OADK,EACE,EAAQ,SAAW,GAAoB,EAAQ,SAAW,EAD5C,EAEvB,CAAC,CACH,CAEA,SAAgB,EAAU,EAA2B,EAAqB,CACxE,OAAO,EAAmB,EAAU,CAAI,CAAC,CAAC,OAAS,CACrD"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("../logSinkTelemetry.cjs"),n=require("./processLiveness.cjs"),r=require("./types.cjs"),i=require("./paths.cjs");let a=require("node:path");a=e.__toESM(a,1);let o=require("node:fs");o=e.__toESM(o,1);const s=`utf8`,c=`ENOENT`,l=`store.path`;function u(e){return new Promise(t=>setTimeout(t,e))}function d(e){if(!e||typeof e!=`object`)return r.emptyDocument();let t=e;if(!Array.isArray(t.tasks))return r.emptyDocument();let n=t.tasks.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`number`),i=n.reduce((e,t)=>Math.max(e,t.id),0);return{version:typeof t.version==`number`?t.version:1,rev:typeof t.rev==`number`?t.rev:0,nextId:typeof t.nextId==`number`&&t.nextId>i?t.nextId:i+1,tasks:n}}var f=class{storePath;cwd;env;cached=r.emptyDocument();lastKnownRev=-1;watcher;pollTimer;debounceTimer;listeners=new Set;pollIntervalMs;lockTimeoutMs;report;constructor(e={}){this.cwd=e.cwd??process.cwd(),this.env=e.env??process.env,this.storePath=e.storePath??i.resolveStorePath(this.cwd,this.env),this.pollIntervalMs=e.pollIntervalMs??2e3,this.lockTimeoutMs=e.lockTimeoutMs??2e3,this.report=e.report}configureSession(e){this.env.DOOM_TASK_STORE?.trim()||(this.stopWatching(),this.storePath=i.resolveStorePath(this.cwd,this.env,e),this.cached=r.emptyDocument(),this.lastKnownRev=-1)}get snapshot(){return this.cached}read(){try{let e=o.default.readFileSync(this.storePath,s);this.cached=d(JSON.parse(e))}catch(e){e.code!==c&&this.report?.error(t.TASK_EVENT.storeReadFailed,e,{[l]:this.storePath}),this.cached=r.emptyDocument()}return this.lastKnownRev=this.cached.rev,this.cached}async mutate(e){let t=await this.acquireLock();try{let t=this.read(),n=e(t);return n.document?{document:this.write(n.document),value:n.value}:{document:t,value:n.value}}finally{t()}}write(e){let t={...e,version:1,rev:e.rev+1};o.default.mkdirSync(a.default.dirname(this.storePath),{recursive:!0});let n=i.tempPathFor(this.storePath);return o.default.writeFileSync(n,`${JSON.stringify(t,void 0,2)}\n`,s),o.default.renameSync(n,this.storePath),this.cached=t,this.lastKnownRev=t.rev,t}async acquireLock(){let e=i.lockPathFor(this.storePath);o.default.mkdirSync(a.default.dirname(this.storePath),{recursive:!0});let n=Date.now()+this.lockTimeoutMs;for(;;)try{let t=o.default.openSync(e,`wx`);return o.default.writeSync(t,JSON.stringify({pid:process.pid,time:Date.now()})),o.default.closeSync(t),()=>o.default.rmSync(e,{force:!0})}catch(r){if(r.code!==`EEXIST`)throw r;if(Date.now()>=n)return this.report?.warn(t.TASK_EVENT.storeLockTimeout,Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),{[l]:this.storePath}),()=>{};this.breakStaleLock(e),await u(10+Math.random()*60)}}breakStaleLock(e){try{let t=JSON.parse(o.default.readFileSync(e,s)),r=typeof t.time==`number`&&Date.now()-t.time>1e4,i=typeof t.pid==`number`&&!n.isProcessAlive(t.pid);return!r&&!i?!1:(o.default.unlinkSync(e),!0)}catch(n){return n.code!==c&&this.report?.warn(t.TASK_EVENT.storeLockBreakFailed,n,{[l]:e}),!1}}onExternalChange(e){return this.listeners.add(e),this.startWatching(),()=>{this.listeners.delete(e),this.listeners.size===0&&this.stopWatching()}}startWatching(){if(this.watcher||this.pollTimer)return;let e=a.default.dirname(this.storePath),n=a.default.basename(this.storePath);try{o.default.mkdirSync(e,{recursive:!0}),this.watcher=o.default.watch(e,(e,t)=>{t&&t!==n||this.scheduleCheck()})}catch(e){this.report?.warn(t.TASK_EVENT.storeWatchFailed,e,{[l]:this.storePath})}this.pollTimer=setInterval(()=>this.checkForChange(),this.pollIntervalMs),this.pollTimer.unref?.()}scheduleCheck(){clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>this.checkForChange(),150),this.debounceTimer.unref?.()}checkForChange(){let e=this.lastKnownRev,n=this.read();if(n.rev!==e)for(let e of this.listeners)try{e(n)}catch(e){this.report?.error(t.TASK_EVENT.storeListenerFailed,e,{[l]:this.storePath})}}stopWatching(){this.watcher?.close(),this.watcher=void 0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=void 0,clearTimeout(this.debounceTimer),this.debounceTimer=void 0}dispose(){this.listeners.clear(),this.stopWatching()}};exports.TaskStore=f;
|
|
2
|
+
//# sourceMappingURL=taskStore.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"taskStore.cjs","names":["emptyDocument","resolveStorePath","fs","TASK_EVENT","path","tempPathFor","lockPathFor","isProcessAlive"],"sources":["../../src/store/taskStore.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { TASK_EVENT, type TaskFailureReporter } from '../logSinkTelemetry.ts';\nimport { lockPathFor, resolveStorePath, STORE_PATH_ENV, tempPathFor } from './paths.ts';\nimport { isProcessAlive } from './processLiveness.ts';\nimport { emptyDocument, STORE_SCHEMA_VERSION, type Task, type TaskDocument } from './types.ts';\n\nconst LOCK_TIMEOUT_MS = 2000;\nconst LOCK_STALE_MS = 10_000;\nconst LOCK_RETRY_BASE_MS = 10;\nconst LOCK_RETRY_MAX_MS = 60;\nconst WATCH_DEBOUNCE_MS = 150;\nconst POLL_INTERVAL_MS = 2000;\nconst UTF8_ENCODING = 'utf8';\nconst MISSING_FILE_CODE = 'ENOENT';\nconst LOCK_EXISTS_CODE = 'EEXIST';\nconst STORE_PATH_ATTRIBUTE = 'store.path';\n\nexport interface TaskStoreOptions {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n storePath?: string;\n /** Backstop poll cadence for change detection. Lowered in tests so they do\n * not depend on `fs.watch`, whose delivery timing is platform-dependent. */\n pollIntervalMs?: number;\n /** How long to wait for the advisory lock before proceeding lock-free. */\n lockTimeoutMs?: number;\n /** Where swallowed failures go, so silent degradation stays visible. */\n report?: TaskFailureReporter;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Coerce arbitrary parsed JSON into a valid document.\n *\n * A corrupt or truncated store must not take the session down: the worst\n * acceptable outcome is starting from an empty list, never a crash on startup.\n */\nfunction normalizeDocument(parsed: unknown): TaskDocument {\n if (!parsed || typeof parsed !== 'object') return emptyDocument();\n const candidate = parsed as Partial<TaskDocument>;\n if (!Array.isArray(candidate.tasks)) return emptyDocument();\n\n const tasks = candidate.tasks.filter(\n (task): task is Task => Boolean(task) && typeof task === 'object' && typeof (task as Task).id === 'number',\n );\n const maxId = tasks.reduce((max, task) => Math.max(max, task.id), 0);\n return {\n version: typeof candidate.version === 'number' ? candidate.version : STORE_SCHEMA_VERSION,\n rev: typeof candidate.rev === 'number' ? candidate.rev : 0,\n nextId: typeof candidate.nextId === 'number' && candidate.nextId > maxId ? candidate.nextId : maxId + 1,\n tasks,\n };\n}\n\n/**\n * File-backed task store shared by one root session and its delegated children.\n *\n * Durability model: the JSON file is the source of truth. Mutations are\n * read-modify-write under an advisory lock so concurrent delegated processes\n * cannot clobber each other, and writes land via temp-file rename so a\n * crash mid-write can never leave a partial document behind.\n */\nexport class TaskStore {\n storePath: string;\n\n private readonly cwd: string;\n private readonly env: NodeJS.ProcessEnv;\n private cached: TaskDocument = emptyDocument();\n private lastKnownRev = -1;\n private watcher?: fs.FSWatcher;\n private pollTimer?: NodeJS.Timeout;\n private debounceTimer?: NodeJS.Timeout;\n private readonly listeners = new Set<(document: TaskDocument) => void>();\n private readonly pollIntervalMs: number;\n private readonly lockTimeoutMs: number;\n private readonly report?: TaskFailureReporter;\n\n constructor(options: TaskStoreOptions = {}) {\n this.cwd = options.cwd ?? process.cwd();\n this.env = options.env ?? process.env;\n this.storePath = options.storePath ?? resolveStorePath(this.cwd, this.env);\n this.pollIntervalMs = options.pollIntervalMs ?? POLL_INTERVAL_MS;\n this.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;\n this.report = options.report;\n }\n\n /** Bind a default store to the current session tree before reading or watching it. */\n configureSession(sessionKey: string): void {\n if (this.env[STORE_PATH_ENV]?.trim()) return;\n this.stopWatching();\n this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);\n this.cached = emptyDocument();\n this.lastKnownRev = -1;\n }\n\n /** Last document read from disk, without hitting the filesystem. */\n get snapshot(): TaskDocument {\n return this.cached;\n }\n\n read(): TaskDocument {\n try {\n const raw = fs.readFileSync(this.storePath, UTF8_ENCODING);\n this.cached = normalizeDocument(JSON.parse(raw));\n } catch (error) {\n // A missing file is the normal state before the first write. Anything\n // else means the task list just silently became empty, which is worth a\n // record: unreadable or corrupt JSON looks identical to \"no tasks yet\".\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n this.cached = emptyDocument();\n }\n this.lastKnownRev = this.cached.rev;\n return this.cached;\n }\n\n /**\n * Apply a mutation under the store lock.\n *\n * `mutate` receives the freshest on-disk document and returns either the next\n * document to commit or `undefined` for a read-only action (list/get), which\n * skips the write entirely so queries never bump `rev`.\n */\n async mutate<T>(\n mutate: (document: TaskDocument) => { document?: TaskDocument; value: T },\n ): Promise<{ document: TaskDocument; value: T }> {\n const release = await this.acquireLock();\n try {\n const current = this.read();\n const outcome = mutate(current);\n if (!outcome.document) {\n return { document: current, value: outcome.value };\n }\n const committed = this.write(outcome.document);\n return { document: committed, value: outcome.value };\n } finally {\n release();\n }\n }\n\n private write(document: TaskDocument): TaskDocument {\n const next: TaskDocument = { ...document, version: STORE_SCHEMA_VERSION, rev: document.rev + 1 };\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const temp = tempPathFor(this.storePath);\n fs.writeFileSync(temp, `${JSON.stringify(next, undefined, 2)}\\n`, UTF8_ENCODING);\n fs.renameSync(temp, this.storePath);\n this.cached = next;\n this.lastKnownRev = next.rev;\n return next;\n }\n\n private async acquireLock(): Promise<() => void> {\n const lockPath = lockPathFor(this.storePath);\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const deadline = Date.now() + this.lockTimeoutMs;\n\n for (;;) {\n try {\n const handle = fs.openSync(lockPath, 'wx');\n fs.writeSync(handle, JSON.stringify({ pid: process.pid, time: Date.now() }));\n fs.closeSync(handle);\n return () => fs.rmSync(lockPath, { force: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== LOCK_EXISTS_CODE) throw error;\n // The deadline is checked before breaking a stale lock so a peer that\n // keeps recreating one cannot spin this loop without bound.\n if (Date.now() >= deadline) {\n // Proceeding lock-free beats stalling the agent: the rename is atomic,\n // so the worst case is a lost concurrent update, not a corrupt file.\n // Reported because a lost update here can strand a delegation.\n this.report?.warn(\n TASK_EVENT.storeLockTimeout,\n new Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),\n { [STORE_PATH_ATTRIBUTE]: this.storePath },\n );\n return () => {};\n }\n // Clearing a dead holder's lock still goes through the backoff. Yielding\n // on every iteration is what stops a peer that keeps recreating the\n // lock from turning this into a spin.\n this.breakStaleLock(lockPath);\n await sleep(LOCK_RETRY_BASE_MS + Math.random() * LOCK_RETRY_MAX_MS);\n }\n }\n }\n\n /** Remove a lock left behind by a dead process or one held implausibly long. */\n private breakStaleLock(lockPath: string): boolean {\n try {\n const holder = JSON.parse(fs.readFileSync(lockPath, UTF8_ENCODING)) as { pid?: number; time?: number };\n const expired = typeof holder.time === 'number' && Date.now() - holder.time > LOCK_STALE_MS;\n const dead = typeof holder.pid === 'number' && !isProcessAlive(holder.pid);\n if (!expired && !dead) return false;\n fs.unlinkSync(lockPath);\n return true;\n } catch (error) {\n // Losing the race to another breaker is normal; a persistent failure here\n // shows up as the lock timeout above, so this stays a warning.\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.warn(TASK_EVENT.storeLockBreakFailed, error, { [STORE_PATH_ATTRIBUTE]: lockPath });\n }\n return false;\n }\n }\n\n /**\n * Notify when another process changes the store.\n *\n * `fs.watch` alone is unreliable across the rename-based write (and on some\n * network filesystems), so a slow poll backs it up. Writes made by this\n * process are filtered out by revision so the UI does not redraw twice.\n */\n onExternalChange(listener: (document: TaskDocument) => void): () => void {\n this.listeners.add(listener);\n this.startWatching();\n return () => {\n this.listeners.delete(listener);\n if (this.listeners.size === 0) this.stopWatching();\n };\n }\n\n private startWatching(): void {\n if (this.watcher || this.pollTimer) return;\n const directory = path.dirname(this.storePath);\n const fileName = path.basename(this.storePath);\n\n try {\n fs.mkdirSync(directory, { recursive: true });\n this.watcher = fs.watch(directory, (_event, changed) => {\n if (changed && changed !== fileName) return;\n this.scheduleCheck();\n });\n } catch (error) {\n // Polling still covers change detection, just more slowly.\n this.report?.warn(TASK_EVENT.storeWatchFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n\n this.pollTimer = setInterval(() => this.checkForChange(), this.pollIntervalMs);\n this.pollTimer.unref?.();\n }\n\n private scheduleCheck(): void {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => this.checkForChange(), WATCH_DEBOUNCE_MS);\n this.debounceTimer.unref?.();\n }\n\n private checkForChange(): void {\n const previousRev = this.lastKnownRev;\n const document = this.read();\n if (document.rev === previousRev) return;\n for (const listener of this.listeners) {\n try {\n listener(document);\n } catch (error) {\n // This runs from a timer and from the fs.watch callback, so an\n // unguarded listener throw is an uncaught exception that takes the\n // harness down rather than a handled render failure.\n this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n }\n }\n\n private stopWatching(): void {\n this.watcher?.close();\n this.watcher = undefined;\n if (this.pollTimer) clearInterval(this.pollTimer);\n this.pollTimer = undefined;\n clearTimeout(this.debounceTimer);\n this.debounceTimer = undefined;\n }\n\n dispose(): void {\n this.listeners.clear();\n this.stopWatching();\n }\n}\n"],"mappings":"wUAOA,MAMM,EAAgB,OAChB,EAAoB,SAEpB,EAAuB,aAe7B,SAAS,EAAM,EAA2B,CACxC,OAAO,IAAI,QAAS,GAAY,WAAW,EAAS,CAAE,CAAC,CACzD,CAQA,SAAS,EAAkB,EAA+B,CACxD,GAAI,CAAC,GAAU,OAAO,GAAW,SAAU,OAAOA,EAAAA,cAAc,EAChE,IAAM,EAAY,EAClB,GAAI,CAAC,MAAM,QAAQ,EAAU,KAAK,EAAG,OAAOA,EAAAA,cAAc,EAE1D,IAAM,EAAQ,EAAU,MAAM,OAC3B,GAAuB,EAAQ,GAAS,OAAO,GAAS,UAAY,OAAQ,EAAc,IAAO,QACpG,EACM,EAAQ,EAAM,QAAQ,EAAK,IAAS,KAAK,IAAI,EAAK,EAAK,EAAE,EAAG,CAAC,EACnE,MAAO,CACL,QAAS,OAAO,EAAU,SAAY,SAAW,EAAU,QAAA,EAC3D,IAAK,OAAO,EAAU,KAAQ,SAAW,EAAU,IAAM,EACzD,OAAQ,OAAO,EAAU,QAAW,UAAY,EAAU,OAAS,EAAQ,EAAU,OAAS,EAAQ,EACtG,OACF,CACF,CAUA,IAAa,EAAb,KAAuB,CACrB,UAEA,IACA,IACA,OAA+BA,EAAAA,cAAc,EAC7C,aAAuB,GACvB,QACA,UACA,cACA,UAA6B,IAAI,IACjC,eACA,cACA,OAEA,YAAY,EAA4B,CAAC,EAAG,CAC1C,KAAK,IAAM,EAAQ,KAAO,QAAQ,IAAI,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S,EAAO,CAId,KAAK,QAAQ,MAAMA,EAAAA,WAAW,oBAAqB,EAAO,EAAG,GAAuB,KAAK,SAAU,CAAC,CACtG,CAEJ,CAEA,cAA6B,CAC3B,KAAK,SAAS,MAAM,EACpB,KAAK,QAAU,IAAA,GACX,KAAK,WAAW,cAAc,KAAK,SAAS,EAChD,KAAK,UAAY,IAAA,GACjB,aAAa,KAAK,aAAa,EAC/B,KAAK,cAAgB,IAAA,EACvB,CAEA,SAAgB,CACd,KAAK,UAAU,MAAM,EACrB,KAAK,aAAa,CACpB,CACF"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { TaskFailureReporter } from "../logSinkTelemetry.cjs";
|
|
2
|
+
import { TaskDocument } from "./types.cjs";
|
|
3
|
+
//#region src/store/taskStore.d.ts
|
|
4
|
+
interface TaskStoreOptions {
|
|
5
|
+
cwd?: string;
|
|
6
|
+
env?: NodeJS.ProcessEnv;
|
|
7
|
+
storePath?: string;
|
|
8
|
+
/** Backstop poll cadence for change detection. Lowered in tests so they do
|
|
9
|
+
* not depend on `fs.watch`, whose delivery timing is platform-dependent. */
|
|
10
|
+
pollIntervalMs?: number;
|
|
11
|
+
/** How long to wait for the advisory lock before proceeding lock-free. */
|
|
12
|
+
lockTimeoutMs?: number;
|
|
13
|
+
/** Where swallowed failures go, so silent degradation stays visible. */
|
|
14
|
+
report?: TaskFailureReporter;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* File-backed task store shared by one root session and its delegated children.
|
|
18
|
+
*
|
|
19
|
+
* Durability model: the JSON file is the source of truth. Mutations are
|
|
20
|
+
* read-modify-write under an advisory lock so concurrent delegated processes
|
|
21
|
+
* cannot clobber each other, and writes land via temp-file rename so a
|
|
22
|
+
* crash mid-write can never leave a partial document behind.
|
|
23
|
+
*/
|
|
24
|
+
declare class TaskStore {
|
|
25
|
+
storePath: string;
|
|
26
|
+
private readonly cwd;
|
|
27
|
+
private readonly env;
|
|
28
|
+
private cached;
|
|
29
|
+
private lastKnownRev;
|
|
30
|
+
private watcher?;
|
|
31
|
+
private pollTimer?;
|
|
32
|
+
private debounceTimer?;
|
|
33
|
+
private readonly listeners;
|
|
34
|
+
private readonly pollIntervalMs;
|
|
35
|
+
private readonly lockTimeoutMs;
|
|
36
|
+
private readonly report?;
|
|
37
|
+
constructor(options?: TaskStoreOptions);
|
|
38
|
+
/** Bind a default store to the current session tree before reading or watching it. */
|
|
39
|
+
configureSession(sessionKey: string): void;
|
|
40
|
+
/** Last document read from disk, without hitting the filesystem. */
|
|
41
|
+
get snapshot(): TaskDocument;
|
|
42
|
+
read(): TaskDocument;
|
|
43
|
+
/**
|
|
44
|
+
* Apply a mutation under the store lock.
|
|
45
|
+
*
|
|
46
|
+
* `mutate` receives the freshest on-disk document and returns either the next
|
|
47
|
+
* document to commit or `undefined` for a read-only action (list/get), which
|
|
48
|
+
* skips the write entirely so queries never bump `rev`.
|
|
49
|
+
*/
|
|
50
|
+
mutate<T>(mutate: (document: TaskDocument) => {
|
|
51
|
+
document?: TaskDocument;
|
|
52
|
+
value: T;
|
|
53
|
+
}): Promise<{
|
|
54
|
+
document: TaskDocument;
|
|
55
|
+
value: T;
|
|
56
|
+
}>;
|
|
57
|
+
private write;
|
|
58
|
+
private acquireLock;
|
|
59
|
+
/** Remove a lock left behind by a dead process or one held implausibly long. */
|
|
60
|
+
private breakStaleLock;
|
|
61
|
+
/**
|
|
62
|
+
* Notify when another process changes the store.
|
|
63
|
+
*
|
|
64
|
+
* `fs.watch` alone is unreliable across the rename-based write (and on some
|
|
65
|
+
* network filesystems), so a slow poll backs it up. Writes made by this
|
|
66
|
+
* process are filtered out by revision so the UI does not redraw twice.
|
|
67
|
+
*/
|
|
68
|
+
onExternalChange(listener: (document: TaskDocument) => void): () => void;
|
|
69
|
+
private startWatching;
|
|
70
|
+
private scheduleCheck;
|
|
71
|
+
private checkForChange;
|
|
72
|
+
private stopWatching;
|
|
73
|
+
dispose(): void;
|
|
74
|
+
}
|
|
75
|
+
//#endregion
|
|
76
|
+
export { TaskStore, TaskStoreOptions };
|
|
77
|
+
//# sourceMappingURL=taskStore.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"taskStore.d.cts","names":[],"sources":["../../src/store/taskStore.ts"],"mappings":";;;UAkBiB;EACf;EACA,MAAM,OAAO;EACb;;;EAGA;;EAEA;;EAEA,SAAS;;;;;;;;;;cAsCE;EACX;mBAEiB;mBACA;UACT;UACA;UACA;UACA;UACA;mBACS;mBACA;mBACA;mBACA;EAEL,YAAA,UAAS;;EAUrB,iBAAiB;;MASb,YAAY;EAIhB,QAAQ;;;;;;;;EAwBF,OAAO,GACX,SAAS,UAAU;IAAmB,WAAW;IAAc,OAAO;MACrE;IAAU,UAAU;IAAc,OAAO;;UAepC;UAWM;;UAoCN;;;;;;;;EAyBR,iBAAiB,WAAW,UAAU;UAS9B;UAoBA;UAMA;UAgBA;EASR"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { TaskFailureReporter } from "../logSinkTelemetry.mjs";
|
|
2
|
+
import { TaskDocument } from "./types.mjs";
|
|
3
|
+
//#region src/store/taskStore.d.ts
|
|
4
|
+
interface TaskStoreOptions {
|
|
5
|
+
cwd?: string;
|
|
6
|
+
env?: NodeJS.ProcessEnv;
|
|
7
|
+
storePath?: string;
|
|
8
|
+
/** Backstop poll cadence for change detection. Lowered in tests so they do
|
|
9
|
+
* not depend on `fs.watch`, whose delivery timing is platform-dependent. */
|
|
10
|
+
pollIntervalMs?: number;
|
|
11
|
+
/** How long to wait for the advisory lock before proceeding lock-free. */
|
|
12
|
+
lockTimeoutMs?: number;
|
|
13
|
+
/** Where swallowed failures go, so silent degradation stays visible. */
|
|
14
|
+
report?: TaskFailureReporter;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* File-backed task store shared by one root session and its delegated children.
|
|
18
|
+
*
|
|
19
|
+
* Durability model: the JSON file is the source of truth. Mutations are
|
|
20
|
+
* read-modify-write under an advisory lock so concurrent delegated processes
|
|
21
|
+
* cannot clobber each other, and writes land via temp-file rename so a
|
|
22
|
+
* crash mid-write can never leave a partial document behind.
|
|
23
|
+
*/
|
|
24
|
+
declare class TaskStore {
|
|
25
|
+
storePath: string;
|
|
26
|
+
private readonly cwd;
|
|
27
|
+
private readonly env;
|
|
28
|
+
private cached;
|
|
29
|
+
private lastKnownRev;
|
|
30
|
+
private watcher?;
|
|
31
|
+
private pollTimer?;
|
|
32
|
+
private debounceTimer?;
|
|
33
|
+
private readonly listeners;
|
|
34
|
+
private readonly pollIntervalMs;
|
|
35
|
+
private readonly lockTimeoutMs;
|
|
36
|
+
private readonly report?;
|
|
37
|
+
constructor(options?: TaskStoreOptions);
|
|
38
|
+
/** Bind a default store to the current session tree before reading or watching it. */
|
|
39
|
+
configureSession(sessionKey: string): void;
|
|
40
|
+
/** Last document read from disk, without hitting the filesystem. */
|
|
41
|
+
get snapshot(): TaskDocument;
|
|
42
|
+
read(): TaskDocument;
|
|
43
|
+
/**
|
|
44
|
+
* Apply a mutation under the store lock.
|
|
45
|
+
*
|
|
46
|
+
* `mutate` receives the freshest on-disk document and returns either the next
|
|
47
|
+
* document to commit or `undefined` for a read-only action (list/get), which
|
|
48
|
+
* skips the write entirely so queries never bump `rev`.
|
|
49
|
+
*/
|
|
50
|
+
mutate<T>(mutate: (document: TaskDocument) => {
|
|
51
|
+
document?: TaskDocument;
|
|
52
|
+
value: T;
|
|
53
|
+
}): Promise<{
|
|
54
|
+
document: TaskDocument;
|
|
55
|
+
value: T;
|
|
56
|
+
}>;
|
|
57
|
+
private write;
|
|
58
|
+
private acquireLock;
|
|
59
|
+
/** Remove a lock left behind by a dead process or one held implausibly long. */
|
|
60
|
+
private breakStaleLock;
|
|
61
|
+
/**
|
|
62
|
+
* Notify when another process changes the store.
|
|
63
|
+
*
|
|
64
|
+
* `fs.watch` alone is unreliable across the rename-based write (and on some
|
|
65
|
+
* network filesystems), so a slow poll backs it up. Writes made by this
|
|
66
|
+
* process are filtered out by revision so the UI does not redraw twice.
|
|
67
|
+
*/
|
|
68
|
+
onExternalChange(listener: (document: TaskDocument) => void): () => void;
|
|
69
|
+
private startWatching;
|
|
70
|
+
private scheduleCheck;
|
|
71
|
+
private checkForChange;
|
|
72
|
+
private stopWatching;
|
|
73
|
+
dispose(): void;
|
|
74
|
+
}
|
|
75
|
+
//#endregion
|
|
76
|
+
export { TaskStore, TaskStoreOptions };
|
|
77
|
+
//# sourceMappingURL=taskStore.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"taskStore.d.mts","names":[],"sources":["../../src/store/taskStore.ts"],"mappings":";;;UAkBiB;EACf;EACA,MAAM,OAAO;EACb;;;EAGA;;EAEA;;EAEA,SAAS;;;;;;;;;;cAsCE;EACX;mBAEiB;mBACA;UACT;UACA;UACA;UACA;UACA;mBACS;mBACA;mBACA;mBACA;EAEL,YAAA,UAAS;;EAUrB,iBAAiB;;MASb,YAAY;EAIhB,QAAQ;;;;;;;;EAwBF,OAAO,GACX,SAAS,UAAU;IAAmB,WAAW;IAAc,OAAO;MACrE;IAAU,UAAU;IAAc,OAAO;;UAepC;UAWM;;UAoCN;;;;;;;;EAyBR,iBAAiB,WAAW,UAAU;UAS9B;UAoBA;UAMA;UAgBA;EASR"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{TASK_EVENT as e}from"../logSinkTelemetry.mjs";import{isProcessAlive as t}from"./processLiveness.mjs";import{emptyDocument as n}from"./types.mjs";import{lockPathFor as r,resolveStorePath as i,tempPathFor as a}from"./paths.mjs";import o from"node:path";import s from"node:fs";const c=`utf8`,l=`ENOENT`,u=`store.path`;function d(e){return new Promise(t=>setTimeout(t,e))}function f(e){if(!e||typeof e!=`object`)return n();let t=e;if(!Array.isArray(t.tasks))return n();let r=t.tasks.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`number`),i=r.reduce((e,t)=>Math.max(e,t.id),0);return{version:typeof t.version==`number`?t.version:1,rev:typeof t.rev==`number`?t.rev:0,nextId:typeof t.nextId==`number`&&t.nextId>i?t.nextId:i+1,tasks:r}}var p=class{storePath;cwd;env;cached=n();lastKnownRev=-1;watcher;pollTimer;debounceTimer;listeners=new Set;pollIntervalMs;lockTimeoutMs;report;constructor(e={}){this.cwd=e.cwd??process.cwd(),this.env=e.env??process.env,this.storePath=e.storePath??i(this.cwd,this.env),this.pollIntervalMs=e.pollIntervalMs??2e3,this.lockTimeoutMs=e.lockTimeoutMs??2e3,this.report=e.report}configureSession(e){this.env.DOOM_TASK_STORE?.trim()||(this.stopWatching(),this.storePath=i(this.cwd,this.env,e),this.cached=n(),this.lastKnownRev=-1)}get snapshot(){return this.cached}read(){try{let e=s.readFileSync(this.storePath,c);this.cached=f(JSON.parse(e))}catch(t){t.code!==l&&this.report?.error(e.storeReadFailed,t,{[u]:this.storePath}),this.cached=n()}return this.lastKnownRev=this.cached.rev,this.cached}async mutate(e){let t=await this.acquireLock();try{let t=this.read(),n=e(t);return n.document?{document:this.write(n.document),value:n.value}:{document:t,value:n.value}}finally{t()}}write(e){let t={...e,version:1,rev:e.rev+1};s.mkdirSync(o.dirname(this.storePath),{recursive:!0});let n=a(this.storePath);return s.writeFileSync(n,`${JSON.stringify(t,void 0,2)}\n`,c),s.renameSync(n,this.storePath),this.cached=t,this.lastKnownRev=t.rev,t}async acquireLock(){let t=r(this.storePath);s.mkdirSync(o.dirname(this.storePath),{recursive:!0});let n=Date.now()+this.lockTimeoutMs;for(;;)try{let e=s.openSync(t,`wx`);return s.writeSync(e,JSON.stringify({pid:process.pid,time:Date.now()})),s.closeSync(e),()=>s.rmSync(t,{force:!0})}catch(r){if(r.code!==`EEXIST`)throw r;if(Date.now()>=n)return this.report?.warn(e.storeLockTimeout,Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),{[u]:this.storePath}),()=>{};this.breakStaleLock(t),await d(10+Math.random()*60)}}breakStaleLock(n){try{let e=JSON.parse(s.readFileSync(n,c)),r=typeof e.time==`number`&&Date.now()-e.time>1e4,i=typeof e.pid==`number`&&!t(e.pid);return!r&&!i?!1:(s.unlinkSync(n),!0)}catch(t){return t.code!==l&&this.report?.warn(e.storeLockBreakFailed,t,{[u]:n}),!1}}onExternalChange(e){return this.listeners.add(e),this.startWatching(),()=>{this.listeners.delete(e),this.listeners.size===0&&this.stopWatching()}}startWatching(){if(this.watcher||this.pollTimer)return;let t=o.dirname(this.storePath),n=o.basename(this.storePath);try{s.mkdirSync(t,{recursive:!0}),this.watcher=s.watch(t,(e,t)=>{t&&t!==n||this.scheduleCheck()})}catch(t){this.report?.warn(e.storeWatchFailed,t,{[u]:this.storePath})}this.pollTimer=setInterval(()=>this.checkForChange(),this.pollIntervalMs),this.pollTimer.unref?.()}scheduleCheck(){clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>this.checkForChange(),150),this.debounceTimer.unref?.()}checkForChange(){let t=this.lastKnownRev,n=this.read();if(n.rev!==t)for(let t of this.listeners)try{t(n)}catch(t){this.report?.error(e.storeListenerFailed,t,{[u]:this.storePath})}}stopWatching(){this.watcher?.close(),this.watcher=void 0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=void 0,clearTimeout(this.debounceTimer),this.debounceTimer=void 0}dispose(){this.listeners.clear(),this.stopWatching()}};export{p as TaskStore};
|
|
2
|
+
//# sourceMappingURL=taskStore.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"taskStore.mjs","names":[],"sources":["../../src/store/taskStore.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { TASK_EVENT, type TaskFailureReporter } from '../logSinkTelemetry.ts';\nimport { lockPathFor, resolveStorePath, STORE_PATH_ENV, tempPathFor } from './paths.ts';\nimport { isProcessAlive } from './processLiveness.ts';\nimport { emptyDocument, STORE_SCHEMA_VERSION, type Task, type TaskDocument } from './types.ts';\n\nconst LOCK_TIMEOUT_MS = 2000;\nconst LOCK_STALE_MS = 10_000;\nconst LOCK_RETRY_BASE_MS = 10;\nconst LOCK_RETRY_MAX_MS = 60;\nconst WATCH_DEBOUNCE_MS = 150;\nconst POLL_INTERVAL_MS = 2000;\nconst UTF8_ENCODING = 'utf8';\nconst MISSING_FILE_CODE = 'ENOENT';\nconst LOCK_EXISTS_CODE = 'EEXIST';\nconst STORE_PATH_ATTRIBUTE = 'store.path';\n\nexport interface TaskStoreOptions {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n storePath?: string;\n /** Backstop poll cadence for change detection. Lowered in tests so they do\n * not depend on `fs.watch`, whose delivery timing is platform-dependent. */\n pollIntervalMs?: number;\n /** How long to wait for the advisory lock before proceeding lock-free. */\n lockTimeoutMs?: number;\n /** Where swallowed failures go, so silent degradation stays visible. */\n report?: TaskFailureReporter;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Coerce arbitrary parsed JSON into a valid document.\n *\n * A corrupt or truncated store must not take the session down: the worst\n * acceptable outcome is starting from an empty list, never a crash on startup.\n */\nfunction normalizeDocument(parsed: unknown): TaskDocument {\n if (!parsed || typeof parsed !== 'object') return emptyDocument();\n const candidate = parsed as Partial<TaskDocument>;\n if (!Array.isArray(candidate.tasks)) return emptyDocument();\n\n const tasks = candidate.tasks.filter(\n (task): task is Task => Boolean(task) && typeof task === 'object' && typeof (task as Task).id === 'number',\n );\n const maxId = tasks.reduce((max, task) => Math.max(max, task.id), 0);\n return {\n version: typeof candidate.version === 'number' ? candidate.version : STORE_SCHEMA_VERSION,\n rev: typeof candidate.rev === 'number' ? candidate.rev : 0,\n nextId: typeof candidate.nextId === 'number' && candidate.nextId > maxId ? candidate.nextId : maxId + 1,\n tasks,\n };\n}\n\n/**\n * File-backed task store shared by one root session and its delegated children.\n *\n * Durability model: the JSON file is the source of truth. Mutations are\n * read-modify-write under an advisory lock so concurrent delegated processes\n * cannot clobber each other, and writes land via temp-file rename so a\n * crash mid-write can never leave a partial document behind.\n */\nexport class TaskStore {\n storePath: string;\n\n private readonly cwd: string;\n private readonly env: NodeJS.ProcessEnv;\n private cached: TaskDocument = emptyDocument();\n private lastKnownRev = -1;\n private watcher?: fs.FSWatcher;\n private pollTimer?: NodeJS.Timeout;\n private debounceTimer?: NodeJS.Timeout;\n private readonly listeners = new Set<(document: TaskDocument) => void>();\n private readonly pollIntervalMs: number;\n private readonly lockTimeoutMs: number;\n private readonly report?: TaskFailureReporter;\n\n constructor(options: TaskStoreOptions = {}) {\n this.cwd = options.cwd ?? process.cwd();\n this.env = options.env ?? process.env;\n this.storePath = options.storePath ?? resolveStorePath(this.cwd, this.env);\n this.pollIntervalMs = options.pollIntervalMs ?? POLL_INTERVAL_MS;\n this.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;\n this.report = options.report;\n }\n\n /** Bind a default store to the current session tree before reading or watching it. */\n configureSession(sessionKey: string): void {\n if (this.env[STORE_PATH_ENV]?.trim()) return;\n this.stopWatching();\n this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);\n this.cached = emptyDocument();\n this.lastKnownRev = -1;\n }\n\n /** Last document read from disk, without hitting the filesystem. */\n get snapshot(): TaskDocument {\n return this.cached;\n }\n\n read(): TaskDocument {\n try {\n const raw = fs.readFileSync(this.storePath, UTF8_ENCODING);\n this.cached = normalizeDocument(JSON.parse(raw));\n } catch (error) {\n // A missing file is the normal state before the first write. Anything\n // else means the task list just silently became empty, which is worth a\n // record: unreadable or corrupt JSON looks identical to \"no tasks yet\".\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n this.cached = emptyDocument();\n }\n this.lastKnownRev = this.cached.rev;\n return this.cached;\n }\n\n /**\n * Apply a mutation under the store lock.\n *\n * `mutate` receives the freshest on-disk document and returns either the next\n * document to commit or `undefined` for a read-only action (list/get), which\n * skips the write entirely so queries never bump `rev`.\n */\n async mutate<T>(\n mutate: (document: TaskDocument) => { document?: TaskDocument; value: T },\n ): Promise<{ document: TaskDocument; value: T }> {\n const release = await this.acquireLock();\n try {\n const current = this.read();\n const outcome = mutate(current);\n if (!outcome.document) {\n return { document: current, value: outcome.value };\n }\n const committed = this.write(outcome.document);\n return { document: committed, value: outcome.value };\n } finally {\n release();\n }\n }\n\n private write(document: TaskDocument): TaskDocument {\n const next: TaskDocument = { ...document, version: STORE_SCHEMA_VERSION, rev: document.rev + 1 };\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const temp = tempPathFor(this.storePath);\n fs.writeFileSync(temp, `${JSON.stringify(next, undefined, 2)}\\n`, UTF8_ENCODING);\n fs.renameSync(temp, this.storePath);\n this.cached = next;\n this.lastKnownRev = next.rev;\n return next;\n }\n\n private async acquireLock(): Promise<() => void> {\n const lockPath = lockPathFor(this.storePath);\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const deadline = Date.now() + this.lockTimeoutMs;\n\n for (;;) {\n try {\n const handle = fs.openSync(lockPath, 'wx');\n fs.writeSync(handle, JSON.stringify({ pid: process.pid, time: Date.now() }));\n fs.closeSync(handle);\n return () => fs.rmSync(lockPath, { force: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== LOCK_EXISTS_CODE) throw error;\n // The deadline is checked before breaking a stale lock so a peer that\n // keeps recreating one cannot spin this loop without bound.\n if (Date.now() >= deadline) {\n // Proceeding lock-free beats stalling the agent: the rename is atomic,\n // so the worst case is a lost concurrent update, not a corrupt file.\n // Reported because a lost update here can strand a delegation.\n this.report?.warn(\n TASK_EVENT.storeLockTimeout,\n new Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),\n { [STORE_PATH_ATTRIBUTE]: this.storePath },\n );\n return () => {};\n }\n // Clearing a dead holder's lock still goes through the backoff. Yielding\n // on every iteration is what stops a peer that keeps recreating the\n // lock from turning this into a spin.\n this.breakStaleLock(lockPath);\n await sleep(LOCK_RETRY_BASE_MS + Math.random() * LOCK_RETRY_MAX_MS);\n }\n }\n }\n\n /** Remove a lock left behind by a dead process or one held implausibly long. */\n private breakStaleLock(lockPath: string): boolean {\n try {\n const holder = JSON.parse(fs.readFileSync(lockPath, UTF8_ENCODING)) as { pid?: number; time?: number };\n const expired = typeof holder.time === 'number' && Date.now() - holder.time > LOCK_STALE_MS;\n const dead = typeof holder.pid === 'number' && !isProcessAlive(holder.pid);\n if (!expired && !dead) return false;\n fs.unlinkSync(lockPath);\n return true;\n } catch (error) {\n // Losing the race to another breaker is normal; a persistent failure here\n // shows up as the lock timeout above, so this stays a warning.\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.warn(TASK_EVENT.storeLockBreakFailed, error, { [STORE_PATH_ATTRIBUTE]: lockPath });\n }\n return false;\n }\n }\n\n /**\n * Notify when another process changes the store.\n *\n * `fs.watch` alone is unreliable across the rename-based write (and on some\n * network filesystems), so a slow poll backs it up. Writes made by this\n * process are filtered out by revision so the UI does not redraw twice.\n */\n onExternalChange(listener: (document: TaskDocument) => void): () => void {\n this.listeners.add(listener);\n this.startWatching();\n return () => {\n this.listeners.delete(listener);\n if (this.listeners.size === 0) this.stopWatching();\n };\n }\n\n private startWatching(): void {\n if (this.watcher || this.pollTimer) return;\n const directory = path.dirname(this.storePath);\n const fileName = path.basename(this.storePath);\n\n try {\n fs.mkdirSync(directory, { recursive: true });\n this.watcher = fs.watch(directory, (_event, changed) => {\n if (changed && changed !== fileName) return;\n this.scheduleCheck();\n });\n } catch (error) {\n // Polling still covers change detection, just more slowly.\n this.report?.warn(TASK_EVENT.storeWatchFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n\n this.pollTimer = setInterval(() => this.checkForChange(), this.pollIntervalMs);\n this.pollTimer.unref?.();\n }\n\n private scheduleCheck(): void {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => this.checkForChange(), WATCH_DEBOUNCE_MS);\n this.debounceTimer.unref?.();\n }\n\n private checkForChange(): void {\n const previousRev = this.lastKnownRev;\n const document = this.read();\n if (document.rev === previousRev) return;\n for (const listener of this.listeners) {\n try {\n listener(document);\n } catch (error) {\n // This runs from a timer and from the fs.watch callback, so an\n // unguarded listener throw is an uncaught exception that takes the\n // harness down rather than a handled render failure.\n this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n }\n }\n\n private stopWatching(): void {\n this.watcher?.close();\n this.watcher = undefined;\n if (this.pollTimer) clearInterval(this.pollTimer);\n this.pollTimer = undefined;\n clearTimeout(this.debounceTimer);\n this.debounceTimer = undefined;\n }\n\n dispose(): void {\n this.listeners.clear();\n this.stopWatching();\n }\n}\n"],"mappings":"yRAOA,MAMM,EAAgB,OAChB,EAAoB,SAEpB,EAAuB,aAe7B,SAAS,EAAM,EAA2B,CACxC,OAAO,IAAI,QAAS,GAAY,WAAW,EAAS,CAAE,CAAC,CACzD,CAQA,SAAS,EAAkB,EAA+B,CACxD,GAAI,CAAC,GAAU,OAAO,GAAW,SAAU,OAAO,EAAc,EAChE,IAAM,EAAY,EAClB,GAAI,CAAC,MAAM,QAAQ,EAAU,KAAK,EAAG,OAAO,EAAc,EAE1D,IAAM,EAAQ,EAAU,MAAM,OAC3B,GAAuB,EAAQ,GAAS,OAAO,GAAS,UAAY,OAAQ,EAAc,IAAO,QACpG,EACM,EAAQ,EAAM,QAAQ,EAAK,IAAS,KAAK,IAAI,EAAK,EAAK,EAAE,EAAG,CAAC,EACnE,MAAO,CACL,QAAS,OAAO,EAAU,SAAY,SAAW,EAAU,QAAA,EAC3D,IAAK,OAAO,EAAU,KAAQ,SAAW,EAAU,IAAM,EACzD,OAAQ,OAAO,EAAU,QAAW,UAAY,EAAU,OAAS,EAAQ,EAAU,OAAS,EAAQ,EACtG,OACF,CACF,CAUA,IAAa,EAAb,KAAuB,CACrB,UAEA,IACA,IACA,OAA+B,EAAc,EAC7C,aAAuB,GACvB,QACA,UACA,cACA,UAA6B,I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,KAAK,SAAS,MAAM,EACpB,KAAK,QAAU,IAAA,GACX,KAAK,WAAW,cAAc,KAAK,SAAS,EAChD,KAAK,UAAY,IAAA,GACjB,aAAa,KAAK,aAAa,EAC/B,KAAK,cAAgB,IAAA,EACvB,CAEA,SAAgB,CACd,KAAK,UAAU,MAAM,EACrB,KAAK,aAAa,CACpB,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});function e(){return{version:1,rev:0,nextId:1,tasks:[]}}function t(e){let t=e.delegation?.state;return t===`requested`||t===`running`}exports.DELETED_STATUS=`deleted`,exports.STORE_SCHEMA_VERSION=1,exports.emptyDocument=e,exports.isDelegationActive=t;
|
|
2
|
+
//# sourceMappingURL=types.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.cjs","names":[],"sources":["../../src/store/types.ts"],"sourcesContent":["/**\n * Domain types for the file-backed task store.\n *\n * The on-disk document is the durable source of truth (unlike rpiv-todo, which\n * replayed state from the transcript). Every field here round-trips through\n * JSON, so nothing may hold non-serializable values.\n */\n\nimport type { InlineAgent } from '@agimon-ai/doompi-extension-contracts/subagent-tool';\n\nexport type TaskStatus = 'pending' | 'in_progress' | 'completed' | 'failed' | 'deleted';\n\nexport const DELETED_STATUS: TaskStatus = 'deleted';\n\nexport type TaskAction = 'upsert' | 'list' | 'get' | 'delete' | 'clear' | 'assign' | 'cancel';\n\nexport type DelegationState = 'requested' | 'running' | 'completed' | 'failed' | 'cancelled';\n\n/** Terminal result of a delegated subagent run, copied off the delegation response. */\nexport interface DelegationResult {\n status: string;\n output?: string;\n outputPath?: string;\n sessionFile?: string;\n error?: string;\n durationMs?: number;\n toolCount?: number;\n}\n\n/**\n * Delegation bookkeeping attached to a task that was handed to a subagent.\n *\n * `pid` is the harness process that owns the run: it is the only way to tell an\n * genuinely-running delegation from one orphaned by a harness crash, since the\n * child dies with its parent but the file survives.\n */\nexport interface TaskDelegation {\n requestId: string;\n agent: string;\n state: DelegationState;\n sessionId?: string;\n pid?: number;\n runId?: string;\n model?: string;\n startedAt?: string;\n endedAt?: string;\n result?: DelegationResult;\n}\n\nexport interface Task {\n id: number;\n subject: string;\n description?: string;\n activeForm?: string;\n status: TaskStatus;\n blockedBy?: number[];\n owner?: string;\n metadata?: Record<string, unknown>;\n createdAt?: string;\n updatedAt?: string;\n delegation?: TaskDelegation;\n}\n\nexport const STORE_SCHEMA_VERSION = 1;\n\n/** The complete on-disk document. `rev` increments on every committed write. */\nexport interface TaskDocument {\n version: number;\n rev: number;\n nextId: number;\n tasks: Task[];\n}\n\nexport function emptyDocument(): TaskDocument {\n return { version: STORE_SCHEMA_VERSION, rev: 0, nextId: 1, tasks: [] };\n}\n\n/**\n * A dependency target inside an upsert item: an existing task id, or the `ref`\n * of a task created earlier in the same call.\n *\n * Refs must start with a letter (see `REF_PATTERN`), so a ref is structurally\n * unconfusable with a stringified id and the discrimination is just `typeof`.\n */\nexport type DepToken = number | string;\n\n/**\n * One entry of an `upsert` call. No `id` creates a task; an `id` updates one.\n *\n * `blockedBy` (absolute set) is create-only and `addBlockedBy`/`removeBlockedBy`\n * (additive merge) are update-only, matching the split the two former actions\n * had. A field used against the wrong kind fails that item rather than being\n * silently ignored.\n */\nexport interface TaskItemMutation {\n id?: number;\n ref?: string;\n subject?: string;\n description?: string;\n activeForm?: string;\n status?: TaskStatus;\n blockedBy?: DepToken[];\n addBlockedBy?: DepToken[];\n removeBlockedBy?: DepToken[];\n owner?: string;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * What one upsert item did. `index` is its position in the request array, so a\n * model reading a partial result can tell which entries still need resending.\n *\n * `message` is unprefixed: the `item[N] failed:` framing belongs to the\n * formatter, because the Task Space overlay shows this text on its own.\n */\nexport type UpsertItemOutcome =\n | {\n index: number;\n kind: 'created';\n id: number;\n subject: string;\n status: TaskStatus;\n ref?: string;\n blockedBy?: number[];\n }\n | { index: number; kind: 'updated'; id: number; fromStatus: TaskStatus; toStatus: TaskStatus }\n | { index: number; kind: 'unchanged'; id: number; status: TaskStatus }\n | { index: number; kind: 'failed'; message: string; id?: number; ref?: string };\n\n/** Which tasks an upsert touched, so renderResult names them instead of guessing. */\nexport interface UpsertSummary {\n /** Ids of applied entries, in request order. A failed entry contributes nothing. */\n applied: number[];\n failed: number;\n}\n\n/**\n * Open-shape input bag the reducer accepts. The index signature lets the\n * runtime pass a TypeBox `Static<typeof TaskParamsSchema>` through without\n * casting each field.\n *\n * Per-task fields live on `tasks[]`, not here: a top-level `subject` or\n * `status` would be ambiguous once one call can carry many tasks.\n */\nexport interface TaskMutationParams {\n [key: string]: unknown;\n tasks?: TaskItemMutation[];\n /** `list` filter only. To set a status, upsert the task by id. */\n status?: TaskStatus;\n /** `get`, `delete`, `assign` and `cancel` only. */\n id?: number;\n includeDeleted?: boolean;\n agent?: string;\n inlineAgent?: InlineAgent;\n instructions?: string;\n /** `assign` only: the context pack the parent hands to the child. */\n relevantFiles?: string[];\n priorFindings?: string;\n model?: string;\n context?: 'fresh' | 'fork';\n}\n\n/** Snapshot returned under a tool result's `details` for renderResult. */\nexport interface TaskDetails {\n action: TaskAction;\n params: Record<string, unknown>;\n tasks: Task[];\n nextId: number;\n rev: number;\n error?: string;\n upsert?: UpsertSummary;\n}\n\n/** A delegation is \"live\" while the owning run may still produce a response. */\nexport function isDelegationActive(task: Task): boolean {\n const state = task.delegation?.state;\n return state === 'requested' || state === 'running';\n}\n"],"mappings":"mEAyEA,SAAgB,GAA8B,CAC5C,MAAO,CAAE,QAAA,EAA+B,IAAK,EAAG,OAAQ,EAAG,MAAO,CAAC,CAAE,CACvE,CAmGA,SAAgB,EAAmB,EAAqB,CACtD,IAAM,EAAQ,EAAK,YAAY,MAC/B,OAAO,IAAU,aAAe,IAAU,SAC5C"}
|