opencode-work-context 0.17.0 → 0.18.1

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 CHANGED
@@ -55,12 +55,17 @@ Then create a task and its first stage in OpenCode:
55
55
  /wc resume 000001 02
56
56
  ```
57
57
 
58
- `stage add` only creates a `planned` stage. It never starts a stage session or
59
- changes the invoking OpenCode session's current stage, regardless of whether
60
- that session is already associated with a workspace. Use
61
- `/wc resume <workspace> <stage>` in a separate OpenCode session to enter the new
62
- stage. Multiple sessions may work on the same non-terminal stage through
63
- explicit resume and handoff operations.
58
+ An explicit user-issued `/wc create` enters Planning, and an explicit
59
+ user-issued `/wc stage add` enters the new stage, when the invoking native
60
+ OpenCode session has no historical work-context affinity. This supports opening
61
+ a fresh native session before issuing either command. If the session already
62
+ has an affinity, creation remains session-neutral and the result directs the
63
+ user to resume in a separate native session.
64
+
65
+ Autonomous agent calls remain different: creating a workspace or adding a stage
66
+ without explicit user command intent never captures the invoking session. An
67
+ agent-added stage stays `planned`. Multiple sessions may work on the same
68
+ non-terminal stage through explicit resume and handoff operations.
64
69
 
65
70
  Stages remain in progress until the user explicitly requests `/wc stage finish`.
66
71
  Do not infer that request from completed work. Automatic completion is allowed
@@ -167,6 +172,50 @@ Resume a stage with:
167
172
  /wc resume 000001 02
168
173
  ```
169
174
 
175
+ ### Narrow an Overly Broad Stage Safely
176
+
177
+ `start_work` normally means the agent continues without a generic confirmation.
178
+ One exception is a genuine unresolved scope decision: the saved prompt or a new
179
+ request contains several materially independent user outcomes, some can be
180
+ deferred without making the primary outcome useless, and choosing full versus
181
+ minimal scope materially changes the product or architecture contract or makes
182
+ an honest Current item impossible.
183
+
184
+ This is a semantic judgment, not a count of files, tables, entities, or prompt
185
+ bullets. A migration, persistence, backend logic, UI, authorization, audit,
186
+ tests, and documentation may all form one coherent vertical slice. The agent
187
+ must also continue immediately when the prompt or execution decisions already
188
+ record the complete scope as intentional and coherent.
189
+
190
+ For genuinely decomposable scope, the agent first summarizes the actual workload
191
+ in three to seven outcome-oriented blocks, proposes one concrete minimal vertical
192
+ slice, and asks one focused question: implement the full scope, or accept the
193
+ minimal slice and preserve the rest as planned stages. The agent does not
194
+ estimate time, discard requirements, or simplify automatically.
195
+
196
+ If the user confirms the full scope, the agent records that decision in the
197
+ stage execution ledger, creates an ordered Current/Queued checklist, and does not
198
+ repeat the question without a material scope change. If the user selects the
199
+ minimal slice, the agent preserves the original stage prompt and records the
200
+ accepted current outcome and non-goals in execution `scope` and `decisions`.
201
+ Only outcomes the user confirms are still needed but deferred become planned
202
+ stages. Rejected work and speculative ideas do not become backlog.
203
+
204
+ The agent creates those follow-up stages autonomously, so they remain `planned`
205
+ and do not capture or switch the current native OpenCode session. Each stage
206
+ represents a coherent future outcome rather than one entity by default.
207
+ Dependencies are added only for genuine sequencing between working stages;
208
+ Planning stage 01 is never a prerequisite. External tracker issues are optional
209
+ separate actions and require explicit user agreement.
210
+
211
+ Multiple `stage add` calls are individually transactional but not one batch
212
+ transaction. If a later creation fails, earlier stages remain. The agent must
213
+ report exactly what was created and what is missing, safely retry only missing
214
+ operations or record a blocker, and must not begin the narrowed implementation
215
+ until all confirmed deferred work is persisted or the user explicitly permits
216
+ proceeding without it. This focused decision flow is not a new approval token or
217
+ mandatory ceremony for every non-trivial stage.
218
+
170
219
  ### Capability Recommendations
171
220
 
