@agimon-ai/doompi-task 0.0.1-alpha.2 → 0.0.1-alpha.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -12
- package/dist/adapters/pi/extension.cjs +3 -0
- package/dist/adapters/pi/extension.cjs.map +1 -0
- package/dist/adapters/pi/extension.d.cts +12 -0
- package/dist/adapters/pi/extension.d.cts.map +1 -0
- package/dist/adapters/pi/extension.d.mts +12 -0
- package/dist/adapters/pi/extension.d.mts.map +1 -0
- package/dist/adapters/pi/extension.mjs +3 -0
- package/dist/adapters/pi/extension.mjs.map +1 -0
- package/dist/adapters/store/paths.cjs +2 -0
- package/dist/adapters/store/paths.cjs.map +1 -0
- package/dist/adapters/store/paths.d.cts +26 -0
- package/dist/adapters/store/paths.d.cts.map +1 -0
- package/dist/adapters/store/paths.d.mts +26 -0
- package/dist/adapters/store/paths.d.mts.map +1 -0
- package/dist/adapters/store/paths.mjs +2 -0
- package/dist/adapters/store/paths.mjs.map +1 -0
- package/dist/adapters/store/taskStore.cjs +2 -0
- package/dist/adapters/store/taskStore.cjs.map +1 -0
- package/dist/adapters/store/taskStore.d.cts +87 -0
- package/dist/adapters/store/taskStore.d.cts.map +1 -0
- package/dist/adapters/store/taskStore.d.mts +87 -0
- package/dist/adapters/store/taskStore.d.mts.map +1 -0
- package/dist/adapters/store/taskStore.mjs +2 -0
- package/dist/adapters/store/taskStore.mjs.map +1 -0
- package/dist/adapters/telemetry/logSinkTelemetry.cjs +2 -0
- package/dist/adapters/telemetry/logSinkTelemetry.cjs.map +1 -0
- package/dist/adapters/telemetry/logSinkTelemetry.d.cts +52 -0
- package/dist/adapters/telemetry/logSinkTelemetry.d.cts.map +1 -0
- package/dist/adapters/telemetry/logSinkTelemetry.d.mts +52 -0
- package/dist/adapters/telemetry/logSinkTelemetry.d.mts.map +1 -0
- package/dist/adapters/telemetry/logSinkTelemetry.mjs +2 -0
- package/dist/adapters/telemetry/logSinkTelemetry.mjs.map +1 -0
- package/dist/commands/index.cjs +2 -0
- package/dist/commands/index.cjs.map +1 -0
- package/dist/commands/index.d.cts +15 -0
- package/dist/commands/index.d.cts.map +1 -0
- package/dist/commands/index.d.mts +15 -0
- package/dist/commands/index.d.mts.map +1 -0
- package/dist/commands/index.mjs +2 -0
- package/dist/commands/index.mjs.map +1 -0
- package/dist/commands/task/promptGuidelines.cjs +2 -0
- package/dist/commands/task/promptGuidelines.cjs.map +1 -0
- package/dist/commands/task/promptGuidelines.d.cts +5 -0
- package/dist/commands/task/promptGuidelines.d.cts.map +1 -0
- package/dist/commands/task/promptGuidelines.d.mts +5 -0
- package/dist/commands/task/promptGuidelines.d.mts.map +1 -0
- package/dist/commands/task/promptGuidelines.mjs +2 -0
- package/dist/commands/task/promptGuidelines.mjs.map +1 -0
- package/dist/commands/task/responseEnvelope.cjs +7 -0
- package/dist/commands/task/responseEnvelope.cjs.map +1 -0
- package/dist/commands/task/responseEnvelope.d.cts +51 -0
- package/dist/commands/task/responseEnvelope.d.cts.map +1 -0
- package/dist/commands/task/responseEnvelope.d.mts +51 -0
- package/dist/commands/task/responseEnvelope.d.mts.map +1 -0
- package/dist/commands/task/responseEnvelope.mjs +7 -0
- package/dist/commands/task/responseEnvelope.mjs.map +1 -0
- package/dist/commands/task/taskTool.cjs +3 -0
- package/dist/commands/task/taskTool.cjs.map +1 -0
- package/dist/commands/task/taskTool.d.cts +19 -0
- package/dist/commands/task/taskTool.d.cts.map +1 -0
- package/dist/commands/task/taskTool.d.mts +19 -0
- package/dist/commands/task/taskTool.d.mts.map +1 -0
- package/dist/commands/task/taskTool.mjs +3 -0
- package/dist/commands/task/taskTool.mjs.map +1 -0
- package/dist/commands.cjs +1 -2
- package/dist/commands.d.cts +2 -14
- package/dist/commands.d.mts +2 -14
- package/dist/commands.mjs +1 -2
- package/dist/config.cjs +1 -2
- package/dist/config.d.cts +2 -38
- package/dist/config.d.mts +2 -38
- package/dist/config.mjs +1 -2
- package/dist/delegation/manager.cjs +1 -6
- package/dist/delegation/manager.d.cts +2 -189
- package/dist/delegation/manager.d.mts +2 -189
- package/dist/delegation/manager.mjs +1 -6
- package/dist/extension.cjs +1 -3
- package/dist/extension.d.cts +2 -12
- package/dist/extension.d.mts +2 -12
- package/dist/extension.mjs +1 -3
- package/dist/extensions/doom.cjs +1 -1
- package/dist/extensions/doom.cjs.map +1 -1
- package/dist/extensions/doom.mjs +1 -1
- package/dist/extensions/doom.mjs.map +1 -1
- package/dist/extensions/pi.cjs +1 -1
- package/dist/extensions/pi.cjs.map +1 -1
- package/dist/extensions/pi.d.cts +1 -1
- package/dist/extensions/pi.d.mts +1 -1
- package/dist/extensions/pi.mjs +1 -1
- package/dist/extensions/pi.mjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +15 -14
- package/dist/index.d.mts +15 -14
- package/dist/index.mjs +1 -1
- package/dist/logSinkTelemetry.cjs +1 -2
- package/dist/logSinkTelemetry.d.cts +2 -51
- package/dist/logSinkTelemetry.d.mts +2 -51
- package/dist/logSinkTelemetry.mjs +1 -2
- package/dist/schemas/task.cjs +2 -0
- package/dist/schemas/task.cjs.map +1 -0
- package/dist/schemas/task.d.cts +103 -0
- package/dist/schemas/task.d.cts.map +1 -0
- package/dist/schemas/task.d.mts +103 -0
- package/dist/schemas/task.d.mts.map +1 -0
- package/dist/schemas/task.mjs +2 -0
- package/dist/schemas/task.mjs.map +1 -0
- package/dist/services/delegation/manager.cjs +6 -0
- package/dist/services/delegation/manager.cjs.map +1 -0
- package/dist/services/delegation/manager.d.cts +188 -0
- package/dist/services/delegation/manager.d.cts.map +1 -0
- package/dist/services/delegation/manager.d.mts +188 -0
- package/dist/services/delegation/manager.d.mts.map +1 -0
- package/dist/services/delegation/manager.mjs +6 -0
- package/dist/services/delegation/manager.mjs.map +1 -0
- package/dist/services/narration/taskNarration.cjs +2 -0
- package/dist/services/narration/taskNarration.cjs.map +1 -0
- package/dist/services/narration/taskNarration.mjs +2 -0
- package/dist/services/narration/taskNarration.mjs.map +1 -0
- package/dist/services/store/invariants.cjs +2 -0
- package/dist/services/store/invariants.cjs.map +1 -0
- package/dist/services/store/invariants.d.cts +14 -0
- package/dist/services/store/invariants.d.cts.map +1 -0
- package/dist/services/store/invariants.d.mts +14 -0
- package/dist/services/store/invariants.d.mts.map +1 -0
- package/dist/services/store/invariants.mjs +2 -0
- package/dist/services/store/invariants.mjs.map +1 -0
- package/dist/services/store/paths.cjs +1 -0
- package/dist/services/store/paths.mjs +1 -0
- package/dist/services/store/processLiveness.cjs +2 -0
- package/dist/services/store/processLiveness.cjs.map +1 -0
- package/dist/services/store/processLiveness.d.cts +12 -0
- package/dist/services/store/processLiveness.d.cts.map +1 -0
- package/dist/services/store/processLiveness.d.mts +12 -0
- package/dist/services/store/processLiveness.d.mts.map +1 -0
- package/dist/services/store/processLiveness.mjs +2 -0
- package/dist/services/store/processLiveness.mjs.map +1 -0
- package/dist/services/store/reconcile.cjs +2 -0
- package/dist/services/store/reconcile.cjs.map +1 -0
- package/dist/services/store/reconcile.d.cts +34 -0
- package/dist/services/store/reconcile.d.cts.map +1 -0
- package/dist/services/store/reconcile.d.mts +34 -0
- package/dist/services/store/reconcile.d.mts.map +1 -0
- package/dist/services/store/reconcile.mjs +2 -0
- package/dist/services/store/reconcile.mjs.map +1 -0
- package/dist/services/store/reducer.cjs +3 -0
- package/dist/services/store/reducer.cjs.map +1 -0
- package/dist/services/store/reducer.d.cts +72 -0
- package/dist/services/store/reducer.d.cts.map +1 -0
- package/dist/services/store/reducer.d.mts +72 -0
- package/dist/services/store/reducer.d.mts.map +1 -0
- package/dist/services/store/reducer.mjs +3 -0
- package/dist/services/store/reducer.mjs.map +1 -0
- package/dist/services/store/taskGraph.cjs +2 -0
- package/dist/services/store/taskGraph.cjs.map +1 -0
- package/dist/services/store/taskGraph.d.cts +25 -0
- package/dist/services/store/taskGraph.d.cts.map +1 -0
- package/dist/services/store/taskGraph.d.mts +25 -0
- package/dist/services/store/taskGraph.d.mts.map +1 -0
- package/dist/services/store/taskGraph.mjs +2 -0
- package/dist/services/store/taskGraph.mjs.map +1 -0
- package/dist/services/store/taskStore.cjs +1 -0
- package/dist/services/store/taskStore.d.cts +2 -0
- package/dist/services/store/taskStore.d.mts +2 -0
- package/dist/services/store/taskStore.mjs +1 -0
- package/dist/services/store/types.cjs +2 -0
- package/dist/services/store/types.cjs.map +1 -0
- package/dist/services/store/types.d.cts +177 -0
- package/dist/services/store/types.d.cts.map +1 -0
- package/dist/services/store/types.d.mts +177 -0
- package/dist/services/store/types.d.mts.map +1 -0
- package/dist/services/store/types.mjs +2 -0
- package/dist/services/store/types.mjs.map +1 -0
- package/dist/store/invariants.cjs +1 -2
- package/dist/store/invariants.d.cts +2 -14
- package/dist/store/invariants.d.mts +2 -14
- package/dist/store/invariants.mjs +1 -2
- package/dist/store/paths.cjs +1 -2
- package/dist/store/paths.d.cts +2 -23
- package/dist/store/paths.d.mts +2 -23
- package/dist/store/paths.mjs +1 -2
- package/dist/store/processLiveness.cjs +1 -2
- package/dist/store/processLiveness.d.cts +2 -12
- package/dist/store/processLiveness.d.mts +2 -12
- package/dist/store/processLiveness.mjs +1 -2
- package/dist/store/reconcile.cjs +1 -2
- package/dist/store/reconcile.d.cts +2 -34
- package/dist/store/reconcile.d.mts +2 -34
- package/dist/store/reconcile.mjs +1 -2
- package/dist/store/reducer.cjs +1 -3
- package/dist/store/reducer.d.cts +2 -72
- package/dist/store/reducer.d.mts +2 -72
- package/dist/store/reducer.mjs +1 -3
- package/dist/store/taskGraph.cjs +1 -2
- package/dist/store/taskGraph.d.cts +2 -25
- package/dist/store/taskGraph.d.mts +2 -25
- package/dist/store/taskGraph.mjs +1 -2
- package/dist/store/taskStore.cjs +1 -2
- package/dist/store/taskStore.d.cts +3 -77
- package/dist/store/taskStore.d.mts +3 -77
- package/dist/store/taskStore.mjs +1 -2
- package/dist/store/types.cjs +1 -2
- package/dist/store/types.d.cts +2 -165
- package/dist/store/types.d.mts +2 -165
- package/dist/store/types.mjs +1 -2
- package/dist/tool/promptGuidelines.cjs +1 -2
- package/dist/tool/promptGuidelines.d.cts +2 -5
- package/dist/tool/promptGuidelines.d.mts +2 -5
- package/dist/tool/promptGuidelines.mjs +1 -2
- package/dist/tool/responseEnvelope.cjs +1 -6
- package/dist/tool/responseEnvelope.d.cts +2 -39
- package/dist/tool/responseEnvelope.d.mts +2 -39
- package/dist/tool/responseEnvelope.mjs +1 -6
- package/dist/tool/schema.cjs +1 -2
- package/dist/tool/schema.d.cts +2 -86
- package/dist/tool/schema.d.mts +2 -86
- package/dist/tool/schema.mjs +1 -2
- package/dist/tool/taskTool.cjs +1 -3
- package/dist/tool/taskTool.d.cts +3 -17
- package/dist/tool/taskTool.d.mts +3 -17
- package/dist/tool/taskTool.mjs +1 -3
- package/dist/tui/format.cjs +3 -3
- package/dist/tui/format.cjs.map +1 -1
- package/dist/tui/format.d.cts +5 -5
- package/dist/tui/format.d.cts.map +1 -1
- package/dist/tui/format.d.mts +5 -5
- package/dist/tui/format.d.mts.map +1 -1
- package/dist/tui/format.mjs +3 -3
- package/dist/tui/format.mjs.map +1 -1
- package/dist/tui/selectors.cjs +1 -1
- package/dist/tui/selectors.cjs.map +1 -1
- package/dist/tui/selectors.d.cts +8 -1
- package/dist/tui/selectors.d.cts.map +1 -1
- package/dist/tui/selectors.d.mts +8 -1
- package/dist/tui/selectors.d.mts.map +1 -1
- package/dist/tui/selectors.mjs +1 -1
- package/dist/tui/selectors.mjs.map +1 -1
- package/dist/tui/taskOverlay.cjs +1 -1
- package/dist/tui/taskOverlay.cjs.map +1 -1
- package/dist/tui/taskOverlay.d.cts +2 -2
- package/dist/tui/taskOverlay.d.cts.map +1 -1
- package/dist/tui/taskOverlay.d.mts +2 -2
- package/dist/tui/taskOverlay.d.mts.map +1 -1
- package/dist/tui/taskOverlay.mjs +1 -1
- package/dist/tui/taskOverlay.mjs.map +1 -1
- package/dist/tui/taskSpace.cjs +3 -3
- package/dist/tui/taskSpace.cjs.map +1 -1
- package/dist/tui/taskSpace.d.cts +2 -1
- package/dist/tui/taskSpace.d.cts.map +1 -1
- package/dist/tui/taskSpace.d.mts +2 -1
- package/dist/tui/taskSpace.d.mts.map +1 -1
- package/dist/tui/taskSpace.mjs +3 -3
- package/dist/tui/taskSpace.mjs.map +1 -1
- package/dist/types/config.cjs +2 -0
- package/dist/types/config.cjs.map +1 -0
- package/dist/types/config.d.cts +43 -0
- package/dist/types/config.d.cts.map +1 -0
- package/dist/types/config.d.mts +43 -0
- package/dist/types/config.d.mts.map +1 -0
- package/dist/types/config.mjs +2 -0
- package/dist/types/config.mjs.map +1 -0
- package/package.json +16 -9
- package/dist/commands.cjs.map +0 -1
- package/dist/commands.d.cts.map +0 -1
- package/dist/commands.d.mts.map +0 -1
- package/dist/commands.mjs.map +0 -1
- package/dist/config.cjs.map +0 -1
- package/dist/config.d.cts.map +0 -1
- package/dist/config.d.mts.map +0 -1
- package/dist/config.mjs.map +0 -1
- package/dist/delegation/manager.cjs.map +0 -1
- package/dist/delegation/manager.d.cts.map +0 -1
- package/dist/delegation/manager.d.mts.map +0 -1
- package/dist/delegation/manager.mjs.map +0 -1
- package/dist/extension.cjs.map +0 -1
- package/dist/extension.d.cts.map +0 -1
- package/dist/extension.d.mts.map +0 -1
- package/dist/extension.mjs.map +0 -1
- package/dist/logSinkTelemetry.cjs.map +0 -1
- package/dist/logSinkTelemetry.d.cts.map +0 -1
- package/dist/logSinkTelemetry.d.mts.map +0 -1
- package/dist/logSinkTelemetry.mjs.map +0 -1
- package/dist/store/invariants.cjs.map +0 -1
- package/dist/store/invariants.d.cts.map +0 -1
- package/dist/store/invariants.d.mts.map +0 -1
- package/dist/store/invariants.mjs.map +0 -1
- package/dist/store/paths.cjs.map +0 -1
- package/dist/store/paths.d.cts.map +0 -1
- package/dist/store/paths.d.mts.map +0 -1
- package/dist/store/paths.mjs.map +0 -1
- package/dist/store/processLiveness.cjs.map +0 -1
- package/dist/store/processLiveness.d.cts.map +0 -1
- package/dist/store/processLiveness.d.mts.map +0 -1
- package/dist/store/processLiveness.mjs.map +0 -1
- package/dist/store/reconcile.cjs.map +0 -1
- package/dist/store/reconcile.d.cts.map +0 -1
- package/dist/store/reconcile.d.mts.map +0 -1
- package/dist/store/reconcile.mjs.map +0 -1
- package/dist/store/reducer.cjs.map +0 -1
- package/dist/store/reducer.d.cts.map +0 -1
- package/dist/store/reducer.d.mts.map +0 -1
- package/dist/store/reducer.mjs.map +0 -1
- package/dist/store/taskGraph.cjs.map +0 -1
- package/dist/store/taskGraph.d.cts.map +0 -1
- package/dist/store/taskGraph.d.mts.map +0 -1
- package/dist/store/taskGraph.mjs.map +0 -1
- package/dist/store/taskStore.cjs.map +0 -1
- package/dist/store/taskStore.d.cts.map +0 -1
- package/dist/store/taskStore.d.mts.map +0 -1
- package/dist/store/taskStore.mjs.map +0 -1
- package/dist/store/types.cjs.map +0 -1
- package/dist/store/types.d.cts.map +0 -1
- package/dist/store/types.d.mts.map +0 -1
- package/dist/store/types.mjs.map +0 -1
- package/dist/tool/promptGuidelines.cjs.map +0 -1
- package/dist/tool/promptGuidelines.d.cts.map +0 -1
- package/dist/tool/promptGuidelines.d.mts.map +0 -1
- package/dist/tool/promptGuidelines.mjs.map +0 -1
- package/dist/tool/responseEnvelope.cjs.map +0 -1
- package/dist/tool/responseEnvelope.d.cts.map +0 -1
- package/dist/tool/responseEnvelope.d.mts.map +0 -1
- package/dist/tool/responseEnvelope.mjs.map +0 -1
- package/dist/tool/schema.cjs.map +0 -1
- package/dist/tool/schema.d.cts.map +0 -1
- package/dist/tool/schema.d.mts.map +0 -1
- package/dist/tool/schema.mjs.map +0 -1
- package/dist/tool/taskTool.cjs.map +0 -1
- package/dist/tool/taskTool.d.cts.map +0 -1
- package/dist/tool/taskTool.d.mts.map +0 -1
- package/dist/tool/taskTool.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
# @agimon-ai/doompi-task
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**A task list that survives the conversation.**
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
This is a file-backed task graph, not a checklist copied into chat. Tasks have statuses and
|
|
6
|
+
dependencies, can be handed to subagents, and remain authoritative after compaction rewrites
|
|
7
|
+
the transcript. The agent can forget the prose; it does not get to forget the work.
|
|
7
8
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
This is part of [Doompi](https://www.npmjs.com/package/@agimon-ai/doompi). Most users get
|
|
10
|
+
it with the distribution; install it directly when embedding the task graph in another Pi
|
|
11
|
+
setup.
|
|
11
12
|
|
|
12
13
|
## Install
|
|
13
14
|
|
|
@@ -17,18 +18,44 @@ npm install @agimon-ai/doompi-task
|
|
|
17
18
|
|
|
18
19
|
## How it loads
|
|
19
20
|
|
|
20
|
-
|
|
21
|
-
|
|
21
|
+
Task is a major-mode capability selected through `.doom/modes.yaml`. Fresh Doompi
|
|
22
|
+
configuration enables it in both `minimal` and `copilot` so existing sessions keep the
|
|
23
|
+
persistent task graph, while a custom major mode can omit the tool entirely:
|
|
22
24
|
|
|
23
|
-
|
|
25
|
+
```yaml
|
|
26
|
+
layers:
|
|
27
|
+
task:
|
|
28
|
+
packages: ['@agimon-ai/doompi-task']
|
|
29
|
+
|
|
30
|
+
majorMode:
|
|
31
|
+
minimal:
|
|
32
|
+
description: Lean mode with persistent tasks.
|
|
33
|
+
layers: [task]
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The bare package name follows its Pi manifest and selects the Doom adapter. That adapter
|
|
37
|
+
connects the graph to the Doom TUI and team runtime.
|
|
38
|
+
|
|
39
|
+
## What it does
|
|
40
|
+
|
|
41
|
+
- Stores tasks on disk instead of relying on transcript memory.
|
|
42
|
+
- Enforces dependency and lifecycle transitions.
|
|
43
|
+
- Shares one board with Doompi subagents.
|
|
44
|
+
- Keeps delegation visible to the parent session.
|
|
45
|
+
- Gives compaction an authoritative task snapshot to carry forward.
|
|
24
46
|
|
|
25
47
|
## Leader
|
|
26
48
|
|
|
27
|
-
`SPC t t` opens
|
|
49
|
+
`SPC t t` opens the task board.
|
|
50
|
+
|
|
51
|
+
## Task limit
|
|
52
|
+
|
|
53
|
+
A board allows 15 non-deleted tasks by default. Set `DOOM_TASK_MAX_TASKS` to a positive integer to change the limit. When the board is full, updates still apply, but new tasks are rejected until completed tasks are deleted.
|
|
28
54
|
|
|
29
|
-
##
|
|
55
|
+
## Public API
|
|
30
56
|
|
|
31
|
-
|
|
57
|
+
The package exports its task model, storage, tools, TUI, and Pi/Doom adapters through
|
|
58
|
+
supported subpaths. See `package.json` for the complete list.
|
|
32
59
|
|
|
33
60
|
## License
|
|
34
61
|
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const e=require("../telemetry/logSinkTelemetry.cjs"),t=require("../../services/delegation/manager.cjs"),n=require("../../schemas/task.cjs"),r=require("../../commands/index.cjs"),i=require("../../types/config.cjs"),a=require("../../commands/task/taskTool.cjs"),o=require("../../services/narration/taskNarration.cjs"),s=require("../store/paths.cjs");require("../../services/store/paths.cjs");const c=require("../store/taskStore.cjs");require("../../services/store/taskStore.cjs");const l=require("../../tui/taskOverlay.cjs");let u=require("@agimon-ai/doompi-extension-contracts/background-work"),d=require("@agimon-ai/doompi-extension-contracts/narration"),f=require("@agimon-ai/doompi-extension-contracts/protocol"),p=require("@agimon-ai/doompi-ui/leader"),m=require("@earendil-works/pi-tui");const h=`@agimon-ai/doompi-task`,g={narrate:()=>void 0};function _(_){let v=e.createTaskErrorReporter(),y=e.toFailureReporter(v),b=g,x=new c.TaskStore({report:y,onCommitted:(e,t)=>o.narrateTaskCommit(b,e,t)}),S,C,w,T,E=()=>{C?.update(),T?.update()},D=new t.DelegationManager({events:_.events,store:x,cwd:process.cwd(),notify:(e,t)=>_.sendMessage(e,t),getSessionId:()=>S,onChange:E,runTimeoutMs:i.getDelegationTimeoutMs(),report:y,onNotifyError:(e,t)=>{v.recordNotificationError(e,t)}});C=new l.TaskOverlay({getTasks:()=>x.snapshot.tasks,delegation:D}),a.registerTaskTool(_,{store:x,delegation:D,maxTasks:i.getMaxTasks(),onChange:E,report:y}),r.registerTasksCommand(_,x),(0,p.registerDoomLeaderContribution)(_,{source:h,bindings:[{id:`tasks.open`,path:[{key:`t`,label:`tasks`,order:65},{key:`t`,label:`tasks`}],command:{name:n.COMMAND_NAME}}]}),_.registerMessageRenderer(t.NOTIFY_CUSTOM_TYPE,(e,t,n)=>{let r=typeof e.content==`string`?e.content:``;return new m.Text(n.fg(`muted`,r),0,0)});let O=i.resolveCollapseKey();O!==`off`&&_.registerShortcut(O,{description:`Collapse or expand the task overlay`,handler:e=>{!e.hasUI||!C?.isRegistered()||C.toggleCollapse()}}),_.on(`session_start`,async(n,r)=>{try{let n=r;if(S=n.sessionManager?.getSessionId(),!S)throw Error(`doom-task requires a session id`);b=(0,d.createNarrationRequester)({bus:_.events,source:h,sessionId:S}),T?.dispose(),T=n.hasUI?void 0:(0,u.registerBackgroundWorkProvider)((0,f.createProtocolRuntime)({bus:_.events,source:h,sessionId:S}),{provider:t.BACKGROUND_WORK_PROVIDER,listActiveWork:()=>D.listActiveWork()}),x.configureSession(s.resolveSessionKey(S));let a=await s.removeLegacyStoreDirectoryAsync(x.storePath),o=s.hasStorePathOverride()?{removed:[],errors:[]}:await s.sweepStoreFilesAsync(x.storePath,i.getStoreTtlMs()),c=[...a.errors,...o.errors];for(let t of c)y.warn(e.TASK_EVENT.storeSweepFailed,Error(t));c.length>0&&n.hasUI&&n.ui.notify(c.join(`
|
|
2
|
+
`),`warning`),n.hasUI&&C?.setUICtx(n.ui),await x.readAsync(),w=x.onExternalChange(E),D.start(),await D.reconcile(),E()}catch(t){throw y.error(e.TASK_EVENT.sessionStartFailed,t),t}}),_.on(`session_compact`,()=>E()),_.on(`session_tree`,()=>E()),_.on(`tool_execution_end`,e=>{e.toolName===`task`&&E()}),_.on(`session_shutdown`,async()=>{try{w?.(),T?.dispose(),T=void 0,D.dispose(),C?.dispose(),x.dispose(),b=g}finally{await v.shutdown()}})}exports.default=_,exports.taskExtension=_;
|
|
3
|
+
//# sourceMappingURL=extension.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extension.cjs","names":["createTaskErrorReporter","toFailureReporter","TaskStore","narrateTaskCommit","DelegationManager","getDelegationTimeoutMs","TaskOverlay","getMaxTasks","COMMAND_NAME","NOTIFY_CUSTOM_TYPE","Text","resolveCollapseKey","createNarrationRequester","registerBackgroundWorkProvider","createProtocolRuntime","BACKGROUND_WORK_PROVIDER","resolveSessionKey","removeLegacyStoreDirectoryAsync","hasStorePathOverride","sweepStoreFilesAsync","getStoreTtlMs","TASK_EVENT"],"sources":["../../../src/adapters/pi/extension.ts"],"sourcesContent":["import {\n type BackgroundWorkProviderHandle,\n registerBackgroundWorkProvider,\n} from '@agimon-ai/doompi-extension-contracts/background-work';\nimport { createNarrationRequester, type NarrationRequester } from '@agimon-ai/doompi-extension-contracts/narration';\nimport { createProtocolRuntime } from '@agimon-ai/doompi-extension-contracts/protocol';\nimport { registerDoomLeaderContribution } from '@agimon-ai/doompi-ui/leader';\nimport type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\nimport type { KeyId } from '@earendil-works/pi-tui';\nimport { Text } from '@earendil-works/pi-tui';\nimport { registerTasksCommand } from '../../commands/index.ts';\nimport { registerTaskTool } from '../../commands/task/taskTool.ts';\nimport { COMMAND_NAME, TOOL_NAME } from '../../schemas/task.ts';\nimport { BACKGROUND_WORK_PROVIDER, DelegationManager, NOTIFY_CUSTOM_TYPE } from '../../services/delegation/manager.ts';\nimport { narrateTaskCommit } from '../../services/narration/taskNarration.ts';\nimport {\n hasStorePathOverride,\n removeLegacyStoreDirectoryAsync,\n resolveSessionKey,\n sweepStoreFilesAsync,\n} from '../../services/store/paths.ts';\nimport { TaskStore } from '../../services/store/taskStore.ts';\nimport { TaskOverlay } from '../../tui/taskOverlay.ts';\nimport {\n COLLAPSE_KEY_OFF,\n getDelegationTimeoutMs,\n getMaxTasks,\n getStoreTtlMs,\n resolveCollapseKey,\n} from '../../types/config.ts';\nimport { createTaskErrorReporter, TASK_EVENT, toFailureReporter } from '../telemetry/logSinkTelemetry.ts';\n\ninterface SessionContextLike {\n hasUI: boolean;\n ui: Parameters<TaskOverlay['setUICtx']>[0];\n sessionManager?: { getSessionId(): string };\n}\n\nconst LEADER_SOURCE = '@agimon-ai/doompi-task';\nconst SILENT_NARRATION_REQUESTER: NarrationRequester = { narrate: () => undefined };\n/** Between doom-plan's 60 and the core help group's 70, so `t` sits after `p`. */\nconst LEADER_GROUP_ORDER = 65;\nconst SESSION_START_EVENT = 'session_start';\nconst SESSION_COMPACT_EVENT = 'session_compact';\nconst SESSION_TREE_EVENT = 'session_tree';\nconst TOOL_EXECUTION_END_EVENT = 'tool_execution_end';\nconst SESSION_SHUTDOWN_EVENT = 'session_shutdown';\n\n/**\n * doom-task: a session-tree-scoped, file-backed task list with delegation.\n *\n * A root session and its delegated descendants share one durable JSON file.\n * Unrelated sessions resolve to separate stores outside repository metadata.\n */\nexport function taskExtension(pi: ExtensionAPI): void {\n const errorReporter = createTaskErrorReporter();\n const report = toFailureReporter(errorReporter);\n let narrationRequester = SILENT_NARRATION_REQUESTER;\n const store = new TaskStore({\n report,\n onCommitted: (previous, committed) => narrateTaskCommit(narrationRequester, previous, committed),\n });\n let sessionId: string | undefined;\n let overlay: TaskOverlay | undefined;\n let unwatch: (() => void) | undefined;\n let backgroundWork: BackgroundWorkProviderHandle | undefined;\n\n const refresh = (): void => {\n overlay?.update();\n backgroundWork?.update();\n };\n\n const delegation = new DelegationManager({\n events: pi.events,\n store,\n cwd: process.cwd(),\n notify: (message, options) => pi.sendMessage(message, options),\n getSessionId: () => sessionId,\n onChange: refresh,\n runTimeoutMs: getDelegationTimeoutMs(),\n report,\n onNotifyError: (error, taskId) => {\n void errorReporter.recordNotificationError(error, taskId);\n },\n });\n\n overlay = new TaskOverlay({ getTasks: () => store.snapshot.tasks, delegation });\n\n registerTaskTool(pi, { store, delegation, maxTasks: getMaxTasks(), onChange: refresh, report });\n registerTasksCommand(pi, store);\n\n // `SPC t` remains a group so other task-related surfaces can share the prefix.\n // doom-pi-ui keeps no core group on `t`; a conflicting claim is rejected there\n // with a diagnostic.\n registerDoomLeaderContribution(pi, {\n source: LEADER_SOURCE,\n bindings: [\n {\n id: 'tasks.open',\n path: [\n { key: 't', label: 'tasks', order: LEADER_GROUP_ORDER },\n { key: 't', label: 'tasks' },\n ],\n command: { name: COMMAND_NAME },\n },\n ],\n });\n\n pi.registerMessageRenderer(NOTIFY_CUSTOM_TYPE, (message, _options, theme) => {\n const content = typeof message.content === 'string' ? message.content : '';\n return new Text(theme.fg('muted', content), 0, 0);\n });\n\n const collapseKey = resolveCollapseKey();\n if (collapseKey !== COLLAPSE_KEY_OFF) {\n pi.registerShortcut(collapseKey as KeyId, {\n description: 'Collapse or expand the task overlay',\n handler: (ctx) => {\n if (!ctx.hasUI || !overlay?.isRegistered()) return;\n overlay.toggleCollapse();\n },\n });\n }\n\n pi.on(SESSION_START_EVENT, async (_event, ctx) => {\n // Anything thrown before reconcile() skips the only recovery pass for\n // delegations left behind by the previous session, so the failure must not\n // disappear into the harness.\n try {\n const context = ctx as unknown as SessionContextLike;\n sessionId = context.sessionManager?.getSessionId();\n if (!sessionId) throw new Error('doom-task requires a session id');\n narrationRequester = createNarrationRequester({\n bus: pi.events,\n source: LEADER_SOURCE,\n sessionId,\n });\n backgroundWork?.dispose();\n backgroundWork = context.hasUI\n ? undefined\n : registerBackgroundWorkProvider(\n createProtocolRuntime({\n bus: pi.events,\n source: LEADER_SOURCE,\n sessionId,\n }),\n {\n provider: BACKGROUND_WORK_PROVIDER,\n listActiveWork: () => delegation.listActiveWork(),\n },\n );\n store.configureSession(resolveSessionKey(sessionId));\n const cleanup = await removeLegacyStoreDirectoryAsync(store.storePath);\n const sweep = hasStorePathOverride()\n ? { removed: [], errors: [] }\n : await sweepStoreFilesAsync(store.storePath, getStoreTtlMs());\n const storeErrors = [...cleanup.errors, ...sweep.errors];\n for (const failure of storeErrors) report.warn(TASK_EVENT.storeSweepFailed, new Error(failure));\n if (storeErrors.length > 0 && context.hasUI) context.ui.notify(storeErrors.join('\\n'), 'warning');\n if (context.hasUI) overlay?.setUICtx(context.ui);\n await store.readAsync();\n unwatch = store.onExternalChange(refresh);\n // A shutdown that kept the process alive left the manager unsubscribed.\n delegation.start();\n await delegation.reconcile();\n refresh();\n } catch (error) {\n report.error(TASK_EVENT.sessionStartFailed, error);\n throw error;\n }\n });\n\n pi.on(SESSION_COMPACT_EVENT, () => refresh());\n pi.on(SESSION_TREE_EVENT, () => refresh());\n\n pi.on(TOOL_EXECUTION_END_EVENT, (event) => {\n if (event.toolName === TOOL_NAME) refresh();\n });\n\n pi.on(SESSION_SHUTDOWN_EVENT, async () => {\n try {\n unwatch?.();\n backgroundWork?.dispose();\n backgroundWork = undefined;\n delegation.dispose();\n overlay?.dispose();\n store.dispose();\n narrationRequester = SILENT_NARRATION_REQUESTER;\n } finally {\n // Runs even if teardown throws: the buffered records are most valuable\n // exactly when something went wrong on the way out.\n await errorReporter.shutdown();\n }\n });\n}\n\nexport default taskExtension;\n"],"mappings":"wxBAsCA,MAAM,EAAgB,yBAChB,EAAiD,CAAE,YAAe,IAAA,EAAU,EAelF,SAAgB,EAAc,EAAwB,CACpD,IAAM,EAAgBA,EAAAA,wBAAwB,EACxC,EAASC,EAAAA,kBAAkB,CAAa,EAC1C,EAAqB,EACnB,EAAQ,IAAIC,EAAAA,UAAU,CAC1B,SACA,aAAc,EAAU,IAAcC,EAAAA,kBAAkB,EAAoB,EAAU,CAAS,CACjG,CAAC,EACG,EACA,EACA,EACA,EAEE,MAAsB,CAC1B,GAAS,OAAO,EAChB,GAAgB,OAAO,CACzB,EAEM,EAAa,IAAIC,EAAAA,kBAAkB,CACvC,OAAQ,EAAG,OACX,QACA,IAAK,QAAQ,IAAI,EACjB,QAAS,EAAS,IAAY,EAAG,YAAY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ACjB,EAAM,QAAQ,EACd,EAAqB,CACvB,QAAU,CAGR,MAAM,EAAc,SAAS,CAC/B,CACF,CAAC,CACH"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
//#region src/adapters/pi/extension.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* doom-task: a session-tree-scoped, file-backed task list with delegation.
|
|
5
|
+
*
|
|
6
|
+
* A root session and its delegated descendants share one durable JSON file.
|
|
7
|
+
* Unrelated sessions resolve to separate stores outside repository metadata.
|
|
8
|
+
*/
|
|
9
|
+
declare function taskExtension(pi: ExtensionAPI): void;
|
|
10
|
+
//#endregion
|
|
11
|
+
export { taskExtension as default, taskExtension };
|
|
12
|
+
//# sourceMappingURL=extension.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extension.d.cts","names":[],"sources":["../../../src/adapters/pi/extension.ts"],"mappings":";;;;;;;;iBAsDgB,cAAc,IAAI"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
//#region src/adapters/pi/extension.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* doom-task: a session-tree-scoped, file-backed task list with delegation.
|
|
5
|
+
*
|
|
6
|
+
* A root session and its delegated descendants share one durable JSON file.
|
|
7
|
+
* Unrelated sessions resolve to separate stores outside repository metadata.
|
|
8
|
+
*/
|
|
9
|
+
declare function taskExtension(pi: ExtensionAPI): void;
|
|
10
|
+
//#endregion
|
|
11
|
+
export { taskExtension as default, taskExtension };
|
|
12
|
+
//# sourceMappingURL=extension.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extension.d.mts","names":[],"sources":["../../../src/adapters/pi/extension.ts"],"mappings":";;;;;;;;iBAsDgB,cAAc,IAAI"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{TASK_EVENT as e,createTaskErrorReporter as t,toFailureReporter as n}from"../telemetry/logSinkTelemetry.mjs";import{BACKGROUND_WORK_PROVIDER as r,DelegationManager as i,NOTIFY_CUSTOM_TYPE as a}from"../../services/delegation/manager.mjs";import{COMMAND_NAME as o}from"../../schemas/task.mjs";import{registerTasksCommand as s}from"../../commands/index.mjs";import{getDelegationTimeoutMs as c,getMaxTasks as l,getStoreTtlMs as u,resolveCollapseKey as d}from"../../types/config.mjs";import{registerTaskTool as f}from"../../commands/task/taskTool.mjs";import{narrateTaskCommit as p}from"../../services/narration/taskNarration.mjs";import{hasStorePathOverride as m,removeLegacyStoreDirectoryAsync as h,resolveSessionKey as g,sweepStoreFilesAsync as _}from"../store/paths.mjs";import"../../services/store/paths.mjs";import{TaskStore as v}from"../store/taskStore.mjs";import"../../services/store/taskStore.mjs";import{TaskOverlay as y}from"../../tui/taskOverlay.mjs";import{registerBackgroundWorkProvider as b}from"@agimon-ai/doompi-extension-contracts/background-work";import{createNarrationRequester as x}from"@agimon-ai/doompi-extension-contracts/narration";import{createProtocolRuntime as S}from"@agimon-ai/doompi-extension-contracts/protocol";import{registerDoomLeaderContribution as C}from"@agimon-ai/doompi-ui/leader";import{Text as w}from"@earendil-works/pi-tui";const T=`@agimon-ai/doompi-task`,E={narrate:()=>void 0};function D(D){let O=t(),k=n(O),A=E,j=new v({report:k,onCommitted:(e,t)=>p(A,e,t)}),M,N,P,F,I=()=>{N?.update(),F?.update()},L=new i({events:D.events,store:j,cwd:process.cwd(),notify:(e,t)=>D.sendMessage(e,t),getSessionId:()=>M,onChange:I,runTimeoutMs:c(),report:k,onNotifyError:(e,t)=>{O.recordNotificationError(e,t)}});N=new y({getTasks:()=>j.snapshot.tasks,delegation:L}),f(D,{store:j,delegation:L,maxTasks:l(),onChange:I,report:k}),s(D,j),C(D,{source:T,bindings:[{id:`tasks.open`,path:[{key:`t`,label:`tasks`,order:65},{key:`t`,label:`tasks`}],command:{name:o}}]}),D.registerMessageRenderer(a,(e,t,n)=>{let r=typeof e.content==`string`?e.content:``;return new w(n.fg(`muted`,r),0,0)});let R=d();R!==`off`&&D.registerShortcut(R,{description:`Collapse or expand the task overlay`,handler:e=>{!e.hasUI||!N?.isRegistered()||N.toggleCollapse()}}),D.on(`session_start`,async(t,n)=>{try{let t=n;if(M=t.sessionManager?.getSessionId(),!M)throw Error(`doom-task requires a session id`);A=x({bus:D.events,source:T,sessionId:M}),F?.dispose(),F=t.hasUI?void 0:b(S({bus:D.events,source:T,sessionId:M}),{provider:r,listActiveWork:()=>L.listActiveWork()}),j.configureSession(g(M));let i=await h(j.storePath),a=m()?{removed:[],errors:[]}:await _(j.storePath,u()),o=[...i.errors,...a.errors];for(let t of o)k.warn(e.storeSweepFailed,Error(t));o.length>0&&t.hasUI&&t.ui.notify(o.join(`
|
|
2
|
+
`),`warning`),t.hasUI&&N?.setUICtx(t.ui),await j.readAsync(),P=j.onExternalChange(I),L.start(),await L.reconcile(),I()}catch(t){throw k.error(e.sessionStartFailed,t),t}}),D.on(`session_compact`,()=>I()),D.on(`session_tree`,()=>I()),D.on(`tool_execution_end`,e=>{e.toolName===`task`&&I()}),D.on(`session_shutdown`,async()=>{try{P?.(),F?.dispose(),F=void 0,L.dispose(),N?.dispose(),j.dispose(),A=E}finally{await O.shutdown()}})}export{D as default,D as taskExtension};
|
|
3
|
+
//# sourceMappingURL=extension.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extension.mjs","names":[],"sources":["../../../src/adapters/pi/extension.ts"],"sourcesContent":["import {\n type BackgroundWorkProviderHandle,\n registerBackgroundWorkProvider,\n} from '@agimon-ai/doompi-extension-contracts/background-work';\nimport { createNarrationRequester, type NarrationRequester } from '@agimon-ai/doompi-extension-contracts/narration';\nimport { createProtocolRuntime } from '@agimon-ai/doompi-extension-contracts/protocol';\nimport { registerDoomLeaderContribution } from '@agimon-ai/doompi-ui/leader';\nimport type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\nimport type { KeyId } from '@earendil-works/pi-tui';\nimport { Text } from '@earendil-works/pi-tui';\nimport { registerTasksCommand } from '../../commands/index.ts';\nimport { registerTaskTool } from '../../commands/task/taskTool.ts';\nimport { COMMAND_NAME, TOOL_NAME } from '../../schemas/task.ts';\nimport { BACKGROUND_WORK_PROVIDER, DelegationManager, NOTIFY_CUSTOM_TYPE } from '../../services/delegation/manager.ts';\nimport { narrateTaskCommit } from '../../services/narration/taskNarration.ts';\nimport {\n hasStorePathOverride,\n removeLegacyStoreDirectoryAsync,\n resolveSessionKey,\n sweepStoreFilesAsync,\n} from '../../services/store/paths.ts';\nimport { TaskStore } from '../../services/store/taskStore.ts';\nimport { TaskOverlay } from '../../tui/taskOverlay.ts';\nimport {\n COLLAPSE_KEY_OFF,\n getDelegationTimeoutMs,\n getMaxTasks,\n getStoreTtlMs,\n resolveCollapseKey,\n} from '../../types/config.ts';\nimport { createTaskErrorReporter, TASK_EVENT, toFailureReporter } from '../telemetry/logSinkTelemetry.ts';\n\ninterface SessionContextLike {\n hasUI: boolean;\n ui: Parameters<TaskOverlay['setUICtx']>[0];\n sessionManager?: { getSessionId(): string };\n}\n\nconst LEADER_SOURCE = '@agimon-ai/doompi-task';\nconst SILENT_NARRATION_REQUESTER: NarrationRequester = { narrate: () => undefined };\n/** Between doom-plan's 60 and the core help group's 70, so `t` sits after `p`. */\nconst LEADER_GROUP_ORDER = 65;\nconst SESSION_START_EVENT = 'session_start';\nconst SESSION_COMPACT_EVENT = 'session_compact';\nconst SESSION_TREE_EVENT = 'session_tree';\nconst TOOL_EXECUTION_END_EVENT = 'tool_execution_end';\nconst SESSION_SHUTDOWN_EVENT = 'session_shutdown';\n\n/**\n * doom-task: a session-tree-scoped, file-backed task list with delegation.\n *\n * A root session and its delegated descendants share one durable JSON file.\n * Unrelated sessions resolve to separate stores outside repository metadata.\n */\nexport function taskExtension(pi: ExtensionAPI): void {\n const errorReporter = createTaskErrorReporter();\n const report = toFailureReporter(errorReporter);\n let narrationRequester = SILENT_NARRATION_REQUESTER;\n const store = new TaskStore({\n report,\n onCommitted: (previous, committed) => narrateTaskCommit(narrationRequester, previous, committed),\n });\n let sessionId: string | undefined;\n let overlay: TaskOverlay | undefined;\n let unwatch: (() => void) | undefined;\n let backgroundWork: BackgroundWorkProviderHandle | undefined;\n\n const refresh = (): void => {\n overlay?.update();\n backgroundWork?.update();\n };\n\n const delegation = new DelegationManager({\n events: pi.events,\n store,\n cwd: process.cwd(),\n notify: (message, options) => pi.sendMessage(message, options),\n getSessionId: () => sessionId,\n onChange: refresh,\n runTimeoutMs: getDelegationTimeoutMs(),\n report,\n onNotifyError: (error, taskId) => {\n void errorReporter.recordNotificationError(error, taskId);\n },\n });\n\n overlay = new TaskOverlay({ getTasks: () => store.snapshot.tasks, delegation });\n\n registerTaskTool(pi, { store, delegation, maxTasks: getMaxTasks(), onChange: refresh, report });\n registerTasksCommand(pi, store);\n\n // `SPC t` remains a group so other task-related surfaces can share the prefix.\n // doom-pi-ui keeps no core group on `t`; a conflicting claim is rejected there\n // with a diagnostic.\n registerDoomLeaderContribution(pi, {\n source: LEADER_SOURCE,\n bindings: [\n {\n id: 'tasks.open',\n path: [\n { key: 't', label: 'tasks', order: LEADER_GROUP_ORDER },\n { key: 't', label: 'tasks' },\n ],\n command: { name: COMMAND_NAME },\n },\n ],\n });\n\n pi.registerMessageRenderer(NOTIFY_CUSTOM_TYPE, (message, _options, theme) => {\n const content = typeof message.content === 'string' ? message.content : '';\n return new Text(theme.fg('muted', content), 0, 0);\n });\n\n const collapseKey = resolveCollapseKey();\n if (collapseKey !== COLLAPSE_KEY_OFF) {\n pi.registerShortcut(collapseKey as KeyId, {\n description: 'Collapse or expand the task overlay',\n handler: (ctx) => {\n if (!ctx.hasUI || !overlay?.isRegistered()) return;\n overlay.toggleCollapse();\n },\n });\n }\n\n pi.on(SESSION_START_EVENT, async (_event, ctx) => {\n // Anything thrown before reconcile() skips the only recovery pass for\n // delegations left behind by the previous session, so the failure must not\n // disappear into the harness.\n try {\n const context = ctx as unknown as SessionContextLike;\n sessionId = context.sessionManager?.getSessionId();\n if (!sessionId) throw new Error('doom-task requires a session id');\n narrationRequester = createNarrationRequester({\n bus: pi.events,\n source: LEADER_SOURCE,\n sessionId,\n });\n backgroundWork?.dispose();\n backgroundWork = context.hasUI\n ? undefined\n : registerBackgroundWorkProvider(\n createProtocolRuntime({\n bus: pi.events,\n source: LEADER_SOURCE,\n sessionId,\n }),\n {\n provider: BACKGROUND_WORK_PROVIDER,\n listActiveWork: () => delegation.listActiveWork(),\n },\n );\n store.configureSession(resolveSessionKey(sessionId));\n const cleanup = await removeLegacyStoreDirectoryAsync(store.storePath);\n const sweep = hasStorePathOverride()\n ? { removed: [], errors: [] }\n : await sweepStoreFilesAsync(store.storePath, getStoreTtlMs());\n const storeErrors = [...cleanup.errors, ...sweep.errors];\n for (const failure of storeErrors) report.warn(TASK_EVENT.storeSweepFailed, new Error(failure));\n if (storeErrors.length > 0 && context.hasUI) context.ui.notify(storeErrors.join('\\n'), 'warning');\n if (context.hasUI) overlay?.setUICtx(context.ui);\n await store.readAsync();\n unwatch = store.onExternalChange(refresh);\n // A shutdown that kept the process alive left the manager unsubscribed.\n delegation.start();\n await delegation.reconcile();\n refresh();\n } catch (error) {\n report.error(TASK_EVENT.sessionStartFailed, error);\n throw error;\n }\n });\n\n pi.on(SESSION_COMPACT_EVENT, () => refresh());\n pi.on(SESSION_TREE_EVENT, () => refresh());\n\n pi.on(TOOL_EXECUTION_END_EVENT, (event) => {\n if (event.toolName === TOOL_NAME) refresh();\n });\n\n pi.on(SESSION_SHUTDOWN_EVENT, async () => {\n try {\n unwatch?.();\n backgroundWork?.dispose();\n backgroundWork = undefined;\n delegation.dispose();\n overlay?.dispose();\n store.dispose();\n narrationRequester = SILENT_NARRATION_REQUESTER;\n } finally {\n // Runs even if teardown throws: the buffered records are most valuable\n // exactly when something went wrong on the way out.\n await errorReporter.shutdown();\n }\n });\n}\n\nexport default taskExtension;\n"],"mappings":"y1CAsCA,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,GAAU,CACrC,EAAM,WAAA,QAAwB,EAAQ,CAC5C,CAAC,EAED,EAAG,GAAG,mBAAwB,SAAY,CACxC,GAAI,CACF,IAAU,EACV,GAAgB,QAAQ,EACxB,EAAiB,IAAA,GACjB,EAAW,QAAQ,EACnB,GAAS,QAAQ,EACjB,EAAM,QAAQ,EACd,EAAqB,CACvB,QAAU,CAGR,MAAM,EAAc,SAAS,CAC/B,CACF,CAAC,CACH"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../../_virtual/_rolldown/runtime.cjs");let t=require("node:path");t=e.__toESM(t,1);let n=require("node:os");n=e.__toESM(n,1);let r=require("node:child_process"),i=require("node:fs");i=e.__toESM(i,1);let a=require("@agimon-ai/doompi-extension-contracts/child-process");const o=`DOOM_TASK_STORE`,s=`doom-task`,c=`tasks.json`,l=`utf8`,u=`ENOENT`;function d(e,t){try{let n=(0,r.execFileSync)(`git`,e,{cwd:t,encoding:l,stdio:[`ignore`,`pipe`,`ignore`]}).trim();return n.length>0?n:void 0}catch{return}}async function f(e,t){return new Promise(n=>{(0,r.execFile)(`git`,e,{cwd:t,encoding:l},(e,t)=>{if(e){n(void 0);return}let r=t.trim();n(r.length>0?r:void 0)})})}function p(e){let r=e.PI_CODING_AGENT_DIR?.trim();return r===`~`?n.default.homedir():r?.startsWith(`~/`)?t.default.join(n.default.homedir(),r.slice(2)):r?t.default.resolve(r):t.default.join(n.default.homedir(),`.pi`,`agent`)}function m(e,n){let r=t.default.relative(t.default.resolve(e),t.default.resolve(n));return r===``||!r.startsWith(`..`)&&!t.default.isAbsolute(r)}function h(e,t=process.env){if(!t[a.SUBAGENT_CHILD_ENV])return e;let n=t[a.SUBAGENT_PARENT_SESSION_ENV]?.trim();if(!n)throw Error(`${a.SUBAGENT_PARENT_SESSION_ENV} is required in a subagent child`);return n}function g(e=process.cwd(),n=process.env,r=`standalone`){let i=n[o]?.trim();if(i)return t.default.resolve(i);let a=r.trim();if(!a)throw Error(`doom-task session id cannot be blank`);return t.default.join(p(n),s,a,c)}function _(e=process.env){return!!e[o]?.trim()}function v(e=process.cwd()){let n=d([`rev-parse`,`--path-format=absolute`,`--git-common-dir`],e);return n?t.default.join(n,s):void 0}async function y(e=process.cwd()){let n=await f([`rev-parse`,`--path-format=absolute`,`--git-common-dir`],e);return n?t.default.join(n,s):void 0}function b(e,n=process.cwd()){let r={removed:[],errors:[]},a=v(n);if(!a||t.default.basename(a)!==s||m(a,e))return r;try{if(!i.default.existsSync(a))return r;i.default.rmSync(a,{recursive:!0,force:!0}),r.removed.push(a)}catch(e){r.errors.push(`Could not remove legacy task store ${a}: ${String(e)}`)}return r}async function x(e,n=process.cwd()){let r={removed:[],errors:[]},a=await y(n);if(!a||t.default.basename(a)!==s||m(a,e))return r;try{await i.default.promises.access(a),await i.default.promises.rm(a,{recursive:!0,force:!0}),r.removed.push(a)}catch(e){e.code!==u&&r.errors.push(`Could not remove legacy task store ${a}: ${String(e)}`)}return r}function S(e,n,r=Date.now()){let a={removed:[],errors:[]},o=t.default.dirname(e),s=t.default.dirname(o),d;try{d=i.default.readdirSync(s)}catch(e){return e.code===u||a.errors.push(`Could not read task store directory ${s}: ${String(e)}`),a}for(let e of d){let u=t.default.join(s,e),d=t.default.join(u,c);if(!(u===o||!i.default.existsSync(d)))try{if(i.default.existsSync(w(d))||(JSON.parse(i.default.readFileSync(d,l)),r-i.default.statSync(d).mtimeMs<=n))continue;i.default.rmSync(u,{recursive:!0,force:!0}),a.removed.push(u)}catch(e){a.errors.push(`Could not sweep task store ${d}: ${String(e)}`)}}return a}async function C(e,n,r=Date.now()){let a={removed:[],errors:[]},o=t.default.dirname(e),s=t.default.dirname(o),d;try{d=await i.default.promises.readdir(s)}catch(e){return e.code===u||a.errors.push(`Could not read task store directory ${s}: ${String(e)}`),a}for(let e of d){let d=t.default.join(s,e),f=t.default.join(d,c);if(d!==o)try{await i.default.promises.access(f);try{await i.default.promises.access(w(f));continue}catch(e){if(e.code!==u)throw e}if(JSON.parse(await i.default.promises.readFile(f,l)),r-(await i.default.promises.stat(f)).mtimeMs<=n)continue;await i.default.promises.rm(d,{recursive:!0,force:!0}),a.removed.push(d)}catch(e){if(e.code===u)continue;a.errors.push(`Could not sweep task store ${f}: ${String(e)}`)}}return a}function w(e){return`${e}.lock`}function T(e,t=process.pid){return`${e}.tmp.${t}`}exports.STORE_PATH_ENV=o,exports.hasStorePathOverride=_,exports.lockPathFor=w,exports.removeLegacyStoreDirectory=b,exports.removeLegacyStoreDirectoryAsync=x,exports.resolveLegacyStoreDirectory=v,exports.resolveLegacyStoreDirectoryAsync=y,exports.resolveSessionKey=h,exports.resolveStorePath=g,exports.sweepStoreFiles=S,exports.sweepStoreFilesAsync=C,exports.tempPathFor=T;
|
|
2
|
+
//# sourceMappingURL=paths.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paths.cjs","names":["execFileSync","os","path","SUBAGENT_CHILD_ENV","SUBAGENT_PARENT_SESSION_ENV","fs"],"sources":["../../../src/adapters/store/paths.ts"],"sourcesContent":["import { execFile, execFileSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from '@agimon-ai/doompi-extension-contracts/child-process';\n\nexport const STORE_PATH_ENV = 'DOOM_TASK_STORE';\n\nconst STORE_DIR_NAME = 'doom-task';\nconst STORE_FILE_NAME = 'tasks.json';\nconst DEFAULT_CONFIG_DIR_NAME = '.pi';\nconst AGENT_DIR_NAME = 'agent';\nconst PI_CODING_AGENT_DIR_ENV = 'PI_CODING_AGENT_DIR';\nconst HOME_ALIAS = '~';\nconst HOME_ALIAS_PREFIX = '~/';\nconst FILE_ENCODING = 'utf8';\nconst NOT_FOUND_ERROR_CODE = 'ENOENT';\n\nfunction git(args: string[], cwd: string): string | undefined {\n try {\n const output = execFileSync('git', args, {\n cwd,\n encoding: FILE_ENCODING,\n stdio: ['ignore', 'pipe', 'ignore'],\n });\n const trimmed = output.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function gitAsync(args: string[], cwd: string): Promise<string | undefined> {\n return new Promise((resolve) => {\n execFile('git', args, { cwd, encoding: FILE_ENCODING }, (error, stdout) => {\n if (error) {\n resolve(undefined);\n return;\n }\n const trimmed = stdout.trim();\n resolve(trimmed.length > 0 ? trimmed : undefined);\n });\n });\n}\n\nfunction resolveAgentDirectory(env: NodeJS.ProcessEnv): string {\n const configured = env[PI_CODING_AGENT_DIR_ENV]?.trim();\n if (configured === HOME_ALIAS) return os.homedir();\n if (configured?.startsWith(HOME_ALIAS_PREFIX)) {\n return path.join(os.homedir(), configured.slice(HOME_ALIAS_PREFIX.length));\n }\n return configured ? path.resolve(configured) : path.join(os.homedir(), DEFAULT_CONFIG_DIR_NAME, AGENT_DIR_NAME);\n}\n\nfunction isWithin(root: string, candidate: string): boolean {\n const relative = path.relative(path.resolve(root), path.resolve(candidate));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\n/** Resolve the tree root without relying on extension startup order. */\nexport function resolveSessionKey(rootSessionId: string, env: NodeJS.ProcessEnv = process.env): string {\n if (!env[SUBAGENT_CHILD_ENV]) return rootSessionId;\n const parentSessionId = env[SUBAGENT_PARENT_SESSION_ENV]?.trim();\n if (!parentSessionId) throw new Error(`${SUBAGENT_PARENT_SESSION_ENV} is required in a subagent child`);\n return parentSessionId;\n}\n\n/** Resolve one root session tree to a task document under the Pi agent directory. */\nexport function resolveStorePath(\n _cwd: string = process.cwd(),\n env: NodeJS.ProcessEnv = process.env,\n sessionKey: string = 'standalone',\n): string {\n const override = env[STORE_PATH_ENV]?.trim();\n if (override) return path.resolve(override);\n\n const trimmedSessionKey = sessionKey.trim();\n if (!trimmedSessionKey) throw new Error('doom-task session id cannot be blank');\n return path.join(resolveAgentDirectory(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);\n}\n\n/** Whether a deliberate unscoped task-store override is active. */\nexport function hasStorePathOverride(env: NodeJS.ProcessEnv = process.env): boolean {\n return Boolean(env[STORE_PATH_ENV]?.trim());\n}\n\n/** Exact legacy Git-directory store, if the current working tree has one. */\nexport function resolveLegacyStoreDirectory(cwd: string = process.cwd()): string | undefined {\n const commonDirectory = git(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport async function resolveLegacyStoreDirectoryAsync(cwd: string = process.cwd()): Promise<string | undefined> {\n const commonDirectory = await gitAsync(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport interface StoreSweepResult {\n removed: string[];\n errors: string[];\n}\n\n/** Remove only the validated legacy Git store unless it contains the active override. */\nexport function removeLegacyStoreDirectory(currentStorePath: string, cwd: string = process.cwd()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = resolveLegacyStoreDirectory(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n if (!fs.existsSync(target)) return result;\n fs.rmSync(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n return result;\n}\n\nexport async function removeLegacyStoreDirectoryAsync(\n currentStorePath: string,\n cwd: string = process.cwd(),\n): Promise<StoreSweepResult> {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = await resolveLegacyStoreDirectoryAsync(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n await fs.promises.access(target);\n await fs.promises.rm(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n }\n return result;\n}\n\n/** Delete expired sibling session stores while preserving active or unreadable stores. */\nexport function sweepStoreFiles(currentStorePath: string, ttlMs: number, now: number = Date.now()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = fs.readdirSync(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory || !fs.existsSync(candidate)) continue;\n try {\n if (fs.existsSync(lockPathFor(candidate))) continue;\n JSON.parse(fs.readFileSync(candidate, FILE_ENCODING));\n if (now - fs.statSync(candidate).mtimeMs <= ttlMs) continue;\n fs.rmSync(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport async function sweepStoreFilesAsync(\n currentStorePath: string,\n ttlMs: number,\n now: number = Date.now(),\n): Promise<StoreSweepResult> {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = await fs.promises.readdir(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory) continue;\n try {\n await fs.promises.access(candidate);\n try {\n await fs.promises.access(lockPathFor(candidate));\n continue;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) throw error;\n }\n JSON.parse(await fs.promises.readFile(candidate, FILE_ENCODING));\n if (now - (await fs.promises.stat(candidate)).mtimeMs <= ttlMs) continue;\n await fs.promises.rm(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) continue;\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport function lockPathFor(storePath: string): string {\n return `${storePath}.lock`;\n}\n\nexport function tempPathFor(storePath: string, pid: number = process.pid): string {\n return `${storePath}.tmp.${pid}`;\n}\n"],"mappings":"6RAMA,MAAa,EAAiB,kBAExB,EAAiB,YACjB,EAAkB,aAMlB,EAAgB,OAChB,EAAuB,SAE7B,SAAS,EAAI,EAAgB,EAAiC,CAC5D,GAAI,CAMF,IAAM,GAAA,EALSA,EAAAA,aAAAA,CAAa,MAAO,EAAM,CACvC,MACA,SAAU,EACV,MAAO,CAAC,SAAU,OAAQ,QAAQ,CACpC,CACqB,CAAC,CAAC,KAAK,EAC5B,OAAO,EAAQ,OAAS,EAAI,EAAU,IAAA,EACxC,MAAQ,CACN,MACF,CACF,CAEA,eAAe,EAAS,EAAgB,EAA0C,CAChF,OAAO,IAAI,QAAS,GAAY,EAC9B,EAAA,EAAA,SAAA,CAAS,MAAO,EAAM,CAAE,MAAK,SAAU,CAAc,GAAI,EAAO,IAAW,CACzE,GAAI,EAAO,CACT,EAAQ,IAAA,EAAS,EACjB,MACF,CACA,IAAM,EAAU,EAAO,KAAK,EAC5B,EAAQ,EAAQ,OAAS,EAAI,EAAU,IAAA,EAAS,CAClD,CAAC,CACH,CAAC,CACH,CAEA,SAAS,EAAsB,EAAgC,CAC7D,IAAM,EAAa,EAAI,qBAA0B,KAAK,EAKtD,OAJI,IAAe,IAAmBC,EAAAA,QAAG,QAAQ,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AAI,CACF,EAAU,MAAMG,EAAAA,QAAG,SAAS,QAAQ,CAAc,CACpD,OAAS,EAAO,CAGd,OAFK,EAAgC,OAAS,GAC9C,EAAO,OAAO,KAAK,uCAAuC,EAAe,IAAI,OAAO,CAAK,GAAG,EADjB,CAG7E,CAEA,IAAK,IAAM,KAAS,EAAS,CAC3B,IAAM,EAAmBH,EAAAA,QAAK,KAAK,EAAgB,CAAK,EAClD,EAAYA,EAAAA,QAAK,KAAK,EAAkB,CAAe,EACzD,OAAqB,EACzB,GAAI,CACF,MAAMG,EAAAA,QAAG,SAAS,OAAO,CAAS,EAClC,GAAI,CACF,MAAMA,EAAAA,QAAG,SAAS,OAAO,EAAY,CAAS,CAAC,EAC/C,QACF,OAAS,EAAO,CACd,GAAK,EAAgC,OAAS,EAAsB,MAAM,CAC5E,CAEA,GADA,KAAK,MAAM,MAAMA,EAAAA,QAAG,SAAS,SAAS,EAAW,CAAa,CAAC,EAC3D,GAAO,MAAMA,EAAAA,QAAG,SAAS,KAAK,CAAS,EAAA,CAAG,SAAW,EAAO,SAChE,MAAMA,EAAAA,QAAG,SAAS,GAAG,EAAkB,CAAE,UAAW,GAAM,MAAO,EAAK,CAAC,EACvE,EAAO,QAAQ,KAAK,CAAgB,CACtC,OAAS,EAAO,CACd,GAAK,EAAgC,OAAS,EAAsB,SACpE,EAAO,OAAO,KAAK,8BAA8B,EAAU,IAAI,OAAO,CAAK,GAAG,CAChF,CACF,CACA,OAAO,CACT,CAEA,SAAgB,EAAY,EAA2B,CACrD,MAAO,GAAG,EAAU,MACtB,CAEA,SAAgB,EAAY,EAAmB,EAAc,QAAQ,IAAa,CAChF,MAAO,GAAG,EAAU,OAAO,GAC7B"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
//#region src/adapters/store/paths.d.ts
|
|
2
|
+
declare const STORE_PATH_ENV = "DOOM_TASK_STORE";
|
|
3
|
+
/** Resolve the tree root without relying on extension startup order. */
|
|
4
|
+
declare function resolveSessionKey(rootSessionId: string, env?: NodeJS.ProcessEnv): string;
|
|
5
|
+
/** Resolve one root session tree to a task document under the Pi agent directory. */
|
|
6
|
+
declare function resolveStorePath(_cwd?: string, env?: NodeJS.ProcessEnv, sessionKey?: string): string;
|
|
7
|
+
/** Whether a deliberate unscoped task-store override is active. */
|
|
8
|
+
declare function hasStorePathOverride(env?: NodeJS.ProcessEnv): boolean;
|
|
9
|
+
/** Exact legacy Git-directory store, if the current working tree has one. */
|
|
10
|
+
declare function resolveLegacyStoreDirectory(cwd?: string): string | undefined;
|
|
11
|
+
declare function resolveLegacyStoreDirectoryAsync(cwd?: string): Promise<string | undefined>;
|
|
12
|
+
interface StoreSweepResult {
|
|
13
|
+
removed: string[];
|
|
14
|
+
errors: string[];
|
|
15
|
+
}
|
|
16
|
+
/** Remove only the validated legacy Git store unless it contains the active override. */
|
|
17
|
+
declare function removeLegacyStoreDirectory(currentStorePath: string, cwd?: string): StoreSweepResult;
|
|
18
|
+
declare function removeLegacyStoreDirectoryAsync(currentStorePath: string, cwd?: string): Promise<StoreSweepResult>;
|
|
19
|
+
/** Delete expired sibling session stores while preserving active or unreadable stores. */
|
|
20
|
+
declare function sweepStoreFiles(currentStorePath: string, ttlMs: number, now?: number): StoreSweepResult;
|
|
21
|
+
declare function sweepStoreFilesAsync(currentStorePath: string, ttlMs: number, now?: number): Promise<StoreSweepResult>;
|
|
22
|
+
declare function lockPathFor(storePath: string): string;
|
|
23
|
+
declare function tempPathFor(storePath: string, pid?: number): string;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { STORE_PATH_ENV, StoreSweepResult, hasStorePathOverride, lockPathFor, removeLegacyStoreDirectory, removeLegacyStoreDirectoryAsync, resolveLegacyStoreDirectory, resolveLegacyStoreDirectoryAsync, resolveSessionKey, resolveStorePath, sweepStoreFiles, sweepStoreFilesAsync, tempPathFor };
|
|
26
|
+
//# sourceMappingURL=paths.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paths.d.cts","names":[],"sources":["../../../src/adapters/store/paths.ts"],"mappings":";cAMa;;iBAsDG,kBAAkB,uBAAuB,MAAK,OAAO;;iBAQrD,iBACd,eACA,MAAK,OAAO,YACZ;;iBAWc,qBAAqB,MAAK,OAAO;;iBAKjC,4BAA4B;iBAKtB,iCAAiC,eAA8B;UAKpE;EACf;EACA;;;iBAIc,2BAA2B,0BAA0B,eAA8B;iBAe7E,gCACpB,0BACA,eACC,QAAQ;;iBAkBK,gBAAgB,0BAA0B,eAAe,eAA2B;iBA8B9E,qBACpB,0BACA,eACA,eACC,QAAQ;iBAqCK,YAAY;iBAIZ,YAAY,mBAAmB"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
//#region src/adapters/store/paths.d.ts
|
|
2
|
+
declare const STORE_PATH_ENV = "DOOM_TASK_STORE";
|
|
3
|
+
/** Resolve the tree root without relying on extension startup order. */
|
|
4
|
+
declare function resolveSessionKey(rootSessionId: string, env?: NodeJS.ProcessEnv): string;
|
|
5
|
+
/** Resolve one root session tree to a task document under the Pi agent directory. */
|
|
6
|
+
declare function resolveStorePath(_cwd?: string, env?: NodeJS.ProcessEnv, sessionKey?: string): string;
|
|
7
|
+
/** Whether a deliberate unscoped task-store override is active. */
|
|
8
|
+
declare function hasStorePathOverride(env?: NodeJS.ProcessEnv): boolean;
|
|
9
|
+
/** Exact legacy Git-directory store, if the current working tree has one. */
|
|
10
|
+
declare function resolveLegacyStoreDirectory(cwd?: string): string | undefined;
|
|
11
|
+
declare function resolveLegacyStoreDirectoryAsync(cwd?: string): Promise<string | undefined>;
|
|
12
|
+
interface StoreSweepResult {
|
|
13
|
+
removed: string[];
|
|
14
|
+
errors: string[];
|
|
15
|
+
}
|
|
16
|
+
/** Remove only the validated legacy Git store unless it contains the active override. */
|
|
17
|
+
declare function removeLegacyStoreDirectory(currentStorePath: string, cwd?: string): StoreSweepResult;
|
|
18
|
+
declare function removeLegacyStoreDirectoryAsync(currentStorePath: string, cwd?: string): Promise<StoreSweepResult>;
|
|
19
|
+
/** Delete expired sibling session stores while preserving active or unreadable stores. */
|
|
20
|
+
declare function sweepStoreFiles(currentStorePath: string, ttlMs: number, now?: number): StoreSweepResult;
|
|
21
|
+
declare function sweepStoreFilesAsync(currentStorePath: string, ttlMs: number, now?: number): Promise<StoreSweepResult>;
|
|
22
|
+
declare function lockPathFor(storePath: string): string;
|
|
23
|
+
declare function tempPathFor(storePath: string, pid?: number): string;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { STORE_PATH_ENV, StoreSweepResult, hasStorePathOverride, lockPathFor, removeLegacyStoreDirectory, removeLegacyStoreDirectoryAsync, resolveLegacyStoreDirectory, resolveLegacyStoreDirectoryAsync, resolveSessionKey, resolveStorePath, sweepStoreFiles, sweepStoreFilesAsync, tempPathFor };
|
|
26
|
+
//# sourceMappingURL=paths.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paths.d.mts","names":[],"sources":["../../../src/adapters/store/paths.ts"],"mappings":";cAMa;;iBAsDG,kBAAkB,uBAAuB,MAAK,OAAO;;iBAQrD,iBACd,eACA,MAAK,OAAO,YACZ;;iBAWc,qBAAqB,MAAK,OAAO;;iBAKjC,4BAA4B;iBAKtB,iCAAiC,eAA8B;UAKpE;EACf;EACA;;;iBAIc,2BAA2B,0BAA0B,eAA8B;iBAe7E,gCACpB,0BACA,eACC,QAAQ;;iBAkBK,gBAAgB,0BAA0B,eAAe,eAA2B;iBA8B9E,qBACpB,0BACA,eACA,eACC,QAAQ;iBAqCK,YAAY;iBAIZ,YAAY,mBAAmB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import e from"node:path";import t from"node:os";import{execFile as n,execFileSync as r}from"node:child_process";import i from"node:fs";import{SUBAGENT_CHILD_ENV as a,SUBAGENT_PARENT_SESSION_ENV as o}from"@agimon-ai/doompi-extension-contracts/child-process";const s=`DOOM_TASK_STORE`,c=`doom-task`,l=`tasks.json`,u=`utf8`,d=`ENOENT`;function f(e,t){try{let n=r(`git`,e,{cwd:t,encoding:u,stdio:[`ignore`,`pipe`,`ignore`]}).trim();return n.length>0?n:void 0}catch{return}}async function p(e,t){return new Promise(r=>{n(`git`,e,{cwd:t,encoding:u},(e,t)=>{if(e){r(void 0);return}let n=t.trim();r(n.length>0?n:void 0)})})}function m(n){let r=n.PI_CODING_AGENT_DIR?.trim();return r===`~`?t.homedir():r?.startsWith(`~/`)?e.join(t.homedir(),r.slice(2)):r?e.resolve(r):e.join(t.homedir(),`.pi`,`agent`)}function h(t,n){let r=e.relative(e.resolve(t),e.resolve(n));return r===``||!r.startsWith(`..`)&&!e.isAbsolute(r)}function g(e,t=process.env){if(!t[a])return e;let n=t[o]?.trim();if(!n)throw Error(`${o} is required in a subagent child`);return n}function _(t=process.cwd(),n=process.env,r=`standalone`){let i=n[s]?.trim();if(i)return e.resolve(i);let a=r.trim();if(!a)throw Error(`doom-task session id cannot be blank`);return e.join(m(n),c,a,l)}function v(e=process.env){return!!e[s]?.trim()}function y(t=process.cwd()){let n=f([`rev-parse`,`--path-format=absolute`,`--git-common-dir`],t);return n?e.join(n,c):void 0}async function b(t=process.cwd()){let n=await p([`rev-parse`,`--path-format=absolute`,`--git-common-dir`],t);return n?e.join(n,c):void 0}function x(t,n=process.cwd()){let r={removed:[],errors:[]},a=y(n);if(!a||e.basename(a)!==c||h(a,t))return r;try{if(!i.existsSync(a))return r;i.rmSync(a,{recursive:!0,force:!0}),r.removed.push(a)}catch(e){r.errors.push(`Could not remove legacy task store ${a}: ${String(e)}`)}return r}async function S(t,n=process.cwd()){let r={removed:[],errors:[]},a=await b(n);if(!a||e.basename(a)!==c||h(a,t))return r;try{await i.promises.access(a),await i.promises.rm(a,{recursive:!0,force:!0}),r.removed.push(a)}catch(e){e.code!==d&&r.errors.push(`Could not remove legacy task store ${a}: ${String(e)}`)}return r}function C(t,n,r=Date.now()){let a={removed:[],errors:[]},o=e.dirname(t),s=e.dirname(o),c;try{c=i.readdirSync(s)}catch(e){return e.code===d||a.errors.push(`Could not read task store directory ${s}: ${String(e)}`),a}for(let t of c){let c=e.join(s,t),d=e.join(c,l);if(!(c===o||!i.existsSync(d)))try{if(i.existsSync(T(d))||(JSON.parse(i.readFileSync(d,u)),r-i.statSync(d).mtimeMs<=n))continue;i.rmSync(c,{recursive:!0,force:!0}),a.removed.push(c)}catch(e){a.errors.push(`Could not sweep task store ${d}: ${String(e)}`)}}return a}async function w(t,n,r=Date.now()){let a={removed:[],errors:[]},o=e.dirname(t),s=e.dirname(o),c;try{c=await i.promises.readdir(s)}catch(e){return e.code===d||a.errors.push(`Could not read task store directory ${s}: ${String(e)}`),a}for(let t of c){let c=e.join(s,t),f=e.join(c,l);if(c!==o)try{await i.promises.access(f);try{await i.promises.access(T(f));continue}catch(e){if(e.code!==d)throw e}if(JSON.parse(await i.promises.readFile(f,u)),r-(await i.promises.stat(f)).mtimeMs<=n)continue;await i.promises.rm(c,{recursive:!0,force:!0}),a.removed.push(c)}catch(e){if(e.code===d)continue;a.errors.push(`Could not sweep task store ${f}: ${String(e)}`)}}return a}function T(e){return`${e}.lock`}function E(e,t=process.pid){return`${e}.tmp.${t}`}export{s as STORE_PATH_ENV,v as hasStorePathOverride,T as lockPathFor,x as removeLegacyStoreDirectory,S as removeLegacyStoreDirectoryAsync,y as resolveLegacyStoreDirectory,b as resolveLegacyStoreDirectoryAsync,g as resolveSessionKey,_ as resolveStorePath,C as sweepStoreFiles,w as sweepStoreFilesAsync,E as tempPathFor};
|
|
2
|
+
//# sourceMappingURL=paths.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paths.mjs","names":[],"sources":["../../../src/adapters/store/paths.ts"],"sourcesContent":["import { execFile, execFileSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from '@agimon-ai/doompi-extension-contracts/child-process';\n\nexport const STORE_PATH_ENV = 'DOOM_TASK_STORE';\n\nconst STORE_DIR_NAME = 'doom-task';\nconst STORE_FILE_NAME = 'tasks.json';\nconst DEFAULT_CONFIG_DIR_NAME = '.pi';\nconst AGENT_DIR_NAME = 'agent';\nconst PI_CODING_AGENT_DIR_ENV = 'PI_CODING_AGENT_DIR';\nconst HOME_ALIAS = '~';\nconst HOME_ALIAS_PREFIX = '~/';\nconst FILE_ENCODING = 'utf8';\nconst NOT_FOUND_ERROR_CODE = 'ENOENT';\n\nfunction git(args: string[], cwd: string): string | undefined {\n try {\n const output = execFileSync('git', args, {\n cwd,\n encoding: FILE_ENCODING,\n stdio: ['ignore', 'pipe', 'ignore'],\n });\n const trimmed = output.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function gitAsync(args: string[], cwd: string): Promise<string | undefined> {\n return new Promise((resolve) => {\n execFile('git', args, { cwd, encoding: FILE_ENCODING }, (error, stdout) => {\n if (error) {\n resolve(undefined);\n return;\n }\n const trimmed = stdout.trim();\n resolve(trimmed.length > 0 ? trimmed : undefined);\n });\n });\n}\n\nfunction resolveAgentDirectory(env: NodeJS.ProcessEnv): string {\n const configured = env[PI_CODING_AGENT_DIR_ENV]?.trim();\n if (configured === HOME_ALIAS) return os.homedir();\n if (configured?.startsWith(HOME_ALIAS_PREFIX)) {\n return path.join(os.homedir(), configured.slice(HOME_ALIAS_PREFIX.length));\n }\n return configured ? path.resolve(configured) : path.join(os.homedir(), DEFAULT_CONFIG_DIR_NAME, AGENT_DIR_NAME);\n}\n\nfunction isWithin(root: string, candidate: string): boolean {\n const relative = path.relative(path.resolve(root), path.resolve(candidate));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\n/** Resolve the tree root without relying on extension startup order. */\nexport function resolveSessionKey(rootSessionId: string, env: NodeJS.ProcessEnv = process.env): string {\n if (!env[SUBAGENT_CHILD_ENV]) return rootSessionId;\n const parentSessionId = env[SUBAGENT_PARENT_SESSION_ENV]?.trim();\n if (!parentSessionId) throw new Error(`${SUBAGENT_PARENT_SESSION_ENV} is required in a subagent child`);\n return parentSessionId;\n}\n\n/** Resolve one root session tree to a task document under the Pi agent directory. */\nexport function resolveStorePath(\n _cwd: string = process.cwd(),\n env: NodeJS.ProcessEnv = process.env,\n sessionKey: string = 'standalone',\n): string {\n const override = env[STORE_PATH_ENV]?.trim();\n if (override) return path.resolve(override);\n\n const trimmedSessionKey = sessionKey.trim();\n if (!trimmedSessionKey) throw new Error('doom-task session id cannot be blank');\n return path.join(resolveAgentDirectory(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);\n}\n\n/** Whether a deliberate unscoped task-store override is active. */\nexport function hasStorePathOverride(env: NodeJS.ProcessEnv = process.env): boolean {\n return Boolean(env[STORE_PATH_ENV]?.trim());\n}\n\n/** Exact legacy Git-directory store, if the current working tree has one. */\nexport function resolveLegacyStoreDirectory(cwd: string = process.cwd()): string | undefined {\n const commonDirectory = git(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport async function resolveLegacyStoreDirectoryAsync(cwd: string = process.cwd()): Promise<string | undefined> {\n const commonDirectory = await gitAsync(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport interface StoreSweepResult {\n removed: string[];\n errors: string[];\n}\n\n/** Remove only the validated legacy Git store unless it contains the active override. */\nexport function removeLegacyStoreDirectory(currentStorePath: string, cwd: string = process.cwd()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = resolveLegacyStoreDirectory(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n if (!fs.existsSync(target)) return result;\n fs.rmSync(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n return result;\n}\n\nexport async function removeLegacyStoreDirectoryAsync(\n currentStorePath: string,\n cwd: string = process.cwd(),\n): Promise<StoreSweepResult> {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = await resolveLegacyStoreDirectoryAsync(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n await fs.promises.access(target);\n await fs.promises.rm(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n }\n return result;\n}\n\n/** Delete expired sibling session stores while preserving active or unreadable stores. */\nexport function sweepStoreFiles(currentStorePath: string, ttlMs: number, now: number = Date.now()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = fs.readdirSync(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory || !fs.existsSync(candidate)) continue;\n try {\n if (fs.existsSync(lockPathFor(candidate))) continue;\n JSON.parse(fs.readFileSync(candidate, FILE_ENCODING));\n if (now - fs.statSync(candidate).mtimeMs <= ttlMs) continue;\n fs.rmSync(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport async function sweepStoreFilesAsync(\n currentStorePath: string,\n ttlMs: number,\n now: number = Date.now(),\n): Promise<StoreSweepResult> {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = await fs.promises.readdir(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory) continue;\n try {\n await fs.promises.access(candidate);\n try {\n await fs.promises.access(lockPathFor(candidate));\n continue;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) throw error;\n }\n JSON.parse(await fs.promises.readFile(candidate, FILE_ENCODING));\n if (now - (await fs.promises.stat(candidate)).mtimeMs <= ttlMs) continue;\n await fs.promises.rm(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) continue;\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport function lockPathFor(storePath: string): string {\n return `${storePath}.lock`;\n}\n\nexport function tempPathFor(storePath: string, pid: number = process.pid): string {\n return `${storePath}.tmp.${pid}`;\n}\n"],"mappings":"iQAMA,MAAa,EAAiB,kBAExB,EAAiB,YACjB,EAAkB,aAMlB,EAAgB,OAChB,EAAuB,SAE7B,SAAS,EAAI,EAAgB,EAAiC,CAC5D,GAAI,CAMF,IAAM,EALS,EAAa,MAAO,EAAM,CACvC,MACA,SAAU,EACV,MAAO,CAAC,SAAU,OAAQ,QAAQ,CACpC,CACqB,CAAC,CAAC,KAAK,EAC5B,OAAO,EAAQ,OAAS,EAAI,EAAU,IAAA,EACxC,MAAQ,CACN,MACF,CACF,CAEA,eAAe,EAAS,EAAgB,EAA0C,CAChF,OAAO,IAAI,QAA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,QAAQ,CAAgB,EACvD,EAAiB,EAAK,QAAQ,CAAuB,EACvD,EACJ,GAAI,CACF,EAAU,MAAM,EAAG,SAAS,QAAQ,CAAc,CACpD,OAAS,EAAO,CAGd,OAFK,EAAgC,OAAS,GAC9C,EAAO,OAAO,KAAK,uCAAuC,EAAe,IAAI,OAAO,CAAK,GAAG,EADjB,CAG7E,CAEA,IAAK,IAAM,KAAS,EAAS,CAC3B,IAAM,EAAmB,EAAK,KAAK,EAAgB,CAAK,EAClD,EAAY,EAAK,KAAK,EAAkB,CAAe,EACzD,OAAqB,EACzB,GAAI,CACF,MAAM,EAAG,SAAS,OAAO,CAAS,EAClC,GAAI,CACF,MAAM,EAAG,SAAS,OAAO,EAAY,CAAS,CAAC,EAC/C,QACF,OAAS,EAAO,CACd,GAAK,EAAgC,OAAS,EAAsB,MAAM,CAC5E,CAEA,GADA,KAAK,MAAM,MAAM,EAAG,SAAS,SAAS,EAAW,CAAa,CAAC,EAC3D,GAAO,MAAM,EAAG,SAAS,KAAK,CAAS,EAAA,CAAG,SAAW,EAAO,SAChE,MAAM,EAAG,SAAS,GAAG,EAAkB,CAAE,UAAW,GAAM,MAAO,EAAK,CAAC,EACvE,EAAO,QAAQ,KAAK,CAAgB,CACtC,OAAS,EAAO,CACd,GAAK,EAAgC,OAAS,EAAsB,SACpE,EAAO,OAAO,KAAK,8BAA8B,EAAU,IAAI,OAAO,CAAK,GAAG,CAChF,CACF,CACA,OAAO,CACT,CAEA,SAAgB,EAAY,EAA2B,CACrD,MAAO,GAAG,EAAU,MACtB,CAEA,SAAgB,EAAY,EAAmB,EAAc,QAAQ,IAAa,CAChF,MAAO,GAAG,EAAU,OAAO,GAC7B"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("../telemetry/logSinkTelemetry.cjs"),n=require("../../services/store/processLiveness.cjs"),r=require("../../services/store/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;checkInFlight;checkQueued=!1;watchGeneration=0;listeners=new Set;pollIntervalMs;lockTimeoutMs;report;onCommitted;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,this.onCommitted=e.onCommitted}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 readAsync(){return this.cached=await this.readDocumentAsync(),this.lastKnownRev=this.cached.rev,this.cached}async readDocumentAsync(){try{let e=await o.default.promises.readFile(this.storePath,s);return d(JSON.parse(e))}catch(e){return e.code!==c&&this.report?.error(t.TASK_EVENT.storeReadFailed,e,{[l]:this.storePath}),r.emptyDocument()}}async mutate(e){let t=await this.acquireLock(),n=(()=>{try{let t=this.read(),n=e(t);if(!n.document)return{result:{document:t,value:n.value}};let r=this.write(n.document);return{result:{document:r,value:n.value},notification:{previous:t,committed:r}}}finally{t()}})();return n.notification&&this.notifyCommitted(n.notification.previous,n.notification.committed),n.result}notifyCommitted(e,n){try{this.onCommitted?.(e,n)}catch(e){this.report?.error(t.TASK_EVENT.storeCommitListenerFailed,e,{[l]:this.storePath})}}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;this.watchGeneration+=1;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.queueChangeCheck(),this.pollIntervalMs),this.pollTimer.unref?.()}scheduleCheck(){clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>this.queueChangeCheck(),150),this.debounceTimer.unref?.()}queueChangeCheck(){if(this.checkInFlight){this.checkQueued=!0;return}let e=this.watchGeneration,t=(async()=>{do this.checkQueued=!1,await this.checkForChange(e);while(this.checkQueued&&e===this.watchGeneration)})().finally(()=>{this.checkInFlight===t&&(this.checkInFlight=void 0)});this.checkInFlight=t}async checkForChange(e){let n=this.lastKnownRev,r=await this.readDocumentAsync();if(e===this.watchGeneration){if(this.lastKnownRev!==n){this.checkQueued=!0;return}if(this.cached=r,this.lastKnownRev=r.rev,r.rev!==n)for(let e of this.listeners)try{e(r)}catch(e){this.report?.error(t.TASK_EVENT.storeListenerFailed,e,{[l]:this.storePath})}}}stopWatching(){this.watchGeneration+=1,this.checkQueued=!1,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/adapters/store/taskStore.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { isProcessAlive } from '../../services/store/processLiveness.ts';\nimport { emptyDocument, STORE_SCHEMA_VERSION, type Task, type TaskDocument } from '../../services/store/types.ts';\nimport { TASK_EVENT, type TaskFailureReporter } from '../telemetry/logSinkTelemetry.ts';\nimport { lockPathFor, resolveStorePath, STORE_PATH_ENV, tempPathFor } from './paths.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 type TaskStoreCommitListener = (previous: TaskDocument, committed: TaskDocument) => void;\n\nexport interface TaskStoreOptions {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n storePath?: string;\n onCommitted?: TaskStoreCommitListener;\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 checkInFlight?: Promise<void>;\n private checkQueued = false;\n private watchGeneration = 0;\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 private readonly onCommitted?: TaskStoreCommitListener;\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 this.onCommitted = options.onCommitted;\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 async readAsync(): Promise<TaskDocument> {\n this.cached = await this.readDocumentAsync();\n this.lastKnownRev = this.cached.rev;\n return this.cached;\n }\n\n private async readDocumentAsync(): Promise<TaskDocument> {\n try {\n const raw = await fs.promises.readFile(this.storePath, UTF8_ENCODING);\n return normalizeDocument(JSON.parse(raw));\n } catch (error) {\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 return emptyDocument();\n }\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 const outcome = (() => {\n try {\n const current = this.read();\n const mutation = mutate(current);\n if (!mutation.document) {\n return { result: { document: current, value: mutation.value } };\n }\n const committed = this.write(mutation.document);\n return {\n result: { document: committed, value: mutation.value },\n notification: { previous: current, committed },\n };\n } finally {\n release();\n }\n })();\n if (outcome.notification) {\n this.notifyCommitted(outcome.notification.previous, outcome.notification.committed);\n }\n return outcome.result;\n }\n\n private notifyCommitted(previous: TaskDocument, committed: TaskDocument): void {\n try {\n this.onCommitted?.(previous, committed);\n } catch (error) {\n this.report?.error(TASK_EVENT.storeCommitListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\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 this.watchGeneration += 1;\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.queueChangeCheck(), this.pollIntervalMs);\n this.pollTimer.unref?.();\n }\n\n private scheduleCheck(): void {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => this.queueChangeCheck(), WATCH_DEBOUNCE_MS);\n this.debounceTimer.unref?.();\n }\n\n private queueChangeCheck(): void {\n if (this.checkInFlight) {\n this.checkQueued = true;\n return;\n }\n const generation = this.watchGeneration;\n const execution = (async () => {\n do {\n this.checkQueued = false;\n await this.checkForChange(generation);\n } while (this.checkQueued && generation === this.watchGeneration);\n })().finally(() => {\n if (this.checkInFlight === execution) this.checkInFlight = undefined;\n });\n this.checkInFlight = execution;\n }\n\n private async checkForChange(generation: number): Promise<void> {\n const previousRev = this.lastKnownRev;\n const document = await this.readDocumentAsync();\n if (generation !== this.watchGeneration) return;\n if (this.lastKnownRev !== previousRev) {\n this.checkQueued = true;\n return;\n }\n this.cached = document;\n this.lastKnownRev = document.rev;\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.watchGeneration += 1;\n this.checkQueued = false;\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":"wTAOA,MAMM,EAAgB,OAChB,EAAoB,SAEpB,EAAuB,aAkB7B,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,cA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A,MAAc,eAAe,EAAmC,CAC9D,IAAM,EAAc,KAAK,aACnB,EAAW,MAAM,KAAK,kBAAkB,EAC1C,OAAe,KAAK,gBACxB,IAAI,KAAK,eAAiB,EAAa,CACrC,KAAK,YAAc,GACnB,MACF,CACA,QAAK,OAAS,EACd,KAAK,aAAe,EAAS,IACzB,EAAS,MAAQ,EACrB,IAAK,IAAM,KAAY,KAAK,UAC1B,GAAI,CACF,EAAS,CAAQ,CACnB,OAAS,EAAO,CAId,KAAK,QAAQ,MAAMA,EAAAA,WAAW,oBAAqB,EAAO,EAAG,GAAuB,KAAK,SAAU,CAAC,CACtG,CAZF,CAcF,CAEA,cAA6B,CAC3B,KAAK,iBAAmB,EACxB,KAAK,YAAc,GACnB,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,87 @@
|
|
|
1
|
+
import { TaskDocument } from "../../services/store/types.cjs";
|
|
2
|
+
import { TaskFailureReporter } from "../telemetry/logSinkTelemetry.cjs";
|
|
3
|
+
//#region src/adapters/store/taskStore.d.ts
|
|
4
|
+
type TaskStoreCommitListener = (previous: TaskDocument, committed: TaskDocument) => void;
|
|
5
|
+
interface TaskStoreOptions {
|
|
6
|
+
cwd?: string;
|
|
7
|
+
env?: NodeJS.ProcessEnv;
|
|
8
|
+
storePath?: string;
|
|
9
|
+
onCommitted?: TaskStoreCommitListener;
|
|
10
|
+
/** Backstop poll cadence for change detection. Lowered in tests so they do
|
|
11
|
+
* not depend on `fs.watch`, whose delivery timing is platform-dependent. */
|
|
12
|
+
pollIntervalMs?: number;
|
|
13
|
+
/** How long to wait for the advisory lock before proceeding lock-free. */
|
|
14
|
+
lockTimeoutMs?: number;
|
|
15
|
+
/** Where swallowed failures go, so silent degradation stays visible. */
|
|
16
|
+
report?: TaskFailureReporter;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* File-backed task store shared by one root session and its delegated children.
|
|
20
|
+
*
|
|
21
|
+
* Durability model: the JSON file is the source of truth. Mutations are
|
|
22
|
+
* read-modify-write under an advisory lock so concurrent delegated processes
|
|
23
|
+
* cannot clobber each other, and writes land via temp-file rename so a
|
|
24
|
+
* crash mid-write can never leave a partial document behind.
|
|
25
|
+
*/
|
|
26
|
+
declare class TaskStore {
|
|
27
|
+
storePath: string;
|
|
28
|
+
private readonly cwd;
|
|
29
|
+
private readonly env;
|
|
30
|
+
private cached;
|
|
31
|
+
private lastKnownRev;
|
|
32
|
+
private watcher?;
|
|
33
|
+
private pollTimer?;
|
|
34
|
+
private debounceTimer?;
|
|
35
|
+
private checkInFlight?;
|
|
36
|
+
private checkQueued;
|
|
37
|
+
private watchGeneration;
|
|
38
|
+
private readonly listeners;
|
|
39
|
+
private readonly pollIntervalMs;
|
|
40
|
+
private readonly lockTimeoutMs;
|
|
41
|
+
private readonly report?;
|
|
42
|
+
private readonly onCommitted?;
|
|
43
|
+
constructor(options?: TaskStoreOptions);
|
|
44
|
+
/** Bind a default store to the current session tree before reading or watching it. */
|
|
45
|
+
configureSession(sessionKey: string): void;
|
|
46
|
+
/** Last document read from disk, without hitting the filesystem. */
|
|
47
|
+
get snapshot(): TaskDocument;
|
|
48
|
+
read(): TaskDocument;
|
|
49
|
+
readAsync(): Promise<TaskDocument>;
|
|
50
|
+
private readDocumentAsync;
|
|
51
|
+
/**
|
|
52
|
+
* Apply a mutation under the store lock.
|
|
53
|
+
*
|
|
54
|
+
* `mutate` receives the freshest on-disk document and returns either the next
|
|
55
|
+
* document to commit or `undefined` for a read-only action (list/get), which
|
|
56
|
+
* skips the write entirely so queries never bump `rev`.
|
|
57
|
+
*/
|
|
58
|
+
mutate<T>(mutate: (document: TaskDocument) => {
|
|
59
|
+
document?: TaskDocument;
|
|
60
|
+
value: T;
|
|
61
|
+
}): Promise<{
|
|
62
|
+
document: TaskDocument;
|
|
63
|
+
value: T;
|
|
64
|
+
}>;
|
|
65
|
+
private notifyCommitted;
|
|
66
|
+
private write;
|
|
67
|
+
private acquireLock;
|
|
68
|
+
/** Remove a lock left behind by a dead process or one held implausibly long. */
|
|
69
|
+
private breakStaleLock;
|
|
70
|
+
/**
|
|
71
|
+
* Notify when another process changes the store.
|
|
72
|
+
*
|
|
73
|
+
* `fs.watch` alone is unreliable across the rename-based write (and on some
|
|
74
|
+
* network filesystems), so a slow poll backs it up. Writes made by this
|
|
75
|
+
* process are filtered out by revision so the UI does not redraw twice.
|
|
76
|
+
*/
|
|
77
|
+
onExternalChange(listener: (document: TaskDocument) => void): () => void;
|
|
78
|
+
private startWatching;
|
|
79
|
+
private scheduleCheck;
|
|
80
|
+
private queueChangeCheck;
|
|
81
|
+
private checkForChange;
|
|
82
|
+
private stopWatching;
|
|
83
|
+
dispose(): void;
|
|
84
|
+
}
|
|
85
|
+
//#endregion
|
|
86
|
+
export { TaskStore, TaskStoreCommitListener, TaskStoreOptions };
|
|
87
|
+
//# sourceMappingURL=taskStore.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"taskStore.d.cts","names":[],"sources":["../../../src/adapters/store/taskStore.ts"],"mappings":";;;KAkBY,2BAA2B,UAAU,cAAc,WAAW;UAEzD;EACf;EACA,MAAM,OAAO;EACb;EACA,cAAc;;;EAGd;;EAEA;;EAEA,SAAS;;;;;;;;;;cAsCE;EACX;mBAEiB;mBACA;UACT;UACA;UACA;UACA;UACA;UACA;UACA;UACA;mBACS;mBACA;mBACA;mBACA;mBACA;EAEL,YAAA,UAAS;;EAWrB,iBAAiB;;MASb,YAAY;EAIhB,QAAQ;EAiBF,aAAa,QAAQ;UAMb;;;;;;;;EAmBR,OAAO,GACX,SAAS,UAAU;IAAmB,WAAW;IAAc,OAAO;MACrE;IAAU,UAAU;IAAc,OAAO;;UAwBpC;UAQA;UAWM;;UAoCN;;;;;;;;EAyBR,iBAAiB,WAAW,UAAU;UAS9B;UAqBA;UAMA;UAiBM;UAuBN;EAWR"}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { TaskDocument } from "../../services/store/types.mjs";
|
|
2
|
+
import { TaskFailureReporter } from "../telemetry/logSinkTelemetry.mjs";
|
|
3
|
+
//#region src/adapters/store/taskStore.d.ts
|
|
4
|
+
type TaskStoreCommitListener = (previous: TaskDocument, committed: TaskDocument) => void;
|
|
5
|
+
interface TaskStoreOptions {
|
|
6
|
+
cwd?: string;
|
|
7
|
+
env?: NodeJS.ProcessEnv;
|
|
8
|
+
storePath?: string;
|
|
9
|
+
onCommitted?: TaskStoreCommitListener;
|
|
10
|
+
/** Backstop poll cadence for change detection. Lowered in tests so they do
|
|
11
|
+
* not depend on `fs.watch`, whose delivery timing is platform-dependent. */
|
|
12
|
+
pollIntervalMs?: number;
|
|
13
|
+
/** How long to wait for the advisory lock before proceeding lock-free. */
|
|
14
|
+
lockTimeoutMs?: number;
|
|
15
|
+
/** Where swallowed failures go, so silent degradation stays visible. */
|
|
16
|
+
report?: TaskFailureReporter;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* File-backed task store shared by one root session and its delegated children.
|
|
20
|
+
*
|
|
21
|
+
* Durability model: the JSON file is the source of truth. Mutations are
|
|
22
|
+
* read-modify-write under an advisory lock so concurrent delegated processes
|
|
23
|
+
* cannot clobber each other, and writes land via temp-file rename so a
|
|
24
|
+
* crash mid-write can never leave a partial document behind.
|
|
25
|
+
*/
|
|
26
|
+
declare class TaskStore {
|
|
27
|
+
storePath: string;
|
|
28
|
+
private readonly cwd;
|
|
29
|
+
private readonly env;
|
|
30
|
+
private cached;
|
|
31
|
+
private lastKnownRev;
|
|
32
|
+
private watcher?;
|
|
33
|
+
private pollTimer?;
|
|
34
|
+
private debounceTimer?;
|
|
35
|
+
private checkInFlight?;
|
|
36
|
+
private checkQueued;
|
|
37
|
+
private watchGeneration;
|
|
38
|
+
private readonly listeners;
|
|
39
|
+
private readonly pollIntervalMs;
|
|
40
|
+
private readonly lockTimeoutMs;
|
|
41
|
+
private readonly report?;
|
|
42
|
+
private readonly onCommitted?;
|
|
43
|
+
constructor(options?: TaskStoreOptions);
|
|
44
|
+
/** Bind a default store to the current session tree before reading or watching it. */
|
|
45
|
+
configureSession(sessionKey: string): void;
|
|
46
|
+
/** Last document read from disk, without hitting the filesystem. */
|
|
47
|
+
get snapshot(): TaskDocument;
|
|
48
|
+
read(): TaskDocument;
|
|
49
|
+
readAsync(): Promise<TaskDocument>;
|
|
50
|
+
private readDocumentAsync;
|
|
51
|
+
/**
|
|
52
|
+
* Apply a mutation under the store lock.
|
|
53
|
+
*
|
|
54
|
+
* `mutate` receives the freshest on-disk document and returns either the next
|
|
55
|
+
* document to commit or `undefined` for a read-only action (list/get), which
|
|
56
|
+
* skips the write entirely so queries never bump `rev`.
|
|
57
|
+
*/
|
|
58
|
+
mutate<T>(mutate: (document: TaskDocument) => {
|
|
59
|
+
document?: TaskDocument;
|
|
60
|
+
value: T;
|
|
61
|
+
}): Promise<{
|
|
62
|
+
document: TaskDocument;
|
|
63
|
+
value: T;
|
|
64
|
+
}>;
|
|
65
|
+
private notifyCommitted;
|
|
66
|
+
private write;
|
|
67
|
+
private acquireLock;
|
|
68
|
+
/** Remove a lock left behind by a dead process or one held implausibly long. */
|
|
69
|
+
private breakStaleLock;
|
|
70
|
+
/**
|
|
71
|
+
* Notify when another process changes the store.
|
|
72
|
+
*
|
|
73
|
+
* `fs.watch` alone is unreliable across the rename-based write (and on some
|
|
74
|
+
* network filesystems), so a slow poll backs it up. Writes made by this
|
|
75
|
+
* process are filtered out by revision so the UI does not redraw twice.
|
|
76
|
+
*/
|
|
77
|
+
onExternalChange(listener: (document: TaskDocument) => void): () => void;
|
|
78
|
+
private startWatching;
|
|
79
|
+
private scheduleCheck;
|
|
80
|
+
private queueChangeCheck;
|
|
81
|
+
private checkForChange;
|
|
82
|
+
private stopWatching;
|
|
83
|
+
dispose(): void;
|
|
84
|
+
}
|
|
85
|
+
//#endregion
|
|
86
|
+
export { TaskStore, TaskStoreCommitListener, TaskStoreOptions };
|
|
87
|
+
//# sourceMappingURL=taskStore.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"taskStore.d.mts","names":[],"sources":["../../../src/adapters/store/taskStore.ts"],"mappings":";;;KAkBY,2BAA2B,UAAU,cAAc,WAAW;UAEzD;EACf;EACA,MAAM,OAAO;EACb;EACA,cAAc;;;EAGd;;EAEA;;EAEA,SAAS;;;;;;;;;;cAsCE;EACX;mBAEiB;mBACA;UACT;UACA;UACA;UACA;UACA;UACA;UACA;UACA;mBACS;mBACA;mBACA;mBACA;mBACA;EAEL,YAAA,UAAS;;EAWrB,iBAAiB;;MASb,YAAY;EAIhB,QAAQ;EAiBF,aAAa,QAAQ;UAMb;;;;;;;;EAmBR,OAAO,GACX,SAAS,UAAU;IAAmB,WAAW;IAAc,OAAO;MACrE;IAAU,UAAU;IAAc,OAAO;;UAwBpC;UAQA;UAWM;;UAoCN;;;;;;;;EAyBR,iBAAiB,WAAW,UAAU;UAS9B;UAqBA;UAMA;UAiBM;UAuBN;EAWR"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{TASK_EVENT as e}from"../telemetry/logSinkTelemetry.mjs";import{isProcessAlive as t}from"../../services/store/processLiveness.mjs";import{emptyDocument as n}from"../../services/store/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;checkInFlight;checkQueued=!1;watchGeneration=0;listeners=new Set;pollIntervalMs;lockTimeoutMs;report;onCommitted;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,this.onCommitted=e.onCommitted}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 readAsync(){return this.cached=await this.readDocumentAsync(),this.lastKnownRev=this.cached.rev,this.cached}async readDocumentAsync(){try{let e=await s.promises.readFile(this.storePath,c);return f(JSON.parse(e))}catch(t){return t.code!==l&&this.report?.error(e.storeReadFailed,t,{[u]:this.storePath}),n()}}async mutate(e){let t=await this.acquireLock(),n=(()=>{try{let t=this.read(),n=e(t);if(!n.document)return{result:{document:t,value:n.value}};let r=this.write(n.document);return{result:{document:r,value:n.value},notification:{previous:t,committed:r}}}finally{t()}})();return n.notification&&this.notifyCommitted(n.notification.previous,n.notification.committed),n.result}notifyCommitted(t,n){try{this.onCommitted?.(t,n)}catch(t){this.report?.error(e.storeCommitListenerFailed,t,{[u]:this.storePath})}}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;this.watchGeneration+=1;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.queueChangeCheck(),this.pollIntervalMs),this.pollTimer.unref?.()}scheduleCheck(){clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>this.queueChangeCheck(),150),this.debounceTimer.unref?.()}queueChangeCheck(){if(this.checkInFlight){this.checkQueued=!0;return}let e=this.watchGeneration,t=(async()=>{do this.checkQueued=!1,await this.checkForChange(e);while(this.checkQueued&&e===this.watchGeneration)})().finally(()=>{this.checkInFlight===t&&(this.checkInFlight=void 0)});this.checkInFlight=t}async checkForChange(t){let n=this.lastKnownRev,r=await this.readDocumentAsync();if(t===this.watchGeneration){if(this.lastKnownRev!==n){this.checkQueued=!0;return}if(this.cached=r,this.lastKnownRev=r.rev,r.rev!==n)for(let t of this.listeners)try{t(r)}catch(t){this.report?.error(e.storeListenerFailed,t,{[u]:this.storePath})}}}stopWatching(){this.watchGeneration+=1,this.checkQueued=!1,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
|