opencode-work-context 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/core.js CHANGED
@@ -9,10 +9,22 @@ import { nextKnowledgeId, parseKnowledge, renderKnowledge, validateKnowledgeInpu
9
9
  import { normalizeStageId, normalizeWorkspaceId } from "./identifiers.js";
10
10
  import { isDependencySatisfied } from "./stage-status.js";
11
11
  import { CandidateStore } from "./candidates.js";
12
+ import { DeliveryStore } from "./delivery.js";
12
13
  import { applyExecutionPatch, assertExecutionSize, executionState, normalizeExecutionState } from "./stage-execution.js";
14
+ import { CAPABILITY_CLASSIFICATIONS, CAPABILITY_DEPTHS, CAPABILITY_MAPPINGS_FILE, CAPABILITY_PROFILES, capabilityProfileMode, capabilityRecommendations, readCapabilityMappings, validateCapabilityMappings } from "./capability-profiles.js";
13
15
 
14
16
  const actor = (options) => options.actor || "OpenCode";
15
17
  const workspaceMode = (data) => data.mode || "standard";
18
+ const assertCapabilityProfile = (value, name) => {
19
+ if (value !== undefined && value !== null && !CAPABILITY_PROFILES.includes(value)) fail(ERROR_CODES.INVALID_ARGUMENT, `${name} must be one of: ${CAPABILITY_PROFILES.join(", ")}`);
20
+ };
21
+ const assertCapabilityDepth = (value, name) => {
22
+ if (value !== undefined && value !== null && !CAPABILITY_DEPTHS.includes(value)) fail(ERROR_CODES.INVALID_ARGUMENT, `${name} must be one of: ${CAPABILITY_DEPTHS.join(", ")}`);
23
+ };
24
+ const assertCapabilityClassification = (value) => {
25
+ if (value !== undefined && !CAPABILITY_CLASSIFICATIONS.includes(value)) fail(ERROR_CODES.INVALID_ARGUMENT, `classification must be one of: ${CAPABILITY_CLASSIFICATIONS.join(", ")}`);
26
+ };
27
+ const capabilityData = (storage, stage) => ({ mode: capabilityProfileMode(storage), ...(stage.execution_profile ? { execution_profile: stage.execution_profile } : {}), ...(stage.execution_depth ? { execution_depth: stage.execution_depth } : {}), ...(stage.execution_classification ? { execution_classification: stage.execution_classification } : {}), ...(stage.review_profile ? { review_profile: stage.review_profile } : {}) });
16
28
  const activeKnowledge = (records) => records
17
29
  .filter((record) => record.status === "active")
18
30
  .map(({ id: knowledgeId, title, kind, text, sources }) => ({ id: knowledgeId, title, kind, text, sources }));
@@ -35,6 +47,8 @@ const startupWorkflowPolicy = () => ({
35
47
  guidance: [
36
48
  "A shared dirty worktree and concurrent stages are expected; stages do not own files or commits.",
37
49
  "Capture ready work promptly as an explicit commit candidate while unrelated work remains in progress.",
50
+ "Once a coherent commit intent exists, create or refresh its draft candidate before switching stages or handing off so pending publication remains visible in related stage context.",
51
+ "On resume, inspect related pending candidates before creating a duplicate or starting another commit boundary.",
38
52
  "Choose an exact candidate when separable, a shared foundation candidate when several stages use one change, or an integration candidate when intertwined changes form one coherent reviewable result.",
39
53
  "Mixed-stage provenance or complete files containing unrelated stage work are not reasons to stop, require prior commits, or reconstruct ownership after the fact.",
40
54
  "Stop only for a concrete patch conflict, an incoherent candidate boundary, or failed required verification, and report it explicitly.",
@@ -50,6 +64,7 @@ const resumePresentationInstruction = ({ confirmationRequired }) => `Before doin
50
64
  - State the immediate next action in one sentence.
51
65
  ${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."}`;
52
66
  const executionInstruction = (record) => record ? `\n\nCurrent stage execution state:\n${JSON.stringify(record, null, 2)}\nTreat this bounded stage-local ledger as the current operational checkpoint. Update it after meaningful scope changes, decisions, substantial work, blockers, or verification changes, and before handoff; do not update it for trivial tool calls.` : "";
67
+ 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.`;
53
68
  const assertNoSymlinkPath = (file) => { let current = path.parse(file).root; for (const part of file.slice(current.length).split(path.sep).filter(Boolean)) { current = path.join(current, part); try { if (fs.lstatSync(current).isSymbolicLink()) fail(ERROR_CODES.STORAGE_ERROR, `Symlink path component is not supported: ${current}`); } catch (error) { if (error.code !== "ENOENT") throw error; break; } } };
54
69
 
55
70
  function parseIssue(url) {
@@ -248,7 +263,7 @@ export class WorkContext {
248
263
  lifecycle: { automatic_finish_allowed: false },
249
264
  },
250
265
  next_action: "start_work",
251
- 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.`,
266
+ 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.`,
252
267
  },
253
268
  }, [workspace, "01"]);
254
269
  });
@@ -284,6 +299,7 @@ export class WorkContext {
284
299
  }
285
300
 
286
301
  candidates() { return new CandidateStore(this); }
302
+ deliveries() { return new DeliveryStore(this); }
287
303
 
288
304
  createCandidate(workspace, title, message = null, options = {}) {
289
305
  return this.transact("candidate-create", () => this.result(this.candidates().create(workspace, title, message, options), ["local:candidates"]));
@@ -319,6 +335,15 @@ export class WorkContext {
319
335
  ), { session: this.options.sessionId, owner: actor(this.options) });
320
336
  }
321
337
 
338
+ readDelivery(workspace, options = {}) { return { ok: true, data: this.deliveries().readContext(workspace, options) }; }
339
+
340
+ markDelivery(workspace, environment, commit, confirmation) {
341
+ this.storage.assertSafeRoots();
342
+ return withLock(this.storage.lockPath("candidate-git"), () => this.transact("delivery-mark", () =>
343
+ this.result(this.deliveries().mark(workspace, environment, commit, confirmation), ["local:delivery"])
344
+ ), { session: this.options.sessionId, owner: actor(this.options) });
345
+ }
346
+
322
347
  nextWorkspace() {
323
348
  const ids = this.listWorkspaces().data.map((workspace) => Number(workspace.workspace));
324
349
  return String(Math.max(0, ...ids) + 1).padStart(6, "0");
@@ -362,9 +387,13 @@ export class WorkContext {
362
387
  const workspaceRecord = this.storage.readWorkspace(workspace).data;
363
388
  const workspaceTitle = workspaceRecord.title;
364
389
  const workflowPolicy = workspaceMode(workspaceRecord) === "startup" && options.opencodeSessionId ? startupWorkflowPolicy() : null;
390
+ const pendingCandidates = workflowPolicy ? this.candidates().activeProjection(workspace).by_stage[stage] || null : null;
391
+ const deliveryContext = stage === "01" ? this.deliveries().projection(workspace) : null;
392
+ const hasDeliveryContext = deliveryContext && (deliveryContext.committed.count || deliveryContext.environments.length || deliveryContext.unavailable);
365
393
  const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
366
394
  const execution = this.storage.readStageExecution(workspace, stage);
367
- const automaticFinish = automaticFinishAllowed(this.storage, workspace);
395
+ const automaticFinish = automaticFinishAllowed(this.storage, workspace);
396
+ const recommendations = capabilityRecommendations(this.storage, stageRecord.data);
368
397
  return this.result({
369
398
  workspace,
370
399
  stage,
@@ -386,20 +415,24 @@ export class WorkContext {
386
415
  scope: stageRecord.data.prompt || null,
387
416
  previous_result: previousResult,
388
417
  previous_session_summary: previousSessionSummary,
389
- ...(execution ? { execution_state: execution } : {}),
418
+ ...(execution ? { execution_state: execution } : {}),
419
+ ...(recommendations ? { capability_profiles: recommendations } : {}),
390
420
  },
391
421
  context: {
392
422
  essence: stageRecord.data.goal || stageRecord.data.title,
393
423
  previous: previousSessionSummary || previousResult || "No previous progress was recorded.",
394
424
  now: hasPrompt ? stageRecord.data.prompt : "First clarify the task and work plan with the user.",
395
425
  workspace_knowledge: workspaceKnowledge,
396
- ...(execution ? { execution_state: execution } : {}),
426
+ ...(execution ? { execution_state: execution } : {}),
427
+ ...(recommendations ? { capability_profiles: recommendations } : {}),
428
+ ...(pendingCandidates ? { pending_candidates: pendingCandidates } : {}),
429
+ ...(hasDeliveryContext ? { delivery_context: deliveryContext } : {}),
397
430
  ...(workflowPolicy ? { workflow_policy: workflowPolicy } : {}),
398
431
  lifecycle: { automatic_finish_allowed: automaticFinish },
399
432
  },
400
433
  next_action: hasPrompt ? confirmationRequired ? "await_confirmation" : "start_work" : "ask_questions",
401
434
  instruction: `${hasPrompt
402
- ? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}${executionInstruction(execution)}${startupWorkflowInstruction(workflowPolicy)}`
435
+ ? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}${executionInstruction(execution)}${startupWorkflowInstruction(workflowPolicy)}${stage === "01" ? deliveryPlanningInstruction : ""}`
403
436
  : `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.`,
404
437
  },
405
438
  }, [workspace, stage]);
@@ -412,6 +445,11 @@ export class WorkContext {
412
445
  if (!Array.isArray(options.dependsOn || [])) fail(ERROR_CODES.INVALID_ARGUMENT, "dependsOn must contain unique stage IDs");
413
446
  const dependsOn = (options.dependsOn || []).map(normalizeStageId);
414
447
  if (new Set(dependsOn).size !== dependsOn.length) fail(ERROR_CODES.INVALID_ARGUMENT, "dependsOn must contain unique stage IDs");
448
+ assertCapabilityProfile(options.executionProfile, "executionProfile");
449
+ assertCapabilityDepth(options.executionDepth, "executionDepth");
450
+ assertCapabilityClassification(options.classification);
451
+ assertCapabilityProfile(options.reviewProfile, "reviewProfile");
452
+ if (Boolean(options.executionProfile) !== Boolean(options.executionDepth)) fail(ERROR_CODES.INVALID_ARGUMENT, "executionProfile and executionDepth must be provided together");
415
453
  return this.transact(`workspace-${workspace}`, () => {
416
454
  const stages = this.listStages(workspace).data.stages;
417
455
  if (stages.length >= 99) fail(ERROR_CODES.INVALID_STATE, "A workspace cannot contain more than 99 stages");
@@ -420,10 +458,138 @@ export class WorkContext {
420
458
  if (dependsOn.some((dependency) => !stages.some((item) => item.stage === dependency))) fail(ERROR_CODES.INVALID_ARGUMENT, "dependsOn must reference existing stages");
421
459
  const now = new Date().toISOString();
422
460
  const prompt = options.prompt?.trim() || undefined;
423
- const metadata = { schema: 1, workspace, stage, title: title.trim(), status: "planned", goal: options.goal || title.trim(), ...(prompt ? { prompt } : {}), depends_on: dependsOn, owner: options.owner || actor(this.options), created_at: now, updated_at: now, tracker_links: [] };
461
+ const metadata = { schema: 1, workspace, stage, title: title.trim(), status: "planned", goal: options.goal || title.trim(), ...(prompt ? { prompt } : {}), depends_on: dependsOn, owner: options.owner || actor(this.options), ...(options.executionProfile ? { execution_profile: options.executionProfile, execution_depth: options.executionDepth, execution_classification: options.classification || "explicit" } : {}), ...(options.reviewProfile ? { review_profile: options.reviewProfile } : {}), created_at: now, updated_at: now, tracker_links: [] };
424
462
  this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), metadata, body(title, options.goal || title, prompt));
425
463
  generateProjections(this.storage);
426
- return this.result({ workspace, stage, status: "planned", session_started: false, resume_required: true }, [stage]);
464
+ const capabilityProfiles = metadata.execution_profile || metadata.review_profile
465
+ ? { capability_profiles: capabilityData(this.storage, metadata) }
466
+ : {};
467
+ return this.result({ workspace, stage, status: "planned", session_started: false, resume_required: true, ...capabilityProfiles }, [stage]);
468
+ });
469
+ }
470
+
471
+ setStageProfiles(workspace, stage, profiles = {}) {
472
+ workspace = normalizeWorkspaceId(workspace);
473
+ stage = normalizeStageId(stage);
474
+ const hasExecution = Object.hasOwn(profiles, "executionProfile");
475
+ const hasDepth = Object.hasOwn(profiles, "executionDepth");
476
+ const hasReview = Object.hasOwn(profiles, "reviewProfile");
477
+ if (!hasExecution && !hasDepth && !hasReview) fail(ERROR_CODES.INVALID_ARGUMENT, "At least one profile or depth must be set or cleared");
478
+ assertCapabilityProfile(profiles.executionProfile, "executionProfile");
479
+ assertCapabilityDepth(profiles.executionDepth, "executionDepth");
480
+ assertCapabilityProfile(profiles.reviewProfile, "reviewProfile");
481
+ if ((profiles.executionProfile === null) !== (profiles.executionDepth === null) && (profiles.executionProfile === null || profiles.executionDepth === null)) fail(ERROR_CODES.INVALID_ARGUMENT, "Clear executionProfile and executionDepth together");
482
+ return this.transact(`stage-${workspace}-${stage}`, () => {
483
+ const record = this.storage.readStage(workspace, stage);
484
+ let changed = false;
485
+ for (const [provided, input, key] of [[hasExecution, profiles.executionProfile, "execution_profile"], [hasDepth, profiles.executionDepth, "execution_depth"], [hasReview, profiles.reviewProfile, "review_profile"]]) {
486
+ if (!provided) continue;
487
+ if (input === null) {
488
+ if (record.data[key] !== undefined) { delete record.data[key]; changed = true; }
489
+ } else if (record.data[key] !== input) { record.data[key] = input; changed = true; }
490
+ }
491
+ if ((hasExecution || hasDepth) && record.data.execution_profile && record.data.execution_depth && record.data.execution_classification !== "explicit") { record.data.execution_classification = "explicit"; changed = true; }
492
+ if ((hasExecution || hasDepth) && !record.data.execution_profile && !record.data.execution_depth && record.data.execution_classification !== undefined) { delete record.data.execution_classification; changed = true; }
493
+ if (Boolean(record.data.execution_profile) !== Boolean(record.data.execution_depth)) fail(ERROR_CODES.INVALID_ARGUMENT, "executionProfile and executionDepth must both be set or cleared");
494
+ if (changed) {
495
+ record.data.updated_at = new Date().toISOString();
496
+ this.storage.writeMarkdown(this.storage.stageFile(workspace, stage), record.data, record.body);
497
+ generateProjections(this.storage);
498
+ }
499
+ return this.result({ workspace, stage, capability_profiles: capabilityData(this.storage, record.data) }, changed ? [workspace, stage] : []);
500
+ });
501
+ }
502
+
503
+ refreshStageProfiles(workspace, recommendations, options = {}) {
504
+ workspace = normalizeWorkspaceId(workspace);
505
+ if (!Array.isArray(recommendations) || !recommendations.length || recommendations.length > 99) fail(ERROR_CODES.INVALID_ARGUMENT, "recommendations must contain 1 to 99 stage classifications");
506
+ const normalized = recommendations.map((item) => {
507
+ const stage = normalizeStageId(item.stage);
508
+ assertCapabilityProfile(item.executionProfile, "executionProfile");
509
+ assertCapabilityDepth(item.executionDepth, "executionDepth");
510
+ if (!item.executionProfile || !item.executionDepth) fail(ERROR_CODES.INVALID_ARGUMENT, "Each recommendation requires executionProfile and executionDepth");
511
+ return { stage, executionProfile: item.executionProfile, executionDepth: item.executionDepth };
512
+ });
513
+ if (new Set(normalized.map((item) => item.stage)).size !== normalized.length) fail(ERROR_CODES.INVALID_ARGUMENT, "recommendations must contain unique stage IDs");
514
+ return this.transact(`workspace-${workspace}`, () => {
515
+ const updated = [];
516
+ const unchanged = [];
517
+ const skipped = [];
518
+ for (const recommendation of normalized) {
519
+ const record = this.storage.readStage(workspace, recommendation.stage);
520
+ if (["completed", "archived", "cancelled"].includes(record.data.status)) { skipped.push({ stage: recommendation.stage, reason: "terminal" }); continue; }
521
+ if (record.data.execution_classification === "explicit" && !options.includeExplicit) { skipped.push({ stage: recommendation.stage, reason: "explicit" }); continue; }
522
+ const before = { profile: record.data.execution_profile || null, depth: record.data.execution_depth || null, classification: record.data.execution_classification || null };
523
+ const after = { profile: recommendation.executionProfile, depth: recommendation.executionDepth, classification: "inferred" };
524
+ if (before.profile === after.profile && before.depth === after.depth && before.classification === after.classification) { unchanged.push(recommendation.stage); continue; }
525
+ record.data.execution_profile = after.profile;
526
+ record.data.execution_depth = after.depth;
527
+ record.data.execution_classification = after.classification;
528
+ record.data.updated_at = new Date().toISOString();
529
+ this.storage.writeMarkdown(this.storage.stageFile(workspace, recommendation.stage), record.data, record.body);
530
+ updated.push({ stage: recommendation.stage, before, after });
531
+ }
532
+ if (updated.length) generateProjections(this.storage);
533
+ return this.result({ workspace, updated, unchanged, skipped }, updated.length ? [workspace, ...updated.map((item) => item.stage)] : []);
534
+ });
535
+ }
536
+
537
+ showCapabilityProfiles() {
538
+ const local = readCapabilityMappings(this.storage);
539
+ return this.result({ mode: capabilityProfileMode(this.storage), mappings: local.mappings, warnings: local.warnings }, []);
540
+ }
541
+
542
+ configureCapabilityProfiles(options = {}) {
543
+ if (options.mode === undefined && options.mappings === undefined) fail(ERROR_CODES.INVALID_ARGUMENT, "mode or mappings is required");
544
+ if (options.mode !== undefined && options.mappings !== undefined) fail(ERROR_CODES.INVALID_ARGUMENT, "Configure mode and mappings in separate atomic calls");
545
+ if (options.mode !== undefined && !["advisory", "off"].includes(options.mode)) fail(ERROR_CODES.INVALID_ARGUMENT, "mode must be advisory or off");
546
+ if (options.mappings !== undefined && !validateCapabilityMappings(options.mappings)) fail(ERROR_CODES.INVALID_ARGUMENT, `mappings may contain only ${CAPABILITY_DEPTHS.join(", ")} with bounded non-empty string values`);
547
+ return withLock(this.storage.lockPath("capability-profiles"), () => {
548
+ this.storage.assertNoSymlinks();
549
+ const changed = [];
550
+ const configFile = path.join(this.storage.projectRoot, ".work-context", "config.yaml");
551
+ const mappingFile = path.join(this.storage.personalRoot, CAPABILITY_MAPPINGS_FILE);
552
+ const previousConfig = fs.readFileSync(configFile);
553
+ let previousMapping = null;
554
+ if (fs.existsSync(mappingFile)) {
555
+ if (!fs.lstatSync(mappingFile).isFile()) fail(ERROR_CODES.STORAGE_ERROR, `Invalid ${CAPABILITY_MAPPINGS_FILE} path`);
556
+ previousMapping = fs.readFileSync(mappingFile);
557
+ }
558
+ try {
559
+ if (options.mode !== undefined && options.mode !== capabilityProfileMode(this.storage)) {
560
+ const current = fs.readFileSync(configFile, "utf8");
561
+ const section = `capability_profiles:\n mode: ${options.mode}\n`;
562
+ const next = /^capability_profiles:\n(?: .*\n)*/m.test(current)
563
+ ? current.replace(/^capability_profiles:\n(?: .*\n)*/m, section)
564
+ : `${current.trimEnd()}\n${section}`;
565
+ atomicWrite(configFile, next);
566
+ changed.push(configFile);
567
+ }
568
+ if (options.mappings !== undefined) {
569
+ atomicWrite(mappingFile, `${JSON.stringify({ schema: 1, mappings: options.mappings }, null, 2)}\n`);
570
+ changed.push(mappingFile);
571
+ }
572
+ } catch (error) {
573
+ try { atomicWrite(configFile, previousConfig.toString("utf8")); } catch {}
574
+ try {
575
+ if (previousMapping) atomicWrite(mappingFile, previousMapping.toString("utf8"));
576
+ else fs.rmSync(mappingFile, { force: true });
577
+ } catch {}
578
+ throw error;
579
+ }
580
+ if (options.mode !== undefined) this.storage.config.capability_profiles.mode = options.mode;
581
+ const local = readCapabilityMappings(this.storage);
582
+ return this.result({ mode: capabilityProfileMode(this.storage), mappings: local.mappings, warnings: local.warnings }, changed);
583
+ }, { owner: actor(this.options), session: this.options.sessionId || null });
584
+ }
585
+
586
+ resetCapabilityProfiles(confirmation) {
587
+ if (confirmation !== "RESET_PROFILES") fail(ERROR_CODES.CONFIRMATION_REQUIRED, "Reset requires RESET_PROFILES confirmation");
588
+ return this.transact("capability-profiles", () => {
589
+ const file = path.join(this.storage.personalRoot, CAPABILITY_MAPPINGS_FILE);
590
+ const existed = fs.existsSync(file);
591
+ if (existed) fs.rmSync(file);
592
+ return this.result({ mode: capabilityProfileMode(this.storage), mappings: {} }, existed ? [file] : []);
427
593
  });
428
594
  }