172
221
  An execution recommendation combines a portable capability (`routine`,
@@ -281,9 +330,19 @@ each direct commit or candidate fallback, the agent must read the effective mode
281
330
  again and proceed only while it returns `per_item`. This is an agent-policy
282
331
  preflight, not atomic Git enforcement. Before completing Current, the agent must
283
332
  define an explicit patch boundary, run relevant verification, and create a safe
284
- direct commit. Candidate publication remains separate. The user-only
285
- `commited <SHA>` acknowledgement contract is independent of agent-created
286
- per-item commits.
333
+ direct commit. Candidate publication remains separate. After a direct commit,
334
+ `commited <SHA>` validates current HEAD and records publication against the exact
335
+ Current item. A committed exact candidate related only to the stage records the
336
+ same evidence automatically.
337
+
338
+ For a non-Planning working stage, `startup` plus effective `per_item` mode makes
339
+ the execution ledger mandatory. The agent must establish Current before changing
340
+ application code, work only on Current, verify and publish its explicit patch,
341
+ complete Current, and only then begin the next item. Native OpenCode Todos do not
342
+ replace the work-context execution ledger. A compact system instruction repeats
343
+ this policy throughout the associated session, and `complete-current` requires
344
+ publication evidence bound to the exact Current item. Planning remains a
345
+ coordination surface rather than a per-item publication gate.
287
346
 
288
347
  In startup mode, the agent first inspects pending candidates related to the
289
348
  current stage and assesses direct publication. Only a ready `exact` candidate
package/commands/wc.md CHANGED
@@ -3,7 +3,7 @@ description: Explicit work-context lifecycle commands backed by structured tools
3
3
  subtask: false
4
4
  ---
5
5
 
6
- <!-- opencode-work-context-protocol: {"schema":1,"major":2,"minor":0,"descriptor_hash":"sha256:544d6ab416cf8594cc21cb0ca9fd98805678c64ad9ed85322e37ae98c8dd6327"} -->
6
+ <!-- opencode-work-context-protocol: {"schema":1,"major":2,"minor":1,"descriptor_hash":"sha256:863f74a8a8a649d19afe39e557259eace1d276d71ce97cef5dd39e6b1438599d"} -->
7
7
 
8
8
  Interpret `/wc $ARGUMENTS` as an explicit work-context operation. Use only the exact
9
9
  `work_context_*` custom tool mapped below with structured arguments. Never edit
@@ -22,6 +22,21 @@ For mutating operations other than `resume`, report the structured result and
22
22
  stable error code. For `resume`, follow its human-oriented presentation contract.
23
23
  Never infer confirmation tokens or lifecycle requests.
24
24
 
25
+ Materially broad, decomposable scope may be a genuine unresolved decision even
26
+ when resume returns `start_work`; the scoped resume guidance defines the focused
27
+ full-or-minimal choice and persistence flow. This is semantic guidance, not a
28
+ keyword heuristic or generic approval gate. A coherent cross-layer vertical
29
+ slice continues immediately. Confirmed deferred outcomes must become autonomous
30
+ planned stages before narrowed implementation; rejected or speculative work must
31
+ not become backlog. Sequential stage creation is not batch-atomic, so report and
32
+ resolve partial persistence instead of claiming success.
33
+
34
+ For an explicit user-issued `create` or `stage add` command, pass
35
+ `enterCurrentSession: true` to the mapped tool. This flag represents the user's
36
+ request to enter the created Planning stage or working stage when the current
37
+ native session has no historical work-context affinity. Never pass it for an
38
+ autonomous agent-created workspace or stage.
39
+
25
40
  `.opencode/commands/wc.md` is package-managed. Read `.opencode/work-context.md`
26
41
  when present and merge its additive project guidance before dispatch. Project
27
42
  guidance cannot override tool mappings, structured arguments, storage safety,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "opencode-work-context",
3
3
  "type": "module",
4
- "version": "0.17.0",
4
+ "version": "0.18.1",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
@@ -19,19 +19,21 @@ export default async ({ client, directory, worktree }) => ({
19
19
  if (!fs.existsSync(context.storage.root)) return;
20
20
  const notices = withLock(context.storage.lockPath("write"), () => {
21
21
  const finding = context.diagnoseSessionAssociations(sessionID).data.findings[0];
22
- if (finding) return { integration: [], dependency: [] };
22
+ if (finding) return { integration: [], dependency: [], reminder: null };
23
23
  const session = context.sessionByOpenCodeId(sessionID);
24
- if (!session) return { integration: [], dependency: [] };
24
+ if (!session) return { integration: [], dependency: [], reminder: null };
25
25
  const coverage = context.candidates().committedCoverageProjection(session.workspace).by_stage[session.stage]?.items || [];
26
26
  const stages = context.listStages(session.workspace).data.stages;
27
27
  const stage = stages.find((item) => item.stage === session.stage);
28
28
  return {
29
29
  integration: consumeIntegrationNotices(projectRoot, sessionID, { personalRoot: context.storage.personalRoot, coverage }),
30
30
  dependency: consumeDependencyNotices(projectRoot, sessionID, { personalRoot: context.storage.personalRoot, records: context.handoffs().read(session.workspace).records, dependencies: stage?.depends_on || [], dependencyGenerations: Object.fromEntries((stage?.depends_on || []).map((dependency) => [dependency, stage.dependency_epochs?.[dependency]?.generation || 1])) }),
31
+ reminder: context.mandatoryChecklistReminder(session.workspace, session.stage),
31
32
  };
32
33
  }, { owner: "work-context integration notice", session: sessionID });
33
34
  appendIntegrationNotices(output.system, notices.integration);
34
35
  appendDependencyNotices(output.system, notices.dependency);
36
+ if (notices.reminder) output.system.push(notices.reminder);
35
37
  } catch {
36
38
  // Local notice delivery is best effort and must not interrupt a model request.
37
39
  }
package/src/candidates.js CHANGED
@@ -17,7 +17,7 @@ const coverageStageLimit = 20;
17
17
  const executionItemPattern = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|legacy-[0-9a-f]{24})$/;
18
18
  const timestamp = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
19
19
  const metadataKeys = ["schema", "candidate", "workspace", "title", "message", "base_head", "status", "created_at", "updated_at", "selected_paths", "patch_file"];
20
- const optionalMetadataKeys = ["strategy", "related_stages", "coverage"];
20
+ const optionalMetadataKeys = ["strategy", "related_stages", "coverage", "publication"];
21
21
 
22
22
  const validCoverage = (coverage) => coverage && typeof coverage === "object" && !Array.isArray(coverage)
23
23
  && Object.keys(coverage).every((key) => ["schema", "confirmed_at", "entries"].includes(key))
@@ -29,6 +29,11 @@ const validCoverage = (coverage) => coverage && typeof coverage === "object" &&
29
29
  && Number.isInteger(entry.execution_revision) && entry.execution_revision >= 0)
30
30
  && new Set(coverage.entries.map((entry) => entry.stage)).size === coverage.entries.length
31
31
  && coverage.entries.every((entry, index) => index === 0 || coverage.entries[index - 1].stage.localeCompare(entry.stage) < 0);
32
+ const validPublication = (publication) => publication && typeof publication === "object" && !Array.isArray(publication)
33
+ && Object.keys(publication).every((key) => ["schema", "stage", "current_item_id", "execution_revision"].includes(key))
34
+ && publication.schema === 1 && /^\d{2}$/.test(publication.stage) && publication.stage !== "00"
35
+ && executionItemPattern.test(publication.current_item_id)
36
+ && Number.isInteger(publication.execution_revision) && publication.execution_revision >= 0;
32
37
 
33
38
  function validateCandidate(data, expectedId = null) {
34
39
  const valid = data && typeof data === "object" && !Array.isArray(data)
@@ -47,6 +52,7 @@ function validateCandidate(data, expectedId = null) {
47
52
  && Array.isArray(data.related_stages) && data.related_stages.every((stage) => /^\d{2}$/.test(stage) && stage !== "00")
48
53
  && new Set(data.related_stages).size === data.related_stages.length))
49
54
  && (!Object.hasOwn(data, "coverage") || (data.strategy === "integration" && validCoverage(data.coverage)))
55
+ && (!Object.hasOwn(data, "publication") || (data.strategy === "exact" && data.related_stages.length === 1 && validPublication(data.publication) && data.publication.stage === data.related_stages[0]))
50
56
  && (data.status === "committed"
51
57
  ? /^[0-9a-f]{40,64}$/.test(data.commit_hash) && timestamp(data.committed_at)
52
58
  : !Object.hasOwn(data, "commit_hash") && !Object.hasOwn(data, "committed_at"));
@@ -289,6 +295,28 @@ export class CandidateStore {
289
295
  return projection;
290
296
  }
291
297
 
