@workit-dev/opencode 2.13.0 → 2.15.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/dist/plugin.js CHANGED
@@ -9500,7 +9500,7 @@ var workspaceConfigSchema = object({
9500
9500
  fanout: object({
9501
9501
  tierModels: unknown().optional().describe("The model per slice TIER (mundane, standard, hard), as one name or per host.")
9502
9502
  }).passthrough().optional().describe("Fanout settings."),
9503
- models: object({ roles: modelRoles }).passthrough().optional().describe("Model and effort per role and host (roles), the lead's own advisory model (lead) and whether a model the lead names on a spawn wins (allowLeadOverride, default false); the same key at the top of workspaces.json is the global default."),
9503
+ models: object({ roles: modelRoles }).passthrough().optional().describe("Model and effort per role and host (roles), the lead's own advisory model (lead), how a role model applies (enforce: advise, the default, or strict) and, under strict, whether a model the lead names on a spawn wins (allowLeadOverride, default false); the same key at the top of workspaces.json is the global default."),
9504
9504
  resources: unknown().optional().describe("Heavy-check limits on this machine: slots, scope, heavy, light, memoryMax, cpuQuota, wait."),
9505
9505
  remotes: array(nonBlank.refine((pattern) => remotePattern(pattern) !== null, "is not a remote URL (https://host/owner/repo, git@host:owner/repo, a path, or owner/*)")).optional().describe("Remote URLs this entry owns: a checkout pushing to or opening PRs on one never exceeds this entry's grants, wherever the folder is (`owner/*` claims a whole owner). Only the user changes it, in their own terminal."),
9506
9506
  autonomy: object(Object.fromEntries(["push", "pr", "merge", "release", "rerun"].map((kind) => [
@@ -9538,7 +9538,7 @@ var workspaceConfigSchema = object({
9538
9538
  });
9539
9539
  var workspacesFileSchema = object({
9540
9540
  workspaces: array(workspaceConfigSchema).optional().describe("Workspace entries, each mapping a path glob to its forge, policies and grants."),
9541
- models: object({ roles: modelRoles }).passthrough().optional().describe("The global default model and effort per role and host (roles), the lead's own advisory model (lead) and whether a model the lead names on a spawn wins (allowLeadOverride, default false).")
9541
+ models: object({ roles: modelRoles }).passthrough().optional().describe("The global default model and effort per role and host (roles), the lead's own advisory model (lead), how a role model applies (enforce: advise, the default, or strict) and, under strict, whether a model the lead names on a spawn wins (allowLeadOverride, default false).")
9542
9542
  }).passthrough().superRefine((file, context) => {
9543
9543
  const names = new Set;
9544
9544
  for (const [index, workspace] of (file.workspaces ?? []).entries()) {
@@ -9552,6 +9552,7 @@ var workspacesFileSchema = object({
9552
9552
  names.add(workspace.name);
9553
9553
  }
9554
9554
  });
9555
+ var workspacesPath = () => path9.join(configDir2(), "workspaces.json");
9555
9556
  var workspacesRevision = (contents) => createHash5("sha256").update(contents ?? "<missing>").digest("hex");
9556
9557
  var validateWorkspacesDocument = (parsed, file) => {
9557
9558
  if (!isConfigObject(parsed)) {
@@ -10466,7 +10467,7 @@ function resolveTrackFor(cwd, options) {
10466
10467
  }
10467
10468
 
10468
10469
  // packages/workit-core/src/core/vcs-config.ts
10469
- var workspacesPath = () => path10.join(configDir2(), "workspaces.json");
10470
+ var workspacesPath2 = () => path10.join(configDir2(), "workspaces.json");
10470
10471
  var vcsCwd = (cwd) => cwd ?? process.env.WORKIT_WORKSPACE_ROOT ?? process.cwd();
10471
10472
  var remoteProvider = (cwd) => {
10472
10473
  const url = originUrl(cwd) ?? "";
@@ -10644,7 +10645,7 @@ function vcsConfig(mode, cwd, options = {}) {
10644
10645
  defaultBranch: workspaceDefault
10645
10646
  });
10646
10647
  if (trackResolution.status === "invalid")
10647
- return { ok: false, error: trackResolution.error, configPath: workspacesPath() };
10648
+ return { ok: false, error: trackResolution.error, configPath: workspacesPath2() };
10648
10649
  const releaseTrack = trackSummary(trackResolution);
10649
10650
  const defaultTarget = releaseTrack?.track?.pullRequestTarget ?? workspaceDefault;
10650
10651
  const baseBranch = releaseTrack?.track?.baseBranch ?? defaultTarget;
@@ -18077,16 +18078,19 @@ var HOST_KEYS = new Set([
18077
18078
  "pi",
18078
18079
  "default"
18079
18080
  ]);
18080
- var BUILT_IN_CLAUDE_CODE = {
18081
+ var CLAUDE_AGENT_FILES = {
18081
18082
  decider: { model: "fable", effort: "high" },
18082
- "implementer.hard": { model: "opus" },
18083
- "implementer.standard": { model: "sonnet" },
18084
- "implementer.mundane": { model: "haiku" },
18083
+ implementer: { model: "sonnet" },
18085
18084
  verifier: { model: "sonnet" },
18086
18085
  reviewer: { model: "opus" },
18087
- explore: { model: "haiku" },
18088
18086
  babysit: { model: "haiku" }
18089
18087
  };
18088
+ var BUILT_IN_CLAUDE_CODE = {
18089
+ ...CLAUDE_AGENT_FILES,
18090
+ "implementer.hard": { model: "opus" },
18091
+ "implementer.standard": { model: "sonnet" },
18092
+ "implementer.mundane": { model: "haiku" }
18093
+ };
18090
18094
  var isObject6 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
18091
18095
  var name = (value) => typeof value === "string" && value.trim() ? value.trim() : null;
18092
18096
  var leaf = (value) => {
@@ -18170,6 +18174,7 @@ var firstAvailable = (candidates, host, now = new Date) => {
18170
18174
  }
18171
18175
  return { ...primary, skipped, allExhausted: true };
18172
18176
  };
18177
+ var resolveAvailableRoleModel = (cwd, selector, host, now = new Date, dir) => firstAvailable(resolveRoleModels(cwd, selector, host, dir), host, now);
18173
18178
  var fallbackText = (chosen) => {
18174
18179
  if (!chosen.skipped.length)
18175
18180
  return null;
@@ -18208,12 +18213,15 @@ var leadSwitchNotice = (cwd, host, current, now = new Date, dir) => {
18208
18213
  const how = SWITCH_HOW[hostFamily(host) ?? ""] ?? "the host's model switch";
18209
18214
  return next ? `Workit cannot switch this session's model: ${blocked.provider} is exhausted until ${shortTime(blocked.until)}. Switch the lead to ${next.model} with ${how}${hostFamily(host) === "claude_code" && providerOf(next.model, host) !== "anthropic" ? " (another host: Claude Code runs only Anthropic models)" : ""}.` : `Workit cannot switch this session's model: ${blocked.provider} is exhausted until ${shortTime(blocked.until)}, and models.lead names no model of another provider. Add one to models.lead in workspaces.json, then run \`workit models show\`.`;
18210
18215
  };
18211
- var leadOverrideAllowed = (cwd, dir) => {
18216
+ var modelsKey = (cwd, key, dir) => {
18212
18217
  for (const source of modelSources(cwd, dir))
18213
- if (isObject6(source.models) && Object.hasOwn(source.models, "allowLeadOverride"))
18214
- return source.models.allowLeadOverride === true;
18215
- return false;
18218
+ if (isObject6(source.models) && Object.hasOwn(source.models, key))
18219
+ return source.models[key];
18220
+ return;
18216
18221
  };
18222
+ var leadOverrideAllowed = (cwd, dir) => modelsKey(cwd, "allowLeadOverride", dir) === true;
18223
+ var enforceMode = (cwd, dir) => modelsKey(cwd, "enforce", dir) === "strict" ? "strict" : "advise";
18224
+ var FILE_ROLES = new Set(["decider", "verifier", "reviewer", "babysit"]);
18217
18225
  var CLAUDE_ALIASES = new Set(["sonnet", "opus", "haiku", "fable"]);
18218
18226
  var CLAUDE_EFFORTS = new Set(["low", "medium", "high", "xhigh", "max"]);
18219
18227
  var FULL_CLAUDE_ID = /^(?:[\w.-]+[./])?claude-(?:\d[\d.-]*-)?(sonnet|opus|haiku|fable)(?:[-.@[]|$)/u;
@@ -18239,7 +18247,7 @@ var chooseSpawnModel = (cwd, selector, host, given, accept, dir) => {
18239
18247
  const givenModel = name(given.model);
18240
18248
  const label = roleLabel(selector);
18241
18249
  const configured = resolved.source !== "built-in";
18242
- if (givenModel && (!configured || leadOverrideAllowed(cwd, dir)))
18250
+ if (givenModel && (!configured || enforceMode(cwd, dir) === "advise" || leadOverrideAllowed(cwd, dir)))
18243
18251
  return none;
18244
18252
  const model = accept(resolved.model);
18245
18253
  const effort = resolved.effort && !name(given.effort) ? resolved.effort : null;
@@ -18265,40 +18273,39 @@ var chooseSpawnModel = (cwd, selector, host, given, accept, dir) => {
18265
18273
  model,
18266
18274
  effort,
18267
18275
  basis,
18268
- note: givenModel ? `Workit replaced model ${givenModel} with ${model} on this spawn: role ${label} is set in ${resolved.source}.${why} Next time ${next} on the spawn. To let a spawn's own model win, set "allowLeadOverride": true under models in workspaces.json.` : `Workit set ${model}${effort ? ` (effort ${effort})` : ""} on this spawn: role ${label}, ${resolved.source}.${why}${configured ? "" : " Name a model to choose another."}`
18269
- };
18270
- };
18271
- var claudeSpawnArgs = (cwd, selector, dir) => {
18272
- const choice = chooseSpawnModel(cwd, selector, "claude_code", {}, claudeAgentModel, dir);
18273
- if (!choice.model)
18274
- return null;
18275
- const effort = choice.effort?.toLowerCase() ?? null;
18276
- return {
18277
- model: choice.model,
18278
- effort: effort && CLAUDE_EFFORTS.has(effort) ? effort : null
18276
+ note: givenModel ? `Workit replaced model ${givenModel} with ${model} on this spawn: role ${label} is set in ${resolved.source}.${why} Next time ${next} on the spawn, or set models.enforce "advise" so a named model wins.` : `Workit set ${model}${effort ? ` (effort ${effort})` : ""} on this spawn: role ${label}, ${resolved.source}.${why}${configured ? "" : " Name a model to choose another."}`
18279
18277
  };
18280
18278
  };
18281
18279
  var CLAUDE_SPAWNS = [
18282
- ...["hard", "standard", "mundane"].map((tier) => ({
18283
- label: tier === "hard" ? "workit:implementer hard" : tier,
18280
+ ...MODEL_TIERS.map((tier) => ({
18281
+ label: `workit:implementer ${tier}`,
18284
18282
  selector: { role: "implementer", tier }
18285
18283
  })),
18286
- { label: "workit:verifier", selector: { role: "verifier" } },
18287
- { label: "workit:reviewer", selector: { role: "reviewer" } },
18284
+ ...["verifier", "reviewer", "decider"].map((role) => ({
18285
+ label: `workit:${role}`,
18286
+ selector: { role }
18287
+ })),
18288
+ { label: "workit:babysitter", selector: { role: "babysit" } },
18288
18289
  { label: "Explore", selector: { role: "explore" } },
18289
- { label: "ROLE: decider", selector: { role: "decider" } },
18290
- { label: "ROLE: babysit", selector: { role: "babysit" } },
18291
18290
  { label: "general-purpose", selector: { role: "default" } }
18292
18291
  ];
18293
18292
  var claudeSpawnTable = (cwd, dir) => {
18294
18293
  const rows = CLAUDE_SPAWNS.flatMap(({ label, selector }) => {
18295
- const args = claudeSpawnArgs(cwd, selector, dir);
18296
- return args ? [`${label} ${args.model}${args.effort ? `/${args.effort}` : ""}`] : [];
18294
+ const want = resolveRoleModel(cwd, selector, "claude_code", dir);
18295
+ const model = want && want.source !== "built-in" ? claudeAgentModel(want.model) : null;
18296
+ const effort = want?.effort?.toLowerCase();
18297
+ const file = label.startsWith("workit:") ? CLAUDE_AGENT_FILES[selector.role] : undefined;
18298
+ return model && (model !== file?.model || effort !== file.effort) ? [`${label} ${model}${effort ? `/${effort}` : ""}`] : [];
18297
18299
  });
18298
- return rows.length ? `Agent spawn model/effort (pass them, workers with run_in_background: true): ${rows.join(", ")}. Implementer prompt: \`workit fanout brief <slice>\` after \`workit fanout worktree create <slice>\`, even for one slice.` : null;
18300
+ return `Spawn Workit roles by name (workit:implementer, workit:verifier, workit:reviewer, workit:decider, workit:babysitter; search: Explore), workers with run_in_background: true, and pass no model or effort unless the user named one${rows.length ? `; configured here (pass them): ${rows.join(", ")}` : ""}. Implementer prompt: \`workit fanout brief <slice>\` after \`workit fanout worktree create <slice>\`, even for one slice.`;
18301
+ };
18302
+ var uniformImplementerModel = (cwd, host, dir) => {
18303
+ const tiers = MODEL_TIERS.map((tier) => resolveRoleModel(cwd, { role: "implementer", tier }, host, dir));
18304
+ const [first] = tiers;
18305
+ return first && tiers.every((t) => t?.model === first.model && t.effort === first.effort) ? first : null;
18299
18306
  };
18300
18307
  var ROLE_SELECTORS = MODEL_ROLES.flatMap((role) => role === "implementer" ? MODEL_TIERS.map((tier) => ({ role, tier })) : [{ role }]);
18301
- var AGENT_ROLE = /^(?:workit[:-])?(decider|implementer|verifier|reviewer|explore|babysit)$/iu;
18308
+ var AGENT_ROLE = /^(?:workit[:-])?(decider|implementer|verifier|reviewer|explore|babysit)(?:(?<=babysit)ter)?$/iu;
18302
18309
  var ROLE_LINE = /^[ \t]*ROLE:[ \t]*(decider|implementer|verifier|reviewer|explore|babysit)\b/imu;
18303
18310
  var TIER_LINE = /^[ \t]*TIER:[ \t]*(mundane|standard|hard)\b/imu;
18304
18311
  var isBrief = (text) => TIER_LINE.test(text) && /^WORKTREE:/mu.test(text);
@@ -28242,11 +28249,12 @@ var FLAGS = {
28242
28249
  var CLAUDE_CODE_DESCRIPTOR = {
28243
28250
  host: "claude_code",
28244
28251
  label: "Claude Code",
28245
- verifiedAgainst: "claude 2.1.288 (hook zod schemas in the binary)",
28252
+ verifiedAgainst: "claude 2.1.288 (hook zod schemas in the binary; SessionEnd: 2.1.327)",
28246
28253
  docs: ["https://code.claude.com/docs/en/hooks"],
28247
28254
  transport: "hook-process",
28248
28255
  events: {
28249
28256
  "session.start": { support: "native", native: "SessionStart" },
28257
+ "session.end": { support: "native", native: "SessionEnd" },
28250
28258
  "context.turn": { support: "native", native: "UserPromptSubmit" },
28251
28259
  "shell.pre": { support: "native", native: "PreToolUse" },
28252
28260
  "tool.pre": { support: "native", native: "PreToolUse" },
@@ -28356,6 +28364,7 @@ var CODEX_DESCRIPTOR = {
28356
28364
  transport: "hook-process",
28357
28365
  events: {
28358
28366
  "session.start": { support: "native", native: "SessionStart" },
28367
+ "session.end": { support: "none", native: null },
28359
28368
  "context.turn": { support: "native", native: "UserPromptSubmit" },
28360
28369
  "shell.pre": { support: "native", native: "PreToolUse" },
28361
28370
  "tool.pre": { support: "native", native: "PreToolUse" },
@@ -28466,6 +28475,7 @@ var CURSOR_DESCRIPTOR = {
28466
28475
  transport: "hook-process",
28467
28476
  events: {
28468
28477
  "session.start": { support: "native", native: "sessionStart" },
28478
+ "session.end": { support: "native", native: "sessionEnd" },
28469
28479
  "context.turn": none,
28470
28480
  "shell.pre": { support: "native", native: "beforeShellExecution" },
28471
28481
  "tool.pre": { support: "native", native: "preToolUse" },
@@ -28572,6 +28582,7 @@ var OPENCODE_DESCRIPTOR = {
28572
28582
  transport: "in-process-plugin",
28573
28583
  events: {
28574
28584
  "session.start": { support: "none", native: null },
28585
+ "session.end": { support: "partial", native: 'event("session.deleted")' },
28575
28586
  "context.turn": { support: "native", native: 'session.hook("context")' },
28576
28587
  "shell.pre": { support: "native", native: 'permission.hook("evaluate")' },
28577
28588
  "tool.pre": { support: "native", native: 'tool.hook("execute.before")' },
@@ -28641,6 +28652,7 @@ var PI_DESCRIPTOR = {
28641
28652
  transport: "in-process-plugin",
28642
28653
  events: {
28643
28654
  "session.start": { support: "native", native: "session_start" },
28655
+ "session.end": { support: "native", native: "session_shutdown" },
28644
28656
  "context.turn": { support: "native", native: "before_agent_start" },
28645
28657
  "shell.pre": { support: "native", native: "tool_call" },
28646
28658
  "tool.pre": { support: "native", native: "tool_call" },
@@ -29093,6 +29105,239 @@ function takeProcNotice(session, env = process.env) {
29093
29105
  }
29094
29106
  }
29095
29107
 
29108
+ // packages/workit-core/src/hooks/teardown.ts
29109
+ import { spawn } from "node:child_process";
29110
+ import fs31 from "node:fs";
29111
+ import path46 from "node:path";
29112
+
29113
+ // packages/workit-core/src/core/cli-locate.ts
29114
+ import { closeSync as closeSync3, existsSync as existsSync16, openSync as openSync3, readSync } from "node:fs";
29115
+ import path45 from "node:path";
29116
+ var LAUNCHER_MARKER = "workit-owned-launcher";
29117
+ var CLI_PACKAGE_PATH = ["node_modules", "@workit-dev", "cli"];
29118
+ var installRoot = (env, platform = process.platform) => {
29119
+ if (env.WORKIT_INSTALL_ROOT)
29120
+ return env.WORKIT_INSTALL_ROOT;
29121
+ const data = dataDir(env, platform);
29122
+ return platform === "win32" ? path45.join(data, "install") : data;
29123
+ };
29124
+ var ownedLauncherPath = (env, platform = process.platform) => path45.join(installRoot(env, platform), "bin", platform === "win32" ? "workit.cmd" : "workit");
29125
+ var ownedCurrentEntry = (env, platform = process.platform) => path45.join(installRoot(env, platform), "current", ...CLI_PACKAGE_PATH, "dist", "index.js");
29126
+ var head = (file) => {
29127
+ let fd;
29128
+ try {
29129
+ fd = openSync3(file, "r");
29130
+ const buffer = Buffer.alloc(256);
29131
+ const read = readSync(fd, buffer, 0, buffer.length, 0);
29132
+ return buffer.subarray(0, read).toString("utf8");
29133
+ } catch {
29134
+ return "";
29135
+ } finally {
29136
+ if (fd !== undefined)
29137
+ closeSync3(fd);
29138
+ }
29139
+ };
29140
+ var locateWorkitCli = (options = {}) => {
29141
+ const env = options.env ?? process.env;
29142
+ const platform = options.platform ?? process.platform;
29143
+ const exists = options.exists ?? existsSync16;
29144
+ const read = options.read ?? head;
29145
+ const node = options.node ?? process.execPath;
29146
+ const launcher = ownedLauncherPath(env, platform);
29147
+ if (exists(launcher) && read(launcher).includes(LAUNCHER_MARKER))
29148
+ return {
29149
+ source: "owned-launcher",
29150
+ command: launcher,
29151
+ args: [],
29152
+ binDir: path45.dirname(launcher)
29153
+ };
29154
+ const current = ownedCurrentEntry(env, platform);
29155
+ if (exists(current))
29156
+ return {
29157
+ source: "owned-current",
29158
+ command: node,
29159
+ args: [current],
29160
+ binDir: null
29161
+ };
29162
+ if (options.bundled && exists(options.bundled))
29163
+ return {
29164
+ source: "bundled",
29165
+ command: node,
29166
+ args: [options.bundled],
29167
+ binDir: null
29168
+ };
29169
+ return { source: "path", command: "workit", args: [], binDir: null };
29170
+ };
29171
+ var pathKey = (env) => Object.keys(env).find((key) => key.toUpperCase() === "PATH") ?? "PATH";
29172
+ var workitCliEnv = (located, env = process.env, platform = process.platform) => {
29173
+ if (located.source === "path")
29174
+ return {};
29175
+ const patch = {
29176
+ WORKIT_CLI: [located.command, ...located.args].join(" ")
29177
+ };
29178
+ if (located.binDir) {
29179
+ const key = pathKey(env);
29180
+ const delimiter = platform === "win32" ? ";" : ":";
29181
+ const same = (dir) => platform === "win32" ? path45.win32.normalize(dir).toLowerCase() === path45.win32.normalize(located.binDir).toLowerCase() : path45.posix.normalize(dir) === path45.posix.normalize(located.binDir);
29182
+ const rest = (env[key] ?? "").split(delimiter).filter((dir) => dir && !same(dir));
29183
+ patch[key] = [located.binDir, ...rest].join(delimiter);
29184
+ }
29185
+ return patch;
29186
+ };
29187
+ var useOwnedWorkitCli = (options = {}) => {
29188
+ const env = options.env ?? process.env;
29189
+ const located = locateWorkitCli({ ...options, env });
29190
+ Object.assign(env, workitCliEnv(located, env, options.platform));
29191
+ return located;
29192
+ };
29193
+
29194
+ // packages/workit-core/src/hooks/teardown.ts
29195
+ var REAP_INTERVAL_MS = 10 * 60000;
29196
+ var LOG_MAX_BYTES = 1 << 20;
29197
+ var ENDS = {
29198
+ claude_code: new Set(["logout", "prompt_input_exit", "other"]),
29199
+ cursor: new Set(["completed", "aborted", "error", "window_close", "user_close"]),
29200
+ pi: new Set(["quit"]),
29201
+ opencode: new Set(["deleted"])
29202
+ };
29203
+ var SAFE_SESSION = /^[\w.@+][\w.:@/+-]{0,127}$/u;
29204
+ var HOST_SESSION_VARS2 = ["OPENCODE_SESSION_ID", "PI_SESSION_ID", "CODEX_THREAD_ID"];
29205
+ var teardownDir = (env) => path46.join(stateDir(env), "procs");
29206
+ var teardownLog = (env) => path46.join(teardownDir(env), "teardown.log");
29207
+ var reapStamp = (env) => path46.join(teardownDir(env), "reap-at-start.stamp");
29208
+ function spawnDetached(request) {
29209
+ try {
29210
+ const shell = process.platform === "win32" && !/\.exe$/iu.test(request.command);
29211
+ const line = [`"${request.command}"`, ...request.args].join(" ");
29212
+ const child = spawn(shell ? line : request.command, shell ? [] : request.args, {
29213
+ cwd: request.cwd,
29214
+ env: request.env,
29215
+ detached: true,
29216
+ shell,
29217
+ stdio: ["ignore", request.log ?? "ignore", request.log ?? "ignore"],
29218
+ windowsHide: true
29219
+ });
29220
+ child.on("error", () => {});
29221
+ child.unref();
29222
+ return child.pid !== undefined;
29223
+ } catch {
29224
+ return false;
29225
+ }
29226
+ }
29227
+ var teardownDeps = {
29228
+ spawn: (request) => request.env.WORKIT_TEST_RUN === undefined && spawnDetached(request),
29229
+ now: () => Date.now()
29230
+ };
29231
+ var openLog = (env, args) => {
29232
+ try {
29233
+ const file = teardownLog(env);
29234
+ fs31.mkdirSync(path46.dirname(file), { recursive: true });
29235
+ let size = 0;
29236
+ try {
29237
+ size = fs31.statSync(file).size;
29238
+ } catch {}
29239
+ const fd = fs31.openSync(file, size > LOG_MAX_BYTES ? "w" : "a", 384);
29240
+ fs31.writeSync(fd, `${new Date(teardownDeps.now()).toISOString()} workit ${args.join(" ")}
29241
+ `);
29242
+ return fd;
29243
+ } catch {
29244
+ return null;
29245
+ }
29246
+ };
29247
+ function runCli(args, env, cwd) {
29248
+ let log = null;
29249
+ try {
29250
+ const cli = locateWorkitCli({ env });
29251
+ log = openLog(env, args);
29252
+ const started = teardownDeps.spawn({
29253
+ command: cli.command,
29254
+ args: [...cli.args, ...args],
29255
+ env,
29256
+ cwd: fs31.existsSync(cwd) ? cwd : teardownDir(env),
29257
+ log
29258
+ });
29259
+ if (!started && log !== null)
29260
+ fs31.writeSync(log, ` not started
29261
+ `);
29262
+ return started;
29263
+ } catch {
29264
+ return false;
29265
+ } finally {
29266
+ if (log !== null)
29267
+ try {
29268
+ fs31.closeSync(log);
29269
+ } catch {}
29270
+ }
29271
+ }
29272
+ function endSession(end, env = process.env) {
29273
+ const session = end.session?.trim() ?? "";
29274
+ if (!SAFE_SESSION.test(session) || !ENDS[end.host]?.has(end.reason ?? ""))
29275
+ return false;
29276
+ const outer = env.WORKIT_SESSION_ID?.trim();
29277
+ if (end.agentId || env.WORKIT_PI_WORKER_SESSION || leadOf(session) !== session || outer && leadOf(outer) !== outer)
29278
+ return false;
29279
+ const child = { ...env, WORKIT_SESSION_ID: session, WORKIT_HOST: end.host };
29280
+ for (const key of HOST_SESSION_VARS2)
29281
+ delete child[key];
29282
+ return runCli(["stop", "--session", session, "--reason", "session-end"], child, end.cwd);
29283
+ }
29284
+ var claim2 = (file, now) => {
29285
+ for (let attempt = 0;attempt < 2; attempt += 1)
29286
+ try {
29287
+ fs31.writeFileSync(file, String(now), { flag: "wx", mode: 384 });
29288
+ return true;
29289
+ } catch (error) {
29290
+ if (error.code !== "EEXIST")
29291
+ return false;
29292
+ let held = Number.NaN;
29293
+ try {
29294
+ held = Number(fs31.readFileSync(file, "utf8"));
29295
+ } catch {}
29296
+ if (now - held < REAP_INTERVAL_MS)
29297
+ return false;
29298
+ fs31.rmSync(file, { force: true });
29299
+ }
29300
+ return false;
29301
+ };
29302
+ var fresh = (stamp, now) => {
29303
+ try {
29304
+ const last = Number(fs31.readFileSync(stamp, "utf8"));
29305
+ return now - last < REAP_INTERVAL_MS && last <= now;
29306
+ } catch {
29307
+ return false;
29308
+ }
29309
+ };
29310
+ function reapAtStart(cwd, env = process.env) {
29311
+ const stamp = reapStamp(env);
29312
+ const lock = `${stamp}.claim`;
29313
+ const now = teardownDeps.now();
29314
+ try {
29315
+ if (fresh(stamp, now))
29316
+ return false;
29317
+ fs31.mkdirSync(path46.dirname(stamp), { recursive: true });
29318
+ if (!claim2(lock, now))
29319
+ return false;
29320
+ } catch {
29321
+ return false;
29322
+ }
29323
+ let started = false;
29324
+ try {
29325
+ if (fresh(stamp, now))
29326
+ return false;
29327
+ started = runCli(["stop", "--orphans", "--reason", "session-start"], env, cwd);
29328
+ if (started) {
29329
+ const temp = `${stamp}.${process.pid}`;
29330
+ fs31.writeFileSync(temp, String(now), { mode: 384 });
29331
+ fs31.renameSync(temp, stamp);
29332
+ }
29333
+ } catch {} finally {
29334
+ try {
29335
+ fs31.rmSync(lock, { force: true });
29336
+ } catch {}
29337
+ }
29338
+ return started;
29339
+ }
29340
+
29096
29341
  // packages/workit-core/src/hooks/ytrack-word.ts
29097
29342
  var YTRACK_WORD = /ytrack(?![\w/-]|\.(?!exe|cmd))/i;
29098
29343
  var namesYtrack = (text) => {
@@ -29599,11 +29844,11 @@ var PROCESS_START = performance.timeOrigin;
29599
29844
  // packages/workit-core/src/hooks/run.ts
29600
29845
  if (false) {}
29601
29846
  // packages/workit-opencode/src/shared/init-apply.ts
29602
- import path49 from "node:path";
29847
+ import path51 from "node:path";
29603
29848
 
29604
29849
  // packages/workit-core/src/core/gitignore.ts
29605
- import { existsSync as existsSync16, readFileSync as readFileSync13, writeFileSync as writeFileSync5 } from "node:fs";
29606
- import path45 from "node:path";
29850
+ import { existsSync as existsSync17, readFileSync as readFileSync13, writeFileSync as writeFileSync5 } from "node:fs";
29851
+ import path47 from "node:path";
29607
29852
  var GITIGNORE_ENTRIES = [
29608
29853
  "# workit: SDD working state (never commit)",
29609
29854
  "docs/*/sdd/",
@@ -29623,8 +29868,8 @@ var GITIGNORE_ENTRIES = [
29623
29868
  var ensureProjectGitignore = (workspaceRoot, confirmed) => {
29624
29869
  if (!confirmed)
29625
29870
  return { ok: false, error: "confirmed: true required" };
29626
- const file = path45.join(workspaceRoot, ".gitignore");
29627
- const existing = existsSync16(file) ? readFileSync13(file, "utf8") : "";
29871
+ const file = path47.join(workspaceRoot, ".gitignore");
29872
+ const existing = existsSync17(file) ? readFileSync13(file, "utf8") : "";
29628
29873
  const existingLines = new Set(existing.split(`
29629
29874
  `).map((l) => l.trim()).filter(Boolean));
29630
29875
  const added = [];
@@ -29643,33 +29888,33 @@ var ensureProjectGitignore = (workspaceRoot, confirmed) => {
29643
29888
  ` : "") + append.join(`
29644
29889
  `) + `
29645
29890
  `, "utf8");
29646
- } else if (!existsSync16(file)) {
29891
+ } else if (!existsSync17(file)) {
29647
29892
  writeFileSync5(file, "", "utf8");
29648
29893
  }
29649
29894
  return { ok: true, path: file, added };
29650
29895
  };
29651
29896
 
29652
29897
  // packages/workit-core/src/core/hygiene.ts
29653
- import { existsSync as existsSync17, readFileSync as readFileSync14, readdirSync as readdirSync6, writeFileSync as writeFileSync6 } from "node:fs";
29654
- import path46 from "node:path";
29898
+ import { existsSync as existsSync18, readFileSync as readFileSync14, readdirSync as readdirSync6, writeFileSync as writeFileSync6 } from "node:fs";
29899
+ import path48 from "node:path";
29655
29900
  var repoRoot3 = assetRoot();
29656
- var templatesDir = () => path46.join(repoRoot3, "templates", "hygiene");
29901
+ var templatesDir = () => path48.join(repoRoot3, "templates", "hygiene");
29657
29902
  var packageJson = (root) => {
29658
- if (!existsSync17(path46.join(root, "package.json")))
29903
+ if (!existsSync18(path48.join(root, "package.json")))
29659
29904
  return null;
29660
29905
  try {
29661
- return JSON.parse(readFileSync14(path46.join(root, "package.json"), "utf8"));
29906
+ return JSON.parse(readFileSync14(path48.join(root, "package.json"), "utf8"));
29662
29907
  } catch {
29663
29908
  return null;
29664
29909
  }
29665
29910
  };
29666
29911
  var isOpenSource = (root) => {
29667
- if (existsSync17(path46.join(root, "LICENSE")))
29912
+ if (existsSync18(path48.join(root, "LICENSE")))
29668
29913
  return true;
29669
29914
  const pkg = packageJson(root);
29670
29915
  if (pkg && !pkg.private)
29671
29916
  return true;
29672
- return path46.basename(root) === "workit";
29917
+ return path48.basename(root) === "workit";
29673
29918
  };
29674
29919
  var licenseHolder = (root) => {
29675
29920
  const pkg = packageJson(root);
@@ -29692,13 +29937,13 @@ var planHygieneFiles = (root, opts = {}) => {
29692
29937
  files.push("LICENSE", "CONTRIBUTING.md");
29693
29938
  const planned = [];
29694
29939
  for (const file of files) {
29695
- if (existsSync17(path46.join(root, file)))
29940
+ if (existsSync18(path48.join(root, file)))
29696
29941
  continue;
29697
- const tpl = path46.join(templatesDir(), file);
29698
- if (!existsSync17(tpl))
29942
+ const tpl = path48.join(templatesDir(), file);
29943
+ if (!existsSync18(tpl))
29699
29944
  continue;
29700
- const content = readFileSync14(tpl, "utf8").replace(/<PROJECT>/g, path46.basename(root)).replace(/<YEAR>/g, String(new Date().getFullYear())).replace(/<HOLDER>\s*/g, licenseHolder(root));
29701
- planned.push({ path: path46.join(root, file), content });
29945
+ const content = readFileSync14(tpl, "utf8").replace(/<PROJECT>/g, path48.basename(root)).replace(/<YEAR>/g, String(new Date().getFullYear())).replace(/<HOLDER>\s*/g, licenseHolder(root));
29946
+ planned.push({ path: path48.join(root, file), content });
29702
29947
  }
29703
29948
  return planned;
29704
29949
  };
@@ -29708,19 +29953,19 @@ var ensureHygieneFiles = (root, opts) => {
29708
29953
  const created = [];
29709
29954
  for (const planned of planHygieneFiles(root, opts)) {
29710
29955
  writeFileSync6(planned.path, planned.content, "utf8");
29711
- created.push(path46.basename(planned.path));
29956
+ created.push(path48.basename(planned.path));
29712
29957
  }
29713
29958
  return { ok: true, created };
29714
29959
  };
29715
29960
 
29716
29961
  // packages/workit-core/src/core/init.ts
29717
- import fs31 from "node:fs";
29718
- import path48 from "node:path";
29962
+ import fs32 from "node:fs";
29963
+ import path50 from "node:path";
29719
29964
  import { spawnSync as spawnSync25 } from "node:child_process";
29720
29965
 
29721
29966
  // packages/workit-core/src/core/workspace-branch-policy.ts
29722
29967
  import { mkdirSync as mkdirSync5, readFileSync as readFileSync15, renameSync as renameSync4, rmSync as rmSync3, writeFileSync as writeFileSync7 } from "node:fs";
29723
- import path47 from "node:path";
29968
+ import path49 from "node:path";
29724
29969
  import { isDeepStrictEqual } from "node:util";
29725
29970
  var readFileSafe = (p) => {
29726
29971
  try {
@@ -29731,7 +29976,7 @@ var readFileSafe = (p) => {
29731
29976
  };
29732
29977
  function applyWorkspaceBranchPolicy(opts) {
29733
29978
  const { workspace_root, env = process.env } = opts;
29734
- const dir = path47.join(env.WORKIT_CONFIG ?? configDir2());
29979
+ const dir = path49.join(env.WORKIT_CONFIG ?? configDir2());
29735
29980
  const {
29736
29981
  status,
29737
29982
  path: wsPath,
@@ -29743,7 +29988,7 @@ function applyWorkspaceBranchPolicy(opts) {
29743
29988
  if (status === "malformed" || status === "invalid")
29744
29989
  return { ok: false, error: workspacesError ?? `invalid workspaces.json: ${wsPath}` };
29745
29990
  const detection = detectBranchPolicy(workspace_root);
29746
- const name = String(env.WORKIT_BP_NAME ?? path47.basename(workspace_root));
29991
+ const name = String(env.WORKIT_BP_NAME ?? path49.basename(workspace_root));
29747
29992
  const integration = env.WORKIT_BP_INTEGRATION ?? detection.integration;
29748
29993
  const policy = {
29749
29994
  preset: detection.preset,
@@ -29792,7 +30037,7 @@ function applyWorkspaceBranchPolicy(opts) {
29792
30037
  ok: false,
29793
30038
  error: `workspaces.json changed while applying the branch policy: ${wsPath}`
29794
30039
  };
29795
- mkdirSync5(path47.dirname(wsPath), { recursive: true });
30040
+ mkdirSync5(path49.dirname(wsPath), { recursive: true });
29796
30041
  const tmp = `${wsPath}.${process.pid}.tmp`;
29797
30042
  try {
29798
30043
  writeFileSync7(tmp, JSON.stringify({ ...document, workspaces: next }, null, 2) + `
@@ -29826,7 +30071,7 @@ function applyWorkspaceBranchPolicy(opts) {
29826
30071
  // packages/workit-core/src/core/init.ts
29827
30072
  var readJson3 = (p) => {
29828
30073
  try {
29829
- const parsed = JSON.parse(fs31.readFileSync(p, "utf8"));
30074
+ const parsed = JSON.parse(fs32.readFileSync(p, "utf8"));
29830
30075
  return isConfigObject(parsed) ? parsed : null;
29831
30076
  } catch {
29832
30077
  return null;
@@ -29889,11 +30134,11 @@ var vcsJsonContent = () => {
29889
30134
  };
29890
30135
  function initApplyData(action, env = process.env) {
29891
30136
  const dir = String(env.WORKIT_CONFIG ?? configDir2());
29892
- fs31.mkdirSync(dir, { recursive: true });
30137
+ fs32.mkdirSync(dir, { recursive: true });
29893
30138
  switch (action) {
29894
30139
  case "youtrack_json": {
29895
- const out = path48.join(dir, "youtrack.json");
29896
- fs31.writeFileSync(out, JSON.stringify(youtrackJsonContent(), null, 2) + `
30140
+ const out = path50.join(dir, "youtrack.json");
30141
+ fs32.writeFileSync(out, JSON.stringify(youtrackJsonContent(), null, 2) + `
29897
30142
  `, "utf8");
29898
30143
  return { action, ok: true, path: out };
29899
30144
  }
@@ -29906,10 +30151,10 @@ function initApplyData(action, env = process.env) {
29906
30151
  };
29907
30152
  }
29908
30153
  case "youtrack_scaffold": {
29909
- const jsonOut = path48.join(dir, "youtrack.json");
29910
- fs31.writeFileSync(jsonOut, JSON.stringify(youtrackJsonContent(), null, 2) + `
30154
+ const jsonOut = path50.join(dir, "youtrack.json");
30155
+ fs32.writeFileSync(jsonOut, JSON.stringify(youtrackJsonContent(), null, 2) + `
29911
30156
  `, "utf8");
29912
- const configPath = path48.resolve(jsonOut);
30157
+ const configPath = path50.resolve(jsonOut);
29913
30158
  const cfg = readJson3(configPath) ?? {};
29914
30159
  const base = String(cfg.baseUrl ?? "").replace(/\/+$/, "");
29915
30160
  const meeting = String(cfg.meetingIssue ?? "");
@@ -29945,10 +30190,10 @@ function initApplyData(action, env = process.env) {
29945
30190
  };
29946
30191
  }
29947
30192
  case "vcs_scaffold": {
29948
- const jsonOut = path48.join(dir, "vcs.json");
29949
- fs31.writeFileSync(jsonOut, JSON.stringify(vcsJsonContent(), null, 2) + `
30193
+ const jsonOut = path50.join(dir, "vcs.json");
30194
+ fs32.writeFileSync(jsonOut, JSON.stringify(vcsJsonContent(), null, 2) + `
29950
30195
  `, "utf8");
29951
- const configPath = path48.resolve(jsonOut);
30196
+ const configPath = path50.resolve(jsonOut);
29952
30197
  const prev = process.env.WORKIT_VCS_CONFIG;
29953
30198
  process.env.WORKIT_VCS_CONFIG = configPath;
29954
30199
  try {
@@ -30067,7 +30312,7 @@ var executeInitApply = (args, directory, runtime) => {
30067
30312
  protectedNames: args.branch_policy_protected
30068
30313
  }, current);
30069
30314
  writeConfig(next);
30070
- return output(ok({ action: "config", path: path49.join(configDir2(), "config.json"), ...next }));
30315
+ return output(ok({ action: "config", path: path51.join(configDir2(), "config.json"), ...next }));
30071
30316
  }
30072
30317
  const env = Object.fromEntries(Object.entries({
30073
30318
  WORKIT_YT_BASE_URL: args.base_url,
@@ -30084,14 +30329,14 @@ var executeInitApply = (args, directory, runtime) => {
30084
30329
 
30085
30330
  // packages/workit-opencode/src/shared/session.ts
30086
30331
  import { realpathSync as realpathSync11 } from "node:fs";
30087
- import path50 from "node:path";
30332
+ import path52 from "node:path";
30088
30333
  var sameWorkspace = (expected, observed) => {
30089
30334
  if (typeof observed !== "string" || !observed)
30090
30335
  return false;
30091
30336
  try {
30092
30337
  return realpathSync11(expected) === realpathSync11(observed);
30093
30338
  } catch {
30094
- return path50.resolve(expected) === path50.resolve(observed);
30339
+ return path52.resolve(expected) === path52.resolve(observed);
30095
30340
  }
30096
30341
  };
30097
30342
 
@@ -30163,7 +30408,7 @@ var workitFamilyOf = (toolName) => {
30163
30408
 
30164
30409
  // packages/workit-opencode/src/tools/context.ts
30165
30410
  import { realpathSync as realpathSync12 } from "node:fs";
30166
- import path51 from "node:path";
30411
+ import path53 from "node:path";
30167
30412
  var createContextTool = () => ({
30168
30413
  description: "Read Git, pull request, YouTrack, issue, changelog, release, or affected-file context.",
30169
30414
  execute: async (args, context) => {
@@ -30173,7 +30418,7 @@ var createContextTool = () => ({
30173
30418
  let root;
30174
30419
  try {
30175
30420
  const cwd = parsed.data.cwd;
30176
- root = realpathSync12(cwd ? path51.resolve(context.directory, cwd) : context.directory);
30421
+ root = realpathSync12(cwd ? path53.resolve(context.directory, cwd) : context.directory);
30177
30422
  } catch {
30178
30423
  return JSON.stringify(failure2("invalid_input", "context target directory cannot be resolved"), null, 2);
30179
30424
  }
@@ -30205,8 +30450,8 @@ var workerCoordinatorFor = (task, worker) => {
30205
30450
  // packages/workit-core/src/fanout.ts
30206
30451
  import { spawnSync as spawnSync29 } from "node:child_process";
30207
30452
  import { createHash as createHash20 } from "node:crypto";
30208
- import fs33 from "node:fs";
30209
- import path54 from "node:path";
30453
+ import fs34 from "node:fs";
30454
+ import path56 from "node:path";
30210
30455
 
30211
30456
  // packages/workit-core/src/fanout-landed.ts
30212
30457
  import { spawnSync as spawnSync26 } from "node:child_process";
@@ -30439,13 +30684,13 @@ var NOTICE_TTL_MS = 7 * 86400000;
30439
30684
  // packages/workit-core/src/stack.ts
30440
30685
  import { spawnSync as spawnSync28 } from "node:child_process";
30441
30686
  import { createHash as createHash19, randomBytes as randomBytes4 } from "node:crypto";
30442
- import fs32 from "node:fs";
30443
- import path53 from "node:path";
30687
+ import fs33 from "node:fs";
30688
+ import path55 from "node:path";
30444
30689
 
30445
30690
  // packages/workit-core/src/git/ops.ts
30446
30691
  import { spawnSync as spawnSync27 } from "node:child_process";
30447
- import { copyFileSync as copyFileSync3, existsSync as existsSync18, readdirSync as readdirSync7, readFileSync as readFileSync16, rmSync as rmSync4 } from "node:fs";
30448
- import path52 from "node:path";
30692
+ import { copyFileSync as copyFileSync3, existsSync as existsSync19, readdirSync as readdirSync7, readFileSync as readFileSync16, rmSync as rmSync4 } from "node:fs";
30693
+ import path54 from "node:path";
30449
30694
  var COMMIT_TIMEOUT_MS = 10 * 60000;
30450
30695
  var git5 = (cwd, args, options = {}) => {
30451
30696
  const result = spawnSync27("git", args, {
@@ -30478,18 +30723,18 @@ function operationInProgress(cwd) {
30478
30723
  if (!run.ok)
30479
30724
  return null;
30480
30725
  const found = run.stdout.split(`
30481
- `).map((line) => path52.resolve(cwd, line.trim()));
30726
+ `).map((line) => path54.resolve(cwd, line.trim()));
30482
30727
  const conflicted = () => git5(cwd, ["ls-files", "-u"]).stdout.trim() !== "";
30483
30728
  for (const [index, [, operation]] of markers.entries()) {
30484
30729
  const marker = found[index];
30485
- if (!marker || !existsSync18(marker))
30730
+ if (!marker || !existsSync19(marker))
30486
30731
  continue;
30487
- if (index === 1 && existsSync18(path52.join(marker, "applying")))
30732
+ if (index === 1 && existsSync19(path54.join(marker, "applying")))
30488
30733
  return { operation: "am", commitAllowed: false, branch: null };
30489
- if (index === 0 && existsSync18(path52.join(marker, "amend")) && !conflicted()) {
30734
+ if (index === 0 && existsSync19(path54.join(marker, "amend")) && !conflicted()) {
30490
30735
  let headName = "";
30491
30736
  try {
30492
- headName = readFileSync16(path52.join(marker, "head-name"), "utf8").trim();
30737
+ headName = readFileSync16(path54.join(marker, "head-name"), "utf8").trim();
30493
30738
  } catch {}
30494
30739
  const branch = headName.startsWith("refs/heads/") ? headName.slice("refs/heads/".length) : null;
30495
30740
  return { operation, commitAllowed: branch !== null, branch };
@@ -30602,7 +30847,7 @@ function rebasingBranch2(dir) {
30602
30847
  if (!found.ok)
30603
30848
  continue;
30604
30849
  try {
30605
- return fs32.readFileSync(found.stdout.trim(), "utf8").trim();
30850
+ return fs33.readFileSync(found.stdout.trim(), "utf8").trim();
30606
30851
  } catch {}
30607
30852
  }
30608
30853
  return null;
@@ -30610,14 +30855,14 @@ function rebasingBranch2(dir) {
30610
30855
  function rebaseInProgress(dir) {
30611
30856
  for (const name of ["rebase-merge", "rebase-apply"]) {
30612
30857
  const found = gitRun4(dir, ["rev-parse", "--path-format=absolute", "--git-path", name]);
30613
- if (found.ok && fs32.existsSync(found.stdout.trim()))
30858
+ if (found.ok && fs33.existsSync(found.stdout.trim()))
30614
30859
  return true;
30615
30860
  }
30616
30861
  return false;
30617
30862
  }
30618
30863
  var scratchDir = (cwd) => {
30619
30864
  const dir = stacksDir(cwd);
30620
- return dir.ok ? path53.join(dir.data, "worktrees") : null;
30865
+ return dir.ok ? path55.join(dir.data, "worktrees") : null;
30621
30866
  };
30622
30867
  function gitRestack(cwd, input) {
30623
30868
  const owner = worktreeOf(cwd, input.branch);
@@ -30631,8 +30876,8 @@ function gitRestack(cwd, input) {
30631
30876
  worktree: cwd,
30632
30877
  error: "no store root"
30633
30878
  };
30634
- fs32.mkdirSync(scratch, { recursive: true });
30635
- dir = path53.join(scratch, `${input.branch.replace(/[^A-Za-z0-9._-]+/gu, "_").slice(0, 40)}-${randomBytes4(4).toString("hex")}`);
30879
+ fs33.mkdirSync(scratch, { recursive: true });
30880
+ dir = path55.join(scratch, `${input.branch.replace(/[^A-Za-z0-9._-]+/gu, "_").slice(0, 40)}-${randomBytes4(4).toString("hex")}`);
30636
30881
  const added = gitRun4(cwd, ["worktree", "add", "-q", dir, input.branch], GIT_TIMEOUTS.worktree);
30637
30882
  if (!added.ok)
30638
30883
  return {
@@ -30691,7 +30936,7 @@ function stacksDir(cwd) {
30691
30936
  const root = storeRoot(cwd);
30692
30937
  if (!root.ok)
30693
30938
  return stackFail(root.code, root.error, root.unblock);
30694
- return { ok: true, data: path53.join(root.value.root, "stacks") };
30939
+ return { ok: true, data: path55.join(root.value.root, "stacks") };
30695
30940
  }
30696
30941
  var HEARTBEAT_STALE_MS = 2 * 60000;
30697
30942
  var SETTLED_BY_RESTACK = new Set(["checks_pending", "behind_base_required"]);
@@ -30838,7 +31083,7 @@ function fanoutsDir(cwd) {
30838
31083
  const root = storeRoot(cwd);
30839
31084
  if (!root.ok)
30840
31085
  return fanoutFail(root.code, root.error, root.unblock);
30841
- return { ok: true, data: path54.join(root.value.root, "fanouts") };
31086
+ return { ok: true, data: path56.join(root.value.root, "fanouts") };
30842
31087
  }
30843
31088
  function parseStored(raw) {
30844
31089
  if (!isRecord8(raw) || typeof raw.name !== "string" || typeof raw.trunk !== "string")
@@ -30906,10 +31151,10 @@ function readFanout(cwd, name) {
30906
31151
  const dir = fanoutsDir(cwd);
30907
31152
  if (!dir.ok)
30908
31153
  return dir;
30909
- const file = path54.join(dir.data, stackFileName(name));
31154
+ const file = path56.join(dir.data, stackFileName(name));
30910
31155
  let parsed = null;
30911
31156
  try {
30912
- parsed = parseStored(JSON.parse(fs33.readFileSync(file, "utf8")));
31157
+ parsed = parseStored(JSON.parse(fs34.readFileSync(file, "utf8")));
30913
31158
  } catch (error) {
30914
31159
  if (error.code === "ENOENT")
30915
31160
  return { ok: true, data: null };
@@ -30923,7 +31168,7 @@ function listFanouts(cwd) {
30923
31168
  return dir;
30924
31169
  let names = [];
30925
31170
  try {
30926
- names = fs33.readdirSync(dir.data).filter((entry) => entry.endsWith(".json"));
31171
+ names = fs34.readdirSync(dir.data).filter((entry) => entry.endsWith(".json"));
30927
31172
  } catch {
30928
31173
  return { ok: true, data: [] };
30929
31174
  }
@@ -30931,7 +31176,7 @@ function listFanouts(cwd) {
30931
31176
  for (const entry of names) {
30932
31177
  let parsed = null;
30933
31178
  try {
30934
- parsed = parseStored(JSON.parse(fs33.readFileSync(path54.join(dir.data, entry), "utf8")));
31179
+ parsed = parseStored(JSON.parse(fs34.readFileSync(path56.join(dir.data, entry), "utf8")));
30935
31180
  } catch {
30936
31181
  parsed = null;
30937
31182
  }
@@ -31515,10 +31760,15 @@ var createV2Lifecycle = (deps) => {
31515
31760
  commitDispatchStart(data.parentID, live, data.sessionID);
31516
31761
  }
31517
31762
  };
31763
+ let reaped = false;
31518
31764
  const handleEvent = async (event) => {
31519
31765
  const type = event.type;
31520
31766
  if (typeof type !== "string")
31521
31767
  return;
31768
+ if (!reaped) {
31769
+ reaped = true;
31770
+ reapAtStart(root);
31771
+ }
31522
31772
  if (type === "session.created") {
31523
31773
  const data = record2(event.data);
31524
31774
  const sessionID = sessionIDOf(data.sessionID);
@@ -31541,6 +31791,13 @@ var createV2Lifecycle = (deps) => {
31541
31791
  const directory = event.location?.directory;
31542
31792
  if (typeof directory === "string" && !sameWorkspace(root, directory))
31543
31793
  return;
31794
+ endSession({
31795
+ host: "opencode",
31796
+ session: sessionID,
31797
+ agentId: null,
31798
+ reason: "deleted",
31799
+ cwd: root
31800
+ });
31544
31801
  await observeLifecycle(sessionID, binding?.parentID ?? "", "stopped", binding, true);
31545
31802
  return;
31546
31803
  }
@@ -31790,7 +32047,7 @@ var childTaskMissing = (store, input) => {
31790
32047
  var childDenial = (identity) => `OpenCode child session has no validated Workit worker: as ${identity} it may only inspect the task summary (workit_task action "inspect") or record evidence or findings (workit_evidence/workit_finding action "record") on an existing task; for anything else the lead assigns it a worker with workit_worker before launching it`;
31791
32048
 
31792
32049
  // packages/workit-opencode/src/v2/shell.ts
31793
- import path55 from "node:path";
32050
+ import path57 from "node:path";
31794
32051
 
31795
32052
  // packages/workit-core/src/hooks/repeat-failure.ts
31796
32053
  import { createHash as createHash21 } from "node:crypto";
@@ -31853,7 +32110,7 @@ var commandOf = (input) => {
31853
32110
  };
31854
32111
  var hookInput = (root, sessionID, id, shell) => ({
31855
32112
  host: "opencode",
31856
- cwd: shell.workdir ? path55.resolve(root, shell.workdir) : root,
32113
+ cwd: shell.workdir ? path57.resolve(root, shell.workdir) : root,
31857
32114
  session: { id: sessionID, agentId: null, agentType: null, parentId: null },
31858
32115
  permissionMode: null,
31859
32116
  transcriptPath: null,
@@ -32015,6 +32272,237 @@ var injectSkillNudge = (root, session, messages, system) => {
32015
32272
  } catch {}
32016
32273
  };
32017
32274
 
32275
+ // packages/workit-opencode/src/v2/agents.ts
32276
+ import { unwatchFile, watchFile } from "node:fs";
32277
+
32278
+ // packages/workit-claude-code/agents/babysitter.md
32279
+ var babysitter_default = "---\nname: babysitter\ndescription: Drives one pushed PR to its endpoint - polls its status, fixes red CI in the PR's own worktree, answers review threads - and reports when it is ready, merged or blocked. Use to babysit a PR in the background after it is opened.\nmodel: haiku\n---\n\nYou are the workit babysitter for one PR. Follow the workit-ship skill\n(`/workit:ship`): its babysit loop is your job.\n\n1. Work only in the checkout or worktree your prompt names, on the PR's own\n branch; never in another branch. Run Workit against it, one verb per call:\n `workit pr status --cwd <worktree> --json`, `workit check --cwd <worktree> <name>`,\n `workit git --cwd <worktree> commit …`.\n2. Act on `babysit` in `workit pr status --json`: wait, fix a red check at its\n root (reproduce it with `workit check` first), answer each unresolved thread,\n or stop at the endpoint your prompt names (`ready` by default).\n3. Merge only when your prompt or the grant says `merged`; never force-push,\n rebase or retarget unless your prompt says so.\n4. A fix you cannot make in one round, a product choice, or a check that stays\n red after one fix: stop and report it.\n\nBefore your final report, wait for or stop every background command you started\n(the host shows you running while one lives); never report with one still running.\n\nReport: the PR, its head SHA and endpoint, each check and thread you acted on,\nand anything left for the lead.\n";
32280
+
32281
+ // packages/workit-claude-code/agents/decider.md
32282
+ var decider_default = `---
32283
+ name: decider
32284
+ description: Fresh read-only decider for a stuck call - a failed fix round and recheck, or a worker and a reviewer who disagree - that returns the options, a pick by reversibility and the exact change list. Use instead of a third review round; never for a product choice.
32285
+ model: fable
32286
+ effort: high
32287
+ tools: Read, Grep, Glob, Bash, Skill
32288
+ disallowedTools: Write, Edit, NotebookEdit
32289
+ ---
32290
+
32291
+ You are the workit decider. You wrote none of the work and change none of it:
32292
+ you read, decide and report. Follow the workit-fanout skill
32293
+ (\`/workit:fanout\`, "Stuck calls: the decider").
32294
+
32295
+ 1. Read the dispute itself: the brief or acceptance, the diff
32296
+ (\`git -C <worktree> diff <base>...HEAD\`), the failed findings and the
32297
+ author's answer, and \`workit ledger list --type decision\`.
32298
+ 2. List the real options (two or three), each with what it costs if wrong.
32299
+ 3. Pick one by reversibility: the option cheapest to undo wins a tie.
32300
+ 4. Give the exact change list for the pick: file, what changes, and the check
32301
+ that proves it, so the fixer applies it once.
32302
+
32303
+ A product choice, or authority nobody here has, is not yours: say so and name
32304
+ the question for the user. The lead records your pick with
32305
+ \`workit ledger decision\`; you record nothing.
32306
+
32307
+ Before your final report, wait for or stop every background command you started
32308
+ (the host shows you running while one lives); never report with one still running.
32309
+
32310
+ Never commit, push, merge or edit. Write only in your session's scratchpad.
32311
+ `;
32312
+
32313
+ // packages/workit-claude-code/agents/implementer.md
32314
+ var implementer_default = `---
32315
+ name: implementer
32316
+ description: Implements one scoped workit brief in the git worktree its lead made with \`workit fanout worktree create\`, and reports what changed and how it was checked. Use to delegate a well-defined slice (goal, scope, acceptance, verify, forbidden, report, worktree) so it can run in parallel with other work.
32317
+ model: sonnet
32318
+ ---
32319
+
32320
+ You are a workit implementer. You work only in the git worktree your brief
32321
+ names (its WORKTREE line), which the lead made with
32322
+ \`workit fanout worktree create <slice>\` before spawning you; never in the
32323
+ lead's checkout.
32324
+
32325
+ Refuse to start without a complete brief. It must state: goal, scope (files
32326
+ or areas you may touch), acceptance (observable outcomes), verify (exact
32327
+ commands), timebox, forbidden (what you must not touch or do), report (what to
32328
+ hand back), standing orders, mode (\`new\` or \`resume\`) and the worktree path.
32329
+ If a field is missing, report which and stop.
32330
+
32331
+ 1. In a Workit worktree (the default), run each git and check command against
32332
+ it, one verb per call:
32333
+ \`workit git --cwd <worktree> commit …\`, \`workit check --cwd <worktree> <name>\`
32334
+ (verb first, so the host's allow rules match).
32335
+ Never \`cd <worktree> && …\` chains, \`$VAR\` paths or compound commands. Edit
32336
+ files by their path under the worktree. Workit's hooks deny an edit or a
32337
+ mutating git command outside it.
32338
+ 2. The worktree is already on the brief's branch. If it is not: \`MODE: new\`,
32339
+ \`workit git --cwd <worktree> branch <branch> --base <base>\`; \`MODE: resume\`
32340
+ (you replace a stopped worker), \`git -C <worktree> switch <branch>\` and
32341
+ continue from its head. A hook denies protected or non-compliant names;
32342
+ follow the unblock it prints.
32343
+ 3. Stay inside the scope. Anything outside it is a follow-up in the report,
32344
+ not a diff. Follow the workit-implement skill (\`/workit:implement\`).
32345
+ 4. Decide ambiguities yourself and record them:
32346
+ \`workit ledger ruling "<what>" --why "<why>" --cost-if-wrong "<cost>"\`.
32347
+ Stop only for an irreversible or security-sensitive action, or a side effect
32348
+ outside your worktree.
32349
+ 5. Commit in small steps with
32350
+ \`workit git --cwd <worktree> commit -m "<conventional message>" -- <paths in scope>\`.
32351
+ Add Co-Authored-By in the same commit with
32352
+ \`workit git commit --trailer "Co-Authored-By: <name> <email>" -- <paths>\`
32353
+ (the brief's RULES give your host's exact line), never by amending.
32354
+ 6. Run every verify command as \`workit check --cwd <worktree> …\` and keep the
32355
+ real exit codes.
32356
+ 7. Never record a verdict on your own work and never pass \`--self\`: a separate
32357
+ verifier judges it. Never push, open a PR, rebase or merge unless the brief
32358
+ says so.
32359
+
32360
+ In a Claude Code host-isolated worktree (\`.claude/worktrees/agent-<id>\`,
32361
+ whose SubagentStart text says "Run git as plain") the rule flips: run git as
32362
+ plain commands there, never \`workit git …\` (Claude Code's isolation refuses a
32363
+ git wrapper), and keep workit for \`check\`, \`ledger\` and \`pr\`.
32364
+
32365
+ Before your final report, wait for or stop every background command you started
32366
+ (the host shows you running while one lives); never report with one still running.
32367
+
32368
+ Report: worktree, branch and head SHA, files changed, each verify command with
32369
+ its exit code, each acceptance item met or not, rulings recorded, and any
32370
+ deviation from the brief.
32371
+ `;
32372
+
32373
+ // packages/workit-claude-code/agents/reviewer.md
32374
+ var reviewer_default = `---
32375
+ name: reviewer
32376
+ description: Fresh-context reviewer for a workit branch or PR - spec fidelity and standards as separate axes, test quality and blast radius - that records findings and a non-author verdict. Use for independent review of a diff, branch or PR.
32377
+ model: opus
32378
+ tools: Read, Grep, Glob, Bash, Skill
32379
+ disallowedTools: Write, Edit, NotebookEdit
32380
+ ---
32381
+
32382
+ You are the workit reviewer. Review the real candidate, not the author's
32383
+ account. Follow the workit-review skill (\`/workit:review\`).
32384
+
32385
+ 1. Pin the candidate: \`git rev-parse HEAD\`, the base, \`git diff <base>...HEAD\`;
32386
+ for a PR, \`workit pr status --json\` (checks, unresolved threads).
32387
+ 2. Read the intent: brief or acceptance, spec, PR body, and
32388
+ \`workit ledger list --type decision\`.
32389
+ 3. Judge two axes separately: spec fidelity (missing, creep, wrong; quote the
32390
+ line) and standards (repo rules first, then smells). Then test quality
32391
+ (\`workit test-audit --diff\`) and blast radius: one fact plus one proof per
32392
+ touched contract or caller, run with \`workit check -- <cmd>\`; label anything
32393
+ unproven UNPROVEN.
32394
+ 4. Each finding: file:line, severity (blocker, major, minor, nit), evidence
32395
+ (hunk, test or output), concrete fix.
32396
+ 5. Record the verdict:
32397
+ start from the exact verdict command the SubagentStart hook gave you (it
32398
+ carries your session and \`--token=<token>\`; the token is yours alone: never put it in a report); it names \`--kind review\`:
32399
+ \`workit ledger verdict verified|failed|blocked --cwd <candidate worktree> --kind review --branch <b> --session <id> --token=<token> --how "<what you read and ran>"\`
32400
+ (\`verified\`: no blocker or major left).
32401
+ Record a design choice as \`workit ledger ruling\`.
32402
+
32403
+ Before your final report, wait for or stop every background command you started
32404
+ (the host shows you running while one lives); never report with one still running.
32405
+
32406
+ Never commit, push, merge or edit. Write only in the candidate
32407
+ worktree's \`.workit-scratch/\` or your session's scratchpad: test cases go into files there via a quoted heredoc
32408
+ (\`<<'EOF'\`), never run by the shell. A \`node -e\` or \`python3 -c\` that only reads runs anywhere. If the ledger refuses you as an author, report that instead of a verdict.
32409
+ `;
32410
+
32411
+ // packages/workit-claude-code/agents/verifier.md
32412
+ var verifier_default = `---
32413
+ name: verifier
32414
+ description: Independently verifies a workit candidate (branch, commit or PR) on its real surface and records a SHA-keyed verdict in the ledger. Use after an implementer finishes and before shipping, never on work this session authored.
32415
+ model: sonnet
32416
+ tools: Read, Grep, Glob, Bash, Skill
32417
+ disallowedTools: Write, Edit, NotebookEdit
32418
+ ---
32419
+
32420
+ You are the workit verifier. You did not write the candidate and never
32421
+ change it: you observe, judge and record. Work backward from the goal: what
32422
+ must be true, exist and be wired. The author's summary is a claim:
32423
+ the goal is unmet until you observe it.
32424
+
32425
+ 1. Pin the candidate in its own checkout (run workit as
32426
+ \`workit <verb> --cwd <worktree> …\`, verb first; never \`cd\` first): \`git -C <worktree> rev-parse HEAD\` and \`git -C <worktree> status --short\`. A dirty tree
32427
+ or a moving HEAD is a finding; the ledger refuses a verdict on it.
32428
+ 2. Read the brief: goal, acceptance (Given/When/Then), verify commands.
32429
+ 3. Run every verify command through the CLI:
32430
+ \`workit check <name>\` for configured checks, \`workit check -- <cmd>\` for the
32431
+ rest. Never substitute an easier command. Run every configured check by name
32432
+ (your SubagentStart context lists them) or cite green CI on that head, else \`verified\` is refused.
32433
+ 4. Drive the real surface with the project's \`verify-<app>\` skill when it
32434
+ exists (\`/workit:verify-app\` generates one). Tests alone are unit evidence.
32435
+ 5. Judge each acceptance line met, not met or not verifiable, citing what
32436
+ you observed. Label every claim measured, inferred or guess.
32437
+ 6. Record the verdict, then report it:
32438
+ start from the exact verdict command the SubagentStart hook put in your context (it
32439
+ carries your session and \`--token=<token>\`; you share the lead's
32440
+ \`WORKIT_SESSION_ID\`, which authored the work) and pick its \`--kind <live|unit>\`:
32441
+ \`workit ledger verdict verified|tests-verified|type-check-only|failed|blocked --cwd <candidate worktree> --kind <live|unit> --branch <b> --session <id> --token=<token> --how "<what you ran and saw>"\`.
32442
+ \`verified\` means the change was seen working on its real surface
32443
+ (verify-<app>, \`--kind live\`); \`tests-verified\` means only tests ran. If the ledger refuses you as an author, report that;
32444
+ never pass \`--self\`.
32445
+
32446
+ Before your final report, wait for or stop every background command you started
32447
+ (the host shows you running while one lives); never report with one still running.
32448
+
32449
+ Write only in the candidate worktree's \`.workit-scratch/\` or your session's
32450
+ scratchpad: a test case goes in a file there via a quoted heredoc (\`<<'EOF'\`),
32451
+ never run by the shell. Reads (\`git fetch -q origin\`, a \`node -e\` or \`python3 -c\`
32452
+ that only reads) run anywhere.
32453
+
32454
+ Report: candidate SHA, each check with its exit code, each acceptance line,
32455
+ the verdict row you recorded. Fix nothing: a failing check is a verdict.
32456
+ `;
32457
+
32458
+ // packages/workit-opencode/src/v2/agents.ts
32459
+ var OPENCODE_AGENTS = [
32460
+ { id: "workit-implementer", role: "implementer", markdown: implementer_default, readOnly: false },
32461
+ { id: "workit-verifier", role: "verifier", markdown: verifier_default, readOnly: true },
32462
+ { id: "workit-reviewer", role: "reviewer", markdown: reviewer_default, readOnly: true },
32463
+ { id: "workit-decider", role: "decider", markdown: decider_default, readOnly: true },
32464
+ { id: "workit-babysitter", role: "babysit", markdown: babysitter_default, readOnly: false }
32465
+ ];
32466
+ var opencodeAgentModel = (value) => {
32467
+ const match = /^([^\s/#]+)\/([^\s#]+)(?:#(\S+))?$/u.exec(value.trim());
32468
+ if (!match)
32469
+ return null;
32470
+ const [, providerID, id, variant] = match;
32471
+ return variant ? { providerID, id, variant } : { providerID, id };
32472
+ };
32473
+ var opencodeAgentText = (markdown) => {
32474
+ const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/u.exec(markdown);
32475
+ const description = /^description:\s*(.+)$/mu.exec(match?.[1] ?? "")?.[1].trim() ?? "";
32476
+ const system = (match?.[2] ?? markdown).trim().replace(/\n\nIn a Claude Code host-isolated worktree[\s\S]*?(?=\n\n)/u, "").replace(/\(`\/workit:([a-z-]+)`\)/gu, "(call the skill tool with `workit-$1`)").replace(/`\/workit:([a-z-]+)`/gu, "`workit-$1`").replace(/\(it\s+carries your session and `--token=<token>`;[^)]*\)/gu, "(it names no --session or --token: your shell already acts as your own session)").replaceAll(" --session <id> --token=<token>", "");
32477
+ return { description, system };
32478
+ };
32479
+ var roleModel = (root, role) => role === "implementer" ? uniformImplementerModel(root, "opencode") : resolveAvailableRoleModel(root, { role }, "opencode");
32480
+ var registerRoleAgents = (root, editor) => {
32481
+ for (const agent of OPENCODE_AGENTS) {
32482
+ const { description, system } = opencodeAgentText(agent.markdown);
32483
+ const configured = roleModel(root, agent.role);
32484
+ const model = configured ? opencodeAgentModel(configured.model) : null;
32485
+ editor.update(agent.id, (info) => {
32486
+ info.description = description;
32487
+ info.system = system;
32488
+ info.mode = "subagent";
32489
+ if (model)
32490
+ info.model = model;
32491
+ if (agent.readOnly)
32492
+ info.permissions.push({ action: "edit", resource: "*", effect: "deny" });
32493
+ });
32494
+ }
32495
+ };
32496
+ var installRoleAgents = async (root, agents) => {
32497
+ if (!agents?.transform)
32498
+ return () => {};
32499
+ await agents.transform((editor) => registerRoleAgents(root, editor));
32500
+ const file = workspacesPath();
32501
+ const reload = () => void agents.reload?.().catch(() => {});
32502
+ watchFile(file, { interval: 2000, persistent: false }, reload);
32503
+ return () => unwatchFile(file, reload);
32504
+ };
32505
+
32018
32506
  // packages/workit-opencode/src/v2/spawn-model.ts
32019
32507
  var opencodeSubagentModel = (value) => {
32020
32508
  const trimmed = value.trim();
@@ -32031,6 +32519,9 @@ var applySpawnModel = (root, event, notes) => {
32031
32519
  if (!selector)
32032
32520
  return;
32033
32521
  const choice = chooseSpawnModel(root, selector, "opencode", { model: fields.model }, opencodeSubagentModel);
32522
+ const agentModel = typeof fields.agent === "string" && fields.agent.startsWith("workit-") && selector.role !== "implementer" ? resolveRoleModels(root, selector, "opencode")[0]?.model : undefined;
32523
+ if (choice.model && choice.model === agentModel)
32524
+ return;
32034
32525
  if (choice.model)
32035
32526
  fields.model = choice.model;
32036
32527
  if (choice.note)
@@ -32133,38 +32624,38 @@ var createStopControl = (root, port) => {
32133
32624
  };
32134
32625
 
32135
32626
  // packages/workit-opencode/src/v2/registry.ts
32136
- import { existsSync as existsSync20, readFileSync as readFileSync17 } from "node:fs";
32137
- import path57 from "node:path";
32627
+ import { existsSync as existsSync21, readFileSync as readFileSync17 } from "node:fs";
32628
+ import path59 from "node:path";
32138
32629
 
32139
32630
  // packages/workit-opencode/src/shared/assets.ts
32140
- import { existsSync as existsSync19, realpathSync as realpathSync13 } from "node:fs";
32141
- import path56 from "node:path";
32631
+ import { existsSync as existsSync20, realpathSync as realpathSync13 } from "node:fs";
32632
+ import path58 from "node:path";
32142
32633
  import { fileURLToPath as fileURLToPath2 } from "node:url";
32143
32634
  var moduleDir = () => {
32144
32635
  try {
32145
- return realpathSync13(path56.dirname(fileURLToPath2(import.meta.url)));
32636
+ return realpathSync13(path58.dirname(fileURLToPath2(import.meta.url)));
32146
32637
  } catch {
32147
- return path56.dirname(fileURLToPath2(import.meta.url));
32638
+ return path58.dirname(fileURLToPath2(import.meta.url));
32148
32639
  }
32149
32640
  };
32150
32641
  var packageRoot2 = () => {
32151
32642
  const dir = moduleDir();
32152
32643
  for (const candidate of [
32153
- path56.resolve(dir, ".."),
32154
- path56.resolve(dir, "..", ".."),
32155
- path56.resolve(dir, "..", "..", "..")
32644
+ path58.resolve(dir, ".."),
32645
+ path58.resolve(dir, "..", ".."),
32646
+ path58.resolve(dir, "..", "..", "..")
32156
32647
  ]) {
32157
- if (existsSync19(path56.join(candidate, "package.json")))
32648
+ if (existsSync20(path58.join(candidate, "package.json")))
32158
32649
  return candidate;
32159
32650
  }
32160
- return path56.resolve(dir, "..");
32651
+ return path58.resolve(dir, "..");
32161
32652
  };
32162
32653
  var skillsRoot = () => {
32163
32654
  const root = packageRoot2();
32164
- const canonical = path56.resolve(root, "..", "workit-core", "skills");
32165
- if (existsSync19(path56.join(root, "src")) && existsSync19(canonical))
32655
+ const canonical = path58.resolve(root, "..", "workit-core", "skills");
32656
+ if (existsSync20(path58.join(root, "src")) && existsSync20(canonical))
32166
32657
  return canonical;
32167
- return path56.join(root, "assets", "skills");
32658
+ return path58.join(root, "assets", "skills");
32168
32659
  };
32169
32660
 
32170
32661
  // packages/workit-opencode/src/v2/registry.ts
@@ -32188,15 +32679,15 @@ var parseFrontmatter = (markdown) => {
32188
32679
  };
32189
32680
  var registerSkills = async (ctx) => {
32190
32681
  const skillsDir = skillsRoot();
32191
- if (!existsSync20(skillsDir))
32682
+ if (!existsSync21(skillsDir))
32192
32683
  return new Set;
32193
32684
  const listed = await ctx.skill.list().catch(() => ({ data: [] }));
32194
- const own = (skill) => typeof skill.path === "string" && path57.resolve(skill.path).startsWith(skillsDir + path57.sep);
32685
+ const own = (skill) => typeof skill.path === "string" && path59.resolve(skill.path).startsWith(skillsDir + path59.sep);
32195
32686
  const userSkills = new Set((listed?.data ?? []).filter((skill) => !own(skill)).map((skill) => skill.id));
32196
32687
  const packaged = new Map;
32197
32688
  for (const id of WORKIT_METHOD_SKILLS) {
32198
- const file = path57.join(skillsDir, id, "SKILL.md");
32199
- if (!userSkills.has(id) && existsSync20(file))
32689
+ const file = path59.join(skillsDir, id, "SKILL.md");
32690
+ if (!userSkills.has(id) && existsSync21(file))
32200
32691
  packaged.set(id, file);
32201
32692
  }
32202
32693
  await ctx.skill.transform((editor) => {
@@ -32242,106 +32733,25 @@ var registerCommands = async (ctx, registeredSkills) => {
32242
32733
  };
32243
32734
 
32244
32735
  // packages/workit-opencode/src/stale-sources.ts
32245
- import { existsSync as existsSync21, readdirSync as readdirSync8 } from "node:fs";
32246
- import path58 from "node:path";
32736
+ import { existsSync as existsSync22, readdirSync as readdirSync8 } from "node:fs";
32737
+ import path60 from "node:path";
32247
32738
  import { fileURLToPath as fileURLToPath3 } from "node:url";
32248
32739
  var typescriptFiles = (directory) => {
32249
- if (!existsSync21(directory))
32740
+ if (!existsSync22(directory))
32250
32741
  return [];
32251
32742
  return readdirSync8(directory, { withFileTypes: true }).flatMap((entry) => {
32252
- const file = path58.join(directory, entry.name);
32743
+ const file = path60.join(directory, entry.name);
32253
32744
  return entry.isDirectory() ? typescriptFiles(file) : entry.isFile() && file.endsWith(".ts") ? [file] : [];
32254
32745
  });
32255
32746
  };
32256
32747
  var pluginSourceFiles = [
32257
32748
  ...new Set([
32258
32749
  fileURLToPath3(import.meta.url),
32259
- ...typescriptFiles(path58.join(packageRoot2(), "src")),
32260
- path58.join(packageRoot2(), "..", "workit-core", "src", "core.ts"),
32261
- ...typescriptFiles(path58.join(packageRoot2(), "..", "workit-core", "src", "core"))
32750
+ ...typescriptFiles(path60.join(packageRoot2(), "src")),
32751
+ path60.join(packageRoot2(), "..", "workit-core", "src", "core.ts"),
32752
+ ...typescriptFiles(path60.join(packageRoot2(), "..", "workit-core", "src", "core"))
32262
32753
  ])
32263
- ].filter((file) => existsSync21(file)).toSorted();
32264
-
32265
- // packages/workit-core/src/core/cli-locate.ts
32266
- import { closeSync as closeSync3, existsSync as existsSync22, openSync as openSync3, readSync } from "node:fs";
32267
- import path59 from "node:path";
32268
- var LAUNCHER_MARKER = "workit-owned-launcher";
32269
- var CLI_PACKAGE_PATH = ["node_modules", "@workit-dev", "cli"];
32270
- var installRoot = (env, platform = process.platform) => {
32271
- if (env.WORKIT_INSTALL_ROOT)
32272
- return env.WORKIT_INSTALL_ROOT;
32273
- const data = dataDir(env, platform);
32274
- return platform === "win32" ? path59.join(data, "install") : data;
32275
- };
32276
- var ownedLauncherPath = (env, platform = process.platform) => path59.join(installRoot(env, platform), "bin", platform === "win32" ? "workit.cmd" : "workit");
32277
- var ownedCurrentEntry = (env, platform = process.platform) => path59.join(installRoot(env, platform), "current", ...CLI_PACKAGE_PATH, "dist", "index.js");
32278
- var head = (file) => {
32279
- let fd;
32280
- try {
32281
- fd = openSync3(file, "r");
32282
- const buffer = Buffer.alloc(256);
32283
- const read = readSync(fd, buffer, 0, buffer.length, 0);
32284
- return buffer.subarray(0, read).toString("utf8");
32285
- } catch {
32286
- return "";
32287
- } finally {
32288
- if (fd !== undefined)
32289
- closeSync3(fd);
32290
- }
32291
- };
32292
- var locateWorkitCli = (options = {}) => {
32293
- const env = options.env ?? process.env;
32294
- const platform = options.platform ?? process.platform;
32295
- const exists = options.exists ?? existsSync22;
32296
- const read = options.read ?? head;
32297
- const node = options.node ?? process.execPath;
32298
- const launcher = ownedLauncherPath(env, platform);
32299
- if (exists(launcher) && read(launcher).includes(LAUNCHER_MARKER))
32300
- return {
32301
- source: "owned-launcher",
32302
- command: launcher,
32303
- args: [],
32304
- binDir: path59.dirname(launcher)
32305
- };
32306
- const current = ownedCurrentEntry(env, platform);
32307
- if (exists(current))
32308
- return {
32309
- source: "owned-current",
32310
- command: node,
32311
- args: [current],
32312
- binDir: null
32313
- };
32314
- if (options.bundled && exists(options.bundled))
32315
- return {
32316
- source: "bundled",
32317
- command: node,
32318
- args: [options.bundled],
32319
- binDir: null
32320
- };
32321
- return { source: "path", command: "workit", args: [], binDir: null };
32322
- };
32323
- var pathKey = (env) => Object.keys(env).find((key) => key.toUpperCase() === "PATH") ?? "PATH";
32324
- var workitCliEnv = (located, env = process.env, platform = process.platform) => {
32325
- if (located.source === "path")
32326
- return {};
32327
- const patch = {
32328
- WORKIT_CLI: [located.command, ...located.args].join(" ")
32329
- };
32330
- if (located.binDir) {
32331
- const key = pathKey(env);
32332
- const delimiter = platform === "win32" ? ";" : ":";
32333
- const same = (dir) => platform === "win32" ? path59.win32.normalize(dir).toLowerCase() === path59.win32.normalize(located.binDir).toLowerCase() : path59.posix.normalize(dir) === path59.posix.normalize(located.binDir);
32334
- const rest = (env[key] ?? "").split(delimiter).filter((dir) => dir && !same(dir));
32335
- patch[key] = [located.binDir, ...rest].join(delimiter);
32336
- }
32337
- return patch;
32338
- };
32339
- var useOwnedWorkitCli = (options = {}) => {
32340
- const env = options.env ?? process.env;
32341
- const located = locateWorkitCli({ ...options, env });
32342
- Object.assign(env, workitCliEnv(located, env, options.platform));
32343
- return located;
32344
- };
32754
+ ].filter((file) => existsSync22(file)).toSorted();
32345
32755
 
32346
32756
  // packages/workit-opencode/src/cli-path.ts
32347
32757
  var useOwnedCliInOpencode = (env = process.env) => useOwnedWorkitCli({ env });
@@ -32481,6 +32891,7 @@ var setup = async (ctx) => {
32481
32891
  });
32482
32892
  }
32483
32893
  });
32894
+ const stopRoleAgents = await installRoleAgents(root, ctx.agent);
32484
32895
  const shellWorkdirs = new Map;
32485
32896
  const pendingShells = new Map;
32486
32897
  const spawnNotes = new Map;
@@ -32596,6 +33007,7 @@ var setup = async (ctx) => {
32596
33007
  })();
32597
33008
  return () => {
32598
33009
  subscription.abort();
33010
+ stopRoleAgents();
32599
33011
  };
32600
33012
  };
32601
33013
  var definition = define({ id: "workit", setup });