@uniqbit/mate-core 1.0.0-canary.2 → 1.0.0-canary.5

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.
Files changed (189) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +1 -1
  2. package/claude-plugin/hooks/hooks.json +21 -1
  3. package/claude-plugin/hooks/session-attention.mjs +10 -0
  4. package/claude-plugin/hooks/session-end.mjs +9 -0
  5. package/claude-plugin/hooks/session-guidance.mjs +1 -1
  6. package/opencode-plugin/src/server.ts +13 -2
  7. package/opencode-plugin/src/tui.tsx +1 -1
  8. package/opencode-plugin/tui.tsx +2 -1
  9. package/package.json +1 -1
  10. package/src/cli/commands/artifact/delivery/archive.ts +2 -2
  11. package/src/cli/commands/artifact/delivery/link.ts +22 -5
  12. package/src/cli/commands/artifact/delivery/output.ts +9 -1
  13. package/src/cli/commands/artifact/finish/openspec.ts +1 -3
  14. package/src/cli/commands/companion/companion.ts +1 -1
  15. package/src/cli/commands/companion/link.ts +36 -4
  16. package/src/cli/commands/companion/open.ts +40 -12
  17. package/src/cli/commands/doctor.ts +122 -0
  18. package/src/cli/commands/session/prepare.ts +32 -4
  19. package/src/cli/commands/session/registry.ts +90 -0
  20. package/src/cli/commands/studio/companion-removal.ts +79 -0
  21. package/src/cli/commands/studio/mate-inventory.ts +1 -1
  22. package/src/cli/commands/studio/payload.ts +12 -1
  23. package/src/cli/commands/studio/server.ts +39 -16
  24. package/src/cli/commands/studio/services.ts +20 -0
  25. package/src/cli/commands/studio/skill-files.ts +133 -0
  26. package/src/cli/commands/studio/vault.ts +218 -44
  27. package/src/cli/commands/studio/views/model.ts +0 -5
  28. package/src/cli/commands/studio/views/vault/markdown-tree.ts +255 -4
  29. package/src/cli/commands/unwrap.ts +8 -0
  30. package/src/cli/commands/update.ts +26 -8
  31. package/src/cli/commands/vscode/setup.ts +155 -0
  32. package/src/cli/commands/vscode/vsix.ts +73 -0
  33. package/src/cli/commands/working/cleanup.ts +34 -10
  34. package/src/cli/commands/working/worktree.ts +58 -8
  35. package/src/cli/commands/wrap.ts +33 -7
  36. package/src/cli/main.ts +9 -2
  37. package/src/cli/usage.ts +6 -1
  38. package/src/hooks/companion-instructions.ts +19 -11
  39. package/src/hooks/hook-io.ts +15 -0
  40. package/src/hooks/session-banner.ts +5 -3
  41. package/src/hooks/session-end.ts +10 -0
  42. package/src/hooks/session-guidance.ts +10 -6
  43. package/src/hooks/session-prepare.ts +47 -31
  44. package/src/hooks/session-register.ts +199 -0
  45. package/src/hooks/tokensave-route.ts +7 -3
  46. package/src/hooks/validate-artifact-path.ts +9 -2
  47. package/src/lib/delivery/archive-change.ts +0 -1
  48. package/src/lib/delivery/branches.ts +15 -0
  49. package/src/lib/delivery/record-delivery.ts +94 -39
  50. package/src/lib/delivery/record.ts +30 -28
  51. package/src/lib/delivery/refresh.ts +37 -17
  52. package/src/lib/delivery/resolve-branch.ts +258 -37
  53. package/src/lib/factory/outcomes/index.ts +11 -1
  54. package/src/lib/factory/runtime.ts +10 -1
  55. package/src/lib/opencode-server.ts +238 -0
  56. package/src/lib/orchestrator/adapters/claude.ts +147 -2
  57. package/src/lib/orchestrator/adapters/opencode.ts +53 -2
  58. package/src/lib/orchestrator/checkout-adoption.ts +125 -0
  59. package/src/lib/orchestrator/companion-registry-store.ts +6 -2
  60. package/src/lib/orchestrator/editor.ts +2 -2
  61. package/src/lib/orchestrator/framework-context.ts +26 -14
  62. package/src/lib/orchestrator/global-config-store.ts +11 -0
  63. package/src/lib/orchestrator/launcher.ts +15 -2
  64. package/src/lib/orchestrator/projection-claude-links.ts +52 -5
  65. package/src/lib/orchestrator/projection-claude-skills.ts +28 -2
  66. package/src/lib/orchestrator/projection-companion-link.ts +12 -1
  67. package/src/lib/orchestrator/registry-checkouts.ts +177 -0
  68. package/src/lib/orchestrator/repository-link.ts +216 -57
  69. package/src/lib/orchestrator/serving-claude-wrap.ts +43 -0
  70. package/src/lib/orchestrator/session-context-link.ts +11 -5
  71. package/src/lib/orchestrator/session-prepare.ts +36 -6
  72. package/src/lib/orchestrator/types.ts +5 -0
  73. package/src/lib/orchestrator/workspace-inventory.ts +5 -1
  74. package/src/lib/public-npm.ts +17 -0
  75. package/src/lib/session-attribution.ts +52 -0
  76. package/src/lib/session-state.ts +285 -0
  77. package/src/lib/session-stop.ts +64 -0
  78. package/src/lib/workset/record.ts +20 -0
  79. package/src/lib/workset/worktree.ts +85 -17
  80. package/src/opencode/background-server.ts +145 -0
  81. package/src/opencode/companion-hooks.ts +3 -1
  82. package/src/opencode/companion-policy.ts +2 -2
  83. package/src/opencode/projected-guidance.ts +2 -1
  84. package/src/opencode/session-register.ts +176 -0
  85. package/src/opencode/tui.tsx +19 -29
  86. package/src/runtime/claude-delivery-plan.ts +14 -3
  87. package/src/runtime/current-branch.ts +10 -0
  88. package/src/runtime/env.ts +13 -7
  89. package/src/runtime/git-layout.ts +164 -17
  90. package/src/runtime/launch-env-guard.ts +65 -0
  91. package/src/runtime/opencode-server-record.ts +136 -0
  92. package/src/runtime/projection.ts +40 -6
  93. package/src/runtime/repo-local.ts +6 -1
  94. package/src/runtime/serving-claude-wrap.ts +28 -0
  95. package/src/runtime/session-context.ts +4 -3
  96. package/src/runtime/session-registry.ts +434 -0
  97. package/src/runtime/tokensave-route.ts +10 -5
  98. package/src/runtime/wrap-state.ts +31 -0
  99. package/src/studio.ts +2 -0
  100. package/src/templates/mate-skills/agents/mate-apply-change/SKILL.md +49 -21
  101. package/src/templates/mate-skills/agents/mate-archive-change/SKILL.md +0 -5
  102. package/src/templates/mate-skills/agents/mate-propose-change/SKILL.md +2 -8
  103. package/src/templates/mate-skills/agents/mate-propose-change/references/mate-revise.md +1 -3
  104. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +2 -4
  105. package/src/templates/mate-skills/claude/mate-apply-change/SKILL.md +49 -21
  106. package/src/templates/mate-skills/claude/mate-archive-change/SKILL.md +0 -5
  107. package/src/templates/mate-skills/claude/mate-propose-change/SKILL.md +2 -8
  108. package/src/templates/mate-skills/claude/mate-propose-change/references/mate-revise.md +1 -3
  109. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +2 -4
  110. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +404 -30
  111. package/src/tools/setup/dynamic-plugins/hydrate.ts +4 -3
  112. package/src/tools/setup/providers/claude-plugin-hooks.ts +26 -0
  113. package/src/tools/setup/providers/claude.ts +21 -1
  114. package/studio-dist/client/assets/app-CdPiFv59.css +2 -0
  115. package/studio-dist/client/assets/button-BIIHE0EQ.js +3 -0
  116. package/studio-dist/client/assets/companion-view-DM6YyXaR.js +1 -0
  117. package/studio-dist/client/assets/delivery-path-DELxj0Av.js +1 -0
  118. package/studio-dist/client/assets/factory-BZy0E8ty.js +4 -0
  119. package/studio-dist/client/assets/index-B3wkMzjA.js +40 -0
  120. package/studio-dist/client/assets/markdown-view-pQ2Qp_i5.js +1 -0
  121. package/studio-dist/client/assets/panel-CbajlC3p.js +1 -0
  122. package/studio-dist/client/assets/{prepaint-CD5OpmTM.js → prepaint-CwSrpdFA.js} +7 -4
  123. package/studio-dist/client/assets/react-CN2GSx7x.js +1 -0
  124. package/studio-dist/client/assets/reports-DllhYQ5_.js +1 -0
  125. package/studio-dist/client/assets/routes-COm-G3mK.js +1 -0
  126. package/studio-dist/client/assets/skills-DmWAy-jZ.js +1 -0
  127. package/studio-dist/client/assets/specs-BG3Wi3ln.js +1 -0
  128. package/studio-dist/client/assets/steps-DFsH3Neu.js +1 -0
  129. package/studio-dist/client/assets/vault-B2q1nBY5.js +1 -0
  130. package/studio-dist/client/assets/warnings-BSXIyuSQ.js +1 -0
  131. package/studio-dist/client/assets/workflow-DlsQD6Hc.js +1 -0
  132. package/studio-dist/server/assets/{__23tanstack-start-server-fn-resolver-BQKuMdJW.js → __23tanstack-start-server-fn-resolver-M2GBs8s3.js} +179 -9
  133. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +35 -25
  134. package/studio-dist/server/assets/button-CIJqAhni.js +11929 -0
  135. package/studio-dist/server/assets/{companion-view-aBady57v.js → companion-view-DISASvdJ.js} +13 -7
  136. package/studio-dist/server/assets/companions-BYbHWKOZ.js +15 -0
  137. package/studio-dist/server/assets/delivery-path-C29fBynY.js +654 -0
  138. package/studio-dist/server/assets/{factory-DT3UzHlh.js → factory-DGPmNGbo.js} +1 -0
  139. package/studio-dist/server/assets/{factory-D6xnjedJ.js → factory-DUTa0eDs.js} +317 -530
  140. package/studio-dist/server/assets/markdown-view-Bn7xPdks.js +86 -0
  141. package/studio-dist/server/assets/panel-3Jmn4awF.js +169 -0
  142. package/studio-dist/server/assets/{prepaint-BMke0fo1.js → prepaint-DJfTQ_VH.js} +6 -2
  143. package/studio-dist/server/assets/{react-COs0LHn-.js → react-Ce6dj15C.js} +4 -9
  144. package/studio-dist/server/assets/reports-C06RXVE2.js +18 -0
  145. package/studio-dist/server/assets/reports-D6YMqhnO.js +142 -0
  146. package/studio-dist/server/assets/router-C8MGqlAY.js +13713 -0
  147. package/studio-dist/server/assets/routes-BcFgvqf7.js +622 -0
  148. package/studio-dist/server/assets/{shell-CboT2f66.js → shell-DS3wUexh.js} +1 -0
  149. package/studio-dist/server/assets/skills-BEnOxiDl.js +266 -0
  150. package/studio-dist/server/assets/skills-CtrBAtX3.js +28 -0
  151. package/studio-dist/server/assets/specs-C8rv34-5.js +211 -0
  152. package/studio-dist/server/assets/{start-BW5ovN0k.js → start-h3ICWwd2.js} +4 -1
  153. package/studio-dist/server/assets/steps-Dq_CwY_s.js +181 -0
  154. package/studio-dist/server/assets/{vault-BGulVoNh.js → vault-BmWnryh3.js} +16 -1
  155. package/studio-dist/server/assets/vault-Fvxt2Tzl.js +1032 -0
  156. package/studio-dist/server/assets/{views-Bd7cRr27.js → views-BgYa-za2.js} +1 -3
  157. package/studio-dist/server/assets/warnings-DzR6fyZh.js +23 -0
  158. package/studio-dist/server/assets/workflow-liRYecHk.js +73 -0
  159. package/studio-dist/server/server.js +3 -157
  160. package/studio-dist/client/assets/companion-view-Csva26Ir.js +0 -1
  161. package/studio-dist/client/assets/delivery-path-DJMpRmiY.js +0 -1
  162. package/studio-dist/client/assets/factory-B7l9ZQyx.js +0 -4
  163. package/studio-dist/client/assets/index-n6uo_92S.js +0 -40
  164. package/studio-dist/client/assets/queries-CN3JwMBX.js +0 -1
  165. package/studio-dist/client/assets/react-CabXf2Ds.js +0 -1
  166. package/studio-dist/client/assets/report-time-Dc-KOqQu.js +0 -1
  167. package/studio-dist/client/assets/reports-C01RsnMA.js +0 -1
  168. package/studio-dist/client/assets/routes-4pbC-2Hj.js +0 -1
  169. package/studio-dist/client/assets/skills-CihQganl.js +0 -1
  170. package/studio-dist/client/assets/spec-areas-C2L48N4C.js +0 -1
  171. package/studio-dist/client/assets/specs-D24_35_K.js +0 -1
  172. package/studio-dist/client/assets/studio-DKxfi691.css +0 -1
  173. package/studio-dist/client/assets/studio-queries-rvbJupCy.js +0 -3
  174. package/studio-dist/client/assets/vault-Bd4CQiTK.js +0 -1
  175. package/studio-dist/client/assets/warnings-V_Ys51wJ.js +0 -1
  176. package/studio-dist/client/assets/workflow-BJejeVwQ.js +0 -1
  177. package/studio-dist/server/assets/delivery-path-BkKNjgkf.js +0 -778
  178. package/studio-dist/server/assets/queries-Ag2iL8q2.js +0 -107
  179. package/studio-dist/server/assets/report-time-DAfzln-N.js +0 -8
  180. package/studio-dist/server/assets/reports-BnUNJVtx.js +0 -126
  181. package/studio-dist/server/assets/router-BH--drIx.js +0 -4298
  182. package/studio-dist/server/assets/routes-khSDK1bV.js +0 -361
  183. package/studio-dist/server/assets/skills-MWYnWoKs.js +0 -106
  184. package/studio-dist/server/assets/spec-areas-DcnO6vW-.js +0 -16
  185. package/studio-dist/server/assets/specs-DE3w8hZP.js +0 -155
  186. package/studio-dist/server/assets/studio-queries-CLnP9kGu.js +0 -3365
  187. package/studio-dist/server/assets/vault-CuyyhLyB.js +0 -832
  188. package/studio-dist/server/assets/warnings-BH05rOuG.js +0 -15
  189. package/studio-dist/server/assets/workflow-BSuIKWqH.js +0 -42
