opencode-work-context 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +58 -0
- package/bin/opencode-work-context.js +269 -0
- package/commands/wc.md +27 -0
- package/package.json +52 -0
- package/plugin/work-context.js +21 -0
- package/src/core.js +304 -0
- package/src/errors.js +11 -0
- package/src/index.js +8 -0
- package/src/knowledge.js +116 -0
- package/src/markdown.js +37 -0
- package/src/opencode-adapter.js +16 -0
- package/src/projections.js +30 -0
- package/src/sessions.js +20 -0
- package/src/storage.js +254 -0
- package/src/title.js +6 -0
- package/src/tool-definitions.js +30 -0
- package/tools/work_context_add_knowledge.js +1 -0
- package/tools/work_context_add_stage.js +2 -0
- package/tools/work_context_close_session.js +2 -0
- package/tools/work_context_create_workspace.js +2 -0
- package/tools/work_context_finish_stage.js +2 -0
- package/tools/work_context_handoff_stage.js +2 -0
- package/tools/work_context_help.js +2 -0
- package/tools/work_context_link_issue.js +2 -0
- package/tools/work_context_list_knowledge.js +1 -0
- package/tools/work_context_list_stages.js +2 -0
- package/tools/work_context_list_workspaces.js +2 -0
- package/tools/work_context_rename_session.js +2 -0
- package/tools/work_context_start_session.js +2 -0
- package/tools/work_context_supersede_knowledge.js +1 -0
- package/tools/work_context_update_knowledge.js +1 -0
package/src/core.js
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { FileStorage, atomicWrite, withLock, defaultConfig, loadConfig } from "./storage.js";
|
|
5
|
+
import { ERROR_CODES, fail } from "./errors.js";
|
|
6
|
+
import { event, reduceSessions, activeSession, assertActive } from "./sessions.js";
|
|
7
|
+
import { generateProjections, renderSessions } from "./projections.js";
|
|
8
|
+
import { nextKnowledgeId, parseKnowledge, renderKnowledge, validateKnowledgeInput, validateKnowledgeRecords } from "./knowledge.js";
|
|
9
|
+
|
|
10
|
+
const id = (value, digits) => {
|
|
11
|
+
const normalized = String(value);
|
|
12
|
+
if (!new RegExp(`^\\d{${digits}}$`).test(normalized)) fail(ERROR_CODES.INVALID_ARGUMENT, `Expected ${digits}-digit identifier`);
|
|
13
|
+
return normalized;
|
|
14
|
+
};
|
|
15
|
+
const stageId = (value) => id(String(value).padStart(2, "0"), 2);
|
|
16
|
+
const actor = (options) => options.actor || "OpenCode";
|
|
17
|
+
const body = (title, goal = "") => `# ${title}\n\n${goal ? `## Goal\n\n${goal}\n` : ""}`;
|
|
18
|
+
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
|
+
|
|
20
|
+
function parseIssue(url) {
|
|
21
|
+
try {
|
|
22
|
+
const parsed = new URL(url);
|
|
23
|
+
const match = parsed.pathname.match(/\/([^/]+)\/-\/issues\/(\d+)\/?$/);
|
|
24
|
+
if (!/^https?:$/.test(parsed.protocol) || !match) fail(ERROR_CODES.INVALID_ISSUE_URL, "Expected a GitLab issue URL");
|
|
25
|
+
return { url: parsed.toString(), provider: "gitlab", project: parsed.pathname.split("/-/issues/")[0].replace(/^\//, ""), iid: Number(match[2]) };
|
|
26
|
+
} catch (error) {
|
|
27
|
+
if (error.code === ERROR_CODES.INVALID_ISSUE_URL) throw error;
|
|
28
|
+
fail(ERROR_CODES.INVALID_ISSUE_URL, "Invalid issue URL");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export class WorkContext {
|
|
33
|
+
constructor(storage, options = {}) {
|
|
34
|
+
this.storage = storage.configure(options.initialize !== false);
|
|
35
|
+
this.options = options;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
static open(projectRoot, options = {}) {
|
|
39
|
+
const root = path.resolve(projectRoot);
|
|
40
|
+
const configDir = path.join(root, ".work-context");
|
|
41
|
+
assertNoSymlinkPath(configDir);
|
|
42
|
+
if (!fs.existsSync(configDir)) fs.mkdirSync(configDir, { recursive: true });
|
|
43
|
+
const configFile = path.join(configDir, "config.yaml");
|
|
44
|
+
assertNoSymlinkPath(configFile);
|
|
45
|
+
if (!fs.existsSync(configFile)) atomicWrite(configFile, defaultConfig());
|
|
46
|
+
return new WorkContext(new FileStorage(root, { ...loadConfig(root), ...(options.config || {}) }), options);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
static openExisting(projectRoot, options = {}) {
|
|
50
|
+
const root = path.resolve(projectRoot);
|
|
51
|
+
assertNoSymlinkPath(path.join(root, ".work-context"));
|
|
52
|
+
assertNoSymlinkPath(path.join(root, ".work-context", "config.yaml"));
|
|
53
|
+
return new WorkContext(new FileStorage(root, { ...loadConfig(root), ...(options.config || {}) }), { ...options, initialize: false });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
writeEvents(events) {
|
|
57
|
+
this.storage.appendEvents(events);
|
|
58
|
+
atomicWrite(path.join(this.storage.personalRoot, "SESSIONS.md"), renderSessions(reduceSessions(this.storage.readEvents())));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
transact(name, fn) {
|
|
62
|
+
// Все mutating operations меняют общий sessions.jsonl, поэтому нужен единый lock.
|
|
63
|
+
this.storage.assertSafeRoots();
|
|
64
|
+
return withLock(this.storage.lockPath("write"), () => {
|
|
65
|
+
this.storage.assertNoSymlinks();
|
|
66
|
+
this.storage.recoverTransaction();
|
|
67
|
+
this.storage.assertNoSymlinks();
|
|
68
|
+
const snapshot = this.storage.snapshot();
|
|
69
|
+
this.storage.writeTransaction(snapshot);
|
|
70
|
+
try { const result = fn(); this.storage.clearTransaction(); return result; }
|
|
71
|
+
catch (error) { this.storage.restore(snapshot); this.storage.clearTransaction(); throw error; }
|
|
72
|
+
}, { session: this.options.sessionId, owner: actor(this.options) });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
listWorkspaces() {
|
|
76
|
+
this.storage.assertNoSymlinks();
|
|
77
|
+
if (!fs.existsSync(this.storage.root)) return { ok: true, data: [] };
|
|
78
|
+
const data = fs.readdirSync(this.storage.root, { withFileTypes: true })
|
|
79
|
+
.filter((entry) => entry.isDirectory() && /^\d{6}$/.test(entry.name))
|
|
80
|
+
.map((entry) => this.storage.readWorkspace(entry.name).data);
|
|
81
|
+
return { ok: true, data };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
listStages(workspace) {
|
|
85
|
+
this.storage.assertNoSymlinks();
|
|
86
|
+
id(workspace, 6);
|
|
87
|
+
const dir = path.join(this.storage.workspaceDir(workspace), "stages");
|
|
88
|
+
if (!fs.existsSync(dir)) fail(ERROR_CODES.NOT_FOUND, "Workspace not found");
|
|
89
|
+
const stages = fs.readdirSync(dir).filter((file) => /^\d{2}\.md$/.test(file)).map((file) => this.storage.readStage(workspace, file.slice(0, 2)).data);
|
|
90
|
+
const ids = new Set(stages.map((item) => item.stage));
|
|
91
|
+
const visiting = new Set();
|
|
92
|
+
const visited = new Set();
|
|
93
|
+
const visit = (stage) => {
|
|
94
|
+
if (visiting.has(stage)) fail(ERROR_CODES.STORAGE_ERROR, "Stage dependency cycle detected");
|
|
95
|
+
if (visited.has(stage)) return;
|
|
96
|
+
visiting.add(stage);
|
|
97
|
+
for (const dependency of stages.find((item) => item.stage === stage).depends_on) {
|
|
98
|
+
if (!ids.has(dependency)) fail(ERROR_CODES.STORAGE_ERROR, `Missing stage dependency: ${dependency}`);
|
|
99
|
+
visit(dependency);
|
|
100
|
+
}
|
|
101
|
+
visiting.delete(stage); visited.add(stage);
|
|
102
|
+
};
|
|
103
|
+
for (const stage of ids) visit(stage);
|
|
104
|
+
return { ok: true, data: { workspace, stages, sessions: reduceSessions(this.storage.readEvents()).filter((session) => session.workspace === workspace) } };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
sessionById(sessionId) {
|
|
108
|
+
return reduceSessions(this.storage.readEvents()).find((session) => session.session_id === sessionId) || null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
assertDependenciesCompleted(workspace, stageRecord) {
|
|
112
|
+
const stages = this.listStages(workspace).data.stages;
|
|
113
|
+
for (const dependency of stageRecord.data.depends_on) {
|
|
114
|
+
const record = stages.find((item) => item.stage === dependency);
|
|
115
|
+
if (!record || record.status !== "completed") fail(ERROR_CODES.INVALID_STATE, `Stage dependency is not completed: ${dependency}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
createWorkspace(title, options = {}) {
|
|
120
|
+
if (!title?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Title is required");
|
|
121
|
+
const requestedWorkspace = options.workspace;
|
|
122
|
+
return this.transact("workspace-create", () => {
|
|
123
|
+
const workspace = requestedWorkspace || this.nextWorkspace();
|
|
124
|
+
id(workspace, 6);
|
|
125
|
+
const now = new Date().toISOString();
|
|
126
|
+
if (fs.existsSync(this.storage.workspaceDir(workspace))) fail(ERROR_CODES.CONFLICT, "Workspace already exists");
|
|
127
|
+
fs.mkdirSync(path.join(this.storage.workspaceDir(workspace), "stages"), { recursive: true });
|
|
128
|
+
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));
|
|
129
|
+
this.storage.writeMarkdown(this.storage.stageFile(workspace, "01"), { schema: 1, workspace, stage: "01", title: `Планирование: ${title.trim()}`, status: "in_progress", goal: "Уточнить цель и ограничения работы", depends_on: [], owner: actor(this.options), created_at: now, updated_at: now, tracker_links: [] }, body(`Планирование: ${title.trim()}`, "Уточнить цель и ограничения работы"));
|
|
130
|
+
const sessionId = options.sessionId || randomUUID();
|
|
131
|
+
if (this.storage.readEvents().some((item) => item.session_id === sessionId)) fail(ERROR_CODES.CONFLICT, "Session ID already exists");
|
|
132
|
+
this.writeEvents([event("session.started", workspace, "01", 1, sessionId, actor(this.options), { summary: `планирование ${title.trim()}` })]);
|
|
133
|
+
generateProjections(this.storage);
|
|
134
|
+
return this.result({ workspace, stage: "01", session_id: sessionId, ordinal: "01/01" }, [workspace, "01"]);
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
nextWorkspace() {
|
|
139
|
+
const ids = this.listWorkspaces().data.map((workspace) => Number(workspace.workspace));
|
|
140
|
+
return String(Math.max(0, ...ids) + 1).padStart(6, "0");
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
startSession(workspace, stage, options = {}) {
|
|
144
|
+
id(workspace, 6);
|
|
145
|
+
stage = stageId(stage);
|
|
146
|
+
const sessionId = options.sessionId || randomUUID();
|
|
147
|
+
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
148
|
+
const stageRecord = this.storage.readStage(workspace, stage);
|
|
149
|
+
this.assertDependenciesCompleted(workspace, stageRecord);
|
|
150
|
+
const events = this.storage.readEvents();
|
|
151
|
+
if (activeSession(events, workspace, stage)) fail(ERROR_CODES.ACTIVE_SESSION_EXISTS, "Stage already has an active session");
|
|
152
|
+
if (["completed", "cancelled"].includes(stageRecord.data.status)) fail(ERROR_CODES.INVALID_STATE, "Cannot start a session for a terminal stage");
|
|
153
|
+
if (reduceSessions(events).some((session) => session.session_id === sessionId)) fail(ERROR_CODES.CONFLICT, "Session ID already exists");
|
|
154
|
+
const previous = reduceSessions(events).filter((session) => session.workspace === workspace && session.stage === stage);
|
|
155
|
+
const ordinal = previous.length + 1;
|
|
156
|
+
if (stageRecord.data.status === "planned") {
|
|
157
|
+
stageRecord.data.status = "in_progress";
|
|
158
|
+
stageRecord.data.updated_at = new Date().toISOString();
|
|
159
|
+
this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), stageRecord.data, stageRecord.body);
|
|
160
|
+
}
|
|
161
|
+
this.writeEvents([event("session.started", workspace, stage, ordinal, sessionId, actor(this.options), { summary: options.summary || "продолжение работы", opencode_session_id: options.opencodeSessionId || null, branch: options.branch || null })]);
|
|
162
|
+
generateProjections(this.storage);
|
|
163
|
+
return this.result({ workspace, stage, session_id: sessionId, ordinal: `01/${String(ordinal).padStart(2, "0")}` }, [workspace, stage]);
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
addStage(workspace, title, options = {}) {
|
|
168
|
+
id(workspace, 6);
|
|
169
|
+
if (!title?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Title is required");
|
|
170
|
+
const dependsOn = options.dependsOn || [];
|
|
171
|
+
if (!Array.isArray(dependsOn) || new Set(dependsOn).size !== dependsOn.length || dependsOn.some((item) => typeof item !== "string" || !/^\d{2}$/.test(item))) fail(ERROR_CODES.INVALID_ARGUMENT, "dependsOn must contain unique two-digit stage IDs");
|
|
172
|
+
return this.transact(`workspace-${workspace}`, () => {
|
|
173
|
+
const stages = this.listStages(workspace).data.stages;
|
|
174
|
+
if (stages.length >= 99) fail(ERROR_CODES.INVALID_STATE, "A workspace cannot contain more than 99 stages");
|
|
175
|
+
const stage = String(Math.max(0, ...stages.map((item) => Number(item.stage))) + 1).padStart(2, "0");
|
|
176
|
+
if (dependsOn.includes(stage)) fail(ERROR_CODES.INVALID_ARGUMENT, "A stage cannot depend on itself");
|
|
177
|
+
if (dependsOn.some((dependency) => !stages.some((item) => item.stage === dependency))) fail(ERROR_CODES.INVALID_ARGUMENT, "dependsOn must reference existing stages");
|
|
178
|
+
const now = new Date().toISOString();
|
|
179
|
+
this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), { schema: 1, workspace, stage, title: title.trim(), status: "planned", goal: options.goal || title.trim(), depends_on: dependsOn, owner: options.owner || actor(this.options), created_at: now, updated_at: now, tracker_links: [] }, body(title, options.goal || title));
|
|
180
|
+
generateProjections(this.storage);
|
|
181
|
+
return this.result({ workspace, stage }, [stage]);
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
listKnowledge(workspace) {
|
|
186
|
+
id(workspace, 6);
|
|
187
|
+
this.storage.assertNoSymlinks();
|
|
188
|
+
this.storage.readWorkspace(workspace);
|
|
189
|
+
const text = this.storage.readKnowledge(workspace);
|
|
190
|
+
return { ok: true, data: text ? parseKnowledge(text) : [] };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
addKnowledge(workspace, input) {
|
|
194
|
+
id(workspace, 6);
|
|
195
|
+
validateKnowledgeInput(input);
|
|
196
|
+
return this.transact(`workspace-${workspace}`, () => {
|
|
197
|
+
const records = this.listKnowledge(workspace).data;
|
|
198
|
+
const timestamp = new Date().toISOString();
|
|
199
|
+
const record = { id: nextKnowledgeId(records), title: input.title.trim(), kind: input.kind || "fact", status: "active", created: timestamp, updated: timestamp, sources: input.sources || [], text: input.text.trim() };
|
|
200
|
+
atomicWrite(this.storage.knowledgeFile(workspace), renderKnowledge([...records, record]));
|
|
201
|
+
return this.result(record, [this.storage.knowledgeFile(workspace)]);
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
updateKnowledge(workspace, knowledgeId, input) {
|
|
206
|
+
id(workspace, 6);
|
|
207
|
+
validateKnowledgeInput(input, true);
|
|
208
|
+
return this.transact(`workspace-${workspace}`, () => {
|
|
209
|
+
const records = this.listKnowledge(workspace).data;
|
|
210
|
+
const record = records.find((item) => item.id === knowledgeId);
|
|
211
|
+
if (!record) fail(ERROR_CODES.NOT_FOUND, `Knowledge entry not found: ${knowledgeId}`);
|
|
212
|
+
Object.assign(record, input.title === undefined ? {} : { title: input.title.trim() }, input.kind === undefined ? {} : { kind: input.kind }, input.status === undefined ? {} : { status: input.status, ...(input.status === "active" ? { replacement: null } : {}) }, input.text === undefined ? {} : { text: input.text.trim() }, input.sources === undefined ? {} : { sources: input.sources }, input.replacement === undefined ? {} : { replacement: input.replacement }, { updated: new Date().toISOString() });
|
|
213
|
+
validateKnowledgeRecords(records);
|
|
214
|
+
const rendered = renderKnowledge(records);
|
|
215
|
+
parseKnowledge(rendered);
|
|
216
|
+
atomicWrite(this.storage.knowledgeFile(workspace), rendered);
|
|
217
|
+
return this.result(record, [this.storage.knowledgeFile(workspace)]);
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
supersedeKnowledge(workspace, knowledgeId, replacement = null) {
|
|
222
|
+
if (replacement === knowledgeId) fail(ERROR_CODES.INVALID_ARGUMENT, "Knowledge cannot supersede itself");
|
|
223
|
+
return this.updateKnowledge(workspace, knowledgeId, { status: "superseded", ...(replacement ? { replacement } : {}) });
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
linkIssue(workspace, url, stage = null) {
|
|
227
|
+
const normalizedWorkspace = id(workspace, 6);
|
|
228
|
+
const normalizedStage = stage ? stageId(stage) : null;
|
|
229
|
+
const parsed = parseIssue(url);
|
|
230
|
+
return this.transact(`link-${workspace}-${stage || "workspace"}`, () => {
|
|
231
|
+
const file = normalizedStage ? this.storage.stageFile(normalizedWorkspace, normalizedStage) : this.storage.workspaceFile(normalizedWorkspace);
|
|
232
|
+
const current = normalizedStage ? this.storage.readStage(normalizedWorkspace, normalizedStage) : this.storage.readWorkspace(normalizedWorkspace);
|
|
233
|
+
const links = current.data.tracker_links || [];
|
|
234
|
+
if (links.some((link) => link.url === parsed.url)) return this.result({ workspace: normalizedWorkspace, stage: normalizedStage, issue: parsed }, []);
|
|
235
|
+
links.push(parsed);
|
|
236
|
+
current.data.tracker_links = links;
|
|
237
|
+
current.data.updated_at = new Date().toISOString();
|
|
238
|
+
this.storage.writeMarkdown(file, current.data, current.body);
|
|
239
|
+
generateProjections(this.storage);
|
|
240
|
+
return this.result({ workspace: normalizedWorkspace, stage: normalizedStage, issue: parsed }, [file]);
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
renameSession(workspace, stage, sessionId, summary) {
|
|
245
|
+
if (!summary?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Summary is required");
|
|
246
|
+
stage = stageId(stage);
|
|
247
|
+
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
248
|
+
const session = assertActive(this.storage.readEvents(), workspace, stage, sessionId);
|
|
249
|
+
if (session.summary === summary.trim()) return this.result({ session_id: sessionId, summary: summary.trim() }, []);
|
|
250
|
+
this.writeEvents([event("session.renamed", workspace, stage, session.ordinal, sessionId, actor(this.options), { summary: summary.trim() })]);
|
|
251
|
+
return this.result({ session_id: sessionId, summary: summary.trim() }, []);
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
closeSession(workspace, stage, sessionId, reason = "closed", state = "closed") {
|
|
256
|
+
stage = stageId(stage);
|
|
257
|
+
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
258
|
+
const session = assertActive(this.storage.readEvents(), workspace, stage, sessionId);
|
|
259
|
+
this.writeEvents([event(`session.${state}`, workspace, stage, session.ordinal, sessionId, actor(this.options), { reason })]);
|
|
260
|
+
return this.result({ session_id: sessionId, state }, []);
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
handoff(workspace, stage, sessionId, options = {}) {
|
|
265
|
+
stage = stageId(stage);
|
|
266
|
+
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
267
|
+
const session = assertActive(this.storage.readEvents(), workspace, stage, sessionId);
|
|
268
|
+
this.writeEvents([event("session.handed_off", workspace, stage, session.ordinal, sessionId, actor(this.options), { reason: options.reason || "handoff" })]);
|
|
269
|
+
generateProjections(this.storage);
|
|
270
|
+
return this.result({ session_id: sessionId, state: "handed_off" }, []);
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
finish(workspace, stage, sessionId, options = {}) {
|
|
275
|
+
stage = stageId(stage);
|
|
276
|
+
return this.transact(`stage-${workspace}-${stage}`, () => {
|
|
277
|
+
const events = this.storage.readEvents();
|
|
278
|
+
const current = this.storage.readStage(workspace, stage);
|
|
279
|
+
this.assertDependenciesCompleted(workspace, current);
|
|
280
|
+
const known = reduceSessions(events).find((item) => item.session_id === sessionId && item.workspace === workspace && item.stage === stage);
|
|
281
|
+
if (current.data.status === "completed") {
|
|
282
|
+
if (known?.state === "closed") return this.result({ session_id: sessionId, workspace, stage, state: "closed", status: "completed" }, []);
|
|
283
|
+
fail(ERROR_CODES.SESSION_NOT_ACTIVE, "Session did not complete this stage");
|
|
284
|
+
}
|
|
285
|
+
if (!['added', 'none'].includes(options.knowledgeReview)) fail(ERROR_CODES.INVALID_ARGUMENT, "Knowledge review must be 'added' or 'none'");
|
|
286
|
+
const active = activeSession(events, workspace, stage);
|
|
287
|
+
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");
|
|
288
|
+
this.writeEvents([event("session.closed", workspace, stage, active.ordinal, sessionId, actor(this.options), { reason: "stage_completed" })]);
|
|
289
|
+
current.data.status = "completed";
|
|
290
|
+
current.data.updated_at = new Date().toISOString();
|
|
291
|
+
this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), current.data, `${current.body}\n\n## Result\n\n${options.result || "Stage completed."}`);
|
|
292
|
+
generateProjections(this.storage);
|
|
293
|
+
return this.result({ session_id: sessionId, workspace, stage, state: "closed", status: "completed" }, [workspace, stage]);
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
help(command = "") {
|
|
298
|
+
return this.result({ command, syntax: "/wc [create|list|resume|add-stage|link-issue|session rename|session close|handoff|finish|knowledge list|knowledge add|knowledge update|knowledge supersede|help]", note: "finish requires knowledgeReview=added|none; mutating commands call structured tools; only explicit lifecycle operations change storage." }, []);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
result(data, changed) {
|
|
302
|
+
return { ok: true, data, changed, next: null };
|
|
303
|
+
}
|
|
304
|
+
}
|
package/src/errors.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export const ERROR_CODES = Object.freeze({
|
|
2
|
+
NOT_FOUND: "NOT_FOUND", INVALID_ARGUMENT: "INVALID_ARGUMENT", INVALID_STATE: "INVALID_STATE",
|
|
3
|
+
ACTIVE_SESSION_EXISTS: "ACTIVE_SESSION_EXISTS", SESSION_NOT_ACTIVE: "SESSION_NOT_ACTIVE",
|
|
4
|
+
LOCKED: "LOCKED", STALE_LOCK: "STALE_LOCK", CONFLICT: "CONFLICT", INVALID_ISSUE_URL: "INVALID_ISSUE_URL",
|
|
5
|
+
ADAPTER_UNAVAILABLE: "ADAPTER_UNAVAILABLE", STORAGE_ERROR: "STORAGE_ERROR", CONFIRMATION_REQUIRED: "CONFIRMATION_REQUIRED",
|
|
6
|
+
});
|
|
7
|
+
|
|
8
|
+
export class WorkContextError extends Error {
|
|
9
|
+
constructor(code, message, details = {}) { super(message); this.name = "WorkContextError"; this.code = code; this.details = details; }
|
|
10
|
+
}
|
|
11
|
+
export const fail = (code, message, details) => { throw new WorkContextError(code, message, details); };
|
package/src/index.js
ADDED
package/src/knowledge.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { ERROR_CODES, fail } from "./errors.js";
|
|
3
|
+
|
|
4
|
+
const KINDS = new Set(["fact", "decision", "contract", "risk", "procedure"]);
|
|
5
|
+
const STATUSES = new Set(["active", "superseded"]);
|
|
6
|
+
const validDate = (value) => {
|
|
7
|
+
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(value)) return false;
|
|
8
|
+
const normalized = value.endsWith("Z") && !value.includes(".") ? value.replace("Z", ".000Z") : value;
|
|
9
|
+
return !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === normalized;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
const parseList = (text) => {
|
|
13
|
+
if (!text) fail(ERROR_CODES.STORAGE_ERROR, "Knowledge Sources metadata is required");
|
|
14
|
+
let parsed;
|
|
15
|
+
try { parsed = JSON.parse(text); } catch { fail(ERROR_CODES.STORAGE_ERROR, "Knowledge Sources must be a JSON array"); }
|
|
16
|
+
if (!Array.isArray(parsed) || parsed.some((item) => typeof item !== "string" || !item.trim())) fail(ERROR_CODES.STORAGE_ERROR, "Knowledge Sources must be a non-empty string array");
|
|
17
|
+
return parsed;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export function parseKnowledge(text) {
|
|
21
|
+
if (!text.startsWith("# Durable Knowledge\n")) fail(ERROR_CODES.STORAGE_ERROR, "Invalid knowledge ledger header");
|
|
22
|
+
const records = [];
|
|
23
|
+
const sections = text.split(/^## (KC-\d{4}): (.+)$/m);
|
|
24
|
+
if (sections[0] !== "# Durable Knowledge\n\n") fail(ERROR_CODES.STORAGE_ERROR, "Invalid knowledge ledger preamble");
|
|
25
|
+
for (let index = 1; index < sections.length; index += 3) {
|
|
26
|
+
const id = sections[index];
|
|
27
|
+
const title = sections[index + 1];
|
|
28
|
+
const section = sections[index + 2] || "";
|
|
29
|
+
const lines = section.trim().split("\n");
|
|
30
|
+
if (lines.some((line) => /^## KC-\d{4}:/.test(line))) fail(ERROR_CODES.STORAGE_ERROR, "Knowledge text contains an unescaped record heading");
|
|
31
|
+
const bodyStart = lines.findIndex((line) => line === "") + 1;
|
|
32
|
+
if (bodyStart < 1) fail(ERROR_CODES.STORAGE_ERROR, `Invalid knowledge metadata: ${id}`);
|
|
33
|
+
const metadata = new Map();
|
|
34
|
+
for (const line of lines.slice(0, bodyStart - 1)) {
|
|
35
|
+
const match = line.match(/^- (Kind|Status|Created|Updated|Sources|Replacement):\s*(.*)$/);
|
|
36
|
+
if (!match || metadata.has(match[1])) fail(ERROR_CODES.STORAGE_ERROR, `Invalid or duplicate knowledge metadata: ${id}`);
|
|
37
|
+
metadata.set(match[1], match[2]);
|
|
38
|
+
}
|
|
39
|
+
for (const required of ["Kind", "Status", "Created", "Updated", "Sources"]) if (!metadata.has(required)) fail(ERROR_CODES.STORAGE_ERROR, `Missing knowledge metadata ${required}: ${id}`);
|
|
40
|
+
const record = {
|
|
41
|
+
id,
|
|
42
|
+
title: title.trim(),
|
|
43
|
+
kind: metadata.get("Kind"),
|
|
44
|
+
status: metadata.get("Status"),
|
|
45
|
+
created: metadata.get("Created"),
|
|
46
|
+
updated: metadata.get("Updated"),
|
|
47
|
+
sources: parseList(metadata.get("Sources")),
|
|
48
|
+
replacement: metadata.get("Replacement") || null,
|
|
49
|
+
text: "",
|
|
50
|
+
};
|
|
51
|
+
if (!record.kind || !KINDS.has(record.kind) || !record.status || !STATUSES.has(record.status) || !validDate(record.created) || !validDate(record.updated)) fail(ERROR_CODES.STORAGE_ERROR, `Invalid knowledge entry: ${id}`);
|
|
52
|
+
if (!Array.isArray(record.sources)) fail(ERROR_CODES.STORAGE_ERROR, `Invalid knowledge sources: ${id}`);
|
|
53
|
+
if (record.status === "superseded" && !record.replacement) fail(ERROR_CODES.STORAGE_ERROR, `Superseded knowledge requires replacement: ${id}`);
|
|
54
|
+
if (record.status === "active" && record.replacement) fail(ERROR_CODES.STORAGE_ERROR, `Active knowledge cannot have replacement: ${id}`);
|
|
55
|
+
if (validDate(record.created) && validDate(record.updated) && Date.parse(record.updated) < Date.parse(record.created)) fail(ERROR_CODES.STORAGE_ERROR, `Knowledge dates are out of order: ${id}`);
|
|
56
|
+
record.text = (bodyStart ? lines.slice(bodyStart) : []).join("\n").trim();
|
|
57
|
+
if (!record.title || !record.text) fail(ERROR_CODES.STORAGE_ERROR, `Knowledge entry is incomplete: ${id}`);
|
|
58
|
+
records.push(record);
|
|
59
|
+
}
|
|
60
|
+
if (new Set(records.map((record) => record.id)).size !== records.length) fail(ERROR_CODES.STORAGE_ERROR, "Duplicate knowledge ID");
|
|
61
|
+
validateKnowledgeRecords(records);
|
|
62
|
+
return records;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function validateKnowledgeRecords(records) {
|
|
66
|
+
const ids = new Set(records.map((record) => record.id));
|
|
67
|
+
for (const record of records) {
|
|
68
|
+
if (record.status === "superseded") {
|
|
69
|
+
if (!/^KC-\d{4}$/.test(record.replacement) || record.replacement === record.id || !ids.has(record.replacement)) fail(ERROR_CODES.STORAGE_ERROR, `Invalid knowledge replacement: ${record.id}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
for (const record of records) {
|
|
73
|
+
const seen = new Set([record.id]);
|
|
74
|
+
let next = record;
|
|
75
|
+
while (next.status === "superseded") {
|
|
76
|
+
if (seen.has(next.replacement)) fail(ERROR_CODES.STORAGE_ERROR, "Knowledge replacement cycle detected");
|
|
77
|
+
seen.add(next.replacement);
|
|
78
|
+
next = records.find((item) => item.id === next.replacement);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function renderKnowledge(records) {
|
|
84
|
+
const body = records.map((record) => [
|
|
85
|
+
`## ${record.id}: ${record.title}`,
|
|
86
|
+
"",
|
|
87
|
+
`- Kind: ${record.kind}`,
|
|
88
|
+
`- Status: ${record.status}`,
|
|
89
|
+
`- Created: ${record.created}`,
|
|
90
|
+
`- Updated: ${record.updated}`,
|
|
91
|
+
`- Sources: ${JSON.stringify(record.sources || [])}`,
|
|
92
|
+
...(record.replacement ? [`- Replacement: ${record.replacement}`] : []),
|
|
93
|
+
"",
|
|
94
|
+
record.text.trim(),
|
|
95
|
+
].join("\n")).join("\n\n");
|
|
96
|
+
return `# Durable Knowledge\n\n${body}${body ? "\n" : ""}`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function validateKnowledgeInput(input, partial = false) {
|
|
100
|
+
if (!partial && !input.title?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Knowledge title is required");
|
|
101
|
+
if (input.kind !== undefined && !KINDS.has(input.kind)) fail(ERROR_CODES.INVALID_ARGUMENT, "Invalid knowledge kind");
|
|
102
|
+
if (input.status !== undefined && !STATUSES.has(input.status)) fail(ERROR_CODES.INVALID_ARGUMENT, "Invalid knowledge status");
|
|
103
|
+
if (!partial && !input.text?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Knowledge text is required");
|
|
104
|
+
if (input.title !== undefined && /\r?\n/.test(input.title)) fail(ERROR_CODES.INVALID_ARGUMENT, "Knowledge title must be a single line");
|
|
105
|
+
if (input.text !== undefined && /^## KC-\d{4}:/m.test(input.text)) fail(ERROR_CODES.INVALID_ARGUMENT, "Knowledge text cannot contain record headings");
|
|
106
|
+
if (input.sources !== undefined && (!Array.isArray(input.sources) || input.sources.some((source) => typeof source !== "string" || !source.trim()))) fail(ERROR_CODES.INVALID_ARGUMENT, "Knowledge sources must be a non-empty string array");
|
|
107
|
+
if (input.status === "superseded" && partial && !input.replacement) fail(ERROR_CODES.INVALID_ARGUMENT, "Superseded knowledge requires replacement");
|
|
108
|
+
if (input.replacement !== undefined && (!input.replacement.trim() || (input.id && input.replacement === input.id))) fail(ERROR_CODES.INVALID_ARGUMENT, "Invalid knowledge replacement");
|
|
109
|
+
if (input.status === "active" && input.replacement !== undefined) fail(ERROR_CODES.INVALID_ARGUMENT, "Active knowledge cannot have replacement");
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export const nextKnowledgeId = (records) => {
|
|
113
|
+
const next = Math.max(0, ...records.map((record) => Number(record.id.slice(3)))) + 1;
|
|
114
|
+
if (next > 9999) fail(ERROR_CODES.INVALID_STATE, "Knowledge ID limit reached");
|
|
115
|
+
return `KC-${String(next).padStart(4, "0")}`;
|
|
116
|
+
};
|
package/src/markdown.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { ERROR_CODES, fail } from "./errors.js";
|
|
3
|
+
|
|
4
|
+
const scalar = (value) => {
|
|
5
|
+
const text = value.trim();
|
|
6
|
+
if (text === "null") return null;
|
|
7
|
+
if (text === "[]") return [];
|
|
8
|
+
if (text === "{}") return {};
|
|
9
|
+
if (/^(true|false)$/.test(text)) return text === "true";
|
|
10
|
+
if (/^-?\d+(\.\d+)?$/.test(text)) return Number(text);
|
|
11
|
+
if (text.startsWith('"') || text.endsWith('"')) { try { return JSON.parse(text); } catch { fail(ERROR_CODES.STORAGE_ERROR, "Invalid quoted Markdown scalar"); } }
|
|
12
|
+
if (text.startsWith("'") && text.endsWith("'")) return text.slice(1, -1).replace(/''/g, "'");
|
|
13
|
+
if (text.startsWith("[") || text.startsWith("{")) {
|
|
14
|
+
try { return JSON.parse(text); } catch { fail(ERROR_CODES.STORAGE_ERROR, "Invalid JSON Markdown scalar"); }
|
|
15
|
+
}
|
|
16
|
+
return text;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export function parseFrontmatter(text) {
|
|
20
|
+
if (!text.startsWith("---\n")) return { data: {}, body: text };
|
|
21
|
+
const closing = text.match(/\n---\n/);
|
|
22
|
+
const end = closing?.index ?? -1;
|
|
23
|
+
if (end < 0) return { data: {}, body: text };
|
|
24
|
+
const data = Object.create(null);
|
|
25
|
+
for (const line of text.slice(4, end).split("\n")) {
|
|
26
|
+
const match = line.match(/^([A-Za-z_][\w-]*):\s*(.*)$/);
|
|
27
|
+
if (!match || Object.hasOwn(data, match[1])) fail(ERROR_CODES.STORAGE_ERROR, "Invalid or duplicate Markdown metadata");
|
|
28
|
+
data[match[1]] = scalar(match[2]);
|
|
29
|
+
}
|
|
30
|
+
return { data, body: text.slice(end + 4).replace(/^\n/, "") };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const yamlValue = (value) => Array.isArray(value) || (value && typeof value === "object") ? JSON.stringify(value) : value === null ? "null" : typeof value === "string" ? JSON.stringify(value) : String(value);
|
|
34
|
+
export function renderMarkdown(data, body = "") {
|
|
35
|
+
return `---\n${Object.entries(data).map(([key, value]) => `${key}: ${yamlValue(value)}`).join("\n")}\n---\n\n${body.trimEnd()}\n`;
|
|
36
|
+
}
|
|
37
|
+
export const readMarkdown = (file) => parseFrontmatter(fs.readFileSync(file, "utf8"));
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { WorkContext } from "./core.js";
|
|
4
|
+
import { renderTitle } from "./title.js";
|
|
5
|
+
|
|
6
|
+
export function contextFor(directory, sessionId, actor = "OpenCode") {
|
|
7
|
+
return WorkContext.openExisting(directory, { sessionId, actor });
|
|
8
|
+
}
|
|
9
|
+
export function titleFor(context, workspace, stage, sessionId, knownSession = null) {
|
|
10
|
+
const current = knownSession || context.sessionById(sessionId);
|
|
11
|
+
if (!current) return null;
|
|
12
|
+
const meta = context.storage.readWorkspace(workspace).data;
|
|
13
|
+
const stageMeta = context.storage.readStage(workspace, stage).data;
|
|
14
|
+
return renderTitle({ workspace, stage, ordinal: current.ordinal, summary: current.summary, state: current.state, trackerLinks: stageMeta.tracker_links?.length ? stageMeta.tracker_links : meta.tracker_links, issuePrefix: context.storage.config.title?.issue_prefix || "short" });
|
|
15
|
+
}
|
|
16
|
+
export const packageRoot = () => path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { atomicWrite } from "./storage.js";
|
|
4
|
+
export function renderIndex(workspaces) {
|
|
5
|
+
const rows = workspaces.map(({ data }) => `| ${data.workspace} | ${data.title} | ${data.status} | ${data.updated_at} |`).join("\n");
|
|
6
|
+
return `# Work Context\n\n| Workspace | Title | Status | Updated |\n|---|---|---|---|\n${rows || "| - | No workspaces | - | - |"}\n`;
|
|
7
|
+
}
|
|
8
|
+
export function renderSessions(sessions) {
|
|
9
|
+
const rows = sessions.map((s) => `| ${s.ordinal} | ${s.stage} | ${s.summary || ""} | ${s.state} | ${s.updated_at || ""} |`).join("\n");
|
|
10
|
+
return `# Sessions\n\n| # | Stage | Summary | State | Updated |\n|---:|---:|---|---|---|\n${rows || "| - | - | No sessions | - | - |"}\n`;
|
|
11
|
+
}
|
|
12
|
+
export function generateProjections(storage) {
|
|
13
|
+
const dirs = fs.existsSync(storage.root) ? fs.readdirSync(storage.root, { withFileTypes: true }).filter((item) => item.isDirectory() && /^\d{6}$/.test(item.name)) : [];
|
|
14
|
+
const workspaces = dirs.map((item) => storage.readWorkspace(item.name));
|
|
15
|
+
atomicWrite(path.join(storage.root, "INDEX.md"), renderIndex(workspaces));
|
|
16
|
+
atomicWrite(path.join(storage.personalRoot, "SESSIONS.md"), renderSessions(sessionsFor(storage)));
|
|
17
|
+
}
|
|
18
|
+
export const sessionsFor = (storage) => {
|
|
19
|
+
const byId = new Map();
|
|
20
|
+
for (const event of storage.readEvents()) {
|
|
21
|
+
const current = byId.get(event.session_id) || { session_id: event.session_id, stage: event.stage, ordinal: event.ordinal, summary: "", state: "" };
|
|
22
|
+
if (event.event === "session.started") Object.assign(current, event.data, { state: "active" });
|
|
23
|
+
if (event.event === "session.renamed") current.summary = event.data.summary;
|
|
24
|
+
if (event.event === "session.handed_off") current.state = "handed_off";
|
|
25
|
+
if (event.event === "session.closed") current.state = "closed";
|
|
26
|
+
if (event.event === "session.abandoned") current.state = "abandoned";
|
|
27
|
+
current.updated_at = event.occurred_at; byId.set(event.session_id, current);
|
|
28
|
+
}
|
|
29
|
+
return [...byId.values()];
|
|
30
|
+
};
|
package/src/sessions.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { ERROR_CODES, fail } from "./errors.js";
|
|
3
|
+
|
|
4
|
+
export const SESSION_STATES = ["active", "handed_off", "closed", "abandoned"];
|
|
5
|
+
export function reduceSessions(events) {
|
|
6
|
+
const sessions = new Map();
|
|
7
|
+
for (const event of events) {
|
|
8
|
+
let state = sessions.get(event.session_id) ?? { session_id: event.session_id, workspace: event.workspace, stage: event.stage, ordinal: event.ordinal, actor: event.actor, summary: "", state: null, started_at: event.occurred_at };
|
|
9
|
+
if (event.event === "session.started") { state = { ...state, ...event.data, state: "active", started_at: event.occurred_at }; }
|
|
10
|
+
if (event.event === "session.renamed") state.summary = event.data.summary;
|
|
11
|
+
if (event.event === "session.handed_off") state.state = "handed_off";
|
|
12
|
+
if (event.event === "session.closed") state.state = "closed";
|
|
13
|
+
if (event.event === "session.abandoned") state.state = "abandoned";
|
|
14
|
+
state.updated_at = event.occurred_at; sessions.set(event.session_id, state);
|
|
15
|
+
}
|
|
16
|
+
return [...sessions.values()];
|
|
17
|
+
}
|
|
18
|
+
export const activeSession = (events, workspace, stage) => reduceSessions(events).find((item) => item.workspace === workspace && item.stage === stage && item.state === "active");
|
|
19
|
+
export function event(event, workspace, stage, ordinal, sessionId, actor, data = {}) { return { schema: 1, event_id: randomUUID(), event, occurred_at: new Date().toISOString(), session_id: sessionId, workspace, stage, ordinal, actor, data }; }
|
|
20
|
+
export function assertActive(events, workspace, stage, sessionId) { const session = reduceSessions(events).find((item) => item.session_id === sessionId && item.workspace === workspace && item.stage === stage); if (!session || session.state !== "active") fail(ERROR_CODES.SESSION_NOT_ACTIVE, "Session is not active"); return session; }
|