298
+ exactPublicationEntry(workspace, data) {
299
+ if (data.strategy !== "exact" || data.related_stages.length !== 1 || data.related_stages[0] === "01") return null;
300
+ const stage = data.related_stages[0];
301
+ const workspaceRecord = this.context.storage.readWorkspace(workspace).data;
302
+ const stageRecord = this.context.storage.readStage(workspace, stage).data;
303
+ if (this.effectiveCommitMode(workspaceRecord, stageRecord) !== "per_item") return null;
304
+ const execution = this.context.storage.readStageExecution(workspace, stage);
305
+ const current = execution ? this.context.readStageExecution(workspace, stage).data.current : null;
306
+ return current ? { schema: 1, stage, current_item_id: current.id, execution_revision: execution.revision } : null;
307
+ }
308
+
309
+ publicationForCurrent(workspace, stage, currentItemId, executionRevision) {
310
+ const matches = this.projectionRecords(workspace).filter((candidate) => candidate.status === "committed").flatMap((candidate) => {
311
+ if (candidate.publication?.stage === stage && candidate.publication.current_item_id === currentItemId && candidate.publication.execution_revision === executionRevision) {
312
+ return [{ candidate: candidate.candidate, commit_hash: candidate.commit_hash, source: "exact_candidate" }];
313
+ }
314
+ const covered = candidate.coverage?.entries?.find((entry) => entry.stage === stage && entry.current_item_id === currentItemId && entry.execution_revision === executionRevision);
315
+ return covered ? [{ candidate: candidate.candidate, commit_hash: candidate.commit_hash, source: "integration_coverage" }] : [];
316
+ });
317
+ return matches.at(-1) || null;
318
+ }
319
+
292
320
  capture(workspace, id, input, options = {}) {
293
321
  workspace = options.allowStandard ? this.assertWorkspace(workspace) : this.assertStartup(workspace);
294
322
  const data = this.read(id, workspace);
@@ -334,6 +362,8 @@ export class CandidateStore {
334
362
  if (message !== undefined && (typeof message !== "string" || !message.trim())) fail(ERROR_CODES.INVALID_ARGUMENT, "Commit message must be a non-empty string");
335
363
  const commitMessage = message === undefined ? data.message : message.trim();
336
364
  this.validateCoverage(workspace, data);
365
+ const publication = this.exactPublicationEntry(workspace, data);
366
+ if (publication) data.publication = publication;
337
367
  let metadata;
338
368
  const published = commitPatch(this.context.storage.projectRoot, data.base_head, data.patch, commitMessage, {
339
369
  expectedHead: options.expectedHead,
@@ -7,7 +7,7 @@ const COMMON_GUIDANCE = Object.freeze([
7
7
  const TOPICS = Object.freeze({
8
8
  basic: Object.freeze([
9
9
  "Workspace list output includes workspace status and workflow mode, followed by every stage as: stage - status - title - description.",
10
- "Creating a workspace starts Planning only when the native OpenCode session has no active or historical work-context stage affinity.",
10
+ "For an explicit user-issued /wc create operation, pass enterCurrentSession: true. It starts Planning only when the native OpenCode session has no active or historical work-context stage affinity. Autonomous agent creation must omit this flag and remain session-neutral.",
11
11
  ]),
12
12
  commit_mode: Object.freeze([
13
13
  "Workspace commit mode is manual or per_item; a stage override may be cleared to inherit the workspace value.",
@@ -35,7 +35,9 @@ const TOPICS = Object.freeze({
35
35
  "Profiles setup asks interactively for scope, mode, and depth mappings, applies mode and mappings separately, then offers to refresh unfinished stages. Profiles reset asks for scope and requires the exact RESET_PROFILES confirmation token before removing mappings.",
36
36
  ]),
37
37
  stage_creation: Object.freeze([
38
- "Stage add creates only a planned stage and never starts or rebinds a session. Infer missing execution capability and depth from complete context and pass classification inferred.",
38
+ "For an explicit user-issued /wc stage add operation, pass enterCurrentSession: true. It enters the new stage only when the native OpenCode session has no historical affinity. Autonomous agent stage creation must omit this flag and remain planned and session-neutral. Infer missing execution capability and depth from complete context and pass classification inferred.",
39
+ "When a user selects a narrower current slice, create stages only for confirmed deferred outcomes, grouping each coherent future outcome rather than mechanically splitting entities. Rejected and speculative work must not become stages.",
40
+ "Several autonomous stage-add calls are sequential, not batch-atomic. On partial failure, report created and missing stages, retry only missing operations or block, and do not begin the narrowed implementation until confirmed deferred work is persisted or the user explicitly permits otherwise.",
39
41
  "Stage delegate requires the active delegating working-stage session and atomically creates the delegated stage plus the dependency edge; failure leaves neither partial state.",
40
42
  "Planning stage 01 is a coordination surface and must never be used as a dependency gate.",
41
43
  ]),
@@ -51,12 +53,16 @@ const TOPICS = Object.freeze({
51
53
  execution: Object.freeze([
52
54
  "Read execution state first and pass its revision as expectedRevision. Missing legacy state has revision 0; stale mutations return EXECUTION_REVISION_CONFLICT without changing newer state.",
53
55
  "Execution state uses stable item IDs, with Current as the first remaining item and Queued as the ordered remainder. Work only on Current unless the user explicitly requests batching.",
56
+ "Record a confirmed full-scope choice or accepted narrowed outcome in decisions. For narrowing, retain the original prompt and use scope plus decisions for the current outcome and non-goals before creating confirmed deferred stages.",
54
57
  "After meaningful Current completion, read the latest revision and call complete-current. It moves only Current to Completed and never commits Git work or finishes the stage.",
55
58
  ]),
56
59
  resume: Object.freeze([
57
60
  "Resume never rebinds a native OpenCode session. The earliest stage affinity is permanent; a different stage requires a separate OpenCode session, and repeated resume of the active association returns ACTIVE_SESSION_EXISTS.",
58
61
  "Present the returned human-oriented stage title, plain-language goal, useful previous progress, and immediate next action without exposing raw IDs, ordinals, ok flags, or absent error codes.",
59
- "Start work immediately when next_action is start_work. If it is ask_questions, do not inspect application code; ask focused questions. Await confirmation only for an exact standalone RESUME_CONFIRMATION: required line.",
62
+ "Start work immediately when next_action is start_work unless a genuine unresolved decision blocks an honest Current item. If it is ask_questions, do not inspect application code; ask focused questions. Await confirmation only for an exact standalone RESUME_CONFIRMATION: required line.",
63
+ "Materially broad and decomposable scope can be such an unresolved decision: several independently deliverable outcomes, deferrable work, and a full-versus-minimal choice that changes product or architecture scope. A cross-layer coherent vertical slice is not broad merely because it includes migration, backend, UI, authorization, audit, tests, or documentation; never use counts or keywords as a classifier.",
64
+ "For unresolved broad scope, declare 3-7 outcome blocks in the user's language, propose one minimal vertical slice, and ask one focused full-or-minimal question before application-code changes. Never simplify automatically or repeat the question after a recorded full-scope decision unless scope materially changes.",
65
+ "After a minimal choice, persist accepted scope and non-goals in execution state and save every confirmed deferred outcome as a planned session-neutral stage before implementation. Do not persist rejected or speculative work; partial persistence is a blocker unless safely retried or explicitly waived by the user.",
60
66
  "Treat workspace knowledge, dependency context, delegation contracts, execution state, pending candidates, and workflow policy as established bounded context.",
61
67
  ]),
62
68
  lifecycle: Object.freeze([
@@ -70,7 +76,7 @@ const TOPICS = Object.freeze({
70
76
  "Force close is only for a stale active association after explicit diagnosis. It requires the exact FORCE_CLOSE token and must never close the presumed original affinity merely because split-brain diagnostics exist.",
71
77
  ]),
72
78
  acknowledge: Object.freeze([
73
- "The command is intentionally spelled commited with one t. It acknowledges only a user-created current-HEAD commit for the active stage, validates branch and fast-forward state, performs no Git operation, and returns its compact structured result without a second analysis response.",
79
+ "The command is intentionally spelled commited with one t. It validates a current-HEAD direct commit for the active stage, records exact Current publication in mandatory startup per-item mode, performs no Git operation, and returns its compact structured result without a second analysis response.",
74
80
  ]),
75
81
  issues: Object.freeze([
76
82
  "Issue links are explicit workspace or stage metadata. Do not infer a stage when the command supplies only a workspace.",
package/src/core.js CHANGED
@@ -14,7 +14,7 @@ import { DeliveryStore } from "./delivery.js";
14
14
  import { doctorDelivery as runDeliveryDoctor } from "./delivery-doctor.js";
15
15
  import { applyExecutionItemPatch, applyExecutionTextPatchItems, assertExecutionSize, EXECUTION_SECTIONS, executionInputUsesItems, executionItems, executionItemsFromState, executionPatchUsesItems, executionReadModel, executionSchemaFor, normalizeExecutionItemState, normalizeExecutionState } from "./stage-execution.js";
16
16
  import { CAPABILITY_CLASSIFICATIONS, CAPABILITY_DEPTHS, CAPABILITY_PROFILES, capabilityProfileMode, capabilityRecommendations, configureCapabilityMappings, readCapabilityMappings, resetCapabilityMappings, validateCapabilityMappings } from "./capability-profiles.js";
17
- import { acknowledgeGitCommit, initializeGitCheckpoint } from "./git-acknowledgement.js";
17
+ import { acknowledgeGitCommit, gitPublicationReceipt, initializeGitCheckpoint } from "./git-acknowledgement.js";
18
18
  import { isCommitAncestor, repositoryState, rollbackCommitRef } from "./git-candidates.js";
19
19
  import { enqueueIntegrationNotice } from "./integration-notices.js";
20
20
  import { DependencyHandoffStore } from "./dependency-handoffs.js";
@@ -114,7 +114,8 @@ const startupWorkflowPolicy = (commitMode = { mode: "manual" }) => ({
114
114
  guidance: commitMode.mode === "per_item" ? [
115
115
  "A shared dirty worktree and concurrent stages are expected; stages do not own files or commits.",
116
116
  "When changes appear mixed or overlapping, report only a bounded, explicitly uncertain list of likely affected stages supported by deterministic local evidence; never infer file or hunk ownership.",
117
- "Before each direct commit or candidate fallback, read the effective commit mode again. Proceed only while per_item remains effective; this is an agent policy preflight, not atomic Git enforcement.",
117
+ "Work only on the authoritative Current execution item. Native OpenCode Todos never replace the work-context ledger or authorize Queued work.",
118
+ "Before each direct commit or candidate fallback, read the effective commit mode again. Proceed only while per_item remains effective.",
118
119
  "Inspect pending candidates related to this stage, then assess direct publication of the explicit Current-item patch first.",
119
120
  "Only a ready exact candidate explicitly related to this stage may ordinarily substitute when direct publication is unsafe but the patch is separable. Shared foundation and unconfirmed integration candidates do not satisfy Current completion.",
120
121
  "A committed integration candidate satisfies publication only when explicit coverage still names this exact Current item. Do not republish or reconstruct provenance; perform remaining verification and complete Current separately.",
@@ -141,6 +142,16 @@ const resumePresentationInstruction = ({ confirmationRequired }) => `Before doin
141
142
  - Mention previous progress only when presentation.previous_result or presentation.previous_session_summary contains useful information.
142
143
  - State the immediate next action in one sentence.
143
144
  ${confirmationRequired ? "- Ask for the explicitly required confirmation and wait before inspecting or changing application code." : "- Then continue with the work immediately. Do not ask for generic confirmation; ask a focused question only when an unresolved decision genuinely blocks progress."}`;
145
+ const scopeDecisionInstruction = `
146
+
147
+ Scope decision policy:
148
+ - Continue immediately for a coherent vertical slice. Migration, persistence, backend or use-case logic, UI, authorization, audit, tests, and documentation may all be necessary parts of one outcome; their presence or number alone does not make a stage too broad.
149
+ - Treat scope as an unresolved decision only when the complete context contains several materially independent user outcomes, some can be deferred without making the primary outcome useless, and choosing full versus minimal scope materially changes the product or architecture contract or prevents an honest Current item. Do not use keyword, file, entity, table, or bullet counts. Do not ask again when the prompt or a recorded execution decision already confirms the full scope as intentional and coherent, unless the scope materially changes.
150
+ - Before application-code changes for unresolved scope, use the user's language to group the actual workload into 3-7 outcome-oriented blocks, propose one concrete minimal vertical slice without discarding requirements, and ask one focused question: implement the full scope, or accept the minimal slice and preserve the rest as planned stages. This is not a generic approval gate and never authorizes automatic simplification.
151
+ - If full scope is confirmed, record that decision in the current stage execution decisions, create an ordered Current/Queued checklist, and proceed without repeating the scope question absent a material change.
152
+ - If the minimal slice is selected, clarify only genuinely ambiguous boundaries. Preserve the original saved prompt; record the accepted current outcome and non-goals in execution scope and decisions. Separate confirmed deferred outcomes from rejected or speculative ideas. Before implementation, create one or more coherent confirmed deferred outcomes with work_context_add_stage as autonomous planned, session-neutral stages; omit enterCurrentSession. Never create stages for rejected or merely speculative work, and never turn unconfirmed ideas into backlog.
153
+ - Add dependencies only for real sequencing requirements between working stages; dependency edges point from dependent to dependency, and Planning stage 01 is never a dependency. Report the created backlog before implementation. External tracker issues are optional separate actions that require explicit user agreement.
154
+ - Stage creation calls are individually transactional, not batch-atomic. If persistence partially fails, report exactly what was and was not created, safely retry only missing operations or record a concrete blocker, and do not claim the backlog is saved or start implementation until all confirmed deferred work is persisted or the user explicitly permits proceeding without it.`;
144
155
  const executionInstruction = (record) => {
145
156
  if (!record) return "";
146
157
  const execution = executionReadModel(record);
@@ -152,7 +163,13 @@ const executionInstruction = (record) => {
152
163
  };
153
164
  const commitModeInstruction = (commitMode) => {
154
165
  if (commitMode.mode !== "per_item") return "";
155
- return `\n\nChecklist commit policy: per_item (${commitMode.source}). This is persistent authorization to publish an explicit, coherent Current-item patch; it never authorizes unrelated changes. Immediately before each direct commit or candidate fallback, call work_context_read_effective_commit_mode and proceed only if it still returns per_item. This is an agent policy preflight, not atomic Git enforcement. Before completing Current, define its explicit patch boundary and run relevant verification. When a direct commit is safe, create it before complete-current. Candidate publication remains separate. A committed integration candidate is a narrow substitute only when explicit durable coverage still names this exact Current item; do not publish it again, and complete Current only after remaining verification. Ordinary integration relations are traceability-only. A true patch or merge conflict, failed verification, or incoherent boundary is a blocker: record it and do not complete Current.`;
166
+ return `\n\nChecklist commit policy: per_item (${commitMode.source}). This is persistent authorization to publish an explicit, coherent Current-item patch; it never authorizes unrelated changes. Immediately before each direct commit or candidate fallback, call work_context_read_effective_commit_mode and proceed only if it still returns per_item. Before completing Current, define its explicit patch boundary and run relevant verification. When a direct commit is safe, create it, then call work_context_acknowledge_commit to bind publication to Current before complete-current. Candidate publication remains separate. A committed exact candidate related only to this stage records the same Current-bound evidence automatically. A committed integration candidate is a narrow substitute only when explicit durable coverage still names this exact Current item; do not publish it again. Ordinary integration relations are traceability-only. A true patch or merge conflict, failed verification, or incoherent boundary is a blocker: record it and do not complete Current.`;
167
+ };
168
+ const mandatoryChecklist = (workspaceRecord, stage, commitMode) => stage !== "01" && workspaceMode(workspaceRecord) === "startup" && commitMode.mode === "per_item";
169
+ const mandatoryChecklistInstruction = (execution) => {
170
+ const current = execution ? executionReadModel(execution).current : null;
171
+ if (!current) return `\n\nMandatory startup per-item checklist: no Current item exists. Do not inspect or modify application code. First create or repair the authoritative work-context execution ledger with one bounded Current item and ordered Queued items. Native OpenCode Todos do not replace this ledger.`;
172
+ return `\n\nMandatory startup per-item checklist: work only on Current (${current.text}). Do not begin a Queued item. After implementation, record verification, re-read effective commit mode, publish the exact Current patch, record publication when using a direct commit, then call complete-current before starting the next item. Native OpenCode Todos do not replace this ledger.`;
156
173
  };
157
174
  const deliveryPlanningInstruction = `\n\nDelivery planning policy:\n- When the user asks how to deploy, treat this as workspace-level delivery planning across all relevant committed changes, not as ownership by the current stage.\n- Inspect the exact commit range and the repository's own deployment documentation, scripts, infrastructure, migrations, container definitions, configuration examples, and CI before proposing commands.\n- Produce an ordered plan covering prerequisites, deployment, verification, rollback, and unresolved blockers. Ask one focused question when the target environment or baseline is genuinely ambiguous.\n- Never persist secret values. Mention only required secret or configuration names.\n- Never mark delivery from a successful commit or push alone. Use explicit delivery confirmation only after the user confirms that the target environment was updated successfully.`;
158
175
  const assertOpenCodeSessionAvailable = (events, opencodeSessionId, workspace, stage) => {
@@ -401,7 +418,7 @@ export class WorkContext {
401
418
  lifecycle: { automatic_finish_allowed: false },
402
419
  },
403
420
  next_action: "start_work",
404
- instruction: `${planningPrompt}${startupWorkflowInstruction(workflowPolicy)}${deliveryPlanningInstruction}\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.`,
421
+ instruction: `${planningPrompt}${scopeDecisionInstruction}${startupWorkflowInstruction(workflowPolicy)}${deliveryPlanningInstruction}\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.`,
405
422
  },
406
423
  }, [workspace, "01"]);
407
424
  });
@@ -460,6 +477,16 @@ export class WorkContext {
460
477
  return { ok: true, data: { workspace, stage, mode: effective.mode, source: effective.source } };
461
478
  }
462
479
 
480
+ mandatoryChecklistReminder(workspace, stage) {
481
+ workspace = normalizeWorkspaceId(workspace);
482
+ stage = normalizeStageId(stage);
483
+ const workspaceRecord = this.storage.readWorkspace(workspace).data;
484
+ const stageRecord = this.storage.readStage(workspace, stage).data;
485
+ const commitMode = effectiveCommitMode(workspaceRecord, stageRecord);
486
+ if (!mandatoryChecklist(workspaceRecord, stage, commitMode)) return null;
487
+ return mandatoryChecklistInstruction(this.storage.readStageExecution(workspace, stage)).trim();
488
+ }
489
+
463
490
  candidates() { return new CandidateStore(this); }
464
491
  deliveries() { return new DeliveryStore(this); }
465
492
  handoffs() { return new DependencyHandoffStore(this.storage); }
@@ -629,8 +656,10 @@ export class WorkContext {
629
656
  const committedCoverage = workflowPolicy ? this.candidates().committedCoverageProjection(workspace).by_stage[stage] || null : null;
630
657
  const deliveryContext = stage === "01" ? this.deliveries().projection(workspace) : null;
631
658
  const hasDeliveryContext = deliveryContext && (deliveryContext.committed.count || deliveryContext.environments.length || deliveryContext.unavailable);
632
- const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
633
- const execution = this.storage.readStageExecution(workspace, stage);
659
+ const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
660
+ const execution = this.storage.readStageExecution(workspace, stage);
661
+ const checklistRequired = mandatoryChecklist(workspaceRecord, stage, commitMode);
662
+ const executionCurrent = execution ? executionReadModel(execution).current : null;
634
663
  const dependencyContext = stageRecord.data.depends_on.length ? this.handoffs().context(workspace, stage, this.listStages(workspace).data.stages) : null;
635
664
  const automaticFinish = automaticFinishAllowed(this.storage, workspace);
636
665
  const recommendations = capabilityRecommendations(this.storage, stageRecord.data, readCapabilityMappings(this.storage, { homeDir: this.options.capabilityProfilesHome }));
@@ -675,10 +704,10 @@ export class WorkContext {
675
704
  ...(workflowPolicy ? { workflow_policy: workflowPolicy } : {}),
676
705
  lifecycle: { automatic_finish_allowed: automaticFinish },
677
706
  },
678
- next_action: hasPrompt ? confirmationRequired ? "await_confirmation" : "start_work" : "ask_questions",
707
+ next_action: checklistRequired && !executionCurrent ? "initialize_execution" : hasPrompt ? confirmationRequired ? "await_confirmation" : "start_work" : "ask_questions",
679
708
  instruction: `${hasPrompt
680
- ? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}${executionInstruction(execution)}${startupWorkflowInstruction(workflowPolicy)}${stage === "01" ? deliveryPlanningInstruction : ""}`
681
- : `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.`}${commitModeInstruction(commitMode)}\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.`,
709
+ ? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}${scopeDecisionInstruction}${executionInstruction(execution)}${startupWorkflowInstruction(workflowPolicy)}${stage === "01" ? deliveryPlanningInstruction : ""}`
710
+ : `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.${scopeDecisionInstruction}`}${commitModeInstruction(commitMode)}${checklistRequired ? mandatoryChecklistInstruction(execution) : ""}\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.`,
682
711
  },
683
712
  }, [workspace, stage]);
684
713
  });
@@ -690,7 +719,16 @@ export class WorkContext {
690
719
  this.storage.assertSafeRoots();
691
720
  return withLock(this.storage.lockPath("git-acknowledgement"), () => {
692
721
  assertActive(this.storage.readEvents(), workspace, stage, sessionId);
693
- return this.result(acknowledgeGitCommit(this.storage, { workspace, stage, sessionId, sha }), ["local:git-checkpoint"]);
722
+ const workspaceRecord = this.storage.readWorkspace(workspace).data;
723
+ const stageRecord = this.storage.readStage(workspace, stage).data;
724
+ const commitMode = effectiveCommitMode(workspaceRecord, stageRecord);
725
+ const execution = this.storage.readStageExecution(workspace, stage);
726
+ const current = execution ? executionReadModel(execution).current : null;
727
+ if (mandatoryChecklist(workspaceRecord, stage, commitMode) && !current) fail(ERROR_CODES.EXECUTION_CURRENT_REQUIRED, "A Current execution item is required before recording per-item publication");
728
+ const publication = mandatoryChecklist(workspaceRecord, stage, commitMode)
729
+ ? { schema: 1, workspace, stage, current_item_id: current.id, execution_revision: execution.revision }
730
+ : null;
731
+ return this.result(acknowledgeGitCommit(this.storage, { workspace, stage, sessionId, sha, publication }), ["local:git-checkpoint"]);
694
732
  }, { session: sessionId, owner: actor(this.options) });
695
733
  }
696
734
 
@@ -1130,6 +1168,20 @@ export class WorkContext {
1130
1168
  const items = current && executionItems(current);
1131
1169
  const currentItem = items?.remaining.shift();
1132
1170
  if (!currentItem) fail(ERROR_CODES.INVALID_STATE, "No current execution item to complete");
1171
+ const workspaceRecord = this.storage.readWorkspace(workspace).data;
1172
+ const commitMode = effectiveCommitMode(workspaceRecord, stageRecord.data);
1173
+ if (mandatoryChecklist(workspaceRecord, stage, commitMode)) {
1174
+ const candidatePublication = this.candidates().publicationForCurrent(workspace, stage, currentItem.id, revision);
1175
+ const directPublication = gitPublicationReceipt(this.storage, sessionId);
1176
+ const matchingDirect = directPublication?.workspace === workspace && directPublication.stage === stage
1177
+ && directPublication.current_item_id === currentItem.id && directPublication.execution_revision === revision
1178
+ ? { commit_hash: directPublication.commit, source: "direct_commit" }
1179
+ : null;
1180
+ const publication = candidatePublication || matchingDirect;
1181
+ if (!publication) fail(ERROR_CODES.EXECUTION_PUBLICATION_REQUIRED, "Current must have publication evidence bound to its exact item and revision before completion", { current_item_id: currentItem.id, execution_revision: revision });
1182
+ const repository = repositoryState(this.storage.projectRoot);
1183
+ if (!isCommitAncestor(repository.root, publication.commit_hash, repository.head)) fail(ERROR_CODES.EXECUTION_PUBLICATION_REQUIRED, "Current publication commit is not reachable from HEAD", { commit: publication.commit_hash, current_head: repository.head });
1184
+ }
1133
1185
  items.completed.push(currentItem);
1134
1186
  const nextItems = normalizeExecutionItemState(items, current);
1135
1187
  const timestamp = new Date().toISOString();
package/src/errors.js CHANGED
@@ -22,6 +22,7 @@ export const ERROR_CODES = Object.freeze({
22
22
  COMMIT_ALL_UNSAFE_STATE: "COMMIT_ALL_UNSAFE_STATE", COMMIT_ALL_INCOHERENT_BOUNDARY: "COMMIT_ALL_INCOHERENT_BOUNDARY",
23
23
  COMMIT_ALL_STALE_PLAN: "COMMIT_ALL_STALE_PLAN", COMMIT_ALL_VERIFICATION_FAILED: "COMMIT_ALL_VERIFICATION_FAILED",
24
24
  EXECUTION_REVISION_CONFLICT: "EXECUTION_REVISION_CONFLICT", EXECUTION_LIMIT_EXCEEDED: "EXECUTION_LIMIT_EXCEEDED",
25
+ EXECUTION_CURRENT_REQUIRED: "EXECUTION_CURRENT_REQUIRED", EXECUTION_PUBLICATION_REQUIRED: "EXECUTION_PUBLICATION_REQUIRED",
25
26
  DELIVERY_INVALID_RANGE: "DELIVERY_INVALID_RANGE", DELIVERY_RANGE_TOO_LARGE: "DELIVERY_RANGE_TOO_LARGE",
26
27
  DELIVERY_INVALID_FINDINGS: "DELIVERY_INVALID_FINDINGS", DELIVERY_DIAGNOSTIC_TOO_LARGE: "DELIVERY_DIAGNOSTIC_TOO_LARGE",
27
28
  DELIVERY_COMMAND_PROTOCOL_MISMATCH: "DELIVERY_COMMAND_PROTOCOL_MISMATCH",
@@ -31,7 +31,14 @@ const checkpointFor = (personalRoot, sessionId) => {
31
31
  const file = checkpointPath(personalRoot, sessionId);
32
32
  try {
33
33
  const value = JSON.parse(fs.readFileSync(file, "utf8"));
34
- if (!value || value.schema !== 1 || value.session_id !== sessionId || typeof value.head !== "string" || !/^[0-9a-f]{40,64}$/.test(value.head) || typeof value.ref !== "string" || !value.ref.startsWith("refs/heads/")) {
34
+ const publication = value?.publication;
35
+ const validPublication = publication === undefined || (publication && publication.schema === 1
36
+ && typeof publication.workspace === "string" && /^\d{6}$/.test(publication.workspace)
37
+ && typeof publication.stage === "string" && /^\d{2}$/.test(publication.stage)
38
+ && typeof publication.current_item_id === "string" && publication.current_item_id.length <= 100
39
+ && Number.isInteger(publication.execution_revision) && publication.execution_revision >= 0
40
+ && typeof publication.commit === "string" && /^[0-9a-f]{40,64}$/.test(publication.commit));
41
+ if (!value || value.schema !== 1 || value.session_id !== sessionId || typeof value.head !== "string" || !/^[0-9a-f]{40,64}$/.test(value.head) || typeof value.ref !== "string" || !value.ref.startsWith("refs/heads/") || !validPublication) {
35
42
  fail(ERROR_CODES.STORAGE_ERROR, "Invalid Git acknowledgement checkpoint");
36
43
  }
37
44
  return { file, value };
@@ -78,7 +85,7 @@ export function initializeGitCheckpoint(storage, { workspace, stage, sessionId }
78
85
  return value;
79
86
  }
80
87
 
81
- export function acknowledgeGitCommit(storage, { workspace, stage, sessionId, sha }) {
88
+ export function acknowledgeGitCommit(storage, { workspace, stage, sessionId, sha, publication = null }) {
82
89
  const input = assertAcknowledgementHash(sha);
83
90
  const checkpoint = checkpointFor(storage.personalRoot, sessionId);
84
91
  if (!checkpoint.value) fail(ERROR_CODES.GIT_ACKNOWLEDGEMENT_CHECKPOINT_MISSING, "No Git checkpoint exists for this active session");
@@ -93,7 +100,11 @@ export function acknowledgeGitCommit(storage, { workspace, stage, sessionId, sha
93
100
  if (verified.head !== state.head || verified.ref !== state.ref || gitOperationInProgress(verified.root)) {
94
101
  fail(ERROR_CODES.GIT_ACKNOWLEDGEMENT_REF_CHANGED, "Git state changed while acknowledging the commit");
95
102
  }
96
- const value = { ...checkpoint.value, head: state.head, updated_at: new Date().toISOString() };
103
+ const value = { ...checkpoint.value, head: state.head, updated_at: new Date().toISOString(), ...(publication ? { publication: { ...publication, commit: state.head } } : {}) };
97
104
  atomicWrite(checkpoint.file, `${JSON.stringify(value, null, 2)}\n`);
98
- return { acknowledged: true, commit: state.head };
105
+ return { acknowledged: true, commit: state.head, ...(value.publication ? { publication: value.publication } : {}) };
106
+ }
107
+
108
+ export function gitPublicationReceipt(storage, sessionId) {
109
+ return checkpointFor(storage.personalRoot, sessionId).value?.publication || null;
99
110
  }
package/src/protocol.js CHANGED
@@ -3,7 +3,7 @@ import { createHash } from "node:crypto";
3
3
  export const WORK_CONTEXT_PROTOCOL = Object.freeze({
4
4
  schema: 1,
5
5
  major: 2,
6
- minor: 0,
6
+ minor: 1,
7
7
  });
8
8
 
9
9
  export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR = Object.freeze({
@@ -13,7 +13,7 @@ export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR = Object.freeze({
13
13
  major: WORK_CONTEXT_PROTOCOL.major,
14
14
  minor: WORK_CONTEXT_PROTOCOL.minor,
15
15
  }),
16
- operations: Object.freeze(["delivery.doctor", "commit.acknowledge", "commit.inspect_all", "commit.all", "candidate.confirm_coverage", "commit_mode.workspace.set", "commit_mode.stage.set", "commit_mode.effective.read", "execution.complete_current", "stage.delegate", "dependency.add", "dependency.remove", "dependency.handoff.publish", "dependency.context.read", "help.scoped"]),
16
+ operations: Object.freeze(["delivery.doctor", "commit.acknowledge", "commit.inspect_all", "commit.all", "candidate.confirm_coverage", "commit_mode.workspace.set", "commit_mode.stage.set", "commit_mode.effective.read", "execution.complete_current", "stage.delegate", "dependency.add", "dependency.remove", "dependency.handoff.publish", "dependency.context.read", "help.scoped", "scope.narrowing.guidance"]),
17
17
  });
18
18
 
19
19
  export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR_BYTES = JSON.stringify(WORK_CONTEXT_PROTOCOL_DESCRIPTOR);
@@ -84,9 +84,26 @@ const activeSessionFromContext = (ctx, workspace, stage) => {
84
84
  return direct?.workspace === workspace && direct.stage === stage && direct.state === "active" ? direct : null;
85
85
  };
86
86
  const sessionFor = (ctx, oc, workspace, stage) => activeSessionFromContext(ctx, workspace, stage)?.session_id || oc.sessionID;
87
- const addStageFromTool = (ctx, args) => {
87
+ const addStageFromTool = (ctx, args, oc) => {
88
88
  const workspace = workspaceFromSession(ctx, args.workspace);
89
- return ctx.addStage(workspace, args.title, { goal: args.goal, prompt: args.prompt, dependsOn: args.dependsOn, executionProfile: args.executionProfile, executionDepth: args.executionDepth, classification: args.classification, reviewProfile: args.reviewProfile });
89
+ const created = ctx.addStage(workspace, args.title, { goal: args.goal, prompt: args.prompt, dependsOn: args.dependsOn, executionProfile: args.executionProfile, executionDepth: args.executionDepth, classification: args.classification, reviewProfile: args.reviewProfile });
90
+ if (!args.enterCurrentSession) return created;
91
+ if (ctx.sessionAffinityByOpenCodeId(oc.sessionID)) return {
92
+ ...created,
93
+ data: { ...created.data, next_action: "start_new_opencode_session_and_resume" },
94
+ };
95
+ const started = ctx.startSession(workspace, created.data.stage, { sessionId: randomUUID(), opencodeSessionId: oc.sessionID });
96
+ return {
97
+ ...started,
98
+ data: {
99
+ ...started.data,
100
+ created: true,
101
+ status: "in_progress",
102
+ session_started: true,
103
+ resume_required: false,
104
+ },
105
+ changed: [...new Set([...(created.changed || []), ...(started.changed || [])])],
106
+ };
90
107
  };
91
108
  export const work_context_list_workspaces = tool({ description: "List work-context workspaces.", args: {}, execute: run((ctx) => ctx.listWorkspaces()) });
92
109
  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)) });
@@ -118,18 +135,19 @@ export const work_context_doctor_delivery = createDoctorDeliveryTool();
118
135
  export const work_context_mark_delivery = tool({ description: "Record a confirmed environment delivery checkpoint without executing deployment. Requires DELIVERY_CONFIRMED.", args: { workspace: tool.schema.string(), environment: tool.schema.string(), commit: tool.schema.string(), confirmation: tool.schema.string() }, execute: run((ctx, a) => ctx.markDelivery(a.workspace, a.environment, a.commit, a.confirmation)) });
119
136
  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)) });
120
137
  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)) });
121
- export const work_context_create_workspace = tool({ description: "Create a workspace; enter its planning stage only when the native OpenCode session has no active or historical work-context stage affinity.", args: { title: tool.schema.string(), mode: tool.schema.enum(["standard", "startup"]).optional() }, execute: run((ctx, a, oc) => {
138
+ export const work_context_create_workspace = tool({ description: "Create a workspace. Pass enterCurrentSession only for an explicit user-issued /wc create operation; autonomous agent creation remains session-neutral.", args: { title: tool.schema.string(), mode: tool.schema.enum(["standard", "startup"]).optional(), enterCurrentSession: tool.schema.boolean().optional() }, execute: run((ctx, a, oc) => {
122
139
  const currentSession = ctx.sessionAffinityByOpenCodeId(oc.sessionID);
123
- return ctx.createWorkspace(a.title, { mode: a.mode, ...(currentSession ? { startSession: false } : { sessionId: randomUUID(), opencodeSessionId: oc.sessionID }) });
140
+ const enterCurrentSession = a.enterCurrentSession === true && !currentSession;
141
+ return ctx.createWorkspace(a.title, { mode: a.mode, ...(enterCurrentSession ? { sessionId: randomUUID(), opencodeSessionId: oc.sessionID } : { startSession: false }) });
124
142
  }) });
125
143
  export const work_context_start_session = tool({ description: "Start a new active session for the stage permanently associated with this OpenCode session and return its human-oriented presentation, prompt, active workspace knowledge, and startup policy when applicable. A different stage requires a separate OpenCode session.", 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 })) });
126
- export const work_context_acknowledge_commit = tool({ description: "Acknowledge a user-created current-HEAD commit for the active session using a short or full commit hash. This is a deterministic light control-plane operation and does not infer ownership.", args: { sha: tool.schema.string() }, execute: run((ctx, a) => {
144
+ export const work_context_acknowledge_commit = tool({ description: "Validate and record a current-HEAD direct commit for the active session using a short or full commit hash. In mandatory startup per-item mode this binds publication to the exact Current item and revision.", args: { sha: tool.schema.string() }, execute: run((ctx, a) => {
127
145
  const affinity = sessionFromContext(ctx);
128
146
  const session = affinity && activeSessionFromContext(ctx, affinity.workspace, affinity.stage);
129
147
  if (!session) fail(ERROR_CODES.STAGE_CONTEXT_REQUIRED, "An active work-context stage is required to acknowledge a commit");
130
148
  return ctx.acknowledgeCommit(session.workspace, session.stage, session.session_id, a.sha);
131
149
  }) });
132
- export const work_context_add_stage = tool({ description: "Add a planned stage without starting or changing a stage session. When the user did not specify execution capability and depth, infer both from the prompt and pass classification: inferred. Explicit user choices use classification: explicit.", 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(), executionProfile: capabilityProfile.optional(), executionDepth: capabilityDepth.optional(), classification: tool.schema.enum(["inferred", "explicit"]).optional(), reviewProfile: capabilityProfile.optional() }, execute: run(addStageFromTool) });
150
+ export const work_context_add_stage = tool({ description: "Add a stage. Pass enterCurrentSession only for an explicit user-issued /wc stage add operation; autonomous agent creation remains planned and session-neutral. When the user did not specify execution capability and depth, infer both from the prompt and pass classification: inferred. Explicit user choices use classification: explicit.", 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(), executionProfile: capabilityProfile.optional(), executionDepth: capabilityDepth.optional(), classification: tool.schema.enum(["inferred", "explicit"]).optional(), reviewProfile: capabilityProfile.optional(), enterCurrentSession: tool.schema.boolean().optional() }, execute: run(addStageFromTool) });
133
151
  export const work_context_delegate_stage = tool({ description: "Atomically create a delegated working stage and add it as a dependency of the active delegating stage.", args: { ...contextualStage, title: tool.schema.string(), requestedOutcome: tool.schema.string(), goal: tool.schema.string().optional(), prompt: tool.schema.string().optional(), dependsOn: tool.schema.array(tool.schema.string()).optional(), executionProfile: capabilityProfile.optional(), executionDepth: capabilityDepth.optional(), classification: tool.schema.enum(["inferred", "explicit"]).optional(), reviewProfile: capabilityProfile.optional() }, execute: run((ctx, a, oc) => { const workspace = workspaceFromSession(ctx, a.workspace); const stage = stageFromSession(ctx, workspace, a.stage); return ctx.delegateStage(workspace, stage, sessionFor(ctx, oc, workspace, stage), a.title, a.requestedOutcome, a); }) });
134
152
  export const work_context_add_stage_dependency = tool({ description: "Add one explicit cycle-safe dependency edge to an actionable dependent stage.", args: { ...contextualStage, dependency: tool.schema.string() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.addStageDependency(workspace, stageFromSession(ctx, workspace, a.stage), a.dependency); }) });
135
153
  export const work_context_remove_stage_dependency = tool({ description: "Remove one explicit dependency edge while retaining historical handoffs.", args: { ...contextualStage, dependency: tool.schema.string() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.removeStageDependency(workspace, stageFromSession(ctx, workspace, a.stage), a.dependency); }) });