@@ -104,6 +104,23 @@ export async function fetchPublicPackageVersion(
104
104
  return stdout.trim();
105
105
  }
106
106
 
107
+ /** `npm pack` a package from the public registry into `destination`; returns the tarball path. */
108
+ export async function packPublicPackage(
109
+ packageSpec: string,
110
+ destination: string,
111
+ registry = PUBLIC_NPM_REGISTRY,
112
+ ): Promise<string> {
113
+ const { stdout } = await withPublicNpmConfig(packageNameFromSpec(packageSpec), registry, (env) =>
114
+ publicNpmDeps.execFile("npm", ["pack", packageSpec, "--pack-destination", destination], {
115
+ timeout: 120_000,
116
+ env,
117
+ }),
118
+ );
119
+ const tarball = stdout.trim().split("\n").at(-1)?.trim();
120
+ if (!tarball) throw new Error(`npm pack ${packageSpec} printed no tarball name`);
121
+ return path.join(destination, tarball);
122
+ }
123
+
107
124
  export function installPublicPackageSync(packageSpec: string, registry = PUBLIC_NPM_REGISTRY) {
108
125
  return withPublicNpmConfigSync(packageNameFromSpec(packageSpec), registry, (env) =>
109
126
  publicNpmDeps.spawnSync("npm", ["install", "-g", packageSpec], {
@@ -0,0 +1,52 @@
1
+ import fs from "node:fs/promises";
2
+
3
+ import {
4
+ patchSession,
5
+ type RegisteredSession,
6
+ type WriteOptions,
7
+ } from "../runtime/session-registry";
8
+
9
+ /**
10
+ * Records the change a command works on against the agent session it runs
11
+ * in. The session id comes from the runtime's own environment; outside an
12
+ * agent session, or for an unregistered id, nothing changes. Never throws.
13
+ */
14
+
15
+ /** Set by Claude Code and OpenCode for the processes their sessions start; undocumented. */
16
+ const SESSION_ID_VARIABLES = ["CLAUDE_CODE_SESSION_ID", "OPENCODE_SESSION_ID"] as const;
17
+
18
+ export function currentSessionId(env: Record<string, string | undefined>): string | null {
19
+ for (const name of SESSION_ID_VARIABLES) {
20
+ const value = env[name]?.trim();
21
+ if (value) return value;
22
+ }
23
+ return null;
24
+ }
25
+
26
+ export interface Attribution {
27
+ change: string;
28
+ /** The worktree the session is about to move to, with its branch. */
29
+ move?: { cwd: string; branch: string };
30
+ }
31
+
32
+ export async function attributeCurrentSession(
33
+ attribution: Attribution,
34
+ env: Record<string, string | undefined> = process.env,
35
+ options: WriteOptions = { lock: { waitMs: 2000 } },
36
+ ): Promise<RegisteredSession | null> {
37
+ const id = currentSessionId(env);
38
+ if (!id) return null;
39
+ try {
40
+ const cwd = attribution.move ? await fs.realpath(attribution.move.cwd) : undefined;
41
+ return await patchSession(
42
+ id,
43
+ {
44
+ change: attribution.change,
45
+ ...(attribution.move ? { cwd, branch: attribution.move.branch } : {}),
46
+ },
47
+ options,
48
+ );
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
@@ -0,0 +1,285 @@
1
+ import { execFile } from "node:child_process";
2
+ import fs from "node:fs/promises";
3
+
4
+ import { workingRepoGit } from "./delivery/branches";
5
+ import { mergeGit } from "./delivery/merge-git";
6
+ import { processAlive } from "../runtime/opencode-server-record";
7
+ import {
8
+ readSessionRegistry,
9
+ sessionRegistryPath,
10
+ sortSessions,
11
+ updateSessionRegistry,
12
+ type RegisteredSession,
13
+ type SessionActivity,
14
+ type WriteOptions,
15
+ } from "../runtime/session-registry";
16
+
17
+ /**
18
+ * `mate session list` view of the registry: each session's state, computed
19
+ * locally, plus pruning and label fill. Nothing here touches the network.
20
+ */
21
+
22
+ export type SessionState = "running" | "parked" | "done";
23
+
24
+ export interface ListedSession extends RegisteredSession {
25
+ state: SessionState;
26
+ activity?: SessionActivity;
27
+ /** Running Claude sessions: whether Claude's daemon runs it (`claude attach` and `claude stop` work). */
28
+ kind?: "interactive" | "background";
29
+ /** Running Claude background sessions: the id `claude attach` and `claude stop` take. */
30
+ daemonId?: string;
31
+ }
32
+
33
+ /** One entry of `claude agents --json`, as far as Mate reads it. */
34
+ export interface ClaudeAgent {
35
+ /** The daemon's short id of a background session. */
36
+ id?: string | null;
37
+ sessionId: string;
38
+ kind: "interactive" | "background" | string;
39
+ /** Background sessions: `blocked` (waiting for input), `done`, `failed`, … */
40
+ state?: string | null;
41
+ /** Interactive sessions: `idle` or `busy`. */
42
+ status?: string | null;
43
+ }
44
+
45
+ export interface SessionStateDeps {
46
+ now?: () => Date;
47
+ /** Null when the Claude CLI cannot list its sessions. */
48
+ claudeAgents?: () => Promise<ClaudeAgent[] | null>;
49
+ isAlive?: (pid: number) => boolean;
50
+ directoryExists?: (dir: string) => Promise<boolean>;
51
+ /** True when the branch's head is merged into the default branch of the checkout at `cwd`. */
52
+ isMerged?: (cwd: string, branch: string) => Promise<boolean>;
53
+ readFirstPrompt?: (transcript: string) => Promise<string | null>;
54
+ }
55
+
56
+ const PRUNE_AFTER_MS = 30 * 24 * 60 * 60 * 1000;
57
+ const LABEL_MAX = 200;
58
+ const TRANSCRIPT_READ_BYTES = 256 * 1024;
59
+
60
+ function parseAgents(stdout: string): ClaudeAgent[] | null {
61
+ try {
62
+ const parsed = JSON.parse(stdout) as unknown;
63
+ if (!Array.isArray(parsed)) return null;
64
+ return parsed.filter(
65
+ (entry): entry is ClaudeAgent =>
66
+ !!entry && typeof entry === "object" && typeof entry.sessionId === "string",
67
+ );
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ const readClaudeAgents = (): Promise<ClaudeAgent[] | null> =>
74
+ new Promise((resolve) => {
75
+ execFile(
76
+ "claude",
77
+ // Every directory: the sessions run in worktrees as well as this checkout.
78
+ ["agents", "--json", "--all"],
79
+ { timeout: 10_000, maxBuffer: 8 * 1024 * 1024 },
80
+ (error, stdout) => resolve(error ? null : parseAgents(stdout)),
81
+ );
82
+ });
83
+
84
+ async function exists(dir: string): Promise<boolean> {
85
+ return (await fs.stat(dir).catch(() => null))?.isDirectory() ?? false;
86
+ }
87
+
88
+ /**
89
+ * Merged when the head reached `origin/<default>` through a merge commit, or a
90
+ * rebase or squash carried its patches there. A head already on the default
91
+ * branch's own line (no commits of its own, or a fast-forward) is not counted,
92
+ * so a fresh Workset branch is not hidden. A branch gone locally and from
93
+ * `origin` counts as merged: Git keeps a checked-out branch, so its session no
94
+ * longer works on it (the usual cleanup after a merge).
95
+ */
96
+ export async function branchMerged(cwd: string, branch: string): Promise<boolean> {
97
+ const repo = workingRepoGit(cwd);
98
+ const defaultBranch = await repo.defaultBranch();
99
+ if (branch === defaultBranch) return false;
100
+ const git = mergeGit(cwd);
101
+ const tip = await git.tip(branch);
102
+ if (!tip) return git.isRepository();
103
+ if (await git.isAncestor(tip, defaultBranch)) {
104
+ return !(await git.onFirstParent(tip, defaultBranch));
105
+ }
106
+ return (await git.patchMatch(tip, defaultBranch)) !== null;
107
+ }
108
+
109
+ /** Text of a user message line in a Claude transcript; null for anything else. */
110
+ function promptText(line: string): string | null {
111
+ let entry: unknown;
112
+ try {
113
+ entry = JSON.parse(line);
114
+ } catch {
115
+ return null;
116
+ }
117
+ const record = entry as {
118
+ type?: string;
119
+ isMeta?: boolean;
120
+ message?: { role?: string; content?: unknown };
121
+ };
122
+ if (record.type !== "user" || record.isMeta || record.message?.role !== "user") return null;
123
+ const content = record.message.content;
124
+ const text =
125
+ typeof content === "string"
126
+ ? content
127
+ : Array.isArray(content)
128
+ ? content
129
+ .filter((part) => part && typeof part === "object" && part.type === "text")
130
+ .map((part) => String(part.text ?? ""))
131
+ .join(" ")
132
+ : "";
133
+ const trimmed = text.trim();
134
+ // Slash commands, their output, and hook-injected blocks are not prompts.
135
+ if (!trimmed || trimmed.startsWith("<")) return null;
136
+ return trimmed;
137
+ }
138
+
139
+ /** First user prompt of a Claude transcript (JSONL), read from its first 256 KB. */
140
+ export async function readFirstPrompt(transcript: string): Promise<string | null> {
141
+ let handle: fs.FileHandle;
142
+ try {
143
+ handle = await fs.open(transcript, "r");
144
+ } catch {
145
+ return null;
146
+ }
147
+ try {
148
+ const buffer = Buffer.alloc(TRANSCRIPT_READ_BYTES);
149
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
150
+ for (const line of buffer.subarray(0, bytesRead).toString("utf8").split("\n")) {
151
+ const text = promptText(line);
152
+ if (text) return text;
153
+ }
154
+ return null;
155
+ } finally {
156
+ await handle.close();
157
+ }
158
+ }
159
+
160
+ export function shortenLabel(text: string): string {
161
+ const oneLine = text.replace(/\s+/g, " ").trim();
162
+ return oneLine.length > LABEL_MAX ? `${oneLine.slice(0, LABEL_MAX - 1)}…` : oneLine;
163
+ }
164
+
165
+ function claudeRunning(agent: ClaudeAgent): boolean {
166
+ if (agent.kind === "interactive") return true;
167
+ return agent.state !== "done" && agent.state !== "failed";
168
+ }
169
+
170
+ function claudeActivity(agent: ClaudeAgent): SessionActivity {
171
+ if (agent.kind === "background") {
172
+ if (agent.state === "blocked") return "waiting";
173
+ return agent.state === "working" || agent.state === "running" ? "working" : "idle";
174
+ }
175
+ return agent.status === "busy" ? "working" : "idle";
176
+ }
177
+
178
+ type RunningState = Pick<ListedSession, "state" | "activity" | "kind" | "daemonId">;
179
+
180
+ function runningState(
181
+ session: RegisteredSession,
182
+ agents: Map<string, ClaudeAgent> | null,
183
+ isAlive: (pid: number) => boolean,
184
+ ): RunningState | null {
185
+ if (session.runtime === "claude" && agents) {
186
+ const agent = agents.get(session.id);
187
+ if (!agent || !claudeRunning(agent)) return null;
188
+ const background = agent.kind === "background";
189
+ return {
190
+ state: "running",
191
+ activity: claudeActivity(agent),
192
+ kind: background ? "background" : "interactive",
193
+ ...(background && agent.id ? { daemonId: agent.id } : {}),
194
+ };
195
+ }
196
+ if (session.endedAt || session.pid === undefined || !isAlive(session.pid)) return null;
197
+ return session.activity ? { state: "running", activity: session.activity } : { state: "running" };
198
+ }
199
+
200
+ /** A running session stays running on a merged branch: it can still be attached and stopped. */
201
+ async function stateOf(
202
+ session: RegisteredSession,
203
+ agents: Map<string, ClaudeAgent> | null,
204
+ deps: Required<Omit<SessionStateDeps, "claudeAgents" | "now" | "readFirstPrompt">>,
205
+ merged: (cwd: string, branch: string) => Promise<boolean>,
206
+ ): Promise<RunningState> {
207
+ if (!(await deps.directoryExists(session.cwd))) return { state: "done" };
208
+ const running = runningState(session, agents, deps.isAlive);
209
+ if (running) return running;
210
+ if (session.branch && (await merged(session.cwd, session.branch).catch(() => false))) {
211
+ return { state: "done" };
212
+ }
213
+ return { state: "parked" };
214
+ }
215
+
216
+ /**
217
+ * Prunes `done` sessions last seen over 30 days ago, fills missing labels from
218
+ * Claude transcripts, and returns every remaining session with its state,
219
+ * newest first. Writes the registry only when it pruned or labelled.
220
+ */
221
+ export async function listSessionsWithState(
222
+ options: WriteOptions & SessionStateDeps = {},
223
+ ): Promise<{ version: 2; sessions: ListedSession[] }> {
224
+ const deps = {
225
+ isAlive: options.isAlive ?? processAlive,
226
+ directoryExists: options.directoryExists ?? exists,
227
+ isMerged: options.isMerged ?? branchMerged,
228
+ };
229
+ const now = (options.now ?? (() => new Date()))();
230
+ const readPrompt = options.readFirstPrompt ?? readFirstPrompt;
231
+ const agentList = await (options.claudeAgents ?? readClaudeAgents)();
232
+ const agents = agentList ? new Map(agentList.map((agent) => [agent.sessionId, agent])) : null;
233
+
234
+ const mergeCache = new Map<string, Promise<boolean>>();
235
+ const merged = (cwd: string, branch: string) => {
236
+ const key = `${cwd}\0${branch}`;
237
+ if (!mergeCache.has(key)) mergeCache.set(key, deps.isMerged(cwd, branch));
238
+ return mergeCache.get(key)!;
239
+ };
240
+
241
+ const file = options.file ?? sessionRegistryPath();
242
+ // State is computed without the lock: Git checks can outlast a writer's wait.
243
+ const registry = await readSessionRegistry(file);
244
+ const listed: ListedSession[] = [];
245
+ const pruned = new Set<string>();
246
+ const labels = new Map<string, string>();
247
+ for (const session of registry.sessions) {
248
+ // oxlint-disable-next-line no-await-in-loop -- Git checks per session stay sequential
249
+ const state = await stateOf(session, agents, deps, merged);
250
+ const stale = now.getTime() - Date.parse(session.lastSeenAt) > PRUNE_AFTER_MS;
251
+ if (state.state === "done" && stale) {
252
+ pruned.add(session.id);
253
+ continue;
254
+ }
255
+ let entry = session;
256
+ if (!entry.label && entry.transcript) {
257
+ // oxlint-disable-next-line no-await-in-loop -- bounded read per unlabelled session
258
+ const prompt = await readPrompt(entry.transcript);
259
+ if (prompt) {
260
+ entry = { ...entry, label: shortenLabel(prompt) };
261
+ labels.set(entry.id, entry.label!);
262
+ }
263
+ }
264
+ // Stored activity is shown only through `state`, i.e. while running.
265
+ const { activity: _stored, ...shown } = entry;
266
+ listed.push({ ...shown, ...state });
267
+ }
268
+
269
+ if (pruned.size > 0 || labels.size > 0) {
270
+ // Best-effort: a busy lock leaves the write to the next listing.
271
+ await updateSessionRegistry(
272
+ (current) => {
273
+ current.sessions = current.sessions
274
+ .filter((entry) => !pruned.has(entry.id))
275
+ .map((entry) =>
276
+ !entry.label && labels.has(entry.id)
277
+ ? { ...entry, label: labels.get(entry.id)! }
278
+ : entry,
279
+ );
280
+ },
281
+ { file, lock: options.lock },
282
+ ).catch(() => {});
283
+ }
284
+ return { version: 2, sessions: sortSessions(listed) as ListedSession[] };
285
+ }
@@ -0,0 +1,64 @@
1
+ import {
2
+ type Fetch,
3
+ interruptSession,
4
+ openCodeServersDir,
5
+ processAlive,
6
+ readServerPassword,
7
+ readServerRecord,
8
+ serverFileBase,
9
+ } from "../runtime/opencode-server-record";
10
+ import { resolveProjection } from "../runtime/projection";
11
+ import {
12
+ endSession,
13
+ readSessionRegistry,
14
+ type RegisteredSession,
15
+ SessionRegistryError,
16
+ sessionRegistryPath,
17
+ } from "../runtime/session-registry";
18
+
19
+ /**
20
+ * `mate session stop`: interrupts an OpenCode background session's running
21
+ * turn through its Mate OpenCode server and marks the session ended.
22
+ */
23
+
24
+ export interface SessionStopDeps {
25
+ file?: string;
26
+ serversDir?: string;
27
+ repositoryIdOf?: (cwd: string) => string | null;
28
+ alive?: (pid: number) => boolean;
29
+ fetch?: Fetch;
30
+ }
31
+
32
+ const projectedRepositoryId = (cwd: string) => resolveProjection(cwd)?.repositoryId ?? null;
33
+
34
+ export async function stopSession(
35
+ id: string,
36
+ deps: SessionStopDeps = {},
37
+ ): Promise<RegisteredSession> {
38
+ const file = deps.file ?? sessionRegistryPath();
39
+ const session = (await readSessionRegistry(file)).sessions.find((entry) => entry.id === id);
40
+ if (!session) throw new SessionRegistryError(`session not registered: ${id}`);
41
+ if (session.runtime !== "opencode") {
42
+ throw new SessionRegistryError(`session ${id} is not an OpenCode session`);
43
+ }
44
+ const repositoryId = (deps.repositoryIdOf ?? projectedRepositoryId)(session.cwd);
45
+ const base =
46
+ repositoryId && serverFileBase(repositoryId, deps.serversDir ?? openCodeServersDir());
47
+ const record = base ? await readServerRecord(base) : null;
48
+ const password = base ? await readServerPassword(base) : null;
49
+ if (!record || !password || !(deps.alive ?? processAlive)(record.pid)) {
50
+ throw new SessionRegistryError(`no Mate OpenCode server runs for session ${id}`);
51
+ }
52
+ /** Another OpenCode process (a standalone TUI) owns it; the server cannot stop it. */
53
+ if (session.pid !== undefined && session.pid !== record.pid) {
54
+ throw new SessionRegistryError(`session ${id} does not run in the Mate OpenCode server`);
55
+ }
56
+ try {
57
+ await interruptSession(record.url, password, id, deps.fetch);
58
+ } catch (error) {
59
+ throw new SessionRegistryError(
60
+ `the Mate OpenCode server at ${record.url} did not stop session ${id}: ${(error as Error).message}`,
61
+ );
62
+ }
63
+ return (await endSession(id, { file }))!;
64
+ }
@@ -6,6 +6,7 @@ import { parse, stringify } from "yaml";
6
6
 
7
7
  import { errorMessage } from "../../runtime/error-message";
8
8
  import { changeNameOf, locateChange, parseAnchor } from "../change-layout";
9
+ import { isJiraKey, normalizeJiraKey } from "../delivery/record";
9
10
  import { scopedRepositories } from "../openspec-scopes";
10
11
 
11
12
  /**
@@ -24,6 +25,8 @@ export interface WorksetRecord {
24
25
  id: string;
25
26
  title: string;
26
27
  intent: string;
28
+ /** Jira key that names the Workset's new Delivery Branch when no caller gives one. */
29
+ ticket?: string;
27
30
  repositories: string[];
28
31
  changes: string[];
29
32
  /** Meaningful only while `changes` is empty. */
@@ -52,6 +55,7 @@ const KNOWN_FIELDS = [
52
55
  "id",
53
56
  "title",
54
57
  "intent",
58
+ "ticket",
55
59
  "repositories",
56
60
  "changes",
57
61
  "stage",
@@ -114,12 +118,17 @@ export function toWorksetRecord(fileId: string, document: unknown): WorksetRecor
114
118
  if (queuedAt !== undefined && Number.isNaN(Date.parse(queuedAt))) {
115
119
  return "queuedAt must be a timestamp";
116
120
  }
121
+ const ticket = raw.ticket ?? undefined;
122
+ if (ticket !== undefined && (typeof ticket !== "string" || !isJiraKey(ticket))) {
123
+ return "ticket must be a Jira key such as ABC-123";
124
+ }
117
125
  const known = new Set(KNOWN_FIELDS);
118
126
  const extra = Object.fromEntries(Object.entries(raw).filter(([key]) => !known.has(key)));
119
127
  return {
120
128
  id: fileId,
121
129
  title: typeof raw.title === "string" ? raw.title : fileId,
122
130
  intent: typeof raw.intent === "string" ? raw.intent : "",
131
+ ...(ticket !== undefined ? { ticket: normalizeJiraKey(ticket) } : {}),
123
132
  repositories,
124
133
  changes,
125
134
  stage: stage as PreProposeStage,
@@ -254,6 +263,7 @@ function documentOf(record: WorksetRecord): Record<string, unknown> {
254
263
  id: record.id,
255
264
  title: record.title,
256
265
  intent: record.intent,
266
+ ...(record.ticket ? { ticket: record.ticket } : {}),
257
267
  repositories: record.repositories,
258
268
  changes: record.changes,
259
269
  stage: record.stage,
@@ -277,6 +287,8 @@ export interface NewWorkset {
277
287
  repository: string;
278
288
  /** Starts the Workset at once; otherwise it is Later. */
279
289
  start?: boolean;
290
+ /** A Jira key, already validated and normalised. */
291
+ ticket?: string;
280
292
  }
281
293
 
282
294
  /** Writes a new record at stage Clarify intent; an existing identifier is refused and nothing is written. */
@@ -298,6 +310,7 @@ export async function createWorkset(
298
310
  id: input.id,
299
311
  title: input.title.trim() || input.id,
300
312
  intent: input.intent.trim(),
313
+ ...(input.ticket ? { ticket: input.ticket } : {}),
301
314
  repositories: [input.repository],
302
315
  changes: [],
303
316
  stage: "clarify-intent",
@@ -367,6 +380,8 @@ export interface NewOutcome {
367
380
  repository?: string;
368
381
  /** Starts it at once; otherwise it is Later. */
369
382
  start?: boolean;
383
+ /** Optional Jira key naming the Workset's Delivery Branch; empty means none. */
384
+ ticket?: string;
370
385
  }
371
386
 
372
387
  /** Creates a Workset from an outcome text; identifier and title are derived, the repository defaults to the only linked one. */
@@ -389,6 +404,10 @@ export async function createOutcome(
389
404
  if (!linkedRepositories.includes(repository)) {
390
405
  throw new WorksetError(`${repository} is not linked to this companion`);
391
406
  }
407
+ const ticket = input.ticket?.trim() || undefined;
408
+ if (ticket !== undefined && !isJiraKey(ticket)) {
409
+ throw new WorksetError(`ticket ${JSON.stringify(ticket)} is not a Jira key such as ABC-123`);
410
+ }
392
411
  const { worksets, problems } = await readWorksets(companionPath);
393
412
  const taken = new Set([
394
413
  ...worksets.map((workset) => workset.id),
@@ -405,6 +424,7 @@ export async function createOutcome(
405
424
  intent: input.text,
406
425
  repository,
407
426
  ...(input.start ? { start: true } : {}),
427
+ ...(ticket ? { ticket: normalizeJiraKey(ticket) } : {}),
408
428
  },
409
429
  now,
410
430
  );