opencode-work-context 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -101,6 +101,27 @@ Resume a stage with:
101
101
  /wc resume 000001 02
102
102
  ```
103
103
 
104
+ Long-running stages may keep a bounded execution ledger separate from the
105
+ original prompt, workspace knowledge, session summaries, and final result. It
106
+ tracks current scope, completed and remaining work, stage-local decisions,
107
+ blockers, and pending verification. Read it before changing it, then use the
108
+ returned revision as an optimistic concurrency guard:
109
+
110
+ ```text
111
+ /wc stage execution read 000001 02
112
+ /wc stage execution replace 000001 02 0 "{\"scope\":[\"Add CSV export\"],\"remaining\":[\"Implement endpoint\",\"Add tests\"]}"
113
+ /wc stage execution update 000001 02 1 "{\"add\":{\"completed\":[\"Implement endpoint\"]},\"remove\":{\"remaining\":[\"Implement endpoint\"]}}"
114
+ ```
115
+
116
+ `replace` replaces the complete logical state; any omitted section becomes empty. `update`
117
+ atomically adds and removes exact normalized items. Mutations require the active
118
+ stage session. A stale revision fails with `EXECUTION_REVISION_CONFLICT` rather
119
+ than overwriting newer work. Each section is limited to 50 items, the complete
120
+ state to 200 items and 32,768 serialized bytes, and each item to 500 characters.
121
+ Update the ledger at meaningful boundaries, not after every edit. Checklist
122
+ state never completes a stage: explicit stage finish reports unfinished ledger
123
+ entries as warnings and preserves the final record.
124
+
104
125
  After updating the npm package, refresh the generated slash-command contract
105
126
  without touching project configuration or loaders:
106
127
 
@@ -277,6 +298,9 @@ Installed files and project state:
277
298
  - `.work-context/local/` in `.gitignore` for personal session events.
278
299
  - `<workspace>/KNOWLEDGE.md` is the canonical durable knowledge ledger and is
279
300
  created on the first explicit knowledge operation.
301
+ - `<workspace>/stages/<stage>.execution.json` is the optional canonical,
302
+ stage-local execution ledger and is created on the first explicit replacement
303
+ or incremental update.
280
304
 
281
305
  The optional stages panel, action modal, and stage switcher are a separate TUI plugin. `init` installs a
282
306
  project-local loader outside OpenCode's server-plugin autoscan at
@@ -407,6 +431,8 @@ Tools are registered by the installed server export and are not copied into the
407
431
  project. Core and storage remain in the installed package; projects should not
408
432
  copy `src/` or `tools/`. `.work-context` Markdown, JSONL, `INDEX.md`, and
409
433
  `SESSIONS.md` are generated projections and must never be edited manually.
434
+ Canonical execution JSON is also owned by structured tools and must not be
435
+ edited directly.
410
436
  Tracker links support GitLab issues (`/-/issues/<number>`) and work items
411
437
  (`/-/work_items/<number>`), GitHub issues (`/issues/<number>`), and Jira issues
412
438
  (`/browse/KEY-123`). They are URL-based references only; the plugin does not
@@ -422,6 +448,11 @@ Every stage start/resume includes all active entries in
422
448
  workspace-wide context and avoid repeating earlier analysis unless an entry is
423
449
  incomplete, contradicted, or requires verification. Superseded entries and full
424
450
  stage results are not injected into later stages.
451
+ When a stage has execution state, resume also includes it in
452
+ `resume.context.execution_state` and highlights it as the current operational
453
+ checkpoint. The ledger remains local to that stage and is not injected into
454
+ unrelated stages or promoted to workspace knowledge. Existing stages without a
455
+ ledger retain their previous resume shape and are not rewritten.
425
456
  Finishing a stage closes its current session and may report downstream stages
426
457
  whose prompts need review, but it never starts or resumes one of them. Any
427
458
  downstream work begins only in a separate OpenCode session through an explicit
@@ -441,6 +472,8 @@ workspace, every resume also supplies the agent with the startup policy:
441
472
  - a shared dirty worktree and concurrent stages are expected;
442
473
  - stages do not own files or commits;
443
474
  - ready work is captured promptly as an explicit commit candidate;
475
+ - once a coherent commit intent exists, its draft candidate is created or
476
+ refreshed before switching stages or handing off;
444
477
  - exact, shared-foundation, and integration candidates express the intended
445
478
  commit boundary without claiming stage ownership;
446
479
  - mixed-stage provenance and complete files containing unrelated stage work are
@@ -484,10 +517,21 @@ records without strategy or stage-reference metadata remain readable; new
484
517
  candidates default to `exact` with no related stages.
485
518
 
486
519
  The sidebar reads only candidate metadata and shows a compact
487
- `Candidates · pending <count> · ready <count>` line when either count is nonzero.
488
- It does not inspect Git state, patches, paths, or candidate freshness. A `ready`
489
- label therefore means lifecycle status, not a guarantee that a later publication
490
- cannot encounter a conflict.
520
+ `Candidates · <count> draft · <count> ready` line when either count is nonzero.
521
+ With sidebar details enabled (`Ctrl+X D`), a stage with explicitly related active
522
+ candidates also shows `Pending:` metadata. One related candidate includes its
523
+ lifecycle status, strategy, and other related stage IDs; several candidates are
524
+ shown as draft and ready counts. Resume exposes the same bounded metadata in
525
+ `resume.context.pending_candidates`, so an agent can continue an existing commit
526
+ intent instead of creating a duplicate. These projections do not assign
527
+ ownership. They never inspect Git state, patches, selected paths, or candidate
528
+ freshness. A `ready` label therefore means lifecycle status, not a guarantee that
529
+ a later publication cannot encounter a conflict, and uncaptured worktree changes
530
+ remain outside this projection. Per-stage projection counts remain complete, but
531
+ resume and snapshot item details are bounded to 10 candidates with titles limited
532
+ to 120 characters. Malformed local candidate records remain strict errors for
533
+ candidate operations but are omitted from best-effort sidebar and resume
534
+ projections so they cannot block unrelated stage work.
491
535
 
492
536
  Capture accepts either complete repository paths or one exact Git unified patch,
493
537
  which permits selecting individual hunks. Candidate metadata and patches are
@@ -511,6 +555,67 @@ separate those edits by provenance. Use an integration candidate only when the
511
555
  combined patch is coherent and verified; otherwise stop and establish a safe
512
556
  candidate boundary before publication.
513
557
 
558
+ ### Delivery context
559
+
560
+ Committing or pushing does not prove that an environment was updated. Delivery is
561
+ a workspace-level concern that may aggregate committed candidates related to many
562
+ stages. Planning-stage resume receives a bounded `delivery_context` when committed
563
+ candidates or environment checkpoints exist. The sidebar renders metadata only:
564
+
565
+ ```text
566
+ Delivery · 4 commits · plan needed
567
+ Delivery · production · 2 tracked pending
568
+ Delivery · production · 0 tracked pending
569
+ ```
570
+
571
+ `tracked pending` compares committed candidate metadata with the recorded local
572
+ checkpoint; it is not a live Git reachability claim. A reset, rebase, force-push,
573
+ or external deployment change requires an explicit range inspection before acting.
574
+ Malformed or inconsistent checkpoint metadata renders `Delivery · unavailable`
575
+ instead of claiming a clean delivery state.
576
+
577
+ When asked how to deploy, the Planning agent must inspect the exact commit range
578
+ and the repository's own deployment documentation, scripts, infrastructure,
579
+ migrations, container definitions, configuration examples, and CI. It then
580
+ produces an ordered plan with prerequisites, deployment, verification, rollback,
581
+ and unresolved blockers. The package does not encode stack-specific commands and
582
+ does not assume that a push or one release command is sufficient.
583
+
584
+ Delivery state is local and mode-neutral under
585
+ `.work-context/local/delivery/<workspace>.json`. It stores only environment names,
586
+ confirmed commit hashes, timestamps, and committed candidate ID/hash pairs.
587
+ It never stores deployment commands, command output, hostnames, URLs, credentials,
588
+ tokens, or secret values. Secret and configuration requirements may be discussed
589
+ by name only. Each checkpoint carries an integrity checksum; malformed or edited
590
+ checkpoint data fails closed as unavailable.
591
+
592
+ Read metadata without inspecting Git:
593
+
594
+ ```text
595
+ /wc delivery read 000123 production
596
+ ```
597
+
598
+ Inspect one explicit immutable range:
599
+
600
+ ```text
601
+ /wc delivery read 000123 production range <from-commit> <to-commit>
602
+ ```
603
+
604
+ The range result is bounded to 500 commits and 500 changed paths and is returned
605
+ only to the explicit operation; changed-path output also has a 4 MiB subprocess
606
+ limit and fails with `DELIVERY_RANGE_TOO_LARGE` instead of consuming unbounded
607
+ memory. Snapshots and sidebar renderers never invoke Git.
608
+ After the user confirms that the target environment was updated successfully,
609
+ record the checkpoint explicitly:
610
+
611
+ ```text
612
+ /wc delivery mark 000123 production <deployed-commit> DELIVERY_CONFIRMED
613
+ ```
614
+
615
+ Marking validates that the commit is reachable from current `HEAD`, records which
616
+ committed candidates are included, and performs no deployment action. Checkpoints
617
+ are per environment, so staging and production can advance independently.
618
+
514
619
  Candidate publication is serialized by the repository-scoped `candidate-git`
515
620
  lock. Any operation that needs both locks acquires `candidate-git` before the
516
621
  work-context `write` lock; integrations must preserve this ordering to avoid
package/commands/wc.md CHANGED
@@ -37,6 +37,8 @@ Use these exact tool mappings; do not invent shortened tool names:
37
37
  - `candidate ready <workspace> <candidateId>` -> `work_context_ready_candidate`
38
38
  - `candidate commit <workspace> <candidateId> ["message"]` -> `work_context_commit_candidate`
39
39
  - `candidate discard <workspace> <candidateId>` -> `work_context_discard_candidate`
40
+ - `delivery read <workspace> [<environment>] [range <from> <to>]` -> `work_context_read_delivery`
41
+ - `delivery mark <workspace> <environment> <commit> DELIVERY_CONFIRMED` -> `work_context_mark_delivery`
40
42
  - `workspace finish <workspace>` -> `work_context_workspace_finish`
41
43
  - `workspace reopen <workspace> "reason"` -> `work_context_reopen_workspace`
42
44
  - `resume <workspace> <stage>` -> `work_context_start_session`
@@ -48,6 +50,9 @@ Use these exact tool mappings; do not invent shortened tool names:
48
50
  - `stage update [<workspace>] [<stage>] "description"` -> `work_context_update_stage`
49
51
  - `stage update-prompt [<workspace>] [<stage>] "prompt"` -> `work_context_update_stage_prompt`
50
52
  - `stage update-result [<workspace>] [<stage>] "result"` -> `work_context_update_stage_result`
53
+ - `stage execution read [<workspace>] [<stage>]` -> `work_context_read_stage_execution`
54
+ - `stage execution replace [<workspace>] [<stage>] <expectedRevision> "state JSON"` -> `work_context_replace_stage_execution`
55
+ - `stage execution update [<workspace>] [<stage>] <expectedRevision> "changes JSON"` -> `work_context_update_stage_execution`
51
56
  - `stage archive [<workspace>] [<stage>]` -> `work_context_archive_stage`
52
57
  - `stage handoff [<workspace>] [<stage>]` -> `work_context_handoff_stage`
53
58
  - `stage abandon [<workspace>] [<stage>]` -> `work_context_abandon_stage`
@@ -71,6 +76,8 @@ Supported syntax:
71
76
  - `candidate ready <workspace> <candidateId>`
72
77
  - `candidate commit <workspace> <candidateId> ["message"]`
73
78
  - `candidate discard <workspace> <candidateId>`
79
+ - `delivery read <workspace> [<environment>] [range <from> <to>]`
80
+ - `delivery mark <workspace> <environment> <commit> DELIVERY_CONFIRMED`
74
81
  - `workspace finish <workspace>`
75
82
  - `workspace reopen <workspace> "reason"`
76
83
  - `resume <workspace> <stage>`
@@ -82,6 +89,9 @@ Supported syntax:
82
89
  - `stage update [<workspace>] [<stage>] "description"`
83
90
  - `stage update-prompt [<workspace>] [<stage>] "prompt"`
84
91
  - `stage update-result [<workspace>] [<stage>] "result"`
92
+ - `stage execution read [<workspace>] [<stage>]`
93
+ - `stage execution replace [<workspace>] [<stage>] <expectedRevision> "state JSON"`
94
+ - `stage execution update [<workspace>] [<stage>] <expectedRevision> "changes JSON"`
85
95
  - `stage archive [<workspace>] [<stage>]`
86
96
  - `stage handoff [<workspace>] [<stage>]`
87
97
  - `stage abandon [<workspace>] [<stage>]`
@@ -96,11 +106,19 @@ Supported syntax:
96
106
  - explicit workspace and stage positions accept canonical padded IDs or unpadded positive integers (`1..999999` and `1..99`); results and generated commands remain padded
97
107
  - zero, signs, decimals, whitespace, overlong values, and other non-digit identifier forms are invalid; a lone unpadded workspace ID is not reinterpreted under the one-identifier rule
98
108
  - `stage update-result` replaces an existing result and does not create a result for an unfinished stage
109
+ - stage execution state has `scope`, `completed`, `remaining`, `decisions`, `blockers`, and `verification` string-array sections; `replace` accepts the complete state object, while `update` accepts an object with `add` and/or `remove` section objects
110
+ - read stage execution state first and pass its revision as `expectedRevision`; absent legacy state has revision `0`, and a stale mutation returns `EXECUTION_REVISION_CONFLICT` without changing newer state
111
+ - execution mutations require the active stage session, trim and deduplicate items, reject overlap between `completed` and `remaining`, and enforce bounded item counts, lengths, and serialized size
112
+ - update execution state after meaningful scope changes, decisions, substantial work, blockers, or verification changes and before handoff; do not update it for every trivial edit or tool call
99
113
  - `resume` returns `resume.presentation` and `resume.context`; before doing any work, report a concise human-oriented summary in the user's language with the stage title, a plain-language Goal, previous progress when useful, and the immediate next action
100
114
  - when the saved prompt contains several clear deliverables, add `In this stage we will` with 2-5 short outcome-oriented bullets derived only from the prompt, previous result, and workspace knowledge; do not invent scope, and omit this block for a small stage
101
115
  - do not expose raw workspace/stage/session identifiers, ordinals, `ok` flags, or absent error codes in the user-facing resume summary
102
116
  - `resume.context.workspace_knowledge` contains every active durable knowledge entry for the workspace; treat it as established shared context, and do not repeat earlier analysis unless an entry is incomplete, contradicted, or needs verification
103
- - an associated OpenCode session resumed in a `startup` workspace receives `resume.context.workflow_policy`; follow it as active agent policy: a shared dirty worktree and concurrent stages are expected, stages do not own files or commits, and ready work should be captured promptly into an explicit candidate; prefer an `exact` candidate when safely separable, use `shared_foundation` when several stages use one coherent change, and use `integration` when intertwined changes form one reviewable and testable result; mixed provenance and complete files containing unrelated stage work are not reasons to require prior commits or stop; stop only for a concrete patch conflict, an incoherent candidate boundary, or failed required verification
117
+ - when stage execution state exists, `resume.context.execution_state` is the current stage-local operational checkpoint; continue from it without rewriting the original prompt, and never copy it automatically into workspace knowledge or unrelated stages
118
+ - Planning-stage resume may include `resume.context.delivery_context`, a bounded workspace-level summary of committed candidates and environment checkpoints; it is release coordination context, not stage ownership
119
+ - when the user asks how to deploy from Planning, inspect the exact commit range and the repository's own deployment documentation, scripts, infrastructure, migrations, container definitions, configuration examples, and CI; produce ordered prerequisites, deployment, verification, rollback, and unresolved blockers instead of assuming that push or one generic command is sufficient
120
+ - delivery planning must never persist secret values; mention only required secret or configuration names, ask one focused question when environment or baseline is ambiguous, and never mark delivery merely because commit, push, or CI succeeded
121
+ - an associated OpenCode session resumed in a `startup` workspace receives `resume.context.workflow_policy`; follow it as active agent policy: a shared dirty worktree and concurrent stages are expected, stages do not own files or commits, and ready work should be captured promptly into an explicit candidate; once a coherent commit intent exists, create or refresh its draft candidate before switching stages or handing off; on resume inspect `resume.context.pending_candidates` before creating a duplicate or another commit boundary; prefer an `exact` candidate when safely separable, use `shared_foundation` when several stages use one coherent change, and use `integration` when intertwined changes form one reviewable and testable result; mixed provenance and complete files containing unrelated stage work are not reasons to require prior commits or stop; stop only for a concrete patch conflict, an incoherent candidate boundary, or failed required verification
104
122
  - standard-mode and unassociated core sessions do not receive startup policy; retain the existing conservative worktree behavior there
105
123
  - after presenting the summary, continue work immediately when `resume.next_action` is `start_work`; do not ask for generic confirmation
106
124
  - a stage may require confirmation only with an exact standalone `RESUME_CONFIRMATION: required` line in its saved prompt; when `resume.next_action` is `await_confirmation`, present the summary and wait before inspecting or modifying application code
@@ -114,10 +132,12 @@ Supported syntax:
114
132
  - automatic completion is allowed only when the current workspace's Planning-stage prompt contains an exact standalone line `AUTO_STAGE_FINISH: allowed`; otherwise leave the stage in progress and report that the work is ready for the user's lifecycle decision
115
133
  - `stage finish` closes and completes only the current stage session; it never starts, resumes, or binds the same OpenCode session to a downstream stage
116
134
  - `stage finish` always validates the Knowledge Base and returns total and active entry counts plus downstream unfinished stages for informational prompt review; do not begin a downstream stage until the user explicitly resumes it in a separate OpenCode session
135
+ - execution checklist state never finishes a stage; explicit `stage finish` reports remaining items, blockers, and pending verification as warnings and preserves the final execution record for history
117
136
  - `stage reopen <workspace> <stage> "reason"` applies only to a completed stage, preserves its result and completion history, records the reason, changes it to `in_progress`, and does not start a session or affect downstream stages; use an explicit separate-session `resume` to work on it again
118
137
  - `stage restore <workspace> <stage> "reason"` applies only to an archived stage and restores its saved pre-archive status. New archives preserve that status; legacy archives restore to `in_progress`. It records the reason, preserves stage content and results, does not start a session, and requires explicit separate-session `resume` when restored to `planned` or `in_progress`.
119
138
  - `workspace reopen <workspace> "reason"` applies only to a completed workspace, changes it to `in_progress`, and records durable recovery history. Cancelled workspaces cannot be reopened.
120
- - candidate operations require `startup` workflow mode and store metadata and patch payloads only under `.work-context/local/`; create accepts an optional strategy and related stages, which are normalized references for traceability only and never ownership or lifecycle; capture requires exactly one explicit list of complete paths or one Git unified patch and never infers stage ownership; commit requires a ready candidate, uses its stored message unless a non-empty override is supplied, serializes Git publication, bypasses hooks and signing, and never uses the ordinary Git index
139
+ - candidate operations require `startup` workflow mode and store metadata and patch payloads only under `.work-context/local/`; create accepts an optional strategy and related stages, which are normalized references for traceability only and never ownership or lifecycle; active candidates explicitly related to the resumed stage appear as bounded metadata in `resume.context.pending_candidates` and in expanded sidebar details; capture requires exactly one explicit list of complete paths or one Git unified patch and never infers stage ownership; commit requires a ready candidate, uses its stored message unless a non-empty override is supplied, serializes Git publication, bypasses hooks and signing, and never uses the ordinary Git index
140
+ - delivery operations are mode-neutral local operational state and never execute deployment; `delivery read` without a range returns metadata only, exact Git inspection requires both immutable `from` and `to` hashes, and `delivery mark` requires the exact `DELIVERY_CONFIRMED` token only after the user confirms successful delivery to that environment
121
141
  - `knowledge list|add|update|supersede <workspace> ...`
122
142
 
123
143
  Arguments: $ARGUMENTS
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "opencode-work-context",
3
3
  "type": "module",
4
- "version": "0.7.0",
4
+ "version": "0.9.0",
5
5
  "description": "Filesystem work-context core and OpenCode adapter",
6
6
  "license": "MIT",
7
7
  "author": {
@@ -7,6 +7,7 @@ import { createAttentionActivator } from "./attention-activation.js";
7
7
  import { createDesktopNotifier } from "./notifier.js";
8
8
  import { createTuiFocusTracker } from "./tui-focus.js";
9
9
  import { readTuiState, updateTuiState } from "./tui-state.js";
10
+ import { resolveProjectRoot } from "./project-root.js";
10
11
 
11
12
  const ATTENTION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
12
13
  const MAX_SEEN_EVENTS = 500;
@@ -489,7 +490,7 @@ export const createAttentionTuiController = ({ api, projectRoot, read = readWork
489
490
  export const tui = async (api, options = {}) => {
490
491
  if (!api?.event?.on) return;
491
492
  if (activeControllers.has(api) || api[ACTIVE_ATTENTION_KEY]) return activeControllers.get(api) || api[ACTIVE_ATTENTION_KEY];
492
- const projectRoot = api.state?.path?.worktree || api.state?.path?.directory;
493
+ const projectRoot = await resolveProjectRoot(api, options);
493
494
  if (!projectRoot) return;
494
495
  const ownsDesktopNotifier = !options.desktopNotifier;
495
496
  const desktopNotifier = options.desktopNotifier || createDesktopNotifier({ enabled: desktopNotificationsEnabled(projectRoot), ...options.notifierOptions });
@@ -0,0 +1,49 @@
1
+ const PATH_TIMEOUT_MS = 5000;
2
+ const PATH_POLL_MS = 25;
3
+ const usableDirectory = (value) => typeof value === "string" && value && value !== "/";
4
+
5
+ const sleep = (milliseconds, signal) => new Promise((resolve) => {
6
+ const timer = setTimeout(resolve, milliseconds);
7
+ const onAbort = () => { clearTimeout(timer); resolve(); };
8
+ signal?.addEventListener("abort", onAbort, { once: true });
9
+ if (signal) setTimeout(() => signal.removeEventListener("abort", onAbort), milliseconds);
10
+ });
11
+
12
+ const locationWithDeadline = (api, timeoutMs, signal) => new Promise((resolve) => {
13
+ let settled = false;
14
+ const finish = (value) => {
15
+ if (settled) return;
16
+ settled = true;
17
+ clearTimeout(timer);
18
+ signal?.removeEventListener("abort", onAbort);
19
+ resolve(value);
20
+ };
21
+ const timer = setTimeout(() => finish(null), timeoutMs);
22
+ const onAbort = () => finish(null);
23
+ signal?.addEventListener("abort", onAbort, { once: true });
24
+ Promise.resolve().then(() => api.client.location.get({})).then(finish, () => finish(null));
25
+ });
26
+
27
+ export const resolveProjectRoot = async (api, { timeoutMs = PATH_TIMEOUT_MS, pollMs = PATH_POLL_MS } = {}) => {
28
+ const directory = api?.state?.path?.directory;
29
+ if (!usableDirectory(api?.state?.path?.worktree) && usableDirectory(directory)) return directory;
30
+ if (!api?.state?.path && !api?.client?.location?.get) return null;
31
+ const signal = api?.lifecycle?.signal;
32
+ const deadline = Date.now() + timeoutMs;
33
+ while (!signal?.aborted && Date.now() <= deadline) {
34
+ const worktree = api?.state?.path?.worktree;
35
+ if (usableDirectory(worktree)) return worktree;
36
+ if (usableDirectory(directory)) return directory;
37
+ const remaining = deadline - Date.now();
38
+ if (remaining <= 0) break;
39
+ const location = await locationWithDeadline(api, remaining, signal);
40
+ const locationDirectory = location?.data?.directory || location?.data?.project?.directory;
41
+ if (usableDirectory(locationDirectory)) return locationDirectory;
42
+ await sleep(pollMs, signal);
43
+ }
44
+ return null;
45
+ };
46
+
47
+ export const withProjectRoot = (api, projectRoot) => projectRoot
48
+ ? Object.assign(Object.create(api), { state: { ...api.state, path: { ...api.state?.path, directory: projectRoot, worktree: projectRoot } } })
49
+ : api;
@@ -8,13 +8,12 @@ import { createSignal } from "solid-js";
8
8
  import { attentionSummaryText } from "./attention.js";
9
9
  import { createStageSwitcherFlow } from "./stage-switcher.js";
10
10
  import { readTuiState, updateTuiState } from "./tui-state.js";
11
+ import { resolveProjectRoot, withProjectRoot } from "./project-root.js";
11
12
 
12
13
  const DEBOUNCE_MS = 150;
13
14
  const POLL_MS = 1000;
14
15
  const LOADER_MS = 80;
15
16
  const LOADER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
16
- const PATH_TIMEOUT_MS = 5000;
17
- const PATH_POLL_MS = 25;
18
17
  const WORK_CONTEXT_PREFIX = "work" + "_" + "context_";
19
18
  const activeTuiInstances = new WeakMap();
20
19
  const ACTIVE_TUI_KEY = Symbol.for("opencode-work-context.stages-tui");
@@ -36,8 +35,28 @@ const trackerLinkText = (link) => {
36
35
  return `JIRA ${identifier}`;
37
36
  };
38
37
  const candidateSummaryText = (workspace) => workspace.candidates && (workspace.candidates.pending || workspace.candidates.ready)
39
- ? `Candidates · pending ${workspace.candidates.pending} · ready ${workspace.candidates.ready}`
38
+ ? `Candidates · ${workspace.candidates.pending} draft · ${workspace.candidates.ready} ready`
40
39
  : null;
40
+ const deliverySummaryText = (workspace) => {
41
+ const delivery = workspace.delivery;
42
+ if (!delivery) return null;
43
+ if (delivery.unavailable) return "Delivery · unavailable";
44
+ if (delivery.plan_needed) return `Delivery · ${delivery.committed} commits · plan needed`;
45
+ if (delivery.environments.length === 1) {
46
+ const [environment] = delivery.environments;
47
+ return `Delivery · ${environment.environment} · ${environment.pending} tracked pending`;
48
+ }
49
+ const pending = delivery.environments.reduce((total, environment) => total + environment.pending, 0);
50
+ return `Delivery · ${delivery.environments.length} environments · ${pending} tracked pending`;
51
+ };
52
+ const stageCandidateText = (stage) => {
53
+ const projection = stage.candidates;
54
+ if (!projection || !(projection.draft || projection.ready)) return null;
55
+ if (projection.draft + projection.ready > 1) return `Pending: ${projection.draft} draft · ${projection.ready} ready`;
56
+ const [candidate] = projection.items;
57
+ const others = candidate.related_stages.filter((related) => related !== stage.id);
58
+ return `Pending: ${candidate.status} · ${candidate.strategy}${others.length ? ` · also ${others.join(", ")}` : ""}`;
59
+ };
41
60
 
42
61
  export { readStagesSnapshot, renderStagesPanel };
43
62
 
@@ -57,6 +76,7 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention,
57
76
  runtime.jsx("text", { fg: theme?.current?.textMuted, children: `Workflow · ${result.data.workspace.mode || "standard"}` }),
58
77
  workspaceAttention && runtime.jsx("text", { children: ["Attention · ", runtime.jsx("b", { children: workspaceAttention })] }),
59
78
  candidateSummaryText(result.data.workspace) && runtime.jsx("text", { fg: theme?.current?.textMuted, children: candidateSummaryText(result.data.workspace) }),
79
+ deliverySummaryText(result.data.workspace) && runtime.jsx("text", { fg: theme?.current?.textMuted, children: deliverySummaryText(result.data.workspace) }),
60
80
  ].filter(Boolean),
61
81
  }),
62
82
  runtime.jsx("box", {
@@ -69,10 +89,11 @@ const renderStagesContent = (result, theme, runtime = defaultRuntime, attention,
69
89
  ...result.data.stages.map((stage) => {
70
90
  const unread = attention?.attentionForStage?.(result.data.workspace.id, stage.id);
71
91
  const working = attention?.activityForStage?.(result.data.workspace.id, stage.id);
72
- const metadata = showDependencies ? [
92
+ const stageMetadata = [
73
93
  stage.tracker_links?.length && `Tasks: ${stage.tracker_links.map(trackerLinkText).join(", ")}`,
74
94
  stage.depends_on?.length && `Deps: ${stage.depends_on.join(", ")}`,
75
- ].filter(Boolean).join(" · ") : "";
95
+ ].filter(Boolean).join(" · ");
96
+ const metadata = showDependencies ? [stageMetadata, stageCandidateText(stage)].filter(Boolean).join("\n") : "";
76
97
  const attentionSignal = attentionSummaryText(unread);
77
98
  const stageText = [
78
99
  `${stage.id}. ${stage.title}`,
@@ -262,28 +283,7 @@ export const createStagesTuiController = ({ projectRoot, read = readStagesSnapsh
262
283
  };
263
284
  };
264
285
 
265
- const sleep = (milliseconds, signal) => new Promise((resolve) => {
266
- const timer = setTimeout(resolve, milliseconds);
267
- const onAbort = () => { clearTimeout(timer); resolve(); };
268
- signal?.addEventListener("abort", onAbort, { once: true });
269
- if (signal) setTimeout(() => signal.removeEventListener("abort", onAbort), milliseconds);
270
- });
271
-
272
- export const resolveProjectRoot = async (api, { timeoutMs = PATH_TIMEOUT_MS, pollMs = PATH_POLL_MS } = {}) => {
273
- if (!api?.slots?.register) return null;
274
- const signal = api.lifecycle?.signal;
275
- const deadline = Date.now() + timeoutMs;
276
- while (!signal?.aborted && Date.now() <= deadline) {
277
- if (api.state?.path?.worktree) return api.state.path.worktree;
278
- try {
279
- const location = await api.client?.location?.get?.({});
280
- const directory = location?.data?.directory || location?.data?.project?.directory;
281
- if (directory) return directory;
282
- } catch {}
283
- await sleep(pollMs, signal);
284
- }
285
- return null;
286
- };
286
+ export { resolveProjectRoot } from "./project-root.js";
287
287
 
288
288
  const renderStagesSlot = (controller, theme, sessionId, runtime = defaultRuntime, attention, onStageSelect) => runtime.jsx("box", {
289
289
  flexDirection: "column",
@@ -308,8 +308,8 @@ const registerDependencyToggle = (api, controller, projectRoot) => {
308
308
  if (typeof api?.keymap?.registerLayer !== "function") return () => {};
309
309
  const command = {
310
310
  name: DEPENDENCIES_COMMAND,
311
- title: "Toggle sidebar dependencies",
312
- desc: "Show or hide dependency IDs in the stages sidebar",
311
+ title: "Toggle sidebar details",
312
+ desc: "Show or hide stage tasks, dependencies, and pending candidates",
313
313
  category: "Work Context",
314
314
  namespace: "palette",
315
315
  run: () => {
@@ -376,8 +376,10 @@ const ACTIVE_WORKSPACE_SESSION = "__active_" + "work" + "_context_workspace__";
376
376
  // Optional TUI entry point. It is deliberately not imported by the server plugin.
377
377
  export const tui = async (api, options = {}) => {
378
378
  if (activeTuiInstances.has(api) || api?.[ACTIVE_TUI_KEY]) return activeTuiInstances.get(api) || api[ACTIVE_TUI_KEY];
379
+ if (!api?.slots?.register) return;
379
380
  const projectRoot = await resolveProjectRoot(api, options);
380
381
  if (!projectRoot) return;
382
+ const projectApi = withProjectRoot(api, projectRoot);
381
383
 
382
384
  const initialSessionId = api.route?.current?.name === "session"
383
385
  ? api.route.current.params?.sessionID
@@ -393,7 +395,7 @@ export const tui = async (api, options = {}) => {
393
395
  createSignal: options.runtime?.createSignal,
394
396
  attention: api.workContextAttention,
395
397
  });
396
- const stageSwitcher = createStageSwitcherFlow(api);
398
+ const stageSwitcher = createStageSwitcherFlow(projectApi);
397
399
  const unregisterDependencyToggle = registerDependencyToggle(api, controller, projectRoot);
398
400
  let currentSessionId = initialSessionId;
399
401
  const unregisterDependencyTree = registerDependencyTree(api, controller, () => currentSessionId || ACTIVE_WORKSPACE_SESSION);
@@ -8,6 +8,7 @@ import { openStageSwitcher } from "./stage-switcher.js";
8
8
  import { openWorkspaceSwitcher } from "./workspace-switcher.js";
9
9
  import { openSessionSwitcher } from "./session-switcher.js";
10
10
  import { attentionForSession, attentionIndicatorText, attentionReasonText } from "./attention.js";
11
+ import { resolveProjectRoot, withProjectRoot } from "./project-root.js";
11
12
 
12
13
  const COMMAND_NAME = "work_context.open";
13
14
  const ACTIONS_COMMAND_NAME = "work_context.actions";
@@ -585,13 +586,14 @@ export const openCompatibilityDialog = (api, runtime = {}, options = {}) => {
585
586
  return true;
586
587
  };
587
588
 
588
- export const registerWorkContextModal = (api, runtime = {}) => {
589
+ export const registerWorkContextModal = (api, runtime = {}, options = {}) => {
589
590
  if (typeof api?.keymap?.registerLayer !== "function") return { supported: false, dispose: () => {} };
590
- const command = { name: COMMAND_NAME, title: "Open Work Context", desc: "Open work-context navigation and actions", category: "Work Context", namespace: "palette", run: () => openWorkContextActionDialog(api, runtime) };
591
- const stageCommand = { name: "work_context.stage", title: "Switch Work Context Stage", desc: "Open a stage session in the current workspace", category: "Work Context", namespace: "palette", run: () => openStageSwitcher(api) };
592
- const workspaceCommand = { name: "work_context.workspace", title: "Switch Work Context Workspace", desc: "Open a workspace session", category: "Work Context", namespace: "palette", run: () => openWorkspaceSwitcher(api) };
593
- const sessionCommand = { name: "work_context.session", title: "Switch Work Context Session", desc: "Open an active or historical work session", category: "Work Context", namespace: "palette", run: () => openSessionSwitcher(api) };
594
- const actions = { name: ACTIONS_COMMAND_NAME, title: "Open Work Context Actions", desc: "Prepare a work-context command", category: "Work Context", namespace: "palette", run: () => openWorkContextActionDialog(api, runtime) };
591
+ const projectApi = withProjectRoot(api, options.projectRoot);
592
+ const command = { name: COMMAND_NAME, title: "Open Work Context", desc: "Open work-context navigation and actions", category: "Work Context", namespace: "palette", run: () => openWorkContextActionDialog(projectApi, runtime) };
593
+ const stageCommand = { name: "work_context.stage", title: "Switch Work Context Stage", desc: "Open a stage session in the current workspace", category: "Work Context", namespace: "palette", run: () => openStageSwitcher(projectApi) };
594
+ const workspaceCommand = { name: "work_context.workspace", title: "Switch Work Context Workspace", desc: "Open a workspace session", category: "Work Context", namespace: "palette", run: () => openWorkspaceSwitcher(projectApi) };
595
+ const sessionCommand = { name: "work_context.session", title: "Switch Work Context Session", desc: "Open an active or historical work session", category: "Work Context", namespace: "palette", run: () => openSessionSwitcher(projectApi) };
596
+ const actions = { name: ACTIONS_COMMAND_NAME, title: "Open Work Context Actions", desc: "Prepare a work-context command", category: "Work Context", namespace: "palette", run: () => openWorkContextActionDialog(projectApi, runtime) };
595
597
  const registration = api.keymap.registerLayer({
596
598
  commands: [command, stageCommand, workspaceCommand, sessionCommand, actions],
597
599
  bindings: [
@@ -606,7 +608,10 @@ export const registerWorkContextModal = (api, runtime = {}) => {
606
608
 
607
609
  export const tui = async (api, options = {}) => {
608
610
  activeTuiInstances.get(api)?.();
609
- const registration = registerWorkContextModal(api, options.runtime || options);
611
+ if (typeof api?.keymap?.registerLayer !== "function") return;
612
+ const projectRoot = await resolveProjectRoot(api, options);
613
+ if (!projectRoot) return;
614
+ const registration = registerWorkContextModal(api, options.runtime || options, { projectRoot });
610
615
  if (!registration.supported) return;
611
616
  let disposed = false;
612
617
  const cleanup = () => {
package/src/candidates.js CHANGED
@@ -8,6 +8,9 @@ import { capturePatch, capturePaths, commitPatch, previewPatch, repositoryState
8
8
  const candidatePattern = /^CC-(\d{6})$/;
9
9
  const statuses = new Set(["draft", "ready", "discarded", "committed"]);
10
10
  const strategies = new Set(["exact", "shared_foundation", "integration"]);
11
+ const projectionCandidateLimit = 10;
12
+ const projectionTitleLimit = 120;
13
+ const deliveryCandidateLimit = 20;
11
14
  const timestamp = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
12
15
  const metadataKeys = ["schema", "candidate", "workspace", "title", "message", "base_head", "status", "created_at", "updated_at", "selected_paths", "patch_file"];
13
16
  const optionalMetadataKeys = ["strategy", "related_stages"];
@@ -106,11 +109,63 @@ export class CandidateStore {
106
109
  }
107
110
 
108
111
  summary(workspace) {
109
- return this.list(workspace).reduce((summary, candidate) => {
110
- if (candidate.status === "draft") summary.pending += 1;
111
- if (candidate.status === "ready") summary.ready += 1;
112
- return summary;
113
- }, { pending: 0, ready: 0 });
112
+ return this.activeProjection(workspace).summary;
113
+ }
114
+
115
+ projectionRecords(workspace) {
116
+ workspace = normalizeWorkspaceId(workspace);
117
+ this.context.storage.readWorkspace(workspace);
118
+ if (!fs.existsSync(this.directory)) return [];
119
+ return fs.readdirSync(this.directory)
120
+ .filter((file) => candidatePattern.test(file.slice(0, -5)) && file.endsWith(".json"))
121
+ .sort()
122
+ .flatMap((file) => {
123
+ try {
124
+ const data = JSON.parse(fs.readFileSync(path.join(this.directory, file), "utf8"));
125
+ if (data?.workspace !== workspace) return [];
126
+ return [validateCandidate(data, file.slice(0, -5))];
127
+ } catch { return []; }
128
+ });
129
+ }
130
+
131
+ activeProjection(workspace) {
132
+ const projection = { summary: { pending: 0, ready: 0 }, by_stage: {} };
133
+ workspace = this.assertStartup(workspace);
134
+ for (const candidate of this.projectionRecords(workspace)) {
135
+ if (!["draft", "ready"].includes(candidate.status)) continue;
136
+ if (candidate.status === "draft") projection.summary.pending += 1;
137
+ if (candidate.status === "ready") projection.summary.ready += 1;
138
+ const related = {
139
+ candidate: candidate.candidate,
140
+ title: candidate.title.slice(0, projectionTitleLimit),
141
+ status: candidate.status,
142
+ strategy: candidate.strategy || "exact",
143
+ related_stages: candidate.related_stages || [],
144
+ };
145
+ for (const stage of related.related_stages) {
146
+ const stageProjection = projection.by_stage[stage] ||= { draft: 0, ready: 0, items: [] };
147
+ stageProjection[candidate.status] += 1;
148
+ if (stageProjection.items.length < projectionCandidateLimit) stageProjection.items.push(related);
149
+ }
150
+ }
151
+ return projection;
152
+ }
153
+
154
+ committedProjection(workspace) {
155
+ const records = this.projectionRecords(workspace)
156
+ .filter((candidate) => candidate.status === "committed")
157
+ .sort((left, right) => left.committed_at.localeCompare(right.committed_at) || left.candidate.localeCompare(right.candidate));
158
+ return {
159
+ count: records.length,
160
+ items: records.slice(-deliveryCandidateLimit).map((candidate) => ({
161
+ candidate: candidate.candidate,
162
+ title: candidate.title.slice(0, projectionTitleLimit),
163
+ strategy: candidate.strategy || "exact",
164
+ related_stages: candidate.related_stages || [],
165
+ commit_hash: candidate.commit_hash,
166
+ committed_at: candidate.committed_at,
167
+ })),
168
+ };
114
169
  }
115
170
 
116
171
  capture(workspace, id, input) {