opencode-work-context 0.4.15 → 0.5.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/README.md +96 -10
- package/bin/opencode-work-context.js +29 -4
- package/commands/wc.md +34 -1
- package/package.json +1 -1
- package/plugin/stages-tui.js +47 -5
- package/plugin/work-context.js +2 -1
- package/src/candidates.js +165 -0
- package/src/core.js +105 -14
- package/src/errors.js +5 -0
- package/src/git-candidates.js +163 -0
- package/src/index.js +2 -0
- package/src/opencode-adapter.js +7 -2
- package/src/stages-renderer.js +4 -2
- package/src/stages-snapshot.js +4 -1
- package/src/storage.js +3 -3
- package/src/title.js +12 -3
- package/src/tool-definitions.js +14 -4
- package/src/work-context-snapshot.js +5 -0
- package/tools/work_context_capture_candidate.js +3 -0
- package/tools/work_context_commit_candidate.js +3 -0
- package/tools/work_context_create_candidate.js +3 -0
- package/tools/work_context_discard_candidate.js +3 -0
- package/tools/work_context_list_candidates.js +3 -0
- package/tools/work_context_preview_candidate.js +3 -0
- package/tools/work_context_ready_candidate.js +3 -0
- package/tools/work_context_set_workspace_mode.js +3 -0
- package/tools/work_context_show_candidate.js +3 -0
- package/tools/work_context_unlink_issue.js +2 -0
package/src/core.js
CHANGED
|
@@ -8,8 +8,10 @@ import { generateProjections, renderSessions } from "./projections.js";
|
|
|
8
8
|
import { nextKnowledgeId, parseKnowledge, renderKnowledge, validateKnowledgeInput, validateKnowledgeRecords } from "./knowledge.js";
|
|
9
9
|
import { normalizeStageId, normalizeWorkspaceId } from "./identifiers.js";
|
|
10
10
|
import { isDependencySatisfied } from "./stage-status.js";
|
|
11
|
+
import { CandidateStore } from "./candidates.js";
|
|
11
12
|
|
|
12
13
|
const actor = (options) => options.actor || "OpenCode";
|
|
14
|
+
const workspaceMode = (data) => data.mode || "standard";
|
|
13
15
|
const activeKnowledge = (records) => records
|
|
14
16
|
.filter((record) => record.status === "active")
|
|
15
17
|
.map(({ id: knowledgeId, title, kind, text, sources }) => ({ id: knowledgeId, title, kind, text, sources }));
|
|
@@ -27,6 +29,16 @@ const preservedStageResult = (record) => stageResult(record)
|
|
|
27
29
|
const appendHistory = (bodyText, heading, entry) => `${bodyText.trimEnd()}${bodyText.includes(`\n## ${heading}\n`) ? "" : `\n\n## ${heading}\n`}\n- ${entry}\n`;
|
|
28
30
|
const automaticFinishAllowed = (storage, workspace) => /(?:^|\n)AUTO_STAGE_FINISH:\s*allowed\s*$/mi.test(storage.readStage(workspace, "01").data.prompt || "");
|
|
29
31
|
const resumeConfirmationRequired = (prompt) => /(?:^|\r?\n)RESUME_CONFIRMATION: required(?=\r?\n|$)/.test(prompt || "");
|
|
32
|
+
const startupWorkflowPolicy = () => ({
|
|
33
|
+
mode: "startup",
|
|
34
|
+
guidance: [
|
|
35
|
+
"A shared dirty worktree and concurrent stages are expected; stages do not own files or commits.",
|
|
36
|
+
"Capture ready work promptly as an explicit commit candidate while unrelated work remains in progress.",
|
|
37
|
+
"Mixed-stage provenance alone is not a reason to stop; do not reconstruct ownership after the fact.",
|
|
38
|
+
"Stop only for a concrete overlapping or stale candidate conflict, and report that conflict explicitly.",
|
|
39
|
+
],
|
|
40
|
+
});
|
|
41
|
+
const startupWorkflowInstruction = (policy) => policy ? `\n\nStartup workflow policy:\n${policy.guidance.map((item) => `- ${item}`).join("\n")}` : "";
|
|
30
42
|
const resumePresentationInstruction = ({ confirmationRequired }) => `Before doing any work, give the user a concise context summary:
|
|
31
43
|
- Use the user's language.
|
|
32
44
|
- Name the stage without reporting workspace IDs, stage IDs, session UUIDs, ordinals, ok flags, or absent error codes.
|
|
@@ -41,7 +53,7 @@ function parseIssue(url) {
|
|
|
41
53
|
try {
|
|
42
54
|
const parsed = new URL(url);
|
|
43
55
|
if (!/^https?:$/.test(parsed.protocol)) fail(ERROR_CODES.INVALID_ISSUE_URL, "Expected a supported tracker issue URL");
|
|
44
|
-
let match = parsed.pathname.match(/^\/(.+)\/-\/issues\/(\d+)\/?$/);
|
|
56
|
+
let match = parsed.pathname.match(/^\/(.+)\/-\/(?:issues|work_items)\/(\d+)\/?$/);
|
|
45
57
|
if (match) return { url: parsed.toString(), provider: "gitlab", project: match[1], iid: Number(match[2]) };
|
|
46
58
|
match = parsed.pathname.match(/^\/([^/]+\/[^/]+)\/issues\/(\d+)\/?$/);
|
|
47
59
|
if (match) return { url: parsed.toString(), provider: "github", project: match[1], iid: Number(match[2]) };
|
|
@@ -102,7 +114,10 @@ export class WorkContext {
|
|
|
102
114
|
if (!fs.existsSync(this.storage.root)) return { ok: true, data: [] };
|
|
103
115
|
const data = fs.readdirSync(this.storage.root, { withFileTypes: true })
|
|
104
116
|
.filter((entry) => entry.isDirectory() && /^\d{6}$/.test(entry.name))
|
|
105
|
-
.map((entry) =>
|
|
117
|
+
.map((entry) => {
|
|
118
|
+
const data = this.storage.readWorkspace(entry.name).data;
|
|
119
|
+
return { ...data, mode: workspaceMode(data) };
|
|
120
|
+
});
|
|
106
121
|
return { ok: true, data };
|
|
107
122
|
}
|
|
108
123
|
|
|
@@ -129,7 +144,8 @@ export class WorkContext {
|
|
|
129
144
|
visiting.delete(stage); visited.add(stage);
|
|
130
145
|
};
|
|
131
146
|
for (const stage of ids) visit(stage);
|
|
132
|
-
|
|
147
|
+
const workspaceData = this.storage.readWorkspace(workspace).data;
|
|
148
|
+
return { ok: true, data: { workspace, title: workspaceData.title, status: workspaceData.status, mode: workspaceMode(workspaceData), stages, sessions: reduceSessions(this.storage.readEvents()).filter((session) => session.workspace === workspace) } };
|
|
133
149
|
}
|
|
134
150
|
|
|
135
151
|
finishWorkspace(workspace) {
|
|
@@ -190,22 +206,26 @@ export class WorkContext {
|
|
|
190
206
|
|
|
191
207
|
createWorkspace(title, options = {}) {
|
|
192
208
|
if (!title?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Title is required");
|
|
209
|
+
const mode = options.mode === undefined ? "standard" : options.mode;
|
|
210
|
+
if (!["standard", "startup"].includes(mode)) fail(ERROR_CODES.INVALID_ARGUMENT, "Workspace mode must be 'standard' or 'startup'");
|
|
193
211
|
const requestedWorkspace = options.workspace;
|
|
194
212
|
return this.transact("workspace-create", () => {
|
|
195
213
|
const workspace = requestedWorkspace === undefined ? this.nextWorkspace() : normalizeWorkspaceId(requestedWorkspace);
|
|
196
214
|
const now = new Date().toISOString();
|
|
197
215
|
if (fs.existsSync(this.storage.workspaceDir(workspace))) fail(ERROR_CODES.CONFLICT, "Workspace already exists");
|
|
198
216
|
fs.mkdirSync(path.join(this.storage.workspaceDir(workspace), "stages"), { recursive: true });
|
|
199
|
-
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));
|
|
217
|
+
this.storage.writeMarkdown(this.storage.workspaceFile(workspace), { schema: 1, workspace, title: title.trim(), status: "in_progress", mode, created_at: now, updated_at: now, tracker_links: [] }, body(title));
|
|
200
218
|
const planningGoal = "Clarify the work goal and constraints";
|
|
201
219
|
const planningPrompt = "Diagnose and plan the task without functional changes. Discuss possible solutions, record durable workspace-wide facts, decisions, constraints, important files, and risks through explicit knowledge operations, and decompose the work into the following stages. For each new implementation stage, write a separate detailed prompt with local context, concrete actions, constraints, completion criteria, and the expected result; do not duplicate shared knowledge that every stage receives in resume.context.workspace_knowledge. Ask clarifying questions only when genuinely blocked. Stages must remain in progress until the user explicitly requests stage finish. If the user explicitly agrees to automatic completion for this workspace, add the exact standalone line AUTO_STAGE_FINISH: allowed to this Planning-stage prompt.";
|
|
202
220
|
this.storage.writeMarkdown(this.storage.stageFile(workspace, "01"), { schema: 1, workspace, stage: "01", title: "Planning", status: "in_progress", goal: planningGoal, prompt: planningPrompt, depends_on: [], owner: actor(this.options), created_at: now, updated_at: now, tracker_links: [] }, body("Planning", planningGoal, planningPrompt));
|
|
203
221
|
const sessionId = options.sessionId || randomUUID();
|
|
222
|
+
const workflowPolicy = mode === "startup" && options.opencodeSessionId ? startupWorkflowPolicy() : null;
|
|
204
223
|
if (this.storage.readEvents().some((item) => item.session_id === sessionId)) fail(ERROR_CODES.CONFLICT, "Session ID already exists");
|
|
205
224
|
this.writeEvents([event("session.started", workspace, "01", 1, sessionId, actor(this.options), { summary: `planning ${title.trim()}`, opencode_session_id: options.opencodeSessionId || null, branch: options.branch || null })]);
|
|
206
225
|
generateProjections(this.storage);
|
|
207
226
|
return this.result({
|
|
208
227
|
workspace,
|
|
228
|
+
mode,
|
|
209
229
|
stage: "01",
|
|
210
230
|
session_id: sessionId,
|
|
211
231
|
ordinal: "01/01",
|
|
@@ -220,11 +240,12 @@ export class WorkContext {
|
|
|
220
240
|
essence: planningGoal,
|
|
221
241
|
previous: "The previous session did not save a result; the stopping point needs to be clarified.",
|
|
222
242
|
now: planningPrompt,
|
|
223
|
-
|
|
224
|
-
|
|
243
|
+
workspace_knowledge: [],
|
|
244
|
+
...(workflowPolicy ? { workflow_policy: workflowPolicy } : {}),
|
|
245
|
+
lifecycle: { automatic_finish_allowed: false },
|
|
225
246
|
},
|
|
226
247
|
next_action: "start_work",
|
|
227
|
-
|
|
248
|
+
instruction: `${planningPrompt}${startupWorkflowInstruction(workflowPolicy)}\n\nDo not invoke stage finish unless the user explicitly requests the lifecycle command. Automatic completion is permitted only when lifecycle.automatic_finish_allowed is true, which requires the exact AUTO_STAGE_FINISH: allowed line in this workspace's Planning-stage prompt.`,
|
|
228
249
|
},
|
|
229
250
|
}, [workspace, "01"]);
|
|
230
251
|
});
|
|
@@ -245,6 +266,56 @@ export class WorkContext {
|
|
|
245
266
|
});
|
|
246
267
|
}
|
|
247
268
|
|
|
269
|
+
setWorkspaceMode(workspace, mode) {
|
|
270
|
+
workspace = normalizeWorkspaceId(workspace);
|
|
271
|
+
if (!["standard", "startup"].includes(mode)) fail(ERROR_CODES.INVALID_ARGUMENT, "Workspace mode must be 'standard' or 'startup'");
|
|
272
|
+
return this.transact(`workspace-${workspace}`, () => {
|
|
273
|
+
const record = this.storage.readWorkspace(workspace);
|
|
274
|
+
if (workspaceMode(record.data) === mode && record.data.mode === mode) return this.result({ workspace, mode }, []);
|
|
275
|
+
record.data.mode = mode;
|
|
276
|
+
record.data.updated_at = new Date().toISOString();
|
|
277
|
+
this.storage.writeMarkdown(this.storage.workspaceFile(workspace), record.data, record.body);
|
|
278
|
+
generateProjections(this.storage);
|
|
279
|
+
return this.result({ workspace, mode }, [workspace]);
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
candidates() { return new CandidateStore(this); }
|
|
284
|
+
|
|
285
|
+
createCandidate(workspace, title, message = null) {
|
|
286
|
+
return this.transact("candidate-create", () => this.result(this.candidates().create(workspace, title, message), ["local:candidates"]));
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
listCandidates(workspace) { return { ok: true, data: this.candidates().list(workspace) }; }
|
|
290
|
+
|
|
291
|
+
showCandidate(workspace, candidate) {
|
|
292
|
+
const store = this.candidates();
|
|
293
|
+
workspace = store.assertStartup(workspace);
|
|
294
|
+
return { ok: true, data: store.read(candidate, workspace, true) };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
captureCandidate(workspace, candidate, input) {
|
|
298
|
+
return this.transact("candidate-capture", () => this.result(this.candidates().capture(workspace, candidate, input), ["local:candidates"]));
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
previewCandidate(workspace, candidate) { return { ok: true, data: this.candidates().preview(workspace, candidate) }; }
|
|
302
|
+
|
|
303
|
+
readyCandidate(workspace, candidate) {
|
|
304
|
+
return this.transact("candidate-ready", () => this.result(this.candidates().setStatus(workspace, candidate, "ready"), ["local:candidates"]));
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
discardCandidate(workspace, candidate) {
|
|
308
|
+
return this.transact("candidate-discard", () => this.result(this.candidates().setStatus(workspace, candidate, "discarded"), ["local:candidates"]));
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
commitCandidate(workspace, candidate, message = undefined, options = {}) {
|
|
312
|
+
this.storage.assertSafeRoots();
|
|
313
|
+
// Operations needing both locks always acquire candidate-git before write.
|
|
314
|
+
return withLock(this.storage.lockPath("candidate-git"), () => this.transact("candidate-commit", () =>
|
|
315
|
+
this.result(this.candidates().commit(workspace, candidate, message, options), ["local:candidates"])
|
|
316
|
+
), { session: this.options.sessionId, owner: actor(this.options) });
|
|
317
|
+
}
|
|
318
|
+
|
|
248
319
|
nextWorkspace() {
|
|
249
320
|
const ids = this.listWorkspaces().data.map((workspace) => Number(workspace.workspace));
|
|
250
321
|
return String(Math.max(0, ...ids) + 1).padStart(6, "0");
|
|
@@ -285,7 +356,9 @@ export class WorkContext {
|
|
|
285
356
|
const hasPrompt = Boolean(stageRecord.data.prompt?.trim());
|
|
286
357
|
const confirmationRequired = hasPrompt && resumeConfirmationRequired(stageRecord.data.prompt);
|
|
287
358
|
const previousResult = preservedStageResult(stageRecord);
|
|
288
|
-
|
|
359
|
+
const workspaceRecord = this.storage.readWorkspace(workspace).data;
|
|
360
|
+
const workspaceTitle = workspaceRecord.title;
|
|
361
|
+
const workflowPolicy = workspaceMode(workspaceRecord) === "startup" && options.opencodeSessionId ? startupWorkflowPolicy() : null;
|
|
289
362
|
const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
|
|
290
363
|
const automaticFinish = automaticFinishAllowed(this.storage, workspace);
|
|
291
364
|
return this.result({
|
|
@@ -314,12 +387,13 @@ export class WorkContext {
|
|
|
314
387
|
essence: stageRecord.data.goal || stageRecord.data.title,
|
|
315
388
|
previous: previousSessionSummary || previousResult || "No previous progress was recorded.",
|
|
316
389
|
now: hasPrompt ? stageRecord.data.prompt : "First clarify the task and work plan with the user.",
|
|
317
|
-
|
|
318
|
-
|
|
390
|
+
workspace_knowledge: workspaceKnowledge,
|
|
391
|
+
...(workflowPolicy ? { workflow_policy: workflowPolicy } : {}),
|
|
392
|
+
lifecycle: { automatic_finish_allowed: automaticFinish },
|
|
319
393
|
},
|
|
320
394
|
next_action: hasPrompt ? confirmationRequired ? "await_confirmation" : "start_work" : "ask_questions",
|
|
321
395
|
instruction: `${hasPrompt
|
|
322
|
-
|
|
396
|
+
? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}${startupWorkflowInstruction(workflowPolicy)}`
|
|
323
397
|
: `This stage has no non-empty prompt. Give the user a concise plain-language summary of the stage title and goal, then ask focused questions needed to define the intended outcome and scope. Do not inspect or modify application code yet. Do not report raw operation metadata or identifiers.`}\n\nDo not invoke stage finish unless the user explicitly requests the lifecycle command. Automatic completion is permitted only when lifecycle.automatic_finish_allowed is true, which requires the exact AUTO_STAGE_FINISH: allowed line in this workspace's Planning-stage prompt.`,
|
|
324
398
|
},
|
|
325
399
|
}, [workspace, stage]);
|
|
@@ -522,6 +596,24 @@ export class WorkContext {
|
|
|
522
596
|
});
|
|
523
597
|
}
|
|
524
598
|
|
|
599
|
+
unlinkIssue(workspace, url, stage = null) {
|
|
600
|
+
const normalizedWorkspace = normalizeWorkspaceId(workspace);
|
|
601
|
+
const normalizedStage = stage === null || stage === undefined ? null : normalizeStageId(stage);
|
|
602
|
+
const parsed = parseIssue(url);
|
|
603
|
+
return this.transact(`link-${normalizedWorkspace}-${normalizedStage || "workspace"}`, () => {
|
|
604
|
+
const file = normalizedStage ? this.storage.stageFile(normalizedWorkspace, normalizedStage) : this.storage.workspaceFile(normalizedWorkspace);
|
|
605
|
+
const current = normalizedStage ? this.storage.readStage(normalizedWorkspace, normalizedStage) : this.storage.readWorkspace(normalizedWorkspace);
|
|
606
|
+
const links = current.data.tracker_links || [];
|
|
607
|
+
const remaining = links.filter((link) => link.url !== parsed.url);
|
|
608
|
+
if (remaining.length === links.length) return this.result({ workspace: normalizedWorkspace, stage: normalizedStage, issue: parsed }, []);
|
|
609
|
+
current.data.tracker_links = remaining;
|
|
610
|
+
current.data.updated_at = new Date().toISOString();
|
|
611
|
+
this.storage.writeMarkdown(file, current.data, current.body);
|
|
612
|
+
generateProjections(this.storage);
|
|
613
|
+
return this.result({ workspace: normalizedWorkspace, stage: normalizedStage, issue: parsed }, [file]);
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
|
|
525
617
|
renameSession(workspace, stage, sessionId, summary) {
|
|
526
618
|
if (!summary?.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Summary is required");
|
|
527
619
|
workspace = normalizeWorkspaceId(workspace);
|
|
@@ -650,10 +742,9 @@ export class WorkContext {
|
|
|
650
742
|
help(command = "") {
|
|
651
743
|
return this.result({
|
|
652
744
|
command,
|
|
653
|
-
syntax: "/wc [create|list|workspace list|workspace rename|workspace finish|workspace reopen|resume|stage add|stage reopen|stage restore|stage rename|stage update|stage update-prompt|stage update-result|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]",
|
|
654
|
-
|
|
745
|
+
syntax: "/wc [create|list|workspace list|workspace rename|workspace mode|candidate create|candidate capture|candidate preview|candidate show|candidate list|candidate ready|candidate commit|candidate discard|workspace finish|workspace reopen|resume|stage add|stage reopen|stage restore|stage rename|stage update|stage update-prompt|stage update-result|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|unlink-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]",
|
|
746
|
+
note: "associated OpenCode sessions in startup-mode workspaces receive the shared-worktree and commit-candidate policy on resume; standard mode remains conservative; commit candidates are local-only and require startup workflow mode; capture and commit use isolated Git indexes and never alter the ordinary index; candidate commit uses the stored message unless an explicit non-empty override is provided, and bypasses Git hooks and signing; stage finish requires an explicit user lifecycle request unless the Planning-stage prompt contains the exact line AUTO_STAGE_FINISH: allowed; stage reopen requires a completed stage and a reason; stage restore requires an archived stage and a reason, returns its saved pre-archive status (or in_progress for legacy archives), and requires explicit separate-session resume when actionable; workspace reopen requires a completed workspace and a reason.",
|
|
655
747
|
}, []);
|
|
656
|
-
return this.result({ command, syntax: "/wc [create|list|workspace list|workspace rename|workspace finish|resume|stage add|stage rename|stage update|stage update-prompt|stage update-result|stage force-close|stage archive|stage handoff|stage abandon|stage finish|link-issue|session rename|knowledge list|knowledge add|knowledge update|knowledge supersede|help]", note: "workspace and stage are optional for stage rename/update/update-prompt/update-result/archive/handoff/abandon/finish and session rename/close when the current session identifies them; explicit workspace and stage positions accept padded or unpadded positive integer IDs and structured results remain canonical; zero, signs, decimals, whitespace, and overlong identifiers are invalid; stage update-result requires an existing stage result; finish <stage> is a shortcut for stage finish <stage>; when only one numeric identifier is supplied, six digits mean workspace and one or two digits mean stage; stage add accepts an optional local prompt; from an unassociated OpenCode session it also enters the new stage immediately, while an associated session remains on its current stage; resume returns resume.next_action, resume.instruction, and active shared entries in resume.context.workspace_knowledge; implementation may begin only with a non-empty prompt and no unanswered questions; ask focused questions and do not modify application code when next_action is ask_questions; force-close requires a session ID, reason, and exact confirmation FORCE_CLOSE; before stage finish, add, update, or supersede durable findings, or explicitly declare none; stage finish closes only the current stage session and returns downstream stages for informational prompt review without starting one; 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; mutating commands call structured tools; only explicit lifecycle operations change storage." }, []);
|
|
657
748
|
}
|
|
658
749
|
|
|
659
750
|
result(data, changed, next = null) {
|
package/src/errors.js
CHANGED
|
@@ -4,6 +4,11 @@ export const ERROR_CODES = Object.freeze({
|
|
|
4
4
|
LOCKED: "LOCKED", STALE_LOCK: "STALE_LOCK", CONFLICT: "CONFLICT", INVALID_ISSUE_URL: "INVALID_ISSUE_URL",
|
|
5
5
|
ADAPTER_UNAVAILABLE: "ADAPTER_UNAVAILABLE", STORAGE_ERROR: "STORAGE_ERROR", CONFIRMATION_REQUIRED: "CONFIRMATION_REQUIRED",
|
|
6
6
|
STAGE_CONTEXT_REQUIRED: "STAGE_CONTEXT_REQUIRED",
|
|
7
|
+
GIT_UNAVAILABLE: "GIT_UNAVAILABLE", NOT_GIT_REPOSITORY: "NOT_GIT_REPOSITORY",
|
|
8
|
+
CANDIDATE_MODE_REQUIRED: "CANDIDATE_MODE_REQUIRED", CANDIDATE_INVALID_PATCH: "CANDIDATE_INVALID_PATCH",
|
|
9
|
+
CANDIDATE_UNSUPPORTED: "CANDIDATE_UNSUPPORTED", CANDIDATE_STALE_BASE: "CANDIDATE_STALE_BASE",
|
|
10
|
+
CANDIDATE_CONFLICT: "CANDIDATE_CONFLICT", CANDIDATE_DETACHED_HEAD: "CANDIDATE_DETACHED_HEAD",
|
|
11
|
+
CANDIDATE_REF_RACE: "CANDIDATE_REF_RACE", CANDIDATE_COMMIT_FAILED: "CANDIDATE_COMMIT_FAILED",
|
|
7
12
|
});
|
|
8
13
|
|
|
9
14
|
export class WorkContextError extends Error {
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { spawnSync } from "node:child_process";
|
|
5
|
+
import { ERROR_CODES, fail } from "./errors.js";
|
|
6
|
+
|
|
7
|
+
const git = (root, args, options = {}) => {
|
|
8
|
+
const result = spawnSync("git", args, {
|
|
9
|
+
cwd: root,
|
|
10
|
+
encoding: options.encoding === null ? null : "utf8",
|
|
11
|
+
env: { ...process.env, ...options.env },
|
|
12
|
+
input: options.input,
|
|
13
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
14
|
+
});
|
|
15
|
+
if (result.error?.code === "ENOENT") fail(ERROR_CODES.GIT_UNAVAILABLE, "Git executable is unavailable");
|
|
16
|
+
if (result.error) fail(ERROR_CODES.GIT_UNAVAILABLE, "Cannot execute Git", { cause: result.error.message });
|
|
17
|
+
if (result.status !== 0 && !options.allowFailure) {
|
|
18
|
+
fail(options.code || ERROR_CODES.CANDIDATE_INVALID_PATCH, options.message || "Git operation failed", {
|
|
19
|
+
stderr: String(result.stderr || "").trim(),
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
return result;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export function repositoryState(projectRoot) {
|
|
26
|
+
const rootResult = git(projectRoot, ["rev-parse", "--show-toplevel"], {
|
|
27
|
+
allowFailure: true,
|
|
28
|
+
});
|
|
29
|
+
if (rootResult.status !== 0) fail(ERROR_CODES.NOT_GIT_REPOSITORY, "Work context is not at a Git repository root");
|
|
30
|
+
const root = fs.realpathSync(rootResult.stdout.trim());
|
|
31
|
+
if (root !== fs.realpathSync(projectRoot)) fail(ERROR_CODES.NOT_GIT_REPOSITORY, "Work context must be at the Git repository root", { repositoryRoot: root });
|
|
32
|
+
const head = git(root, ["rev-parse", "--verify", "HEAD"], {
|
|
33
|
+
allowFailure: true,
|
|
34
|
+
});
|
|
35
|
+
if (head.status !== 0) fail(ERROR_CODES.CANDIDATE_STALE_BASE, "Git repository has no valid HEAD");
|
|
36
|
+
return { root, head: head.stdout.trim() };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function withTemporaryIndex(root, base, fn) {
|
|
40
|
+
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "work-context-candidate-"));
|
|
41
|
+
const index = path.join(directory, "index");
|
|
42
|
+
const env = { GIT_INDEX_FILE: index, GIT_OPTIONAL_LOCKS: "0", GIT_LITERAL_PATHSPECS: "1" };
|
|
43
|
+
try {
|
|
44
|
+
const baseCheck = git(root, ["cat-file", "-e", `${base}^{commit}`], { allowFailure: true });
|
|
45
|
+
if (baseCheck.status !== 0) fail(ERROR_CODES.CANDIDATE_STALE_BASE, "Candidate base commit is unavailable", { base });
|
|
46
|
+
git(root, ["read-tree", base], { env, code: ERROR_CODES.CANDIDATE_STALE_BASE, message: "Cannot populate the candidate index" });
|
|
47
|
+
return fn(env);
|
|
48
|
+
} finally {
|
|
49
|
+
fs.rmSync(directory, { recursive: true, force: true });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const currentBranch = (root) => {
|
|
54
|
+
const result = git(root, ["symbolic-ref", "--quiet", "HEAD"], { allowFailure: true });
|
|
55
|
+
const branch = result.stdout.trim();
|
|
56
|
+
if (result.status !== 0 || !branch.startsWith("refs/heads/")) {
|
|
57
|
+
fail(ERROR_CODES.CANDIDATE_DETACHED_HEAD, "Candidate commits require an attached local branch");
|
|
58
|
+
}
|
|
59
|
+
return branch;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
const rejectUnsupportedPatch = (patchText) => {
|
|
63
|
+
if (typeof patchText !== "string" || !patchText.trim()) fail(ERROR_CODES.CANDIDATE_INVALID_PATCH, "A non-empty unified patch is required");
|
|
64
|
+
if (patchText.includes("\0") || /^(?:GIT binary patch|Binary files .* differ)$/m.test(patchText)) {
|
|
65
|
+
fail(ERROR_CODES.CANDIDATE_UNSUPPORTED, "Binary candidate patches are not supported");
|
|
66
|
+
}
|
|
67
|
+
if (/^(?:(?:old|new|new file|deleted file) mode 160000|index [0-9a-f]+\.\.[0-9a-f]+ 160000)$/m.test(patchText)) {
|
|
68
|
+
fail(ERROR_CODES.CANDIDATE_UNSUPPORTED, "Gitlink and submodule candidate patches are not supported");
|
|
69
|
+
}
|
|
70
|
+
if (!/^diff --git a\/.+ b\/.+/m.test(patchText)) fail(ERROR_CODES.CANDIDATE_INVALID_PATCH, "Expected a Git unified patch");
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const patchFromIndex = (root, base, env) => {
|
|
74
|
+
const result = git(root, ["diff", "--cached", "--no-ext-diff", "--no-textconv", "--no-color", "--full-index", "--find-renames", base, "--"], { env });
|
|
75
|
+
rejectUnsupportedPatch(result.stdout);
|
|
76
|
+
return result.stdout;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
export function normalizeCandidatePaths(root, personalRoot, values) {
|
|
80
|
+
if (!Array.isArray(values) || !values.length) fail(ERROR_CODES.INVALID_ARGUMENT, "At least one path is required");
|
|
81
|
+
const personal = fs.existsSync(personalRoot) ? fs.realpathSync(personalRoot) : path.resolve(personalRoot);
|
|
82
|
+
const normalized = values.map((value) => {
|
|
83
|
+
if (typeof value !== "string" || !value.trim() || value.includes("\0")) fail(ERROR_CODES.INVALID_ARGUMENT, "Candidate paths must be non-empty strings");
|
|
84
|
+
const absolute = path.resolve(root, value);
|
|
85
|
+
const relative = path.relative(root, absolute);
|
|
86
|
+
if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) fail(ERROR_CODES.INVALID_ARGUMENT, "Candidate path must be inside the repository", { path: value });
|
|
87
|
+
if (absolute === personal || absolute.startsWith(`${personal}${path.sep}`)) fail(ERROR_CODES.INVALID_ARGUMENT, "Candidate storage cannot be captured", { path: value });
|
|
88
|
+
return relative.split(path.sep).join("/");
|
|
89
|
+
});
|
|
90
|
+
return [...new Set(normalized)].sort();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function capturePaths(root, personalRoot, base, values) {
|
|
94
|
+
const paths = normalizeCandidatePaths(root, personalRoot, values);
|
|
95
|
+
return withTemporaryIndex(root, base, (env) => {
|
|
96
|
+
const result = git(root, ["add", "-A", "--", ...paths], { env, allowFailure: true });
|
|
97
|
+
if (result.status !== 0) fail(ERROR_CODES.CANDIDATE_UNSUPPORTED, "Cannot capture one or more candidate paths", { stderr: result.stderr.trim() });
|
|
98
|
+
return { patch: patchFromIndex(root, base, env), paths };
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function capturePatch(root, personalRoot, base, patchText) {
|
|
103
|
+
rejectUnsupportedPatch(patchText);
|
|
104
|
+
const worktreeCheck = git(root, ["apply", "--check", "--reverse", "--whitespace=nowarn", "-"], { input: patchText, allowFailure: true });
|
|
105
|
+
if (worktreeCheck.status !== 0) fail(ERROR_CODES.CANDIDATE_INVALID_PATCH, "Patch does not match the current working tree", { stderr: worktreeCheck.stderr.trim() });
|
|
106
|
+
return withTemporaryIndex(root, base, (env) => {
|
|
107
|
+
const check = git(root, ["apply", "--cached", "--check", "--whitespace=nowarn", "-"], { env, input: patchText, allowFailure: true });
|
|
108
|
+
if (check.status !== 0) fail(ERROR_CODES.CANDIDATE_INVALID_PATCH, "Patch does not apply safely to the candidate base", { stderr: check.stderr.trim() });
|
|
109
|
+
git(root, ["apply", "--cached", "--whitespace=nowarn", "-"], { env, input: patchText });
|
|
110
|
+
const patch = patchFromIndex(root, base, env);
|
|
111
|
+
const names = git(root, ["diff", "--cached", "--name-only", "-z", base, "--"], { env, encoding: null }).stdout;
|
|
112
|
+
return { patch, paths: normalizeCandidatePaths(root, personalRoot, names.toString("utf8").split("\0").filter(Boolean)) };
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function previewPatch(root, base, patchText) {
|
|
117
|
+
rejectUnsupportedPatch(patchText);
|
|
118
|
+
return withTemporaryIndex(root, base, (env) => {
|
|
119
|
+
const applied = git(root, ["apply", "--cached", "--check", "--whitespace=nowarn", "-"], { env, input: patchText, allowFailure: true });
|
|
120
|
+
if (applied.status !== 0) fail(ERROR_CODES.CANDIDATE_INVALID_PATCH, "Stored candidate patch is invalid", { stderr: applied.stderr.trim() });
|
|
121
|
+
git(root, ["apply", "--cached", "--whitespace=nowarn", "-"], { env, input: patchText });
|
|
122
|
+
const patch = patchFromIndex(root, base, env);
|
|
123
|
+
const stat = git(root, ["diff", "--cached", "--stat", "--no-color", base, "--"], { env }).stdout.trimEnd();
|
|
124
|
+
const currentHead = repositoryState(root).head;
|
|
125
|
+
return { patch, stat, stale: currentHead !== base, current_head: currentHead };
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function commitPatch(root, base, patchText, message, options = {}) {
|
|
130
|
+
rejectUnsupportedPatch(patchText);
|
|
131
|
+
if (typeof message !== "string" || !message.trim()) fail(ERROR_CODES.INVALID_ARGUMENT, "Commit message is required");
|
|
132
|
+
const repository = repositoryState(root);
|
|
133
|
+
const branch = currentBranch(repository.root);
|
|
134
|
+
const baseCheck = git(repository.root, ["cat-file", "-e", `${base}^{commit}`], { allowFailure: true });
|
|
135
|
+
if (baseCheck.status !== 0) fail(ERROR_CODES.CANDIDATE_STALE_BASE, "Candidate base commit is unavailable", { base });
|
|
136
|
+
|
|
137
|
+
return withTemporaryIndex(repository.root, repository.head, (env) => {
|
|
138
|
+
const applied = git(repository.root, ["apply", "--cached", "--check", "--whitespace=nowarn", "-"], { env, input: patchText, allowFailure: true });
|
|
139
|
+
if (applied.status !== 0) {
|
|
140
|
+
const stale = repository.head !== base;
|
|
141
|
+
fail(stale ? ERROR_CODES.CANDIDATE_CONFLICT : ERROR_CODES.CANDIDATE_INVALID_PATCH,
|
|
142
|
+
stale ? "Candidate overlaps changes made since its base" : "Stored candidate patch is invalid",
|
|
143
|
+
{ base, currentHead: repository.head, stderr: applied.stderr.trim() });
|
|
144
|
+
}
|
|
145
|
+
git(repository.root, ["apply", "--cached", "--whitespace=nowarn", "-"], { env, input: patchText });
|
|
146
|
+
const tree = git(repository.root, ["write-tree"], { env, code: ERROR_CODES.CANDIDATE_COMMIT_FAILED, message: "Cannot write candidate tree" }).stdout.trim();
|
|
147
|
+
const commitResult = git(repository.root, ["commit-tree", tree, "-p", repository.head], {
|
|
148
|
+
env,
|
|
149
|
+
input: `${message.trim()}\n`,
|
|
150
|
+
allowFailure: true,
|
|
151
|
+
});
|
|
152
|
+
if (commitResult.status !== 0) fail(ERROR_CODES.CANDIDATE_COMMIT_FAILED, "Cannot create candidate commit", { stderr: commitResult.stderr.trim() });
|
|
153
|
+
const commit = commitResult.stdout.trim();
|
|
154
|
+
options.beforeUpdateRef?.({ branch, commit, head: repository.head });
|
|
155
|
+
const updated = git(repository.root, ["update-ref", branch, commit, repository.head], { allowFailure: true });
|
|
156
|
+
if (updated.status !== 0) fail(ERROR_CODES.CANDIDATE_REF_RACE, "Branch changed while publishing the candidate", {
|
|
157
|
+
branch,
|
|
158
|
+
expectedHead: repository.head,
|
|
159
|
+
stderr: updated.stderr.trim(),
|
|
160
|
+
});
|
|
161
|
+
return { branch, previous_head: repository.head, commit, stale: repository.head !== base };
|
|
162
|
+
});
|
|
163
|
+
}
|
package/src/index.js
CHANGED
package/src/opencode-adapter.js
CHANGED
|
@@ -7,11 +7,16 @@ export { readStagesSnapshot } from "./stages-snapshot.js";
|
|
|
7
7
|
export function contextFor(directory, sessionId, actor = "OpenCode") {
|
|
8
8
|
return WorkContext.openExisting(directory, { sessionId, actor });
|
|
9
9
|
}
|
|
10
|
-
export function titleFor(context, workspace, stage, sessionId, knownSession = null) {
|
|
10
|
+
export function titleFor(context, workspace, stage, sessionId, knownSession = null, includeStageTrackerLinks = false) {
|
|
11
11
|
const current = knownSession || context.sessionById(sessionId);
|
|
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
|
-
|
|
15
|
+
const workspaceLinks = meta.tracker_links || [];
|
|
16
|
+
const primaryTrackerLinks = stageMeta.tracker_links?.length ? stageMeta.tracker_links : workspaceLinks;
|
|
17
|
+
const stageTrackerLinks = includeStageTrackerLinks
|
|
18
|
+
? context.listStages(workspace).data.stages.flatMap((item) => item.tracker_links || []).filter((link) => !workspaceLinks.some((workspaceLink) => workspaceLink.url === link.url) && !primaryTrackerLinks.some((primaryLink) => primaryLink.url === link.url))
|
|
19
|
+
: [];
|
|
20
|
+
return renderTitle({ workspace, stageTitle: stageMeta.title, stage, ordinal: current.ordinal, state: current.state, trackerLinks: primaryTrackerLinks, stageTrackerLinks, issuePrefix: context.storage.config.title?.issue_prefix || "short" });
|
|
16
21
|
}
|
|
17
22
|
export const packageRoot = () => path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
package/src/stages-renderer.js
CHANGED
|
@@ -56,9 +56,11 @@ export function renderStagesPanel(result) {
|
|
|
56
56
|
|
|
57
57
|
const lines = [
|
|
58
58
|
snapshot.workspace.title,
|
|
59
|
-
""
|
|
60
|
-
`Stages · ${snapshot.workspace.status}`,
|
|
59
|
+
`Workflow · ${snapshot.workspace.mode || "standard"}`,
|
|
61
60
|
];
|
|
61
|
+
const candidates = snapshot.workspace.candidates;
|
|
62
|
+
if (candidates && (candidates.pending || candidates.ready)) lines.push(`Candidates · pending ${candidates.pending} · ready ${candidates.ready}`);
|
|
63
|
+
lines.push("", `Stages · ${snapshot.workspace.status}`);
|
|
62
64
|
for (const stage of snapshot.stages) {
|
|
63
65
|
lines.push(`${statusMarker(stage.status)} ${stage.id}. ${stage.title}${stage.depends_on?.length ? `\nDeps: ${stage.depends_on.join(", ")}` : ""}`);
|
|
64
66
|
}
|
package/src/stages-snapshot.js
CHANGED
|
@@ -34,6 +34,8 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
|
|
|
34
34
|
if (!session) return { ok: true, data: emptySnapshot() };
|
|
35
35
|
|
|
36
36
|
const workspace = context.storage.readWorkspace(session.workspace).data;
|
|
37
|
+
const mode = workspace.mode || "standard";
|
|
38
|
+
const candidates = mode === "startup" ? context.candidates().summary(session.workspace) : null;
|
|
37
39
|
const stages = context.listStages(session.workspace).data.stages
|
|
38
40
|
.filter((stage) => stage.status !== "archived")
|
|
39
41
|
.sort((left, right) => Number(left.stage) - Number(right.stage))
|
|
@@ -43,6 +45,7 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
|
|
|
43
45
|
status: stage.status,
|
|
44
46
|
description: stage.description,
|
|
45
47
|
depends_on: stage.depends_on,
|
|
48
|
+
tracker_links: stage.tracker_links || [],
|
|
46
49
|
current: stage.stage === session.stage,
|
|
47
50
|
}));
|
|
48
51
|
const currentStage = stages.some((stage) => stage.current) ? session.stage : null;
|
|
@@ -51,7 +54,7 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
|
|
|
51
54
|
ok: true,
|
|
52
55
|
data: {
|
|
53
56
|
schema: 1,
|
|
54
|
-
workspace: { id: workspace.workspace, title: workspace.title, status: workspace.status },
|
|
57
|
+
workspace: { id: workspace.workspace, title: workspace.title, status: workspace.status, mode, ...(candidates ? { candidates } : {}) },
|
|
55
58
|
stages,
|
|
56
59
|
currentStage,
|
|
57
60
|
generatedAt: new Date().toISOString(),
|
package/src/storage.js
CHANGED
|
@@ -19,7 +19,7 @@ const validTrackerLinks = (links) => links.every((link) => {
|
|
|
19
19
|
if (url.protocol !== "http:" && url.protocol !== "https:") return false;
|
|
20
20
|
if (link.provider === "gitlab" || link.provider === "github") {
|
|
21
21
|
const allowed = ["url", "provider", "project", "iid"];
|
|
22
|
-
const match = url.pathname.match(link.provider === "gitlab" ? /^\/(.+)\/-\/issues\/(\d+)\/?$/ : /^\/([^/]+\/[^/]+)\/issues\/(\d+)\/?$/);
|
|
22
|
+
const match = url.pathname.match(link.provider === "gitlab" ? /^\/(.+)\/-\/(?:issues|work_items)\/(\d+)\/?$/ : /^\/([^/]+\/[^/]+)\/issues\/(\d+)\/?$/);
|
|
23
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
24
|
}
|
|
25
25
|
if (link.provider === "jira") {
|
|
@@ -88,13 +88,13 @@ const validateEventStream = (events) => {
|
|
|
88
88
|
}
|
|
89
89
|
};
|
|
90
90
|
function validateMetadata(data, kind, workspace, stage = null) {
|
|
91
|
-
const allowed = kind === "workspace" ? ["schema", "workspace", "title", "status", "created_at", "updated_at", "tracker_links", "reopen_history"] : ["schema", "workspace", "stage", "title", "status", "goal", "prompt", "depends_on", "owner", "created_at", "updated_at", "tracker_links", "reopen_history", "archive_history"];
|
|
91
|
+
const allowed = kind === "workspace" ? ["schema", "workspace", "title", "status", "mode", "created_at", "updated_at", "tracker_links", "reopen_history"] : ["schema", "workspace", "stage", "title", "status", "goal", "prompt", "depends_on", "owner", "created_at", "updated_at", "tracker_links", "reopen_history", "archive_history"];
|
|
92
92
|
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`);
|
|
93
93
|
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`);
|
|
94
94
|
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`);
|
|
95
95
|
const statuses = kind === "workspace" ? ["in_progress", "completed", "cancelled"] : ["planned", "in_progress", "completed", "cancelled", "archived"];
|
|
96
96
|
if (!statuses.includes(data.status)) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${kind} status`);
|
|
97
|
-
const invalidWorkspaceHistory = kind === "workspace" && data.reopen_history !== undefined && !validReopenHistory(data.reopen_history);
|
|
97
|
+
const invalidWorkspaceHistory = kind === "workspace" && ((data.mode !== undefined && !["standard", "startup"].includes(data.mode)) || (data.reopen_history !== undefined && !validReopenHistory(data.reopen_history)));
|
|
98
98
|
const invalidStageMetadata = kind === "stage" && (
|
|
99
99
|
data.stage !== stage || !/^\d{2}$/.test(data.stage) || !requiredString(data, "goal")
|
|
100
100
|
|| (data.prompt !== undefined && !requiredString(data, "prompt")) || !requiredString(data, "owner")
|
package/src/title.js
CHANGED
|
@@ -1,11 +1,20 @@
|
|
|
1
|
-
|
|
1
|
+
const trackerLinkText = (link) => {
|
|
2
|
+
const identifier = link.key || link.iid;
|
|
3
|
+
if ((link.provider || "gitlab") === "gitlab") return `GL#${identifier}`;
|
|
4
|
+
if (link.provider === "github") return `GH#${identifier}`;
|
|
5
|
+
return `JIRA ${identifier}`;
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
export function renderTitle({ workspace, stageTitle, stage, ordinal, state = "active", trackerLinks = [], stageTrackerLinks = [], issuePrefix = "short" }) {
|
|
2
9
|
const link = trackerLinks[0]; let prefix = "";
|
|
3
10
|
if (link && issuePrefix !== "none") {
|
|
4
11
|
const identifier = link.key || link.iid;
|
|
5
|
-
const short = (link
|
|
12
|
+
const short = trackerLinkText(link);
|
|
6
13
|
prefix = issuePrefix === "full" ? `${link.project}#${identifier} | ` : `${short} | `;
|
|
7
14
|
}
|
|
8
15
|
const suffix = state === "active" ? "" : ` (${state})`;
|
|
9
16
|
const description = (stageTitle || stage).replace(/[\r\n|]+/g, " ").trim().slice(0, 80);
|
|
10
|
-
|
|
17
|
+
const taskLinks = [...new Map(stageTrackerLinks.map((item) => [item.url, item])).values()];
|
|
18
|
+
const tasks = taskLinks.length ? `\nTasks: ${taskLinks.map(trackerLinkText).join(", ")}` : "";
|
|
19
|
+
return `${description}\n${prefix}${workspace} ${stage}/${String(ordinal).padStart(2, "0")}${suffix}${tasks}`;
|
|
11
20
|
}
|
package/src/tool-definitions.js
CHANGED
|
@@ -56,13 +56,22 @@ const addStageFromTool = (ctx, args, oc) => {
|
|
|
56
56
|
export const work_context_list_workspaces = tool({ description: "List work-context workspaces.", args: {}, execute: run((ctx) => ctx.listWorkspaces()) });
|
|
57
57
|
export const work_context_workspace_list = tool({ description: "List a workspace with stage descriptions and sessions.", args: { workspace: tool.schema.string() }, execute: run((ctx, a) => ctx.listStages(a.workspace)) });
|
|
58
58
|
export const work_context_rename_workspace = tool({ description: "Rename a workspace.", args: { workspace: tool.schema.string(), title: tool.schema.string() }, execute: run((ctx, a) => ctx.renameWorkspace(a.workspace, a.title)) });
|
|
59
|
+
export const work_context_set_workspace_mode = tool({ description: "Set a workspace workflow mode.", args: { workspace: tool.schema.string(), mode: tool.schema.enum(["standard", "startup"]) }, execute: run((ctx, a) => ctx.setWorkspaceMode(a.workspace, a.mode)) });
|
|
60
|
+
export const work_context_create_candidate = tool({ description: "Create a local draft commit candidate for a startup-mode workspace.", args: { workspace: tool.schema.string(), title: tool.schema.string(), message: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.createCandidate(a.workspace, a.title, a.message)) });
|
|
61
|
+
export const work_context_capture_candidate = tool({ description: "Capture explicit complete paths or an exact unified patch into a draft commit candidate.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string(), paths: tool.schema.array(tool.schema.string()).optional(), patch: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.captureCandidate(a.workspace, a.candidateId, { paths: a.paths, patch: a.patch })) });
|
|
62
|
+
export const work_context_preview_candidate = tool({ description: "Preview a candidate using an isolated temporary Git index.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string() }, execute: run((ctx, a) => ctx.previewCandidate(a.workspace, a.candidateId)) });
|
|
63
|
+
export const work_context_show_candidate = tool({ description: "Show local candidate metadata and its exact captured patch.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string() }, execute: run((ctx, a) => ctx.showCandidate(a.workspace, a.candidateId)) });
|
|
64
|
+
export const work_context_list_candidates = tool({ description: "List local commit candidates associated with a startup-mode workspace.", args: { workspace: tool.schema.string() }, execute: run((ctx, a) => ctx.listCandidates(a.workspace)) });
|
|
65
|
+
export const work_context_ready_candidate = tool({ description: "Mark a captured draft candidate ready for a later explicit commit operation.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string() }, execute: run((ctx, a) => ctx.readyCandidate(a.workspace, a.candidateId)) });
|
|
66
|
+
export const work_context_commit_candidate = tool({ description: "Commit a ready candidate atomically without using the ordinary Git index. Uses its stored message unless message is provided.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string(), message: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.commitCandidate(a.workspace, a.candidateId, a.message)) });
|
|
67
|
+
export const work_context_discard_candidate = tool({ description: "Discard a local commit candidate without changing Git state.", args: { workspace: tool.schema.string(), candidateId: tool.schema.string() }, execute: run((ctx, a) => ctx.discardCandidate(a.workspace, a.candidateId)) });
|
|
59
68
|
export const work_context_workspace_finish = tool({ description: "Finish a workspace after all stages are completed.", args: { workspace: tool.schema.string() }, execute: run((ctx, a) => ctx.finishWorkspace(a.workspace)) });
|
|
60
69
|
export const work_context_reopen_workspace = tool({ description: "Reopen a completed workspace with a required reason and durable history.", args: { workspace: tool.schema.string(), reason: tool.schema.string() }, execute: run((ctx, a) => ctx.reopenWorkspace(a.workspace, a.reason)) });
|
|
61
|
-
export const work_context_create_workspace = tool({ description: "Create a workspace; enter its planning stage only when the current OpenCode session is not associated with a workspace.", args: { title: tool.schema.string() }, execute: run((ctx, a, oc) => {
|
|
70
|
+
export const work_context_create_workspace = tool({ description: "Create a workspace; enter its planning stage only when the current OpenCode session is not associated with a workspace.", args: { title: tool.schema.string(), mode: tool.schema.enum(["standard", "startup"]).optional() }, execute: run((ctx, a, oc) => {
|
|
62
71
|
const currentSession = ctx.sessionByOpenCodeId(oc.sessionID);
|
|
63
|
-
return ctx.createWorkspace(a.title, { sessionId: randomUUID(), ...(currentSession ? {} : { opencodeSessionId: oc.sessionID }) });
|
|
72
|
+
return ctx.createWorkspace(a.title, { sessionId: randomUUID(), mode: a.mode, ...(currentSession ? {} : { opencodeSessionId: oc.sessionID }) });
|
|
64
73
|
}) });
|
|
65
|
-
export const work_context_start_session = tool({ description: "Start a new active session for a stage and return its human-oriented presentation, prompt,
|
|
74
|
+
export const work_context_start_session = tool({ description: "Start a new active session for a stage and return its human-oriented presentation, prompt, active workspace knowledge, and startup policy when applicable.", 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 })) });
|
|
66
75
|
export const work_context_add_stage = tool({ description: "Add a stage; when the current OpenCode session is not associated with a workspace, enter the new stage in that session immediately.", args: { workspace: tool.schema.string().optional(), title: tool.schema.string(), goal: tool.schema.string().optional(), prompt: tool.schema.string().optional(), dependsOn: tool.schema.array(tool.schema.string()).optional() }, execute: run(addStageFromTool) });
|
|
67
76
|
export const work_context_rename_stage = tool({ description: "Rename a stage while preserving its ID and history; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage, title: tool.schema.string() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.renameStage(workspace, stageFromSession(ctx, workspace, a.stage), a.title); }) });
|
|
68
77
|
export const work_context_update_stage = tool({ description: "Update an existing stage description; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage, description: tool.schema.string() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.updateStage(workspace, stageFromSession(ctx, workspace, a.stage), a.description); }) });
|
|
@@ -72,6 +81,7 @@ export const work_context_archive_stage = tool({ description: "Archive a stage w
|
|
|
72
81
|
export const work_context_reopen_stage = tool({ description: "Reopen a completed stage with a reason. This preserves completion history and requires explicit resume in a separate OpenCode session.", args: { ...common, reason: tool.schema.string() }, execute: run((ctx, a) => ctx.reopenStage(a.workspace, a.stage, a.reason)) });
|
|
73
82
|
export const work_context_restore_stage = tool({ description: "Restore an archived stage to its saved pre-archive status with a required reason. Actionable stages require explicit resume in a separate OpenCode session.", args: { ...common, reason: tool.schema.string() }, execute: run((ctx, a) => ctx.restoreStage(a.workspace, a.stage, a.reason)) });
|
|
74
83
|
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)) });
|
|
84
|
+
export const work_context_unlink_issue = tool({ description: "Remove a tracker issue URL from a workspace or stage.", args: { workspace: tool.schema.string(), url: tool.schema.string(), stage: tool.schema.string().optional() }, execute: run((ctx, a) => ctx.unlinkIssue(a.workspace, a.url, a.stage)) });
|
|
75
85
|
export const work_context_rename_session = tool({ description: "Rename the current active session summary; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage, summary: tool.schema.string() }, execute: run((ctx, a, oc) => { const workspace = workspaceFromSession(ctx, a.workspace); const stage = stageFromSession(ctx, workspace, a.stage); return ctx.renameSession(workspace, stage, sessionFor(ctx, oc, workspace, stage), a.summary); }) });
|
|
76
86
|
export const work_context_close_session = tool({ description: "Close the current session without finishing its stage; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage }, execute: run((ctx, a, oc) => { const workspace = workspaceFromSession(ctx, a.workspace); const stage = stageFromSession(ctx, workspace, a.stage); return ctx.closeSession(workspace, stage, sessionFor(ctx, oc, workspace, stage)); }) });
|
|
77
87
|
export const work_context_force_close_session = tool({ description: "Force close a stale active session with an explicit reason and confirmation.", args: { workspace: tool.schema.string(), stage: tool.schema.string(), sessionId: tool.schema.string(), reason: tool.schema.string(), confirmation: tool.schema.string() }, execute: run((ctx, a) => ctx.forceCloseSession(a.workspace, a.stage, a.sessionId, a.reason, a.confirmation)) });
|
|
@@ -84,4 +94,4 @@ export const work_context_add_knowledge = tool({ description: "Add a durable kno
|
|
|
84
94
|
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)) });
|
|
85
95
|
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) ) });
|
|
86
96
|
|
|
87
|
-
export default { work_context_list_workspaces, work_context_workspace_list, work_context_rename_workspace, work_context_workspace_finish, work_context_reopen_workspace, work_context_create_workspace, work_context_start_session, work_context_add_stage, work_context_rename_stage, work_context_update_stage, work_context_update_stage_prompt, work_context_update_stage_result, work_context_archive_stage, work_context_reopen_stage, work_context_restore_stage, work_context_link_issue, work_context_rename_session, work_context_close_session, work_context_force_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 };
|
|
97
|
+
export default { work_context_list_workspaces, work_context_workspace_list, work_context_rename_workspace, work_context_set_workspace_mode, work_context_create_candidate, work_context_capture_candidate, work_context_preview_candidate, work_context_show_candidate, work_context_list_candidates, work_context_ready_candidate, work_context_commit_candidate, work_context_discard_candidate, work_context_workspace_finish, work_context_reopen_workspace, work_context_create_workspace, work_context_start_session, work_context_add_stage, work_context_rename_stage, work_context_update_stage, work_context_update_stage_prompt, work_context_update_stage_result, work_context_archive_stage, work_context_reopen_stage, work_context_restore_stage, work_context_link_issue, work_context_unlink_issue, work_context_rename_session, work_context_close_session, work_context_force_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 };
|
|
@@ -31,10 +31,14 @@ const readWorkspace = (context, record, currentSession) => {
|
|
|
31
31
|
? currentSession
|
|
32
32
|
: sessions.find((session) => session.session_id === currentSession?.session_id);
|
|
33
33
|
const currentStage = matchingSession?.stage || null;
|
|
34
|
+
const mode = record.mode || "standard";
|
|
35
|
+
const candidates = mode === "startup" ? context.candidates().summary(record.workspace) : null;
|
|
34
36
|
return {
|
|
35
37
|
id: record.workspace,
|
|
36
38
|
title: record.title,
|
|
37
39
|
status: record.status,
|
|
40
|
+
mode,
|
|
41
|
+
...(candidates ? { candidates } : {}),
|
|
38
42
|
stages: listed.stages
|
|
39
43
|
.filter((stage) => stage.status !== "archived")
|
|
40
44
|
.sort((left, right) => Number(left.stage) - Number(right.stage))
|
|
@@ -44,6 +48,7 @@ const readWorkspace = (context, record, currentSession) => {
|
|
|
44
48
|
status: stage.status,
|
|
45
49
|
description: stage.description,
|
|
46
50
|
depends_on: stage.depends_on,
|
|
51
|
+
tracker_links: stage.tracker_links || [],
|
|
47
52
|
current: stage.stage === currentStage,
|
|
48
53
|
})),
|
|
49
54
|
currentStage,
|