429
595
 
@@ -805,8 +971,8 @@ export class WorkContext {
805
971
  help(command = "") {
806
972
  return this.result({
807
973
  command,
808
- 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 execution read|stage execution replace|stage execution update|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]",
809
- note: "stage execution state is a bounded stage-local operational checkpoint; replace and update require the current revision and active stage session, while read is available without mutation; checklist state never completes a stage, and explicit stage finish reports remaining execution work while preserving the final ledger; associated OpenCode sessions in startup-mode workspaces receive the shared-worktree and commit-candidate policy on resume; standard mode remains conservative; candidate strategies are exact, shared_foundation, and integration, with optional related stage references for traceability only; 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.",
974
+ 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|delivery read|delivery mark|profiles show|profiles setup|profiles reset|workspace finish|workspace reopen|resume|stage add|stage profiles|stage profiles refresh|stage reopen|stage restore|stage rename|stage update|stage update-prompt|stage update-result|stage execution read|stage execution replace|stage execution update|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]",
975
+ note: "execution recommendations combine a vendor-neutral capability with light, standard, or deep depth; Planning agents infer missing values before stage creation, ordinary refresh updates missing/inferred classifications while preserving explicit assignments, and local depth mappings resolve only an advisory model label; profiles setup gathers mode and mappings through questions, off mode suppresses presentation and resolution, and no profile operation changes a model, agent, reviewer, or session; delivery context is workspace-level local operational state; exact Git range inspection runs only for explicit immutable hashes; stage execution state is a bounded stage-local operational checkpoint; associated startup sessions receive the shared-worktree candidate policy; stage finish requires an explicit user lifecycle request unless Planning contains AUTO_STAGE_FINISH: allowed; recovery operations preserve lifecycle history.",
810
976
  }, []);
