opencode-work-context 0.1.4 → 0.1.6
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 +86 -8
- package/commands/wc.md +17 -6
- package/package.json +7 -3
- package/plugin/server.js +3 -0
- package/plugin/stages-tui.js +137 -37
- package/plugin/work-context.js +1 -1
- package/src/core.js +112 -13
- package/src/opencode-adapter.js +1 -1
- package/src/stages-renderer.js +1 -0
- package/src/stages-snapshot.js +1 -0
- package/src/storage.js +17 -7
- package/src/title.js +7 -3
- package/src/tool-definitions.js +25 -9
- package/tools/work_context_abandon_stage.js +3 -0
- package/tools/work_context_archive_stage.js +2 -0
- package/tools/work_context_rename_stage.js +2 -0
- package/tools/work_context_rename_workspace.js +2 -0
- package/tools/work_context_update_stage.js +2 -0
- package/tools/work_context_list_stages.js +0 -2
package/README.md
CHANGED
|
@@ -1,7 +1,67 @@
|
|
|
1
|
-
#
|
|
1
|
+
# OpenCode Work Context
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
Keep the context of a task between OpenCode sessions.
|
|
4
|
+
|
|
5
|
+
Create one workspace for one task, split it into stages, and return to the
|
|
6
|
+
exact stage where you stopped. The optional sidebar shows the current task and
|
|
7
|
+
its progress at a glance.
|
|
8
|
+
|
|
9
|
+

