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/src/storage.js ADDED
@@ -0,0 +1,254 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { WorkContextError, ERROR_CODES, fail } from "./errors.js";
5
+ import { parseFrontmatter, renderMarkdown } from "./markdown.js";
6
+
7
+ const now = () => new Date().toISOString();
8
+ const ensure = (dir) => fs.mkdirSync(dir, { recursive: true });
9
+ const validTimestamp = (value) => {
10
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(value)) return false;
11
+ const normalized = value.includes(".") ? value : value.replace("Z", ".000Z");
12
+ return !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === normalized;
13
+ };
14
+ const requiredString = (data, key) => typeof data[key] === "string" && data[key].trim().length > 0;
15
+ const validTrackerLinks = (links) => links.every((link) => {
16
+ if (!link || typeof link !== "object" || Object.keys(link).some((key) => !["url", "provider", "project", "iid"].includes(key)) || typeof link.url !== "string" || typeof link.provider !== "string" || typeof link.project !== "string" || !Number.isInteger(link.iid)) return false;
17
+ try {
18
+ const url = new URL(link.url);
19
+ const marker = url.pathname.lastIndexOf("/-/issues/");
20
+ const project = marker > 1 ? url.pathname.slice(1, marker) : "";
21
+ const iid = marker > 1 ? Number(url.pathname.slice(marker + "/-/issues/".length).replace(/\/$/, "")) : NaN;
22
+ return link.provider === "gitlab" && (url.protocol === "http:" || url.protocol === "https:") && project === link.project && iid === link.iid;
23
+ } catch { return false; }
24
+ });
25
+ const validEvents = new Set(["session.started", "session.renamed", "session.handed_off", "session.closed", "session.abandoned"]);
26
+ const validateEvent = (item) => {
27
+ if (!item || item.schema !== 1 || Object.keys(item).some((key) => !["schema", "event_id", "event", "occurred_at", "session_id", "workspace", "stage", "ordinal", "actor", "data"].includes(key)) || !validEvents.has(item.event) || typeof item.event_id !== "string" || !item.event_id.trim() || !validTimestamp(item.occurred_at) || typeof item.session_id !== "string" || !item.session_id.trim() || !/^\d{6}$/.test(item.workspace) || !/^\d{2}$/.test(item.stage) || !Number.isInteger(item.ordinal) || item.ordinal < 1 || typeof item.actor !== "string" || !item.actor.trim() || !item.data || typeof item.data !== "object" || Array.isArray(item.data)) fail(ERROR_CODES.STORAGE_ERROR, "Invalid session event");
28
+ const keys = Object.keys(item.data);
29
+ const allowed = item.event === "session.started" ? ["summary", "opencode_session_id", "branch"] : item.event === "session.renamed" ? ["summary"] : ["reason"];
30
+ if (keys.some((key) => !allowed.includes(key)) || (item.event === "session.started" && (typeof item.data.summary !== "string" || !item.data.summary.trim() || (item.data.opencode_session_id !== null && item.data.opencode_session_id !== undefined && typeof item.data.opencode_session_id !== "string") || (item.data.branch !== null && item.data.branch !== undefined && typeof item.data.branch !== "string"))) || (item.event === "session.renamed" && (typeof item.data.summary !== "string" || !item.data.summary.trim())) || (item.event !== "session.started" && (typeof item.data.reason !== "string" || !item.data.reason.trim()))) fail(ERROR_CODES.STORAGE_ERROR, "Invalid session event data");
31
+ };
32
+ const validateEventStream = (events) => {
33
+ const ids = new Set();
34
+ const sessions = new Map();
35
+ const stages = new Map();
36
+ let previousTimestamp = null;
37
+ for (const item of events) {
38
+ validateEvent(item);
39
+ if (previousTimestamp && Date.parse(item.occurred_at) < Date.parse(previousTimestamp)) fail(ERROR_CODES.STORAGE_ERROR, "Session event timestamps are not ordered");
40
+ previousTimestamp = item.occurred_at;
41
+ if (ids.has(item.event_id)) fail(ERROR_CODES.STORAGE_ERROR, "Duplicate session event ID");
42
+ ids.add(item.event_id);
43
+ const current = sessions.get(item.session_id);
44
+ if (item.event === "session.started") {
45
+ if (current || typeof item.data.summary !== "string" || !item.data.summary.trim()) fail(ERROR_CODES.STORAGE_ERROR, "Invalid session start event");
46
+ const stageKey = `${item.workspace}:${item.stage}`;
47
+ const stageState = stages.get(stageKey) || { active: false, maxOrdinal: 0 };
48
+ if (stageState.active || item.ordinal !== stageState.maxOrdinal + 1) fail(ERROR_CODES.STORAGE_ERROR, "Invalid session ordinal or active session stream");
49
+ stageState.active = true; stageState.maxOrdinal = item.ordinal; stages.set(stageKey, stageState);
50
+ sessions.set(item.session_id, { ...item, state: "active" });
51
+ continue;
52
+ }
53
+ if (!current || current.workspace !== item.workspace || current.stage !== item.stage || current.ordinal !== item.ordinal || current.state !== "active") fail(ERROR_CODES.STORAGE_ERROR, "Invalid session event transition");
54
+ if (item.event === "session.renamed" && (typeof item.data.summary !== "string" || !item.data.summary.trim())) fail(ERROR_CODES.STORAGE_ERROR, "Invalid session rename event");
55
+ if (["session.handed_off", "session.closed", "session.abandoned"].includes(item.event)) {
56
+ current.state = item.event.slice("session.".length);
57
+ stages.get(`${item.workspace}:${item.stage}`).active = false;
58
+ }
59
+ }
60
+ };
61
+ function validateMetadata(data, kind, workspace, stage = null) {
62
+ 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
+ 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
+ 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"];
67
+ if (!statuses.includes(data.status)) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} status`);
68
+ 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
+ }
70
+ export function atomicWrite(file, content) {
71
+ ensure(path.dirname(file));
72
+ const temp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${Date.now()}.tmp`);
73
+ try { fs.writeFileSync(temp, content, { encoding: "utf8", flag: "wx" }); fs.renameSync(temp, file); }
74
+ catch (error) { try { fs.rmSync(temp, { force: true }); } catch {} throw new WorkContextError(ERROR_CODES.STORAGE_ERROR, `Cannot write ${file}`, { cause: error.message }); }
75
+ }
76
+ export function withLock(lockPath, fn, { owner = "work-context", session = null, staleAfterMs = 86400000 } = {}) {
77
+ ensure(path.dirname(lockPath));
78
+ try { fs.mkdirSync(lockPath, { recursive: false }); }
79
+ catch (error) {
80
+ if (error.code !== "EEXIST") throw new WorkContextError(ERROR_CODES.STORAGE_ERROR, "Cannot create lock", { cause: error.message });
81
+ let metadata = {};
82
+ try { metadata = JSON.parse(fs.readFileSync(path.join(lockPath, "owner.json"), "utf8")); } catch {}
83
+ const ageMs = metadata.created_at ? Date.now() - Date.parse(metadata.created_at) : null;
84
+ if (ageMs !== null && ageMs > staleAfterMs) fail(ERROR_CODES.STALE_LOCK, "Stale lock requires explicit removal", { lockPath, metadata, ageMs });
85
+ fail(ERROR_CODES.LOCKED, "Work context is locked", { lockPath, metadata, ageMs });
86
+ }
87
+ const token = randomUUID();
88
+ try { atomicWrite(path.join(lockPath, "owner.json"), JSON.stringify({ owner, session, pid: process.pid, token, created_at: now() }, null, 2) + "\n"); return fn(); }
89
+ finally {
90
+ try { const current = JSON.parse(fs.readFileSync(path.join(lockPath, "owner.json"), "utf8")); if (current.token === token) fs.rmSync(lockPath, { recursive: true, force: true }); } catch {}
91
+ }
92
+ }
93
+
94
+ export class FileStorage {
95
+ constructor(projectRoot, config = {}) {
96
+ this.projectRoot = projectRoot;
97
+ const storage = config.storage || {};
98
+ this.config = { mode: "hybrid", root: ".work-context", personal_root: ".work-context/local", title: { issue_prefix: "short" }, tracker: { provider: null }, ...config, ...storage, title: { issue_prefix: "short", ...(config.title || {}) }, tracker: { provider: null, ...(config.tracker || {}) } };
99
+ this.root = path.resolve(projectRoot, this.config.root);
100
+ this.personalRoot = path.resolve(projectRoot, this.config.personal_root);
101
+ const project = path.resolve(projectRoot);
102
+ const insideProject = (target) => { const relative = path.relative(project, target); return relative && !relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative); };
103
+ if (!insideProject(this.root) || !insideProject(this.personalRoot)) fail(ERROR_CODES.INVALID_ARGUMENT, "Storage roots must be non-root paths inside the project");
104
+ const personalContainsRoot = this.root.startsWith(`${this.personalRoot}${path.sep}`);
105
+ if (this.root === this.personalRoot || personalContainsRoot) fail(ERROR_CODES.INVALID_ARGUMENT, "Storage roots overlap unsafely");
106
+ if (this.personalRoot === path.join(this.root, ".locks") || this.personalRoot.startsWith(`${path.join(this.root, ".locks")}${path.sep}`)) fail(ERROR_CODES.INVALID_ARGUMENT, "Personal root cannot overlap the lock directory");
107
+ }
108
+ configure(create = true) { this.assertSafeRoots(); if (create) { ensure(this.root); ensure(this.personalRoot); } return this; }
109
+ workspaceDir(id) { return path.join(this.root, id); }
110
+ workspaceFile(id) { return path.join(this.workspaceDir(id), "workspace.md"); }
111
+ knowledgeFile(id) { return path.join(this.workspaceDir(id), "KNOWLEDGE.md"); }
112
+ stageFile(id, stage) { return path.join(this.workspaceDir(id), "stages", `${stage}.md`); }
113
+ sessionFile() { return path.join(this.personalRoot, "sessions.jsonl"); }
114
+ lockPath(name = "write") { return path.join(this.root, ".locks", `${name}.lock`); }
115
+ readWorkspace(id) { const record = this.readCanonical(this.workspaceFile(id)); validateMetadata(record.data, "workspace", id); return record; }
116
+ readStage(id, stage) { const record = this.readCanonical(this.stageFile(id, stage)); validateMetadata(record.data, "stage", id, stage); return record; }
117
+ readKnowledge(id) { try { return fs.readFileSync(this.knowledgeFile(id), "utf8"); } catch (error) { if (error.code === "ENOENT") return null; throw error; } }
118
+ transactionFile() { return path.join(this.root, ".locks", "transaction.json"); }
119
+ writeTransaction(snapshot) { atomicWrite(this.transactionFile(), JSON.stringify({ schema: 1, files: snapshot.files.map((item) => ({ file: item.file, content: item.content.toString("base64") })), externalRoots: snapshot.externalRoots }) + "\n"); }
120
+ clearTransaction() { fs.rmSync(this.transactionFile(), { force: true }); }
121
+ recoverTransaction() {
122
+ if (!fs.existsSync(this.transactionFile())) return;
123
+ const journalStat = fs.lstatSync(this.transactionFile());
124
+ if (journalStat.isSymbolicLink() || !journalStat.isFile()) fail(ERROR_CODES.STORAGE_ERROR, "Invalid transaction journal path");
125
+ let journal;
126
+ try { journal = JSON.parse(fs.readFileSync(this.transactionFile(), "utf8")); } catch { fail(ERROR_CODES.STORAGE_ERROR, "Invalid transaction journal"); }
127
+ if (!journal || journal.schema !== 1 || !Array.isArray(journal.files) || !Array.isArray(journal.externalRoots) || journal.files.some((item) => !item || Object.keys(item).some((key) => !["file", "content"].includes(key)) || typeof item.file !== "string" || typeof item.content !== "string" || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(item.content)) || new Set(journal.files.map((item) => item.file)).size !== journal.files.length) fail(ERROR_CODES.STORAGE_ERROR, "Invalid transaction journal");
128
+ const rootPrefix = `${this.root}${path.sep}`;
129
+ const personalPrefix = `${this.personalRoot}${path.sep}`;
130
+ for (const item of journal.files) {
131
+ const resolved = path.resolve(item.file);
132
+ if ((!resolved.startsWith(rootPrefix) && !resolved.startsWith(personalPrefix)) || resolved === path.join(this.root, ".locks") || resolved.startsWith(`${this.root}${path.sep}.locks${path.sep}`) || (fs.existsSync(resolved) && !fs.lstatSync(resolved).isFile())) fail(ERROR_CODES.STORAGE_ERROR, "Transaction journal path is outside storage roots");
133
+ }
134
+ const externalRoots = this.personalRoot.startsWith(rootPrefix) ? [] : [this.personalRoot];
135
+ this.assertNoSymlinks();
136
+ this.restore({ files: journal.files.map((item) => ({ file: item.file, content: Buffer.from(item.content, "base64") })), externalRoots });
137
+ this.clearTransaction();
138
+ }
139
+ snapshot() {
140
+ const files = [];
141
+ const walk = (dir) => {
142
+ if (!fs.existsSync(dir)) return;
143
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
144
+ if (dir === this.root && entry.name === ".locks") continue;
145
+ const file = path.join(dir, entry.name);
146
+ if (entry.isDirectory()) walk(file);
147
+ else if (entry.isFile()) files.push({ file, content: fs.readFileSync(file) });
148
+ }
149
+ };
150
+ walk(this.root);
151
+ const rootPrefix = `${this.root}${path.sep}`;
152
+ const externalPersonalRoot = !this.personalRoot.startsWith(rootPrefix) && this.personalRoot !== this.root;
153
+ if (externalPersonalRoot) walk(this.personalRoot);
154
+ return { files, externalRoots: externalPersonalRoot ? [this.personalRoot] : [] };
155
+ }
156
+ assertSafeRoots() {
157
+ const check = (target) => {
158
+ const parsed = path.parse(target);
159
+ let current = parsed.root;
160
+ for (const part of target.slice(parsed.root.length).split(path.sep).filter(Boolean)) {
161
+ current = path.join(current, part);
162
+ try {
163
+ if (fs.lstatSync(current).isSymbolicLink()) fail(ERROR_CODES.STORAGE_ERROR, `Symlink path component is not supported: ${current}`);
164
+ } catch (error) {
165
+ if (error.code !== "ENOENT") throw error;
166
+ break;
167
+ }
168
+ }
169
+ };
170
+ check(this.root);
171
+ check(this.personalRoot);
172
+ const locks = path.join(this.root, ".locks");
173
+ try {
174
+ const stat = fs.lstatSync(locks);
175
+ if (stat.isSymbolicLink() || !stat.isDirectory()) fail(ERROR_CODES.STORAGE_ERROR, `Invalid lock directory: ${locks}`);
176
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
177
+ }
178
+ assertNoSymlinks() {
179
+ this.assertSafeRoots();
180
+ const walk = (dir) => {
181
+ if (!fs.existsSync(dir)) return;
182
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
183
+ if (dir === this.root && entry.name === ".locks") {
184
+ if (entry.isSymbolicLink() || !entry.isDirectory()) fail(ERROR_CODES.STORAGE_ERROR, `Invalid lock directory: ${path.join(dir, entry.name)}`);
185
+ continue;
186
+ }
187
+ const file = path.join(dir, entry.name);
188
+ if (entry.isSymbolicLink()) fail(ERROR_CODES.STORAGE_ERROR, `Symlinks are not supported in work-context storage: ${file}`);
189
+ if (entry.isDirectory()) walk(file);
190
+ }
191
+ };
192
+ walk(this.root);
193
+ if (this.personalRoot !== this.root && !this.personalRoot.startsWith(`${this.root}${path.sep}`)) walk(this.personalRoot);
194
+ }
195
+ restore(snapshot) {
196
+ const keep = path.join(this.root, ".locks");
197
+ if (fs.existsSync(this.root)) {
198
+ for (const entry of fs.readdirSync(this.root, { withFileTypes: true })) {
199
+ if (path.join(this.root, entry.name) !== keep) fs.rmSync(path.join(this.root, entry.name), { recursive: true, force: true });
200
+ }
201
+ }
202
+ const existing = new Set(snapshot.files.map((item) => item.file));
203
+ for (const root of snapshot.externalRoots) {
204
+ if (!fs.existsSync(root)) continue;
205
+ const removeNew = (dir) => {
206
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
207
+ const file = path.join(dir, entry.name);
208
+ if (entry.isDirectory()) removeNew(file);
209
+ else if (entry.isFile() && !existing.has(file)) fs.rmSync(file, { force: true });
210
+ }
211
+ };
212
+ removeNew(root);
213
+ }
214
+ for (const item of snapshot.files) {
215
+ ensure(path.dirname(item.file));
216
+ fs.writeFileSync(item.file, item.content);
217
+ }
218
+ }
219
+ readCanonical(file) { try { return parseFrontmatter(fs.readFileSync(file, "utf8")); } catch (error) { if (error.code === "ENOENT") fail(ERROR_CODES.NOT_FOUND, `Missing ${file}`); throw error; } }
220
+ writeMarkdown(file, data, body) { atomicWrite(file, renderMarkdown(data, body)); }
221
+ appendEvents(events) {
222
+ ensure(path.dirname(this.sessionFile()));
223
+ const current = fs.existsSync(this.sessionFile()) ? fs.readFileSync(this.sessionFile(), "utf8") : "";
224
+ atomicWrite(this.sessionFile(), current + events.map((item) => JSON.stringify(item)).join("\n") + "\n");
225
+ }
226
+ readEvents() {
227
+ this.assertNoSymlinks();
228
+ try {
229
+ const events = fs.readFileSync(this.sessionFile(), "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line));
230
+ validateEventStream(events);
231
+ return events;
232
+ } catch (error) {
233
+ if (error.code === "ENOENT") return [];
234
+ if (error.code === ERROR_CODES.STORAGE_ERROR) throw error;
235
+ fail(ERROR_CODES.STORAGE_ERROR, "Invalid session event log", { cause: error.message });
236
+ }
237
+ }
238
+ }
239
+
240
+ export function loadConfig(projectRoot, configFile = path.resolve(projectRoot, ".work-context", "config.yaml")) {
241
+ if (!fs.existsSync(configFile)) return {};
242
+ const data = Object.assign(Object.create(null), { storage: Object.create(null), title: Object.create(null), tracker: Object.create(null) });
243
+ let section = null;
244
+ for (const line of fs.readFileSync(configFile, "utf8").split("\n")) {
245
+ if (!line.trim() || line.trim().startsWith("#")) continue;
246
+ const match = line.match(/^(\s*)([\w-]+):\s*(.*)$/); if (!match) fail(ERROR_CODES.STORAGE_ERROR, "Invalid config syntax");
247
+ if (!match[1]) { section = match[3] ? null : match[2]; if (match[3]) data[match[2]] = scalarConfig(match[3]); else if (!data[match[2]] || typeof data[match[2]] !== "object") data[match[2]] = Object.create(null); continue; }
248
+ if (section && data[section] && typeof data[section] === "object") data[section][match[2]] = scalarConfig(match[3]);
249
+ }
250
+ if (Object.keys(data).some((key) => !["schema", "storage", "title", "tracker"].includes(key)) || Object.keys(data.storage).some((key) => !["mode", "root", "personal_root"].includes(key)) || Object.keys(data.title).some((key) => key !== "issue_prefix") || Object.keys(data.tracker).some((key) => key !== "provider") || data.schema !== 1 || !data.storage || !["personal", "shared-git", "hybrid"].includes(data.storage.mode) || typeof data.storage.root !== "string" || typeof data.storage.personal_root !== "string" || !data.title || !["none", "short", "full"].includes(data.title.issue_prefix) || !data.tracker || (data.tracker.provider !== null && typeof data.tracker.provider !== "string")) fail(ERROR_CODES.STORAGE_ERROR, "Invalid work-context config");
251
+ return data;
252
+ }
253
+ const scalarConfig = (value) => value === "null" ? null : value === "[]" ? [] : value === "{}" ? {} : /^(true|false)$/.test(value) ? value === "true" : /^-?\d+(\.\d+)?$/.test(value) ? Number(value) : value;
254
+ export const defaultConfig = () => `schema: 1\nstorage:\n mode: hybrid\n root: .work-context\n personal_root: .work-context/local\ntitle:\n issue_prefix: short\ntracker:\n provider: null\n`;
package/src/title.js ADDED
@@ -0,0 +1,6 @@
1
+ export function renderTitle({ workspace, stage, ordinal, summary, state = "active", trackerLinks = [], issuePrefix = "short" }) {
2
+ const link = trackerLinks[0]; let prefix = "";
3
+ if (link && issuePrefix !== "none") prefix = issuePrefix === "full" ? `${link.project}#${link.iid} | ` : `GL#${link.iid} | `;
4
+ const suffix = state === "active" ? "" : ` (${state})`;
5
+ return `${prefix}${workspace} ${stage}/${String(ordinal).padStart(2, "0")}${suffix}: ${(summary || "продолжение работы").replace(/[\r\n|]+/g, " ").trim().slice(0, 80)}`;
6
+ }
@@ -0,0 +1,30 @@
1
+ import { tool } from "@opencode-ai/plugin";
2
+ import { contextFor, titleFor } from "../src/opencode-adapter.js";
3
+
4
+ const run = (fn) => async (args, context) => {
5
+ try {
6
+ const result = await fn(contextFor(context.worktree || context.directory, context.sessionID), args, context);
7
+ try { await context.metadata({ title: "work-context", metadata: { result } }); } catch {}
8
+ return { output: JSON.stringify(result), metadata: result };
9
+ } catch (error) {
10
+ return { output: JSON.stringify({ ok: false, error: { code: error.code || "STORAGE_ERROR", message: error.message, details: error.details || {} } }), metadata: { code: error.code || "STORAGE_ERROR" } };
11
+ }
12
+ };
13
+ const common = { workspace: tool.schema.string().regex(/^\d{6}$/), stage: tool.schema.string().regex(/^\d{1,2}$/) };
14
+ 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
+ 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 })) });
17
+ 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 })) });
18
+ 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 })) });
19
+ 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)) });
20
+ 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.sessionID, a.summary)) });
21
+ 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.sessionID)) });
22
+ 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.sessionID)) });
23
+ export const work_context_finish_stage = tool({ description: "Finish a stage and close the current active session.", args: { ...common, result: tool.schema.string().optional(), knowledgeReview: tool.schema.string() }, execute: run((ctx, a, oc) => ctx.finish(a.workspace, a.stage, oc.sessionID, { result: a.result, knowledgeReview: a.knowledgeReview })) });
24
+ 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)) });
25
+ 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)) });
26
+ 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)) });
27
+ 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)) });
28
+ 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) ) });
29
+
30
+ export default { work_context_list_workspaces, work_context_list_stages, work_context_create_workspace, work_context_start_session, work_context_add_stage, work_context_link_issue, work_context_rename_session, work_context_close_session, work_context_handoff_stage, work_context_finish_stage, work_context_help, work_context_list_knowledge, work_context_add_knowledge, work_context_update_knowledge, work_context_supersede_knowledge };
@@ -0,0 +1 @@
1
+ export { work_context_add_knowledge as default } from "../src/tool-definitions.js";
@@ -0,0 +1,2 @@
1
+ import { work_context_add_stage } from "../src/tool-definitions.js";
2
+ export default work_context_add_stage;
@@ -0,0 +1,2 @@
1
+ import { work_context_close_session } from "../src/tool-definitions.js";
2
+ export default work_context_close_session;
@@ -0,0 +1,2 @@
1
+ import { work_context_create_workspace } from "../src/tool-definitions.js";
2
+ export default work_context_create_workspace;
@@ -0,0 +1,2 @@
1
+ import { work_context_finish_stage } from "../src/tool-definitions.js";
2
+ export default work_context_finish_stage;
@@ -0,0 +1,2 @@
1
+ import { work_context_handoff_stage } from "../src/tool-definitions.js";
2
+ export default work_context_handoff_stage;
@@ -0,0 +1,2 @@
1
+ import { work_context_help } from "../src/tool-definitions.js";
2
+ export default work_context_help;
@@ -0,0 +1,2 @@
1
+ import { work_context_link_issue } from "../src/tool-definitions.js";
2
+ export default work_context_link_issue;
@@ -0,0 +1 @@
1
+ export { work_context_list_knowledge as default } from "../src/tool-definitions.js";
@@ -0,0 +1,2 @@
1
+ import { work_context_list_stages } from "../src/tool-definitions.js";
2
+ export default work_context_list_stages;
@@ -0,0 +1,2 @@
1
+ import { work_context_list_workspaces } from "../src/tool-definitions.js";
2
+ export default work_context_list_workspaces;
@@ -0,0 +1,2 @@
1
+ import { work_context_rename_session } from "../src/tool-definitions.js";
2
+ export default work_context_rename_session;
@@ -0,0 +1,2 @@
1
+ import { work_context_start_session } from "../src/tool-definitions.js";
2
+ export default work_context_start_session;
@@ -0,0 +1 @@
1
+ export { work_context_supersede_knowledge as default } from "../src/tool-definitions.js";
@@ -0,0 +1 @@
1
+ export { work_context_update_knowledge as default } from "../src/tool-definitions.js";