811
977
  }
812
978
 
@@ -0,0 +1,135 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { atomicWrite } from "./storage.js";
5
+ import { ERROR_CODES, fail } from "./errors.js";
6
+ import { normalizeWorkspaceId } from "./identifiers.js";
7
+ import { inspectCommitRange, isCommitAncestor, repositoryState } from "./git-candidates.js";
8
+
9
+ const environmentPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
10
+ const hashPattern = /^[0-9a-f]{40,64}$/;
11
+ const candidatePattern = /^CC-\d{6}$/;
12
+ const timestamp = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
13
+ const maxEnvironments = 20;
14
+ const maxCandidates = 10000;
15
+ const checkpointIntegrity = (checkpoint) => createHash("sha256").update(JSON.stringify({
16
+ deployed_head: checkpoint.deployed_head,
17
+ deployed_at: checkpoint.deployed_at,
18
+ deployed_candidates: checkpoint.deployed_candidates,
19
+ })).digest("hex");
20
+
21
+ const normalizeEnvironment = (value) => {
22
+ if (typeof value !== "string" || !environmentPattern.test(value)) fail(ERROR_CODES.INVALID_ARGUMENT, "Environment must use 1-64 letters, digits, dots, underscores or hyphens");
23
+ return value;
24
+ };
25
+
26
+ export function validateDeliveryRecord(data, workspace) {
27
+ const valid = data && typeof data === "object" && !Array.isArray(data)
28
+ && Object.keys(data).every((key) => ["schema", "workspace", "updated_at", "environments"].includes(key))
29
+ && data.schema === 1 && data.workspace === workspace && /^\d{6}$/.test(data.workspace)
30
+ && timestamp(data.updated_at) && data.environments && typeof data.environments === "object" && !Array.isArray(data.environments)
31
+ && Object.keys(data.environments).length <= maxEnvironments
32
+ && Object.entries(data.environments).every(([name, item]) => environmentPattern.test(name)
33
+ && item && typeof item === "object" && !Array.isArray(item)
34
+ && Object.keys(item).every((key) => ["deployed_head", "deployed_at", "deployed_candidates", "integrity"].includes(key))
35
+ && hashPattern.test(item.deployed_head) && timestamp(item.deployed_at)
36
+ && Array.isArray(item.deployed_candidates) && item.deployed_candidates.length <= maxCandidates
37
+ && item.deployed_candidates.every((candidate) => candidate && typeof candidate === "object" && !Array.isArray(candidate)
38
+ && Object.keys(candidate).length === 2 && candidatePattern.test(candidate.candidate) && hashPattern.test(candidate.commit_hash))
39
+ && new Set(item.deployed_candidates.map((candidate) => candidate.candidate)).size === item.deployed_candidates.length
40
+ && item.deployed_candidates.every((candidate, index) => index === 0 || item.deployed_candidates[index - 1].candidate < candidate.candidate)
41
+ && typeof item.integrity === "string" && /^[0-9a-f]{64}$/.test(item.integrity)
42
+ && item.integrity === checkpointIntegrity(item));
43
+ if (!valid) fail(ERROR_CODES.STORAGE_ERROR, "Invalid delivery checkpoint metadata");
44
+ return data;
45
+ }
46
+
47
+ export class DeliveryStore {
48
+ constructor(context) {
49
+ this.context = context;
50
+ this.directory = path.join(context.storage.personalRoot, "delivery");
51
+ }
52
+
53
+ file(workspace) { return path.join(this.directory, `${workspace}.json`); }
54
+
55
+ assertWorkspace(workspace) {
56
+ workspace = normalizeWorkspaceId(workspace);
57
+ this.context.storage.readWorkspace(workspace);
58
+ return workspace;
59
+ }
60
+
61
+ read(workspace) {
62
+ workspace = this.assertWorkspace(workspace);
63
+ try { return validateDeliveryRecord(JSON.parse(fs.readFileSync(this.file(workspace), "utf8")), workspace); }
64
+ catch (error) {
65
+ if (error.code === "ENOENT") return null;
66
+ if (error.code === ERROR_CODES.STORAGE_ERROR) throw error;
67
+ fail(ERROR_CODES.STORAGE_ERROR, "Invalid delivery checkpoint metadata", { cause: error.message });
68
+ }
69
+ }
70
+
71
+ projection(workspace) {
72
+ workspace = this.assertWorkspace(workspace);
73
+ let record;
74
+ try { record = this.read(workspace); } catch {
75
+ return { committed: this.context.candidates().committedProjection(workspace), plan_needed: false, environments: [], unavailable: true };
76
+ }
77
+ const candidateStore = this.context.candidates();
78
+ const committedRecords = candidateStore.projectionRecords(workspace).filter((candidate) => candidate.status === "committed");
79
+ const committed = candidateStore.committedProjection(workspace);
80
+ const committedById = new Map(committedRecords.map((candidate) => [candidate.candidate, candidate]));
81
+ const invalidCheckpoint = Object.values(record?.environments || {}).some((checkpoint) => checkpoint.deployed_candidates.some((candidate) => {
82
+ const metadata = committedById.get(candidate.candidate);
83
+ return !metadata || metadata.commit_hash !== candidate.commit_hash;
84
+ }));
85
+ if (invalidCheckpoint) return { committed, plan_needed: false, environments: [], unavailable: true };
86
+ const environments = Object.entries(record?.environments || {}).sort(([left], [right]) => left.localeCompare(right)).map(([environment, checkpoint]) => {
87
+ const delivered = new Set(checkpoint.deployed_candidates.map((candidate) => candidate.candidate));
88
+ return {
89
+ environment,
90
+ deployed_at: checkpoint.deployed_at,
91
+ pending: committedRecords.filter((candidate) => !delivered.has(candidate.candidate)).length,
92
+ };
93
+ });
94
+ return {
95
+ committed,
96
+ plan_needed: committed.count > 0 && environments.length === 0,
97
+ environments,
98
+ };
99
+ }
100
+
101
+ readContext(workspace, options = {}) {
102
+ workspace = this.assertWorkspace(workspace);
103
+ const projection = this.projection(workspace);
104
+ const record = this.read(workspace);
105
+ const environment = options.environment === undefined ? null : normalizeEnvironment(options.environment);
106
+ const checkpoint = environment ? record?.environments?.[environment] || null : null;
107
+ const hasFrom = options.from !== undefined;
108
+ const hasTo = options.to !== undefined;
109
+ if (hasFrom !== hasTo) fail(ERROR_CODES.INVALID_ARGUMENT, "Delivery range requires both from and to commit hashes");
110
+ const range = hasFrom ? inspectCommitRange(this.context.storage.projectRoot, options.from, options.to) : null;
111
+ return { workspace, environment, checkpoint, ...projection, ...(range ? { range } : {}) };
112
+ }
113
+
114
+ mark(workspace, environment, commit, confirmation) {
115
+ workspace = this.assertWorkspace(workspace);
116
+ environment = normalizeEnvironment(environment);
117
+ if (confirmation !== "DELIVERY_CONFIRMED") fail(ERROR_CODES.CONFIRMATION_REQUIRED, "Marking delivery requires DELIVERY_CONFIRMED confirmation");
118
+ if (typeof commit !== "string" || !hashPattern.test(commit)) fail(ERROR_CODES.INVALID_ARGUMENT, "Delivery commit must be a full commit hash");
119
+ const repository = repositoryState(this.context.storage.projectRoot);
120
+ if (!isCommitAncestor(repository.root, commit, repository.head)) fail(ERROR_CODES.DELIVERY_INVALID_RANGE, "Delivery commit must be available and reachable from current HEAD", { commit, currentHead: repository.head });
121
+ const committed = this.context.candidates().projectionRecords(workspace).filter((candidate) => candidate.status === "committed");
122
+ const deployedCandidates = committed.filter((candidate) => isCommitAncestor(repository.root, candidate.commit_hash, commit))
123
+ .map((candidate) => ({ candidate: candidate.candidate, commit_hash: candidate.commit_hash }))
124
+ .sort((left, right) => left.candidate.localeCompare(right.candidate));
125
+ const now = new Date().toISOString();
126
+ const record = this.read(workspace) || { schema: 1, workspace, updated_at: now, environments: {} };
127
+ record.updated_at = now;
128
+ const checkpoint = { deployed_head: commit, deployed_at: now, deployed_candidates: deployedCandidates };
129
+ checkpoint.integrity = checkpointIntegrity(checkpoint);
130
+ record.environments[environment] = checkpoint;
131
+ validateDeliveryRecord(record, workspace);
132
+ atomicWrite(this.file(workspace), `${JSON.stringify(record, null, 2)}\n`);
133
+ return { workspace, environment, checkpoint: record.environments[environment] };
134
+ }
135
+ }
package/src/errors.js CHANGED
@@ -10,6 +10,7 @@ export const ERROR_CODES = Object.freeze({
10
10
  CANDIDATE_CONFLICT: "CANDIDATE_CONFLICT", CANDIDATE_DETACHED_HEAD: "CANDIDATE_DETACHED_HEAD",
11
11
  CANDIDATE_REF_RACE: "CANDIDATE_REF_RACE", CANDIDATE_COMMIT_FAILED: "CANDIDATE_COMMIT_FAILED",
12
12
  EXECUTION_REVISION_CONFLICT: "EXECUTION_REVISION_CONFLICT", EXECUTION_LIMIT_EXCEEDED: "EXECUTION_LIMIT_EXCEEDED",
13
+ DELIVERY_INVALID_RANGE: "DELIVERY_INVALID_RANGE", DELIVERY_RANGE_TOO_LARGE: "DELIVERY_RANGE_TOO_LARGE",
13
14
  });