|
|
10
|
+
|
|
11
|
+
> Example: one workspace for one task, linked to Jira issue `AN-142`, with
|
|
12
|
+
> three completed stages and the current work highlighted at stage 04.
|
|
13
|
+
>
|
|
14
|
+
> The sidebar is an optional read-only TUI panel. The core workflow works
|
|
15
|
+
> through `/wc` commands and OpenCode tools without it.
|
|
16
|
+
|
|
17
|
+
## How It Works
|
|
18
|
+
|
|
19
|
+
```text
|
|
20
|
+
Workspace: Add CSV export to analytics report
|
|
21
|
+
├── ✓ 01. Planning
|
|
22
|
+
├── ✓ 02. Update the export endpoint
|
|
23
|
+
├── ✓ 03. Add the download action
|
|
24
|
+
├── • 04. Handle export edge cases <- current stage
|
|
25
|
+
└── 05. Verify the export flow
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
- **Workspace** is one concrete task, such as adding CSV export.
|
|
29
|
+
- **Stage** is one step in that task.
|
|
30
|
+
- **Planning** is normally the first stage.
|
|
31
|
+
- **Resume** starts a new session at a selected stage.
|
|
32
|
+
- **Handoff** preserves the context when moving work to another session.
|
|
33
|
+
|
|
34
|
+
## Quick Start
|
|
35
|
+
|
|
36
|
+
Run this from the root of a standalone OpenCode project:
|
|
37
|
+
|
|
38
|
+
```sh
|
|
39
|
+
npx opencode-work-context init
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Then create a task and its first stage in OpenCode:
|
|
43
|
+
|
|
44
|
+
```text
|
|
45
|
+
/wc create "Add CSV export to analytics report"
|
|
46
|
+
/wc stage rename 000001 01 "Planning"
|
|
47
|
+
/wc stage add 000001 "Update the export endpoint"
|
|
48
|
+
/wc resume 000001 02
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
When you return later, continue from the active stage:
|
|
52
|
+
|
|
53
|
+
```text
|
|
54
|
+
/wc resume 000001 02
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Useful commands:
|
|
58
|
+
|
|
59
|
+
```text
|
|
60
|
+
/wc list
|
|
61
|
+
/wc workspace list 000001
|
|
62
|
+
/wc stage handoff 000001 02
|
|
63
|
+
/wc stage finish 000001 02
|
|
64
|
+
```
|
|
5
65
|
|
|
6
66
|
## Install
|
|
7
67
|
|
|
@@ -11,7 +71,7 @@ Run from the root of a standalone OpenCode project:
|
|
|
11
71
|
npx opencode-work-context init
|
|
12
72
|
```
|
|
13
73
|
|
|
14
|
-
`init` installs
|
|
74
|
+
`init` installs the current package version as an exact devDependency using
|
|
15
75
|
standard `npm`, preserving normal lifecycle behavior for the host project. The
|
|
16
76
|
dependency root is the project root when it has `package.json`, otherwise
|
|
17
77
|
`.opencode` when `.opencode/package.json` exists, and finally the project root
|
|
@@ -39,13 +99,19 @@ Generated files:
|
|
|
39
99
|
created on the first explicit knowledge operation.
|
|
40
100
|
|
|
41
101
|
The optional read-only stages panel is a separate TUI plugin. Add a project-local
|
|
42
|
-
loader at `.opencode/plugins/work-context-stages.js`:
|
|
102
|
+
loader outside OpenCode's server-plugin autoscan at `.opencode/tui-plugins/work-context-stages.js`:
|
|
43
103
|
|
|
44
104
|
```js
|
|
45
105
|
export { default } from "opencode-work-context/tui";
|
|
46
106
|
```
|
|
47
107
|
|
|
48
|
-
Enable that loader in
|
|
108
|
+
Enable that loader explicitly in `.opencode/tui.json`:
|
|
109
|
+
|
|
110
|
+
```json
|
|
111
|
+
{ "$schema": "https://opencode.ai/tui.json", "plugin": ["./tui-plugins/work-context-stages.js"] }
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
The package keeps the
|
|
49
115
|
existing `opencode-work-context/plugin` server export unchanged and exposes the
|
|
50
116
|
panel as `opencode-work-context/tui`. The panel only reads canonical storage via
|
|
51
117
|
`WorkContext.openExisting`; it does not create `.work-context`, call lifecycle
|
|
@@ -53,11 +119,18 @@ tools, or modify Markdown/JSONL projections. Hosts without the TUI plugin API
|
|
|
53
119
|
continue to load the server plugin and its tools normally.
|
|
54
120
|
|
|
55
121
|
Tools are registered by the installed plugin and are not copied into the project.
|
|
122
|
+
Tracker links support GitLab issues (`/-/issues/<number>`), GitHub issues
|
|
123
|
+
(`/issues/<number>`), and Jira issues (`/browse/KEY-123`). They are URL-based
|
|
124
|
+
references only; the plugin does not call provider APIs or synchronize issue
|
|
125
|
+
metadata.
|
|
56
126
|
Knowledge operations are explicit: list, add, update, and supersede. Finishing a
|
|
57
|
-
stage
|
|
127
|
+
stage automatically validates the Knowledge Base by default (`knowledgeReview=auto`);
|
|
128
|
+
the legacy `added` and `none` modes remain accepted.
|
|
58
129
|
Finish a workspace explicitly with `/wc workspace finish <workspace>`; it is
|
|
59
130
|
accepted only after every stage is `completed`. Use `/wc workspace list <workspace>`
|
|
60
|
-
to list stages with their descriptions.
|
|
131
|
+
to list stages with their descriptions. Workspace titles can be changed with
|
|
132
|
+
`/wc workspace rename <workspace> "title"`, and existing stage descriptions can
|
|
133
|
+
be changed with `/wc stage update <workspace> <stage> "description"`.
|
|
61
134
|
|
|
62
135
|
If the host `opencode.json` restricts `experimental.primary_tools`, add the
|
|
63
136
|
registered `work_context_*` tool names to that allowlist; the installer does not
|
|
@@ -86,3 +159,8 @@ The package layout is intentionally small:
|
|
|
86
159
|
- `test/` contains core contract tests.
|
|
87
160
|
|
|
88
161
|
Run `npm test` when explicitly verifying a checkout.
|
|
162
|
+
|
|
163
|
+
Run `npm run test:integration` for the reusable plugin-boundary scenarios. These
|
|
164
|
+
tests create isolated fixture projects, use a small fake OpenCode host, and
|
|
165
|
+
exercise a new session resume through the server title hook and read-only TUI
|
|
166
|
+
snapshot without requiring an interactive OpenCode process.
|
package/commands/wc.md
CHANGED
|
@@ -17,10 +17,16 @@ Use these exact tool mappings; do not invent shortened tool names:
|
|
|
17
17
|
- `create` -> `work_context_create_workspace`
|
|
18
18
|
- `list` -> `work_context_list_workspaces`
|
|
19
19
|
- `workspace list <workspace>` or `<workspace> list` -> `work_context_workspace_list`
|
|
20
|
+
- `workspace rename <workspace> "title"` -> `work_context_rename_workspace`
|
|
20
21
|
- `workspace finish <workspace>` -> `work_context_workspace_finish`
|
|
21
22
|
- `resume <workspace> <stage>` -> `work_context_start_session`
|
|
22
|
-
- `
|
|
23
|
-
- `
|
|
23
|
+
- `stage add [<workspace>] ...` -> `work_context_add_stage`
|
|
24
|
+
- `stage rename [<workspace>] <stage> "title"` -> `work_context_rename_stage`
|
|
25
|
+
- `stage update [<workspace>] <stage> "description"` -> `work_context_update_stage`
|
|
26
|
+
- `stage archive [<workspace>] <stage>` -> `work_context_archive_stage`
|
|
27
|
+
- `stage handoff <workspace> <stage>` -> `work_context_handoff_stage`
|
|
28
|
+
- `stage abandon <workspace> <stage>` -> `work_context_abandon_stage`
|
|
29
|
+
- `stage finish <workspace> <stage>` -> `work_context_finish_stage`
|
|
24
30
|
|
|
25
31
|
Supported syntax:
|
|
26
32
|
|
|
@@ -28,14 +34,19 @@ Supported syntax:
|
|
|
28
34
|
- `create "title"`
|
|
29
35
|
- `list` or `<workspace> list`
|
|
30
36
|
- `workspace list <workspace>`
|
|
37
|
+
- `workspace rename <workspace> "title"`
|
|
31
38
|
- `workspace finish <workspace>`
|
|
32
39
|
- `resume <workspace> <stage>`
|
|
33
|
-
- `
|
|
40
|
+
- `stage add [<workspace>] "title"`
|
|
41
|
+
- `stage rename [<workspace>] <stage> "title"`
|
|
42
|
+
- `stage update [<workspace>] <stage> "description"`
|
|
43
|
+
- `stage archive [<workspace>] <stage>`
|
|
44
|
+
- `stage finish <workspace> <stage>`
|
|
34
45
|
- `<workspace> [<stage>] link-issue <URL>`
|
|
35
46
|
- `session rename "summary"`
|
|
36
|
-
- `
|
|
37
|
-
- `
|
|
38
|
-
- `finish <workspace> <stage>`
|
|
47
|
+
- `stage handoff <workspace> <stage>`
|
|
48
|
+
- `stage abandon <workspace> <stage>`
|
|
49
|
+
- `stage finish <workspace> <stage>` automatically reviews the Knowledge Base (`auto` by default)
|
|
39
50
|
- `knowledge list|add|update|supersede <workspace> ...`
|
|
40
51
|
|
|
41
52
|
Arguments: $ARGUMENTS
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-work-context",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.1.
|
|
4
|
+
"version": "0.1.6",
|
|
5
5
|
"description": "Filesystem work-context core and OpenCode adapter",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": {
|
|
@@ -29,7 +29,9 @@
|
|
|
29
29
|
"opencode-work-context": "bin/opencode-work-context.js"
|
|
30
30
|
},
|
|
31
31
|
"scripts": {
|
|
32
|
-
"test": "node --test"
|
|
32
|
+
"test": "node --test",
|
|
33
|
+
"test:integration": "node --test test/integration/*.test.js",
|
|
34
|
+
"test:tui": "OPENCODE_TUI_SMOKE=1 bun --conditions=browser test test/stages-tui.test.js"
|
|
33
35
|
},
|
|
34
36
|
"files": [
|
|
35
37
|
"bin",
|
|
@@ -42,12 +44,14 @@
|
|
|
42
44
|
],
|
|
43
45
|
"dependencies": {
|
|
44
46
|
"@opencode-ai/plugin": "^1.14.50",
|
|
45
|
-
"@opentui/solid": "^0.4.5"
|
|
47
|
+
"@opentui/solid": "^0.4.5",
|
|
48
|
+
"solid-js": "1.9.12"
|
|
46
49
|
},
|
|
47
50
|
"exports": {
|
|
48
51
|
".": "./src/index.js",
|
|
49
52
|
"./adapter": "./src/opencode-adapter.js",
|
|
50
53
|
"./plugin": "./plugin/work-context.js",
|
|
54
|
+
"./server": "./plugin/server.js",
|
|
51
55
|
"./tui": "./plugin/stages-tui.js",
|
|
52
56
|
"./tools/*": "./tools/*.js"
|
|
53
57
|
}
|
package/plugin/server.js
ADDED
package/plugin/stages-tui.js
CHANGED
|
@@ -1,57 +1,94 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
1
3
|
import { readStagesSnapshot } from "../src/stages-snapshot.js";
|
|
2
4
|
import { renderStagesPanel } from "../src/stages-renderer.js";
|
|
3
5
|
import { jsx } from "@opentui/solid/jsx-runtime";
|
|
6
|
+
import { createSignal } from "solid-js";
|
|
4
7
|
|
|
5
8
|
const DEBOUNCE_MS = 150;
|
|
9
|
+
const POLL_MS = 1000;
|
|
10
|
+
const PATH_TIMEOUT_MS = 5000;
|
|
11
|
+
const PATH_POLL_MS = 25;
|
|
12
|
+
const WORK_CONTEXT_PREFIX = "work" + "_" + "context_";
|
|
6
13
|
const statusMarker = (status) => ({
|
|
7
14
|
planned: "[ ]",
|
|
8
15
|
in_progress: "[•]",
|
|
9
16
|
completed: "[✓]",
|
|
10
17
|
cancelled: "[!]",
|
|
18
|
+
archived: "[-]",
|
|
11
19
|
}[status] || "[?]");
|
|
12
20
|
|
|
13
21
|
export { readStagesSnapshot, renderStagesPanel };
|
|
14
22
|
|
|
15
|
-
|
|
23
|
+
const defaultRuntime = { jsx };
|
|
24
|
+
|
|
25
|
+
const renderStagesContent = (result, theme, runtime = defaultRuntime) => !result?.ok || !result.data?.workspace
|
|
26
|
+
? [
|
|
27
|
+
runtime.jsx("text", { children: runtime.jsx("b", { children: "Stages" }) }),
|
|
28
|
+
...renderStagesPanel(result).split("\n").slice(1).map((line) => runtime.jsx("text", { children: line })),
|
|
29
|
+
]
|
|
30
|
+
: [
|
|
31
|
+
runtime.jsx("box", {
|
|
32
|
+
flexDirection: "row",
|
|
33
|
+
children: [
|
|
34
|
+
runtime.jsx("text", { children: runtime.jsx("b", { children: "Stages" }) }),
|
|
35
|
+
runtime.jsx("text", { fg: theme?.current?.textMuted, children: ` · ${result.data.workspace.status}` }),
|
|
36
|
+
],
|
|
37
|
+
}),
|
|
38
|
+
...result.data.stages.map((stage) => runtime.jsx("box", {
|
|
39
|
+
flexDirection: "row",
|
|
40
|
+
children: [
|
|
41
|
+
runtime.jsx("text", { flexShrink: 0, marginRight: 1, fg: stage.current || stage.id === result.data.currentStage ? theme?.current?.warning : theme?.current?.textMuted, children: statusMarker(stage.status) }),
|
|
42
|
+
runtime.jsx("text", { flexGrow: 1, flexShrink: 1, wrapMode: "word", fg: stage.current || stage.id === result.data.currentStage ? theme?.current?.warning : theme?.current?.textMuted, children: `${stage.id}. ${stage.title}` }),
|
|
43
|
+
],
|
|
44
|
+
})),
|
|
45
|
+
];
|
|
46
|
+
|
|
47
|
+
export const renderStagesElement = (result, theme, runtime = defaultRuntime) => {
|
|
48
|
+
return runtime.jsx("box", {
|
|
16
49
|
flexDirection: "column",
|
|
17
|
-
children:
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
...renderStagesPanel(result).split("\n").slice(1).map((line) => jsx("text", { children: line })),
|
|
21
|
-
]
|
|
22
|
-
: [
|
|
23
|
-
jsx("box", {
|
|
24
|
-
flexDirection: "row",
|
|
25
|
-
children: [
|
|
26
|
-
jsx("text", { children: jsx("b", { children: "Stages" }) }),
|
|
27
|
-
jsx("text", { fg: theme?.current?.textMuted, children: ` · ${result.data.workspace.status}` }),
|
|
28
|
-
],
|
|
29
|
-
}),
|
|
30
|
-
...result.data.stages.map((stage) => jsx("box", {
|
|
31
|
-
flexDirection: "row",
|
|
32
|
-
children: [
|
|
33
|
-
jsx("text", { flexShrink: 0, marginRight: 1, fg: stage.current || stage.id === result.data.currentStage ? theme?.current?.warning : theme?.current?.textMuted, children: statusMarker(stage.status) }),
|
|
34
|
-
jsx("text", { flexGrow: 1, flexShrink: 1, wrapMode: "word", fg: stage.current || stage.id === result.data.currentStage ? theme?.current?.warning : theme?.current?.textMuted, children: `${stage.id}. ${stage.title}` }),
|
|
35
|
-
],
|
|
36
|
-
})),
|
|
37
|
-
],
|
|
38
|
-
});
|
|
50
|
+
children: () => renderStagesContent(typeof result === "function" ? result() : result, theme, runtime),
|
|
51
|
+
});
|
|
52
|
+
};
|
|
39
53
|
|
|
40
54
|
const sessionIdFromEvent = (event) => event?.properties?.info?.id
|
|
41
55
|
|| event?.properties?.sessionID
|
|
42
56
|
|| event?.sessionID
|
|
43
57
|
|| event?.sessionId
|
|
44
58
|
|| event?.data?.info?.id
|
|
45
|
-
|| event?.data?.sessionID
|
|
59
|
+
|| event?.data?.sessionID
|
|
60
|
+
|| event?.properties?.part?.sessionID;
|
|
61
|
+
const isCompletedWorkContextTool = (event) => {
|
|
62
|
+
const part = event?.properties?.part;
|
|
63
|
+
return event?.type === "message.part.updated"
|
|
64
|
+
&& part?.type === "tool"
|
|
65
|
+
&& part.tool?.startsWith(WORK_CONTEXT_PREFIX)
|
|
66
|
+
&& ["completed", "error"].includes(part.state?.status);
|
|
67
|
+
};
|
|
68
|
+
export const sessionIdForSlot = (api, initialSessionId, slotContext = {}, slotState = {}) => slotState.session_id
|
|
69
|
+
|| slotState.sessionID
|
|
70
|
+
|| slotState.sessionId
|
|
71
|
+
|| slotState.session
|
|
72
|
+
|| slotContext.session_id
|
|
73
|
+
|| slotContext.sessionID
|
|
74
|
+
|| slotContext.sessionId
|
|
75
|
+
|| slotContext.session
|
|
76
|
+
|| api.route?.current?.params?.sessionID
|
|
77
|
+
|| api.route?.current?.params?.sessionId
|
|
78
|
+
|| api.route?.current?.params?.session_id
|
|
79
|
+
|| api.route?.current?.params?.session
|
|
80
|
+
|| initialSessionId;
|
|
46
81
|
const disposeRegistration = (registration) => {
|
|
47
82
|
if (typeof registration === "function") registration();
|
|
48
83
|
else registration?.dispose?.();
|
|
49
84
|
};
|
|
50
85
|
|
|
51
|
-
export const createStagesTuiController = ({ projectRoot, read = readStagesSnapshot, debounceMs = DEBOUNCE_MS } = {}) => {
|
|
86
|
+
export const createStagesTuiController = ({ projectRoot, read = readStagesSnapshot, debounceMs = DEBOUNCE_MS, pollMs = POLL_MS, createSignal: makeSignal = createSignal } = {}) => {
|
|
52
87
|
const snapshots = new Map();
|
|
53
88
|
const generations = new Map();
|
|
54
89
|
const timers = new Map();
|
|
90
|
+
const pollers = new Map();
|
|
91
|
+
const [version, setVersion] = makeSignal(0);
|
|
55
92
|
let disposed = false;
|
|
56
93
|
|
|
57
94
|
const readSnapshot = async (sessionId) => {
|
|
@@ -60,6 +97,7 @@ export const createStagesTuiController = ({ projectRoot, read = readStagesSnapsh
|
|
|
60
97
|
generations.set(sessionId, currentGeneration);
|
|
61
98
|
const entry = snapshots.get(sessionId) || { result: null, successful: null };
|
|
62
99
|
snapshots.set(sessionId, entry);
|
|
100
|
+
setVersion((value) => value + 1);
|
|
63
101
|
try {
|
|
64
102
|
const result = await read({ projectRoot, sessionId });
|
|
65
103
|
if (disposed || currentGeneration !== generations.get(sessionId)) return;
|
|
@@ -78,6 +116,7 @@ export const createStagesTuiController = ({ projectRoot, read = readStagesSnapsh
|
|
|
78
116
|
: { ok: false, error: { code: error.code || "STORAGE_ERROR", message: error.message } };
|
|
79
117
|
}
|
|
80
118
|
snapshots.set(sessionId, entry);
|
|
119
|
+
setVersion((value) => value + 1);
|
|
81
120
|
};
|
|
82
121
|
|
|
83
122
|
const scheduleRefresh = (sessionId) => {
|
|
@@ -90,7 +129,14 @@ export const createStagesTuiController = ({ projectRoot, read = readStagesSnapsh
|
|
|
90
129
|
}, debounceMs));
|
|
91
130
|
};
|
|
92
131
|
|
|
132
|
+
const watch = (sessionId) => {
|
|
133
|
+
if (disposed || !sessionId || pollers.has(sessionId) || !pollMs) return;
|
|
134
|
+
pollers.set(sessionId, setInterval(() => scheduleRefresh(sessionId), pollMs));
|
|
135
|
+
};
|
|
136
|
+
|
|
93
137
|
const resultFor = (sessionId) => {
|
|
138
|
+
version();
|
|
139
|
+
watch(sessionId);
|
|
94
140
|
const entry = snapshots.get(sessionId);
|
|
95
141
|
if (!entry) {
|
|
96
142
|
void readSnapshot(sessionId);
|
|
@@ -109,47 +155,101 @@ export const createStagesTuiController = ({ projectRoot, read = readStagesSnapsh
|
|
|
109
155
|
generations.clear();
|
|
110
156
|
for (const timer of timers.values()) clearTimeout(timer);
|
|
111
157
|
timers.clear();
|
|
158
|
+
for (const poller of pollers.values()) clearInterval(poller);
|
|
159
|
+
pollers.clear();
|
|
112
160
|
snapshots.clear();
|
|
113
161
|
},
|
|
114
162
|
};
|
|
115
163
|
};
|
|
116
164
|
|
|
165
|
+
const sleep = (milliseconds, signal) => new Promise((resolve) => {
|
|
166
|
+
const timer = setTimeout(resolve, milliseconds);
|
|
167
|
+
const onAbort = () => { clearTimeout(timer); resolve(); };
|
|
168
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
169
|
+
if (signal) setTimeout(() => signal.removeEventListener("abort", onAbort), milliseconds);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
export const resolveProjectRoot = async (api, { timeoutMs = PATH_TIMEOUT_MS, pollMs = PATH_POLL_MS } = {}) => {
|
|
173
|
+
if (!api?.slots?.register) return null;
|
|
174
|
+
const signal = api.lifecycle?.signal;
|
|
175
|
+
const deadline = Date.now() + timeoutMs;
|
|
176
|
+
while (!signal?.aborted && Date.now() <= deadline) {
|
|
177
|
+
if (api.state?.path?.worktree) return api.state.path.worktree;
|
|
178
|
+
try {
|
|
179
|
+
const location = await api.client?.location?.get?.({});
|
|
180
|
+
const directory = location?.data?.directory || location?.data?.project?.directory;
|
|
181
|
+
if (directory) return directory;
|
|
182
|
+
} catch {}
|
|
183
|
+
await sleep(pollMs, signal);
|
|
184
|
+
}
|
|
185
|
+
return null;
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
const renderStagesSlot = (controller, theme, sessionId, runtime = defaultRuntime) => runtime.jsx("box", {
|
|
189
|
+
flexDirection: "column",
|
|
190
|
+
children: renderStagesElement(() => controller.resultFor(sessionId), theme, runtime),
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
const ACTIVE_WORKSPACE_SESSION = "__active_" + "work" + "_context_workspace__";
|
|
194
|
+
|
|
117
195
|
// Optional TUI entry point. It is deliberately not imported by the server plugin.
|
|
118
|
-
export const tui = async (api) => {
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
if (!api?.slots?.register || !api?.state?.path?.worktree) return {};
|
|
196
|
+
export const tui = async (api, options = {}) => {
|
|
197
|
+
const projectRoot = await resolveProjectRoot(api, options);
|
|
198
|
+
if (!projectRoot) return;
|
|
122
199
|
|
|
123
|
-
const projectRoot = api.state.path.worktree;
|
|
124
200
|
const initialSessionId = api.route?.current?.name === "session"
|
|
125
201
|
? api.route.current.params?.sessionID
|
|
202
|
+
|| api.route.current.params?.sessionId
|
|
203
|
+
|| api.route.current.params?.session_id
|
|
126
204
|
: undefined;
|
|
127
|
-
const controller = createStagesTuiController({
|
|
205
|
+
const controller = createStagesTuiController({
|
|
206
|
+
projectRoot,
|
|
207
|
+
read: api.stagesSnapshotProvider || readStagesSnapshot,
|
|
208
|
+
debounceMs: options.debounceMs,
|
|
209
|
+
pollMs: options.pollMs,
|
|
210
|
+
createSignal: options.runtime?.createSignal,
|
|
211
|
+
});
|
|
128
212
|
await controller.load(initialSessionId);
|
|
213
|
+
let currentSessionId = initialSessionId;
|
|
214
|
+
let storageWatcher;
|
|
215
|
+
try {
|
|
216
|
+
storageWatcher = fs.watch(path.join(projectRoot, ".work-context"), { recursive: true }, () => {
|
|
217
|
+
controller.scheduleRefresh(currentSessionId);
|
|
218
|
+
});
|
|
219
|
+
} catch {
|
|
220
|
+
// Missing storage is valid; the provider will continue to expose an empty state.
|
|
221
|
+
}
|
|
129
222
|
|
|
223
|
+
let cleanup = () => {};
|
|
130
224
|
const unregisterSlot = api.slots.register({
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
225
|
+
dispose: () => cleanup(),
|
|
226
|
+
slots: {
|
|
227
|
+
sidebar_content: (slotContext = {}, slotState = {}) => {
|
|
228
|
+
const sessionId = sessionIdForSlot(api, initialSessionId, slotContext, slotState) || ACTIVE_WORKSPACE_SESSION;
|
|
229
|
+
currentSessionId = sessionId;
|
|
230
|
+
return renderStagesSlot(controller, api.theme, sessionId, options.runtime);
|
|
134
231
|
},
|
|
135
232
|
},
|
|
136
233
|
});
|
|
137
234
|
const unsubscribe = api.event?.on?.("session.updated", (event) => {
|
|
138
235
|
controller.scheduleRefresh(sessionIdFromEvent(event));
|
|
139
236
|
});
|
|
237
|
+
const unsubscribeTool = api.event?.on?.("message.part.updated", (event) => {
|
|
238
|
+
if (isCompletedWorkContextTool(event)) controller.scheduleRefresh(sessionIdFromEvent(event));
|
|
239
|
+
});
|
|
140
240
|
|
|
141
241
|
let cleaned = false;
|
|
142
|
-
|
|
242
|
+
cleanup = () => {
|
|
143
243
|
if (cleaned) return;
|
|
144
244
|
cleaned = true;
|
|
145
245
|
controller.dispose();
|
|
246
|
+
storageWatcher?.close();
|
|
146
247
|
disposeRegistration(unsubscribe);
|
|
248
|
+
disposeRegistration(unsubscribeTool);
|
|
147
249
|
disposeRegistration(unregisterSlot);
|
|
148
250
|
};
|
|
149
251
|
api.lifecycle?.onDispose?.(cleanup);
|
|
150
252
|
|
|
151
|
-
// Hosts without a lifecycle API can still explicitly release the adapter.
|
|
152
|
-
return { dispose: cleanup };
|
|
153
253
|
};
|
|
154
254
|
|
|
155
255
|
export default { id: "work-context-stages", tui };
|
package/plugin/work-context.js
CHANGED
|
@@ -23,7 +23,7 @@ export default async ({ client, directory, worktree }) => ({
|
|
|
23
23
|
async function updateSessionTitle(client, projectRoot, directory, sessionId) {
|
|
24
24
|
try {
|
|
25
25
|
const context = contextFor(projectRoot, sessionId);
|
|
26
|
-
const session = context.sessionById(sessionId);
|
|
26
|
+
const session = context.sessionById(sessionId) || context.sessionByOpenCodeId(sessionId);
|
|
27
27
|
if (!session) return;
|
|
28
28
|
const title = titleFor(context, session.workspace, session.stage, sessionId, session);
|
|
29
29
|
if (!title) return;
|
package/src/core.js
CHANGED
|
@@ -15,14 +15,23 @@ const id = (value, digits) => {
|
|
|
15
15
|
const stageId = (value) => id(String(value).padStart(2, "0"), 2);
|
|
16
16
|
const actor = (options) => options.actor || "OpenCode";
|
|
17
17
|
const body = (title, goal = "") => `# ${title}\n\n${goal ? `## Goal\n\n${goal}\n` : ""}`;
|
|
18
|
+
const stageBody = (record, title, goal) => {
|
|
19
|
+
const result = record.body.match(/\n## Result[\s\S]*$/)?.[0] || "";
|
|
20
|
+
return `${body(title, goal).trimEnd()}${result}`;
|
|
21
|
+
};
|
|
18
22
|
const assertNoSymlinkPath = (file) => { let current = path.parse(file).root; for (const part of file.slice(current.length).split(path.sep).filter(Boolean)) { current = path.join(current, part); try { if (fs.lstatSync(current).isSymbolicLink()) fail(ERROR_CODES.STORAGE_ERROR, `Symlink path component is not supported: ${current}`); } catch (error) { if (error.code !== "ENOENT") throw error; break; } } };
|
|
19
23
|
|
|
20
24
|
function parseIssue(url) {
|
|
21
25
|
try {
|
|
22
26
|
const parsed = new URL(url);
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
return { url: parsed.toString(), provider: "gitlab", project:
|
|
27
|
+
if (!/^https?:$/.test(parsed.protocol)) fail(ERROR_CODES.INVALID_ISSUE_URL, "Expected a supported tracker issue URL");
|
|
28
|
+
let match = parsed.pathname.match(/^\/(.+)\/-\/issues\/(\d+)\/?$/);
|
|
29
|
+
if (match) return { url: parsed.toString(), provider: "gitlab", project: match[1], iid: Number(match[2]) };
|
|
30
|
+
match = parsed.pathname.match(/^\/([^/]+\/[^/]+)\/issues\/(\d+)\/?$/);
|
|
31
|
+
if (match) return { url: parsed.toString(), provider: "github", project: match[1], iid: Number(match[2]) };
|
|
32
|
+
match = parsed.pathname.match(/^\/browse\/([A-Za-z][A-Za-z0-9]+-\d+)\/?$/);
|
|
33
|
+
if (match) return { url: parsed.toString(), provider: "jira", project: match[1].split("-")[0], key: match[1] };
|
|
34
|
+
fail(ERROR_CODES.INVALID_ISSUE_URL, "Expected a supported tracker issue URL");
|
|
26
35
|
} catch (error) {
|
|
27
36
|
if (error.code === ERROR_CODES.INVALID_ISSUE_URL) throw error;
|
|
28
37
|
fail(ERROR_CODES.INVALID_ISSUE_URL, "Invalid issue URL");
|
|
@@ -113,7 +122,7 @@ export class WorkContext {
|
|
|
113
122
|
const record = this.storage.readWorkspace(workspace);
|
|
114
123
|
const stages = this.listStages(workspace).data.stages;
|
|
115
124
|
if (record.data.status === "cancelled") fail(ERROR_CODES.INVALID_STATE, "Cancelled workspace cannot be finished", { workspace, status: record.data.status });
|
|
116
|
-
|
|
125
|
+
const incompleteStages = stages.filter((stage) => stage.status !== "completed" && stage.status !== "archived");
|
|
117
126
|
if (incompleteStages.length) fail(ERROR_CODES.INVALID_STATE, "All workspace stages must be completed before finishing", {
|
|
118
127
|
workspace,
|
|
119
128
|
incompleteStages: incompleteStages.map(({ stage, title, description, status }) => ({ stage, title, description, status })),
|
|
@@ -131,6 +140,13 @@ export class WorkContext {
|
|
|
131
140
|
return reduceSessions(this.storage.readEvents()).find((session) => session.session_id === sessionId) || null;
|
|
132
141
|
}
|
|
133
142
|
|
|
143
|
+
sessionByOpenCodeId(opencodeSessionId, workspace = null, stage = null, state = "active") {
|
|
144
|
+
return reduceSessions(this.storage.readEvents()).filter((session) => session.opencode_session_id === opencodeSessionId
|
|
145
|
+
&& (!workspace || session.workspace === workspace)
|
|
146
|
+
&& (!stage || session.stage === stage)
|
|
147
|
+
&& (!state || session.state === state)).at(-1) || null;
|
|
148
|
+
}
|
|
149
|
+
|
|
134
150
|
assertDependenciesCompleted(workspace, stageRecord) {
|
|
135
151
|
const stages = this.listStages(workspace).data.stages;
|
|
136
152
|
for (const dependency of stageRecord.data.depends_on) {
|
|
@@ -149,15 +165,30 @@ export class WorkContext {
|
|
|
149
165
|
if (fs.existsSync(this.storage.workspaceDir(workspace))) fail(ERROR_CODES.CONFLICT, "Workspace already exists");
|
|
150
166
|
fs.mkdirSync(path.join(this.storage.workspaceDir(workspace), "stages"), { recursive: true });
|
|
151
167
|
this.storage.writeMarkdown(this.storage.workspaceFile(workspace), { schema: 1, workspace, title: title.trim(), status: "in_progress", created_at: now, updated_at: now, tracker_links: [] }, body(title));
|
|
152
|
-
this.storage.writeMarkdown(this.storage.stageFile(workspace, "01"), { schema: 1, workspace, stage: "01", title:
|
|
168
|
+
this.storage.writeMarkdown(this.storage.stageFile(workspace, "01"), { schema: 1, workspace, stage: "01", title: "Планирование", status: "in_progress", goal: "Уточнить цель и ограничения работы", depends_on: [], owner: actor(this.options), created_at: now, updated_at: now, tracker_links: [] }, body("Планирование", "Уточнить цель и ограничения работы"));
|
|
153
169
|
const sessionId = options.sessionId || randomUUID();
|
|
154
170
|
if (this.storage.readEvents().some((item) => item.session_id === sessionId)) fail(ERROR_CODES.CONFLICT, "Session ID already exists");
|
|
155
|
-
this.writeEvents([event("session.started", workspace, "01", 1, sessionId, actor(this.options), { summary: `планирование ${title.trim()}
|
|
171
|
+
this.writeEvents([event("session.started", workspace, "01", 1, sessionId, actor(this.options), { summary: `планирование ${title.trim()}`, opencode_session_id: options.opencodeSessionId || null, branch: options.branch || null })]);
|
|
156
172
|
generateProjections(this.storage);
|
|
157
173
|
return this.result({ workspace, stage: "01", session_id: sessionId, ordinal: "01/01" }, [workspace, "01"]);
|
|
158
174
|
});
|
|
159
175
|
}
|
|
160
176
|
|
|
177
|
+
renameWorkspace(workspace, title) {
|
|
178
|
+
id(workspace, 6);
|
|
179
|
+
if (!title?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Title is required");
|
|
180
|
+
return this.transact(`workspace-${workspace}`, () => {
|
|
181
|
+
const record = this.storage.readWorkspace(workspace);
|
|
182
|
+
const nextTitle = title.trim();
|
|
183
|
+
if (record.data.title === nextTitle) return this.result({ workspace, title: nextTitle }, []);
|
|
184
|
+
record.data.title = nextTitle;
|
|
185
|
+
record.data.updated_at = new Date().toISOString();
|
|
186
|
+
this.storage.writeMarkdown(this.storage.workspaceFile(workspace), record.data, body(nextTitle));
|
|
187
|
+
generateProjections(this.storage);
|
|
188
|
+
return this.result({ workspace, title: nextTitle }, [workspace]);
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
161
192
|
nextWorkspace() {
|
|
162
193
|
const ids = this.listWorkspaces().data.map((workspace) => Number(workspace.workspace));
|
|
163
194
|
return String(Math.max(0, ...ids) + 1).padStart(6, "0");
|
|
@@ -171,8 +202,15 @@ export class WorkContext {
|
|
|
171
202
|
const stageRecord = this.storage.readStage(workspace, stage);
|
|
172
203
|
this.assertDependenciesCompleted(workspace, stageRecord);
|
|
173
204
|
const events = this.storage.readEvents();
|
|
174
|
-
|
|
175
|
-
if (
|
|
205
|
+
const current = activeSession(events, workspace, stage);
|
|
206
|
+
if (current) {
|
|
207
|
+
const canTakeOver = options.takeover
|
|
208
|
+
&& current.session_id !== sessionId
|
|
209
|
+
&& current.opencode_session_id !== options.opencodeSessionId;
|
|
210
|
+
if (!canTakeOver) fail(ERROR_CODES.ACTIVE_SESSION_EXISTS, "Stage already has an active session");
|
|
211
|
+
this.writeEvents([event("session.handed_off", workspace, stage, current.ordinal, current.session_id, actor(this.options), { reason: "resumed in a new OpenCode session" })]);
|
|
212
|
+
}
|
|
213
|
+
if (["completed", "cancelled", "archived"].includes(stageRecord.data.status)) fail(ERROR_CODES.INVALID_STATE, "Cannot start a session for a terminal stage");
|
|
176
214
|
if (reduceSessions(events).some((session) => session.session_id === sessionId)) fail(ERROR_CODES.CONFLICT, "Session ID already exists");
|
|
177
215
|
const previous = reduceSessions(events).filter((session) => session.workspace === workspace && session.stage === stage);
|
|
178
216
|
const ordinal = previous.length + 1;
|
|
@@ -205,6 +243,53 @@ export class WorkContext {
|
|
|
205
243
|
});
|
|
206
244
|
}
|
|
207
245
|
|
|
246
|
+
renameStage(workspace, stage, title) {
|
|
247
|
+
id(workspace, 6);
|
|
248
|
+
stage = stageId(stage);
|
|
249
|
+
if (!title?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Title is required");
|
|
250
|
+
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
251
|
+
const record = this.storage.readStage(workspace, stage);
|
|
252
|
+
const nextTitle = title.trim();
|
|
253
|
+
if (record.data.title === nextTitle) return this.result({ workspace, stage, title: nextTitle }, []);
|
|
254
|
+
record.data.title = nextTitle;
|
|
255
|
+
record.data.updated_at = new Date().toISOString();
|
|
256
|
+
this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, stageBody(record, nextTitle, record.data.goal));
|
|
257
|
+
generateProjections(this.storage);
|
|
258
|
+
return this.result({ workspace, stage, title: nextTitle }, [workspace, stage]);
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
updateStage(workspace, stage, description) {
|
|
263
|
+
id(workspace, 6);
|
|
264
|
+
stage = stageId(stage);
|
|
265
|
+
if (!description?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Description is required");
|
|
266
|
+
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
267
|
+
const record = this.storage.readStage(workspace, stage);
|
|
268
|
+
const nextDescription = description.trim();
|
|
269
|
+
if (record.data.goal === nextDescription) return this.result({ workspace, stage, description: nextDescription }, []);
|
|
270
|
+
record.data.goal = nextDescription;
|
|
271
|
+
record.data.updated_at = new Date().toISOString();
|
|
272
|
+
this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, stageBody(record, record.data.title, nextDescription));
|
|
273
|
+
generateProjections(this.storage);
|
|
274
|
+
return this.result({ workspace, stage, description: nextDescription }, [workspace, stage]);
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
archiveStage(workspace, stage) {
|
|
279
|
+
id(workspace, 6);
|
|
280
|
+
stage = stageId(stage);
|
|
281
|
+
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
282
|
+
const record = this.storage.readStage(workspace, stage);
|
|
283
|
+
if (record.data.status === "archived") return this.result({ workspace, stage, status: "archived" }, []);
|
|
284
|
+
if (activeSession(this.storage.readEvents(), workspace, stage)) fail(ERROR_CODES.ACTIVE_SESSION_EXISTS, "Cannot archive a stage with an active session");
|
|
285
|
+
record.data.status = "archived";
|
|
286
|
+
record.data.updated_at = new Date().toISOString();
|
|
287
|
+
this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, record.body);
|
|
288
|
+
generateProjections(this.storage);
|
|
289
|
+
return this.result({ workspace, stage, status: "archived" }, [workspace, stage]);
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
|
|
208
293
|
listKnowledge(workspace) {
|
|
209
294
|
id(workspace, 6);
|
|
210
295
|
this.storage.assertNoSymlinks();
|
|
@@ -294,6 +379,10 @@ export class WorkContext {
|
|
|
294
379
|
});
|
|
295
380
|
}
|
|
296
381
|
|
|
382
|
+
abandon(workspace, stage, sessionId, reason = "abandoned") {
|
|
383
|
+
return this.closeSession(workspace, stage, sessionId, reason, "abandoned");
|
|
384
|
+
}
|
|
385
|
+
|
|
297
386
|
finish(workspace, stage, sessionId, options = {}) {
|
|
298
387
|
stage = stageId(stage);
|
|
299
388
|
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
@@ -305,7 +394,9 @@ export class WorkContext {
|
|
|
305
394
|
if (known?.state === "closed") return this.result({ session_id: sessionId, workspace, stage, state: "closed", status: "completed" }, []);
|
|
306
395
|
fail(ERROR_CODES.SESSION_NOT_ACTIVE, "Session did not complete this stage");
|
|
307
396
|
}
|
|
308
|
-
|
|
397
|
+
const knowledgeReview = options.knowledgeReview || "auto";
|
|
398
|
+
if (!['auto', 'added', 'none'].includes(knowledgeReview)) fail(ERROR_CODES.INVALID_ARGUMENT, "Knowledge review must be 'auto', 'added' or 'none'");
|
|
399
|
+
const knowledgeEntries = knowledgeReview === "auto" ? this.listKnowledge(workspace).data : null;
|
|
309
400
|
const active = activeSession(events, workspace, stage);
|
|
310
401
|
if (!active || active.session_id !== sessionId) fail(active ? ERROR_CODES.ACTIVE_SESSION_EXISTS : ERROR_CODES.SESSION_NOT_ACTIVE, active ? "Another active session owns this stage" : "Session is not active");
|
|
311
402
|
this.writeEvents([event("session.closed", workspace, stage, active.ordinal, sessionId, actor(this.options), { reason: "stage_completed" })]);
|
|
@@ -313,15 +404,23 @@ export class WorkContext {
|
|
|
313
404
|
current.data.updated_at = new Date().toISOString();
|
|
314
405
|
this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), current.data, `${current.body}\n\n## Result\n\n${options.result || "Stage completed."}`);
|
|
315
406
|
generateProjections(this.storage);
|
|
316
|
-
|
|
407
|
+
const data = { session_id: sessionId, workspace, stage, state: "closed", status: "completed", knowledge_review: knowledgeReview, ...(knowledgeEntries ? { knowledge_entries: knowledgeEntries.length } : {}) };
|
|
408
|
+
const incompleteStages = this.listStages(workspace).data.stages.filter((item) => !["completed", "archived"].includes(item.status));
|
|
409
|
+
const next = incompleteStages.length ? null : {
|
|
410
|
+
action: "workspace_finish",
|
|
411
|
+
workspace,
|
|
412
|
+
command: `/wc workspace finish ${workspace}`,
|
|
413
|
+
reason: "All workspace stages are completed",
|
|
414
|
+
};
|
|
415
|
+
return this.result(data, [workspace, stage], next);
|
|
317
416
|
});
|
|
318
417
|
}
|
|
319
418
|
|
|
320
419
|
help(command = "") {
|
|
321
|
-
|
|
420
|
+
return this.result({ command, syntax: "/wc [create|list|workspace list|workspace rename|workspace finish|resume|stage add|stage rename|stage update|stage archive|stage handoff|stage abandon|stage finish|link-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]", note: "workspace is optional for stage add/rename/update/archive when the current session identifies one workspace; workspace finish requires all non-archived stages to be completed; archived stages retain their IDs and history and are hidden from the TUI by default; stage finish reviews Knowledge Base automatically by default (knowledgeReview=auto); mutating commands call structured tools; only explicit lifecycle operations change storage." }, []);
|
|
322
421
|
}
|
|
323
422
|
|
|
324
|
-
result(data, changed) {
|
|
325
|
-
return { ok: true, data, changed, next
|
|
423
|
+
result(data, changed, next = null) {
|
|
424
|
+
return { ok: true, data, changed, next };
|
|
326
425
|
}
|
|
327
426
|
}
|
package/src/opencode-adapter.js
CHANGED
|
@@ -12,6 +12,6 @@ export function titleFor(context, workspace, stage, sessionId, knownSession = nu
|
|
|
12
12
|
if (!current) return null;
|
|
13
13
|
const meta = context.storage.readWorkspace(workspace).data;
|
|
14
14
|
const stageMeta = context.storage.readStage(workspace, stage).data;
|
|
15
|
-
return renderTitle({ workspace, stage, ordinal: current.ordinal,
|
|
15
|
+
return renderTitle({ workspace, workspaceTitle: meta.title, stage, ordinal: current.ordinal, state: current.state, trackerLinks: stageMeta.tracker_links?.length ? stageMeta.tracker_links : meta.tracker_links, issuePrefix: context.storage.config.title?.issue_prefix || "short" });
|
|
16
16
|
}
|
|
17
17
|
export const packageRoot = () => path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
package/src/stages-renderer.js
CHANGED
package/src/stages-snapshot.js
CHANGED
|
@@ -35,6 +35,7 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
|
|
|
35
35
|
|
|
36
36
|
const workspace = context.storage.readWorkspace(session.workspace).data;
|
|
37
37
|
const stages = context.listStages(session.workspace).data.stages
|
|
38
|
+
.filter((stage) => stage.status !== "archived")
|
|
38
39
|
.sort((left, right) => Number(left.stage) - Number(right.stage))
|
|
39
40
|
.map((stage) => ({
|
|
40
41
|
id: stage.stage,
|
package/src/storage.js
CHANGED
|
@@ -13,13 +13,23 @@ const validTimestamp = (value) => {
|
|
|
13
13
|
};
|
|
14
14
|
const requiredString = (data, key) => typeof data[key] === "string" && data[key].trim().length > 0;
|
|
15
15
|
const validTrackerLinks = (links) => links.every((link) => {
|
|
16
|
-
if (!link || typeof link !== "object" ||
|
|
16
|
+
if (!link || typeof link !== "object" || typeof link.url !== "string" || typeof link.provider !== "string" || typeof link.project !== "string") return false;
|
|
17
17
|
try {
|
|
18
18
|
const url = new URL(link.url);
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
19
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return false;
|
|
20
|
+
if (link.provider === "gitlab" || link.provider === "github") {
|
|
21
|
+
const allowed = ["url", "provider", "project", "iid"];
|
|
22
|
+
const match = url.pathname.match(link.provider === "gitlab" ? /^\/(.+)\/-\/issues\/(\d+)\/?$/ : /^\/([^/]+\/[^/]+)\/issues\/(\d+)\/?$/);
|
|
23
|
+
return Object.keys(link).every((key) => allowed.includes(key)) && Object.keys(link).length === allowed.length && match && match[1] === link.project && Number(match[2]) === link.iid && Number.isInteger(link.iid) && link.iid > 0;
|
|
24
|
+
}
|
|
25
|
+
if (link.provider === "jira") {
|
|
26
|
+
return Object.keys(link).every((key) => ["url", "provider", "project", "key"].includes(key))
|
|
27
|
+
&& typeof link.key === "string"
|
|
28
|
+
&& /^[A-Za-z][A-Za-z0-9]+-\d+$/.test(link.key)
|
|
29
|
+
&& url.pathname === `/browse/${link.key}`
|
|
30
|
+
&& link.project === link.key.substring(0, link.key.lastIndexOf("-"));
|
|
31
|
+
}
|
|
32
|
+
return false;
|
|
23
33
|
} catch { return false; }
|
|
24
34
|
});
|
|
25
35
|
const validEvents = new Set(["session.started", "session.renamed", "session.handed_off", "session.closed", "session.abandoned"]);
|
|
@@ -62,8 +72,8 @@ function validateMetadata(data, kind, workspace, stage = null) {
|
|
|
62
72
|
const allowed = kind === "workspace" ? ["schema", "workspace", "title", "status", "created_at", "updated_at", "tracker_links"] : ["schema", "workspace", "stage", "title", "status", "goal", "depends_on", "owner", "created_at", "updated_at", "tracker_links"];
|
|
63
73
|
if (Object.keys(data).some((key) => !allowed.includes(key)) || data.schema !== 1 || !requiredString(data, "workspace") || !/^\d{6}$/.test(data.workspace) || data.workspace !== workspace) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} metadata`);
|
|
64
74
|
if (!requiredString(data, "title") || !validTimestamp(data.created_at) || !validTimestamp(data.updated_at) || Date.parse(data.updated_at) < Date.parse(data.created_at) || !Array.isArray(data.tracker_links)) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} metadata`);
|
|
65
|
-
if (!validTrackerLinks(data.tracker_links) || data.tracker_links.some((link) => !link.provider.trim() || !link.project.trim() || !Number.isInteger(link.iid) || link.iid < 1)) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} tracker links`);
|
|
66
|
-
const statuses = kind === "workspace" ? ["in_progress", "completed", "cancelled"] : ["planned", "in_progress", "completed", "cancelled"];
|
|
75
|
+
if (!validTrackerLinks(data.tracker_links) || data.tracker_links.some((link) => !link.provider.trim() || !link.project.trim() || ((link.provider === "gitlab" || link.provider === "github") ? (!Number.isInteger(link.iid) || link.iid < 1) : !link.key?.trim()))) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} tracker links`);
|
|
76
|
+
const statuses = kind === "workspace" ? ["in_progress", "completed", "cancelled"] : ["planned", "in_progress", "completed", "cancelled", "archived"];
|
|
67
77
|
if (!statuses.includes(data.status)) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} status`);
|
|
68
78
|
if (kind === "stage" && (data.stage !== stage || !/^\d{2}$/.test(data.stage) || !requiredString(data, "goal") || !requiredString(data, "owner") || !Array.isArray(data.depends_on) || new Set(data.depends_on).size !== data.depends_on.length || data.depends_on.includes(data.stage) || data.depends_on.some((item) => typeof item !== "string" || !/^\d{2}$/.test(item)))) fail(ERROR_CODES.STORAGE_ERROR, "Invalid stage metadata");
|
|
69
79
|
}
|
package/src/title.js
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
|
-
export function renderTitle({ workspace, stage, ordinal,
|
|
1
|
+
export function renderTitle({ workspace, workspaceTitle, stage, ordinal, state = "active", trackerLinks = [], issuePrefix = "short" }) {
|
|
2
2
|
const link = trackerLinks[0]; let prefix = "";
|
|
3
|
-
if (link && issuePrefix !== "none")
|
|
3
|
+
if (link && issuePrefix !== "none") {
|
|
4
|
+
const identifier = link.key || link.iid;
|
|
5
|
+
const short = (link.provider || "gitlab") === "gitlab" ? `GL#${identifier}` : link.provider === "github" ? `GH#${identifier}` : `JIRA ${identifier}`;
|
|
6
|
+
prefix = issuePrefix === "full" ? `${link.project}#${identifier} | ` : `${short} | `;
|
|
7
|
+
}
|
|
4
8
|
const suffix = state === "active" ? "" : ` (${state})`;
|
|
5
|
-
return `${prefix}${workspace} ${stage}/${String(ordinal).padStart(2, "0")}${suffix}
|
|
9
|
+
return `${prefix}${workspace} ${stage}/${String(ordinal).padStart(2, "0")}${suffix}\n${(workspaceTitle || workspace).replace(/[\r\n|]+/g, " ").trim().slice(0, 80)}`;
|
|
6
10
|
}
|
package/src/tool-definitions.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { tool } from "@opencode-ai/plugin";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
2
3
|
import { contextFor, titleFor } from "../src/opencode-adapter.js";
|
|
4
|
+
import { fail, ERROR_CODES } from "../src/errors.js";
|
|
3
5
|
|
|
4
6
|
const run = (fn) => async (args, context) => {
|
|
5
7
|
try {
|
|
@@ -11,22 +13,36 @@ const run = (fn) => async (args, context) => {
|
|
|
11
13
|
}
|
|
12
14
|
};
|
|
13
15
|
const common = { workspace: tool.schema.string().regex(/^\d{6}$/), stage: tool.schema.string().regex(/^\d{1,2}$/) };
|
|
16
|
+
const workspaceFromSession = (ctx, workspace) => {
|
|
17
|
+
if (workspace) return workspace;
|
|
18
|
+
const session = ctx.sessionByOpenCodeId(ctx.options.sessionId) || ctx.sessionById(ctx.options.sessionId);
|
|
19
|
+
if (!session) fail(ERROR_CODES.INVALID_ARGUMENT, "Workspace is required when the current session is not associated with a workspace");
|
|
20
|
+
return session.workspace;
|
|
21
|
+
};
|
|
22
|
+
const sessionFor = (ctx, oc, workspace, stage) => ctx.sessionById(oc.sessionID)?.workspace === workspace
|
|
23
|
+
&& ctx.sessionById(oc.sessionID)?.stage === stage
|
|
24
|
+
? oc.sessionID
|
|
25
|
+
: ctx.sessionByOpenCodeId(oc.sessionID, workspace, stage)?.session_id || oc.sessionID;
|
|
14
26
|
export const work_context_list_workspaces = tool({ description: "List work-context workspaces.", args: {}, execute: run((ctx) => ctx.listWorkspaces()) });
|
|
15
|
-
export const work_context_list_stages = tool({ description: "List stages and sessions for a workspace.", args: { workspace: tool.schema.string() }, execute: run((ctx, a) => ctx.listStages(a.workspace)) });
|
|
16
27
|
export const work_context_workspace_list = tool({ description: "List a workspace with stage descriptions and sessions.", args: { workspace: tool.schema.string().regex(/^\d{6}$/) }, execute: run((ctx, a) => ctx.listStages(a.workspace)) });
|
|
28
|
+
export const work_context_rename_workspace = tool({ description: "Rename a workspace.", args: { workspace: tool.schema.string().regex(/^\d{6}$/), title: tool.schema.string() }, execute: run((ctx, a) => ctx.renameWorkspace(a.workspace, a.title)) });
|
|
17
29
|
export const work_context_workspace_finish = tool({ description: "Finish a workspace after all stages are completed.", args: { workspace: tool.schema.string().regex(/^\d{6}$/) }, execute: run((ctx, a) => ctx.finishWorkspace(a.workspace)) });
|
|
18
|
-
export const work_context_create_workspace = tool({ description: "Create workspace, stage 01, and active session.", args: { title: tool.schema.string() }, execute: run((ctx, a, oc) => ctx.createWorkspace(a.title, { sessionId: oc.sessionID })) });
|
|
19
|
-
export const work_context_start_session = tool({ description: "Start a new active session for a stage.", args: { ...common, summary: tool.schema.string().optional() }, execute: run((ctx, a, oc) => ctx.startSession(a.workspace, a.stage, { sessionId: oc.sessionID, summary: a.summary })) });
|
|
20
|
-
export const work_context_add_stage = tool({ description: "Add a planned stage.", args: { workspace: tool.schema.string(), title: tool.schema.string(), goal: tool.schema.string().optional(), dependsOn: tool.schema.array(tool.schema.string()).optional() }, execute: run((ctx, a) => ctx.addStage(a.workspace, a.title, { goal: a.goal, dependsOn: a.dependsOn })) });
|
|
30
|
+
export const work_context_create_workspace = tool({ description: "Create workspace, stage 01, and active session.", args: { title: tool.schema.string() }, execute: run((ctx, a, oc) => ctx.createWorkspace(a.title, { sessionId: randomUUID(), opencodeSessionId: oc.sessionID })) });
|
|
31
|
+
export const work_context_start_session = tool({ description: "Start a new active session for a stage.", args: { ...common, summary: tool.schema.string().optional() }, execute: run((ctx, a, oc) => ctx.startSession(a.workspace, a.stage, { sessionId: randomUUID(), opencodeSessionId: oc.sessionID, summary: a.summary, takeover: true })) });
|
|
32
|
+
export const work_context_add_stage = tool({ description: "Add a planned stage to the current or specified workspace.", args: { workspace: tool.schema.string().regex(/^\d{6}$/).optional(), title: tool.schema.string(), goal: tool.schema.string().optional(), dependsOn: tool.schema.array(tool.schema.string()).optional() }, execute: run((ctx, a) => ctx.addStage(workspaceFromSession(ctx, a.workspace), a.title, { goal: a.goal, dependsOn: a.dependsOn })) });
|
|
33
|
+
export const work_context_rename_stage = tool({ description: "Rename a stage while preserving its ID and history.", args: { workspace: tool.schema.string().regex(/^\d{6}$/).optional(), stage: tool.schema.string().regex(/^\d{1,2}$/), title: tool.schema.string() }, execute: run((ctx, a) => ctx.renameStage(workspaceFromSession(ctx, a.workspace), a.stage, a.title)) });
|
|
34
|
+
export const work_context_update_stage = tool({ description: "Update an existing stage description.", args: { workspace: tool.schema.string().regex(/^\d{6}$/).optional(), stage: tool.schema.string().regex(/^\d{1,2}$/), description: tool.schema.string() }, execute: run((ctx, a) => ctx.updateStage(workspaceFromSession(ctx, a.workspace), a.stage, a.description)) });
|
|
35
|
+
export const work_context_archive_stage = tool({ description: "Archive a stage while preserving its ID and history.", args: { workspace: tool.schema.string().regex(/^\d{6}$/), stage: tool.schema.string().regex(/^\d{1,2}$/) }, execute: run((ctx, a) => ctx.archiveStage(a.workspace, a.stage)) });
|
|
21
36
|
export const work_context_link_issue = tool({ description: "Link a GitLab issue URL to workspace or stage.", args: { workspace: tool.schema.string(), url: tool.schema.string(), stage: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.linkIssue(a.workspace, a.url, a.stage)) });
|
|
22
|
-
export const work_context_rename_session = tool({ description: "Rename the current active session summary.", args: { ...common, summary: tool.schema.string() }, execute: run((ctx, a, oc) => ctx.renameSession(a.workspace, a.stage, oc.
|
|
23
|
-
export const work_context_close_session = tool({ description: "Close the current session without finishing its stage.", args: { ...common }, execute: run((ctx, a, oc) => ctx.closeSession(a.workspace, a.stage, oc.
|
|
24
|
-
export const work_context_handoff_stage = tool({ description: "Hand off the current stage by closing the current session.", args: { ...common }, execute: run((ctx, a, oc) => ctx.handoff(a.workspace, a.stage, oc.
|
|
25
|
-
export const
|
|
37
|
+
export const work_context_rename_session = tool({ description: "Rename the current active session summary.", args: { ...common, summary: tool.schema.string() }, execute: run((ctx, a, oc) => ctx.renameSession(a.workspace, a.stage, sessionFor(ctx, oc, a.workspace, a.stage), a.summary)) });
|
|
38
|
+
export const work_context_close_session = tool({ description: "Close the current session without finishing its stage.", args: { ...common }, execute: run((ctx, a, oc) => ctx.closeSession(a.workspace, a.stage, sessionFor(ctx, oc, a.workspace, a.stage))) });
|
|
39
|
+
export const work_context_handoff_stage = tool({ description: "Hand off the current stage by closing the current session.", args: { ...common }, execute: run((ctx, a, oc) => ctx.handoff(a.workspace, a.stage, sessionFor(ctx, oc, a.workspace, a.stage))) });
|
|
40
|
+
export const work_context_abandon_stage = tool({ description: "Abandon the current stage session without completing the stage.", args: { ...common }, execute: run((ctx, a, oc) => ctx.abandon(a.workspace, a.stage, sessionFor(ctx, oc, a.workspace, a.stage))) });
|
|
41
|
+
export const work_context_finish_stage = tool({ description: "Finish a stage and automatically validate the Knowledge Base by default.", args: { ...common, result: tool.schema.string().optional(), knowledgeReview: tool.schema.string().optional() }, execute: run((ctx, a, oc) => ctx.finish(a.workspace, a.stage, sessionFor(ctx, oc, a.workspace, a.stage), { result: a.result, knowledgeReview: a.knowledgeReview })) });
|
|
26
42
|
export const work_context_help = tool({ description: "Show work-context command help.", args: { command: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.help(a.command)) });
|
|
27
43
|
export const work_context_list_knowledge = tool({ description: "List durable knowledge entries for a workspace.", args: { workspace: tool.schema.string() }, execute: run((ctx, a) => ctx.listKnowledge(a.workspace)) });
|
|
28
44
|
export const work_context_add_knowledge = tool({ description: "Add a durable knowledge entry.", args: { workspace: tool.schema.string(), title: tool.schema.string(), kind: tool.schema.string().optional(), text: tool.schema.string(), sources: tool.schema.array(tool.schema.string()).optional() }, execute: run((ctx, a) => ctx.addKnowledge(a.workspace, a)) });
|
|
29
45
|
export const work_context_update_knowledge = tool({ description: "Update a durable knowledge entry.", args: { workspace: tool.schema.string(), knowledgeId: tool.schema.string(), title: tool.schema.string().optional(), kind: tool.schema.string().optional(), status: tool.schema.string().optional(), text: tool.schema.string().optional(), sources: tool.schema.array(tool.schema.string()).optional(), replacement: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.updateKnowledge(a.workspace, a.knowledgeId, a)) });
|
|
30
46
|
export const work_context_supersede_knowledge = tool({ description: "Supersede a durable knowledge entry.", args: { workspace: tool.schema.string(), knowledgeId: tool.schema.string(), replacement: tool.schema.string() }, execute: run((ctx, a) => ctx.supersedeKnowledge(a.workspace, a.knowledgeId, a.replacement) ) });
|
|
31
47
|
|
|
32
|
-
export default { work_context_list_workspaces,
|
|
48
|
+
export default { work_context_list_workspaces, work_context_workspace_list, work_context_rename_workspace, work_context_workspace_finish, work_context_create_workspace, work_context_start_session, work_context_add_stage, work_context_rename_stage, work_context_update_stage, work_context_archive_stage, work_context_link_issue, work_context_rename_session, work_context_close_session, work_context_handoff_stage, work_context_abandon_stage, work_context_finish_stage, work_context_help, work_context_list_knowledge, work_context_add_knowledge, work_context_update_knowledge, work_context_supersede_knowledge };
|