14
15
 
15
16
  export class WorkContextError extends Error {
@@ -10,9 +10,10 @@ const git = (root, args, options = {}) => {
10
10
  encoding: options.encoding === null ? null : "utf8",
11
11
  env: { ...process.env, ...options.env },
12
12
  input: options.input,
13
- maxBuffer: 64 * 1024 * 1024,
13
+ maxBuffer: options.maxBuffer ?? 64 * 1024 * 1024,
14
14
  });
15
15
  if (result.error?.code === "ENOENT") fail(ERROR_CODES.GIT_UNAVAILABLE, "Git executable is unavailable");
16
+ if (result.error?.code === "ENOBUFS") fail(options.code || ERROR_CODES.GIT_UNAVAILABLE, options.message || "Git output exceeded the supported limit", { maxBuffer: options.maxBuffer });
16
17
  if (result.error) fail(ERROR_CODES.GIT_UNAVAILABLE, "Cannot execute Git", { cause: result.error.message });
17
18
  if (result.status !== 0 && !options.allowFailure) {
18
19
  fail(options.code || ERROR_CODES.CANDIDATE_INVALID_PATCH, options.message || "Git operation failed", {
@@ -36,6 +37,48 @@ export function repositoryState(projectRoot) {
36
37
  return { root, head: head.stdout.trim() };
37
38
  }
38
39
 
40
+ const assertCommitHash = (value, label) => {
41
+ if (typeof value !== "string" || !/^[0-9a-f]{40,64}$/.test(value)) fail(ERROR_CODES.INVALID_ARGUMENT, `${label} must be a full commit hash`);
42
+ return value;
43
+ };
44
+
45
+ const commitExists = (root, commit) => git(root, ["cat-file", "-e", `${commit}^{commit}`], { allowFailure: true }).status === 0;
46
+
47
+ export function isCommitAncestor(projectRoot, ancestor, descendant) {
48
+ const repository = repositoryState(projectRoot);
49
+ ancestor = assertCommitHash(ancestor, "Ancestor");
50
+ descendant = assertCommitHash(descendant, "Descendant");
51
+ if (!commitExists(repository.root, ancestor) || !commitExists(repository.root, descendant)) return false;
52
+ return git(repository.root, ["merge-base", "--is-ancestor", ancestor, descendant], { allowFailure: true }).status === 0;
53
+ }
54
+
55
+ export function inspectCommitRange(projectRoot, from, to) {
56
+ const repository = repositoryState(projectRoot);
57
+ from = assertCommitHash(from, "Range start");
58
+ to = assertCommitHash(to, "Range end");
59
+ if (!commitExists(repository.root, from) || !commitExists(repository.root, to) || !isCommitAncestor(repository.root, from, to)) {
60
+ fail(ERROR_CODES.DELIVERY_INVALID_RANGE, "Delivery range must contain available commits in ancestor order", { from, to });
61
+ }
62
+ const commitCount = Number(git(repository.root, ["rev-list", "--count", `${from}..${to}`]).stdout.trim());
63
+ const commits = git(repository.root, ["rev-list", "--reverse", `--skip=${Math.max(0, commitCount - 500)}`, "--max-count=500", `${from}..${to}`]).stdout.trim().split("\n").filter(Boolean);
64
+ const names = git(repository.root, ["diff", "--name-only", "-z", from, to, "--"], {
65
+ encoding: null,
66
+ maxBuffer: 4 * 1024 * 1024,
67
+ code: ERROR_CODES.DELIVERY_RANGE_TOO_LARGE,
68
+ message: "Delivery changed-path output exceeds the supported 4 MiB limit",
69
+ }).stdout.toString("utf8").split("\0").filter(Boolean);
70
+ return {
71
+ from,
72
+ to,
73
+ commit_count: commitCount,
74
+ commits,
75
+ commits_truncated: commitCount > commits.length,
76
+ changed_path_count: names.length,
77
+ changed_paths: names.slice(0, 500),
78
+ paths_truncated: names.length > 500,
79
+ };
80
+ }
81
+
39
82
  function withTemporaryIndex(root, base, fn) {
40
83
  const directory = fs.mkdtempSync(path.join(os.tmpdir(), "work-context-candidate-"));
41
84
  const index = path.join(directory, "index");
package/src/index.js CHANGED
@@ -13,3 +13,5 @@ export * from "./stages-renderer.js";
13
13
  export * from "./work-context-snapshot.js";
14
14
  export * from "./git-candidates.js";
15
15
  export * from "./candidates.js";
16
+ export * from "./delivery.js";
17
+ export * from "./capability-profiles.js";
@@ -7,6 +7,47 @@ const statusMarker = (status) => ({
7
7
  }[status] || "[?]");
8
8
 
9
9
  const compareStageIds = (left, right) => Number(left.id) - Number(right.id);
10
+ const candidateSummary = (stage) => {
11
+ const projection = stage.candidates;
12
+ if (!projection || !(projection.draft || projection.ready)) return null;
13
+ if (projection.draft + projection.ready > 1) return `Pending: ${projection.draft} draft · ${projection.ready} ready`;
14
+ const [candidate] = projection.items;
15
+ const others = candidate.related_stages.filter((related) => related !== stage.id);
16
+ return `Pending: ${candidate.status} · ${candidate.strategy}${others.length ? ` · also ${others.join(", ")}` : ""}`;
17
+ };
18
+ const deliverySummary = (delivery) => {
19
+ if (!delivery) return null;
20
+ if (delivery.unavailable) return "Delivery · unavailable";
21
+ if (delivery.plan_needed) return `Delivery · ${delivery.committed} commits · plan needed`;
22
+ if (delivery.environments.length === 1) {
23
+ const [environment] = delivery.environments;
24
+ return `Delivery · ${environment.environment} · ${environment.pending} tracked pending`;
25
+ }
26
+ const pending = delivery.environments.reduce((total, environment) => total + environment.pending, 0);
27
+ return `Delivery · ${delivery.environments.length} environments · ${pending} tracked pending`;
28
+ };
29
+ const capitalize = (value) => value ? `${value[0].toUpperCase()}${value.slice(1)}` : value;
30
+ export const formatStageIds = (ids = []) => {
31
+ const ranges = [];
32
+ let run = [];
33
+ const flush = () => {
34
+ if (!run.length) return;
35
+ ranges.push(run.length >= 3 ? `${run[0]}—${run.at(-1)}` : run.join(", "));
36
+ run = [];
37
+ };
38
+ for (const id of ids) {
39
+ const previous = run.at(-1);
40
+ if (previous && Number(id) !== Number(previous) + 1) flush();
41
+ run.push(id);
42
+ }
43
+ flush();
44
+ return ranges.join(", ");
45
+ };
46
+ const profileSummary = (stage) => {
47
+ return stage.execution_profile && stage.execution_depth && stage.recommended_model
48
+ ? `${capitalize(stage.execution_profile)} · ${capitalize(stage.execution_depth)} · ${capitalize(stage.recommended_model)}`
49
+ : null;
50
+ };
10
51
 
11
52
  /**
12
53
  * Render normalized stages as a dependency-to-dependent forest. A stage may
@@ -59,10 +100,14 @@ export function renderStagesPanel(result) {
59
100
  `Workflow · ${snapshot.workspace.mode || "standard"}`,
60
101
  ];
61
102
  const candidates = snapshot.workspace.candidates;
62
- if (candidates && (candidates.pending || candidates.ready)) lines.push(`Candidates · pending ${candidates.pending} · ready ${candidates.ready}`);
103
+ if (candidates && (candidates.pending || candidates.ready)) lines.push(`Candidates · ${candidates.pending} draft · ${candidates.ready} ready`);
104
+ const delivery = deliverySummary(snapshot.workspace.delivery);
105
+ if (delivery) lines.push(delivery);
63
106
  lines.push("", `Stages · ${snapshot.workspace.status}`);
64
107
  for (const stage of snapshot.stages) {
65
- lines.push(`${statusMarker(stage.status)} ${stage.id}. ${stage.title}${stage.depends_on?.length ? `\nDeps: ${stage.depends_on.join(", ")}` : ""}`);
108
+ const pending = candidateSummary(stage);
109
+ const profiles = profileSummary(stage);
110
+ lines.push(`${statusMarker(stage.status)} ${stage.id}. ${stage.title}${profiles ? `\n${profiles}` : ""}${stage.depends_on?.length ? `\nDeps: ${formatStageIds(stage.depends_on)}` : ""}${pending ? `\n${pending}` : ""}`);
66
111
  }
67
112
  if (result.stale) lines.push(`! stale: ${result.error?.code || "STORAGE_ERROR"}`);
68
113
  return lines.join("\n");
@@ -1,4 +1,5 @@
1
1
  import { WorkContext } from "./core.js";
2
+ import { capabilityProfileMode, readCapabilityMappings, stageCapabilityProfiles } from "./capability-profiles.js";
2
3
 
3
4
  const emptySnapshot = () => ({
4
5
  schema: 1,
@@ -35,17 +36,26 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
35
36
 
36
37
  const workspace = context.storage.readWorkspace(session.workspace).data;
37
38
  const mode = workspace.mode || "standard";
38
- const candidates = mode === "startup" ? context.candidates().summary(session.workspace) : null;
39
- const stages = context.listStages(session.workspace).data.stages
39
+ const candidateProjection = mode === "startup" ? context.candidates().activeProjection(session.workspace) : null;
40
+ const deliveryProjection = context.deliveries().projection(session.workspace);
41
+ const delivery = deliveryProjection.committed.count || deliveryProjection.environments.length || deliveryProjection.unavailable
42
+ ? { committed: deliveryProjection.committed.count, plan_needed: deliveryProjection.plan_needed, environments: deliveryProjection.environments, ...(deliveryProjection.unavailable ? { unavailable: true } : {}) }
43
+ : null;
44
+ const visibleStages = context.listStages(session.workspace).data.stages
40
45
  .filter((stage) => stage.status !== "archived")
41
- .sort((left, right) => Number(left.stage) - Number(right.stage))
46
+ .sort((left, right) => Number(left.stage) - Number(right.stage));
47
+ const visibleStageIds = new Set(visibleStages.map((stage) => stage.stage));
48
+ const capabilityMappings = capabilityProfileMode(context.storage) === "advisory" ? readCapabilityMappings(context.storage) : null;
49
+ const stages = visibleStages
42
50
  .map((stage) => ({
43
51
  id: stage.stage,
44
52
  title: stage.title,
45
53
  status: stage.status,
46
54
  description: stage.description,
47
- depends_on: stage.depends_on,
55
+ depends_on: stage.depends_on.filter((dependency) => visibleStageIds.has(dependency)),
48
56
  tracker_links: stage.tracker_links || [],
57
+ ...stageCapabilityProfiles(context.storage, stage, capabilityMappings),
58
+ ...(candidateProjection?.by_stage[stage.stage] ? { candidates: candidateProjection.by_stage[stage.stage] } : {}),
49
59
  current: stage.stage === session.stage,
50
60
  }));
51
61
  const currentStage = stages.some((stage) => stage.current) ? session.stage : null;
@@ -54,7 +64,7 @@ export function readStagesSnapshot({ projectRoot, sessionId }) {
54
64
  ok: true,
55
65
  data: {
56
66
  schema: 1,
57
- workspace: { id: workspace.workspace, title: workspace.title, status: workspace.status, mode, ...(candidates ? { candidates } : {}) },
67
+ workspace: { id: workspace.workspace, title: workspace.title, status: workspace.status, mode, ...(candidateProjection ? { candidates: candidateProjection.summary } : {}), ...(delivery ? { delivery } : {}) },
58
68
  stages,
59
69
  currentStage,
60
70
  generatedAt: new Date().toISOString(),