@workit-dev/pi 2.4.3 → 2.5.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/workit.js CHANGED
@@ -26425,7 +26425,21 @@ var gitOutputs = (args) => {
26425
26425
  if (output !== undefined)
26426
26426
  files.push(output);
26427
26427
  if (sub === "init")
26428
- files.push(names[0] ?? ".");
26428
+ files.push(names[0] ?? "./");
26429
+ if (sub === "init" || sub === "clone") {
26430
+ const separate = valueOf(rest, /^--separate-git-dir=?(.*)$/s);
26431
+ if (separate !== undefined)
26432
+ files.push(separate);
26433
+ }
26434
+ if (sub === "worktree") {
26435
+ const end = rest.includes("--") ? rest.indexOf("--") : rest.length;
26436
+ const named = [
26437
+ ...rest.slice(1, end).filter((arg, index, words) => !arg.startsWith("-") && !/^(?:-[bB]|--reason)$/.test(words[index - 1] ?? "")),
26438
+ ...rest.slice(end + 1)
26439
+ ];
26440
+ const count = { add: 1, move: 2, remove: 1, repair: named.length || 1 }[rest[0] ?? ""] ?? 0;
26441
+ files.push(...(named.length ? named : ["."]).slice(0, count));
26442
+ }
26429
26443
  if (sub === "clone")
26430
26444
  files.push(names[1] ?? names[0]?.replace(/(?:\.git)?[\\/]*$/, "").split(/[\\/:]/).at(-1) ?? ".");
26431
26445
  if (sub === "format-patch" && !has(/^--stdout$/))
@@ -26543,6 +26557,28 @@ var MUTATING_GIT = new Set([
26543
26557
  var DRY_N = new Set(["add", "clean", "rm", "mv"]);
26544
26558
  var MUTATING_WORKIT_GIT = new Set(["commit", "branch", "stage", "unstage"]);
26545
26559
  var DIR_TARGET = ".workit-live-target";
26560
+ var PLACEHOLDERS = new WeakMap;
26561
+ var collecting = null;
26562
+ var placeholderIn = (dir, name) => {
26563
+ const target = path41.join(dir, name);
26564
+ collecting?.add(target);
26565
+ return target;
26566
+ };
26567
+ var recording = (make) => {
26568
+ const outer = collecting;
26569
+ const found = new Set;
26570
+ collecting = found;
26571
+ try {
26572
+ const targets = make();
26573
+ PLACEHOLDERS.set(targets, found);
26574
+ for (const target of found)
26575
+ outer?.add(target);
26576
+ return targets;
26577
+ } finally {
26578
+ collecting = outer;
26579
+ }
26580
+ };
26581
+ var placeholdersOf = (targets) => PLACEHOLDERS.get(targets) ?? new Set;
26546
26582
  var OPAQUE_TARGET = ".workit-runs-";
26547
26583
  var UNRESOLVED_TARGET = ".workit-unresolved-target";
26548
26584
  var OVERRIDE = "WORKIT_LIVE_SESSION=override";
@@ -26814,7 +26850,7 @@ var segmentTargets = (cwd, command, dialect, depth = 0, strict = false, inherite
26814
26850
  return [unknownVarTarget(home)];
26815
26851
  if (path41.isAbsolute(home))
26816
26852
  return [home];
26817
- return base === undefined ? [] : [path41.resolve(base, home)];
26853
+ return base === undefined ? [] : [resolvedUnder(base, home)];
26818
26854
  });
26819
26855
  const at = (file) => {
26820
26856
  const all = atAll(file);
@@ -27046,7 +27082,7 @@ var segmentTargets = (cwd, command, dialect, depth = 0, strict = false, inherite
27046
27082
  for (const file of opaque ?? [])
27047
27083
  for (const resolved of atAll(file))
27048
27084
  if (!quiet || !isRoot(resolved))
27049
- targets.push(file === "." ? path41.join(resolved, here) : resolved);
27085
+ targets.push(file === "." ? placeholderIn(resolved, here) : path41.basename(resolved).startsWith(OPAQUE_TARGET) ? placeholderIn(path41.dirname(resolved), path41.basename(resolved)) : resolved);
27050
27086
  const ln = words.findIndex((word) => /^ln$/i.test(word.split(/[\\/]/).at(-1) ?? ""));
27051
27087
  const lnArgs = words.slice(ln + 1);
27052
27088
  if (ln >= 0 && words.slice(0, ln).every((word) => PREFIXES2.has(word)) && (strict !== "registry" || !lnArgs.some((arg) => /^-[a-zA-Z]*s|^--symbolic$/.test(arg))))
@@ -27058,7 +27094,7 @@ var segmentTargets = (cwd, command, dialect, depth = 0, strict = false, inherite
27058
27094
  const edits = editsOf(body);
27059
27095
  if (edits === null) {
27060
27096
  if (dir !== undefined)
27061
- targets.push(path41.join(dir, DIR_TARGET));
27097
+ targets.push(placeholderIn(dir, DIR_TARGET));
27062
27098
  } else
27063
27099
  for (const file of edits)
27064
27100
  targets.push(...atAll(file));
@@ -27066,7 +27102,7 @@ var segmentTargets = (cwd, command, dialect, depth = 0, strict = false, inherite
27066
27102
  for (const invocation of workitInvocations(body.map(quoteWord2).join(" "), "posix")) {
27067
27103
  const { at: runsIn, args } = workitCwd(dir, invocation, atAll);
27068
27104
  if (args[0] === "git" && MUTATING_WORKIT_GIT.has(args[1] ?? "") && !inert(args.slice(2), ""))
27069
- targets.push(...runsIn.map((runs) => path41.join(runs, DIR_TARGET)));
27105
+ targets.push(...runsIn.map((runs) => placeholderIn(runs, DIR_TARGET)));
27070
27106
  }
27071
27107
  }
27072
27108
  return targets;
@@ -27086,10 +27122,10 @@ var workitCwd = (dir, args, resolve) => {
27086
27122
  var shellMutationTargets = (cwd, command, dialect = "posix", strict = false) => {
27087
27123
  try {
27088
27124
  const env = new Map(strict === "registry" ? [...command.matchAll(/\$\{?([A-Za-z_]\w*)/g)].filter((match) => !/^(?:OLD)?PWD$/.test(match[1])).map((match) => [match[1], process.env[match[1]] ?? ""]) : []);
27089
- return [
27125
+ return recording(() => [
27090
27126
  ...segmentTargets(cwd, command, dialect, 0, strict, env),
27091
- ...gitMutationDirs(cwd, command, dialect).map((dir) => path41.join(dir, DIR_TARGET))
27092
- ];
27127
+ ...gitMutationDirs(cwd, command, dialect).map((dir) => placeholderIn(dir, DIR_TARGET))
27128
+ ]);
27093
27129
  } catch (error) {
27094
27130
  if (strict === "registry")
27095
27131
  throw error;
@@ -27148,7 +27184,8 @@ var claimAll = (owner, targets, deps) => {
27148
27184
  for (const target of guarded(targets))
27149
27185
  claimLiveSession(target, owner, deps);
27150
27186
  };
27151
- var liveTargets = (cwd, paths) => paths?.length ? paths.map((file) => path41.resolve(cwd, file)) : [path41.join(cwd, DIR_TARGET)];
27187
+ var resolvedUnder = (dir, file) => !/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(file) ? path41.resolve(dir, file) : path41.isAbsolute(file) ? file : `${dir}${path41.sep}${file}`;
27188
+ var liveTargets = (cwd, paths) => recording(() => paths?.length ? paths.map((file) => resolvedUnder(cwd, file)) : [placeholderIn(cwd, DIR_TARGET)]);
27152
27189
  var CONFIG_FILES = ["workspaces.json", SEAL_FILE];
27153
27190
  var configDirs = () => [resolveConfigDir(), grantsDir()];
27154
27191
  var globbed = (cwd, target, state, configs) => {
@@ -27934,11 +27971,11 @@ var writePaths = (input) => {
27934
27971
  };
27935
27972
  // packages/workit-core/src/hooks/standing.ts
27936
27973
  import fs30 from "node:fs";
27937
- import path45 from "node:path";
27974
+ import path46 from "node:path";
27938
27975
 
27939
27976
  // packages/workit-core/src/approvals/store.ts
27940
27977
  import { createHash as createHash19, randomBytes as randomBytes4 } from "node:crypto";
27941
- import { mkdirSync as mkdirSync6, readdirSync as readdirSync6, readFileSync as readFileSync13 } from "node:fs";
27978
+ import { mkdirSync as mkdirSync6, readdirSync as readdirSync6, readFileSync as readFileSync13, rmSync as rmSync3 } from "node:fs";
27942
27979
  import path43 from "node:path";
27943
27980
  var REQUEST_TTL_MS = 30 * 60000;
27944
27981
  var GRANT_TTL_MS = 15 * 60000;
@@ -27969,6 +28006,13 @@ var write = (file, value) => {
27969
28006
  `);
27970
28007
  };
27971
28008
  var live = (expires, now) => Date.parse(expires) > now.getTime();
28009
+ var names2 = (part) => {
28010
+ try {
28011
+ return readdirSync6(dirOf(part)).filter((name) => name.endsWith(".json"));
28012
+ } catch {
28013
+ return [];
28014
+ }
28015
+ };
27972
28016
  var later = (now, ms) => new Date(now.getTime() + ms).toISOString();
27973
28017
  var readApprovalRequest = (id) => {
27974
28018
  if (!isApprovalId(id))
@@ -28000,12 +28044,21 @@ var liveApprovalRequest = (id, now = new Date) => {
28000
28044
  };
28001
28045
  return { ok: true, request };
28002
28046
  };
28003
- var subjectLine = (subject) => Object.entries(subject).map(([key, value]) => `${key}: ${typeof value === "string" ? value : JSON.stringify(value)}`).join("; ");
28047
+ var SHOWN_LINES = 60;
28048
+ var shownText = (text, indent = " ") => {
28049
+ const lines = text.trimEnd().split(/\r?\n/u);
28050
+ const more = lines.length - SHOWN_LINES;
28051
+ if (more > 0)
28052
+ lines.splice(SHOWN_LINES, more, `… ${more} more lines`);
28053
+ return lines.map((line) => indent + line);
28054
+ };
28055
+ var subjectLines = (subject) => Object.entries(subject).flatMap(([key, value]) => typeof value === "string" && value.includes(`
28056
+ `) ? [` ${key}:`, ...shownText(value)] : [` ${key}: ${typeof value === "string" ? value : JSON.stringify(value)}`]);
28004
28057
  var renderApprovalRequest = (request) => [
28005
28058
  `${request.id} (${request.kind}): ${request.action}`,
28006
28059
  ` target: ${Object.entries(request.target).map(([key, value]) => `${key} ${value}`).join(", ")}`,
28007
28060
  ` effect: ${request.effect}`,
28008
- ` subject: ${subjectLine(request.subject)}`,
28061
+ ...subjectLines(request.subject),
28009
28062
  ` hash: ${request.hash.slice(0, 12)} expires: ${request.expires}`
28010
28063
  ].join(`
28011
28064
  `);
@@ -28067,6 +28120,31 @@ var recordApprovalRejected = (input, now = new Date) => {
28067
28120
  write(fileOf("rejected", input.id), { ...input, at: now.toISOString() });
28068
28121
  };
28069
28122
  var ASKING_HOSTS = new Set(["claude_code", "pi"]);
28123
+ var INLINE_ASK_TTL_MS = 2 * 60000;
28124
+ var INLINE_TICKET_ENV = "WORKIT_APPROVAL_TICKET";
28125
+ var namesTicket = (text) => /WORKIT_APPROVAL_(?:TICKET|UNASKED)/u.test(text.replace(/['"\\]/gu, ""));
28126
+ var TICKET_DENY = "Only the host's prompt adds an approval ticket.";
28127
+ var dropInline = (drop) => {
28128
+ for (const name of names2("inline")) {
28129
+ const file = path43.join(dirOf("inline"), name);
28130
+ const row = readJson3(file);
28131
+ if (!row || drop(row))
28132
+ rmSync3(file, { force: true });
28133
+ }
28134
+ };
28135
+ var sha = (text) => createHash19("sha256").update(text).digest("hex");
28136
+ var recordInlineAsk = (input, now = new Date, ttlMs = INLINE_ASK_TTL_MS) => {
28137
+ dropInline((row) => row.argvHash === input.argvHash && row.contentHash === input.contentHash);
28138
+ const ticket = randomBytes4(24).toString("base64url");
28139
+ const asked = {
28140
+ ...input,
28141
+ ticketHash: sha(ticket),
28142
+ at: now.toISOString(),
28143
+ expires: later(now, ttlMs)
28144
+ };
28145
+ write(fileOf("inline", asked.ticketHash), asked);
28146
+ return { ticket, asked };
28147
+ };
28070
28148
 
28071
28149
  // packages/workit-core/src/approvals/call.ts
28072
28150
  var isWorkitWord2 = (word) => /^(?:.*[\\/])?workit(?:-cli)?$/u.test(word);
@@ -28109,6 +28187,139 @@ var approveCallIn = (command, dialect = "posix") => {
28109
28187
  };
28110
28188
  var approveCallDeny = (fix) => `Run \`${fix}\` as its own call: no chain, pipe, substitution, leading cd, env prefix or redirect around it, so the host can show the request and record the user's answer.`;
28111
28189
 
28190
+ // packages/workit-core/src/approvals/youtrack-ask.ts
28191
+ import { createHash as createHash20 } from "node:crypto";
28192
+ import { readFileSync as readFileSync14, realpathSync as realpathSync11 } from "node:fs";
28193
+ import path44 from "node:path";
28194
+ var TIME = "markdown file minutes text date";
28195
+ var FLAGS = {
28196
+ note: TIME,
28197
+ time: TIME,
28198
+ meeting: TIME,
28199
+ update: `${TIME} attach state command`,
28200
+ create: "project summary description file attach command"
28201
+ };
28202
+ var isYouTrackWriteVerb = (word) => Object.hasOwn(FLAGS, word ?? "");
28203
+ var sha2563 = (data) => createHash20("sha256").update(data).digest("hex");
28204
+ var youTrackAsk = (args, cwd, load = readFileSync14) => {
28205
+ const [verb = "", ...rest] = args;
28206
+ if (!isYouTrackWriteVerb(verb))
28207
+ return null;
28208
+ const known = FLAGS[verb]?.split(" ") ?? [];
28209
+ const values = {};
28210
+ const attach = [];
28211
+ const positionals = [];
28212
+ for (let index = 0;index < rest.length; index += 1) {
28213
+ const arg = rest[index] ?? "";
28214
+ if (arg === "--") {
28215
+ positionals.push(...rest.slice(index + 1));
28216
+ break;
28217
+ }
28218
+ if (arg === "--json")
28219
+ continue;
28220
+ if (!arg.startsWith("--")) {
28221
+ positionals.push(arg);
28222
+ continue;
28223
+ }
28224
+ const eq = arg.indexOf("=");
28225
+ const name = arg.slice(2, eq < 0 ? undefined : eq);
28226
+ const value = eq >= 0 ? arg.slice(eq + 1) : rest[++index];
28227
+ if (!known.includes(name) || !value || eq < 0 && value.startsWith("--"))
28228
+ return null;
28229
+ if (name === "attach")
28230
+ attach.push(value);
28231
+ else
28232
+ values[name] = value;
28233
+ }
28234
+ const files = [];
28235
+ const read = (file) => {
28236
+ try {
28237
+ const named = path44.resolve(cwd, file);
28238
+ const content = load(named);
28239
+ files.push([realpathSync11(named), sha2563(content)]);
28240
+ return content;
28241
+ } catch {
28242
+ return null;
28243
+ }
28244
+ };
28245
+ const fromFile = values.file === undefined ? undefined : read(values.file);
28246
+ if (fromFile === null)
28247
+ return null;
28248
+ const lines = [];
28249
+ const text = fromFile?.toString("utf8") ?? values.markdown ?? values.description;
28250
+ const [target, extra] = positionals;
28251
+ let action = `workit youtrack ${verb} ${target}`;
28252
+ if (verb === "create") {
28253
+ if (!values.project || !values.summary?.trim() || target !== undefined)
28254
+ return null;
28255
+ action = `workit youtrack create --project ${values.project}`;
28256
+ lines.push(`new ${values.project} issue: ${values.summary.trim()}`);
28257
+ if (text !== undefined)
28258
+ lines.push("description:", ...shownText(text));
28259
+ } else {
28260
+ if (!target || !/^[A-Z][A-Z0-9_]*-\d+$/u.test(target) || extra !== undefined)
28261
+ return null;
28262
+ if (text !== undefined)
28263
+ lines.push("comment:", ...shownText(text));
28264
+ if (values.minutes)
28265
+ lines.push(`time: ${values.minutes}m on ${values.date ?? "today"}${values.text === undefined ? "" : ` ("${values.text}")`}`);
28266
+ if (values.state)
28267
+ lines.push(`state: ${values.state}`);
28268
+ }
28269
+ if (values.command)
28270
+ lines.push(`command: ${values.command}`);
28271
+ for (const file of attach) {
28272
+ const content = read(file);
28273
+ if (!content)
28274
+ return null;
28275
+ lines.push(`attach: ${path44.basename(file)} (${content.length} bytes)`);
28276
+ }
28277
+ if (!lines.length)
28278
+ return null;
28279
+ return {
28280
+ kind: "youtrack-write",
28281
+ action,
28282
+ text: [`Yes runs ${action} once:`, ...lines].join(`
28283
+ `),
28284
+ argvHash: sha2563(canonicalJson(args)),
28285
+ contentHash: sha2563(canonicalJson({ args, files }))
28286
+ };
28287
+ };
28288
+
28289
+ // packages/workit-core/src/approvals/inline.ts
28290
+ var asked = (words) => words[0] === "youtrack" && isYouTrackWriteVerb(words[1]);
28291
+ var quote2 = (word) => /^[\w@%+=:,./-]+$/u.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;
28292
+ var inlineCallIn = (command, dialect = "posix") => {
28293
+ if (!/\bworkit\b/u.test(command))
28294
+ return null;
28295
+ const segments = segmentsOf(command, dialect);
28296
+ for (const segment of segments) {
28297
+ if (segment.unanalyzable)
28298
+ continue;
28299
+ const { words } = segment;
28300
+ const script = (words[0] ?? "").endsWith("sh") ? words.find((word) => /\bworkit\s+youtrack\s/u.test(word)) : undefined;
28301
+ if (script)
28302
+ return { plain: false, fix: script.trim() };
28303
+ const start = words.findIndex(isWorkitWord2);
28304
+ if (start < 0)
28305
+ continue;
28306
+ const at = verbIndex(words, start + 1);
28307
+ const call = words.slice(at);
28308
+ if (!asked(call))
28309
+ continue;
28310
+ const plain = segments.length === 1 && start === 0 && words[0] === "workit" && at === 1 && !segment.redirects.length && !segment.subs?.length && !segment.stdin?.length && !segment.expands?.length && !segment.group;
28311
+ if (plain)
28312
+ return { plain: true, words: call };
28313
+ return {
28314
+ plain: false,
28315
+ fix: `workit ${call.map(quote2).join(" ")}`
28316
+ };
28317
+ }
28318
+ return null;
28319
+ };
28320
+ var inlineAskFor = (words, cwd) => asked(words) && youTrackWritesMode(cwd) !== "auto" ? youTrackAsk(words.slice(1), cwd) : null;
28321
+ var inlineCallDeny = (fix) => `Run \`${fix}\` as its own call so the host can ask the user.`;
28322
+
28112
28323
  // packages/workit-core/src/hooks/hosts/claude-code.ts
28113
28324
  var CLAUDE_CODE_DESCRIPTOR = {
28114
28325
  host: "claude_code",
@@ -28216,7 +28427,7 @@ var CONTEXT_EVENTS = new Set([
28216
28427
  "PreToolUse",
28217
28428
  "PostToolUse"
28218
28429
  ]);
28219
- var ASKING_MODES = new Set(["default", "acceptEdits", "plan"]);
28430
+ var ASKING_MODES = new Set(["default", "acceptEdits", "plan", "auto"]);
28220
28431
 
28221
28432
  // packages/workit-core/src/hooks/hosts/codex.ts
28222
28433
  var CODEX_DESCRIPTOR = {
@@ -28582,42 +28793,67 @@ function neededChecks(lane, configured) {
28582
28793
  }
28583
28794
 
28584
28795
  // packages/workit-core/src/hooks/worktree-confine.ts
28585
- import { createHash as createHash20 } from "node:crypto";
28796
+ import { createHash as createHash21 } from "node:crypto";
28586
28797
  import fs29 from "node:fs";
28587
- import path44 from "node:path";
28798
+ import path45 from "node:path";
28588
28799
  var FANOUT_TOKEN_FILE = "workit-fanout-token";
28589
28800
  var NONE5 = { kind: "none" };
28590
28801
  var CASE_INSENSITIVE2 = process.platform === "darwin" || process.platform === "win32";
28591
- var canonical5 = (file) => {
28802
+ var realOf = (file) => {
28592
28803
  let rest = "";
28593
- for (let dir = path44.resolve(file);; dir = path44.dirname(dir)) {
28804
+ for (let dir = file;; dir = path45.dirname(dir)) {
28594
28805
  try {
28595
- return path44.join(fs29.realpathSync.native(dir), rest);
28806
+ return path45.join(fs29.realpathSync.native(dir), rest);
28596
28807
  } catch {
28597
- if (path44.dirname(dir) === dir)
28598
- return path44.resolve(file);
28599
- rest = rest ? path44.join(path44.basename(dir), rest) : path44.basename(dir);
28808
+ if (path45.dirname(dir) === dir)
28809
+ return file;
28810
+ rest = rest ? path45.join(path45.basename(dir), rest) : path45.basename(dir);
28600
28811
  }
28601
28812
  }
28602
28813
  };
28814
+ var canonical5 = (file, hops = { chain: 40, total: 1000 }) => {
28815
+ const start = path45.isAbsolute(file) ? file : `${process.cwd()}${path45.sep}${file}`;
28816
+ const { root } = path45.parse(start);
28817
+ let at = root;
28818
+ let missing = false;
28819
+ for (const part of start.slice(root.length).split(/[\\/]+/)) {
28820
+ if (part === "" || part === ".")
28821
+ continue;
28822
+ if (part === "..") {
28823
+ at = path45.dirname(at);
28824
+ continue;
28825
+ }
28826
+ const next = path45.join(at, part);
28827
+ let link = null;
28828
+ if (!missing)
28829
+ try {
28830
+ link = fs29.readlinkSync(next);
28831
+ } catch (error) {
28832
+ missing = error.code !== "EINVAL";
28833
+ }
28834
+ if (link === null) {
28835
+ at = next;
28836
+ hops.chain = 40;
28837
+ } else if (hops.chain-- > 0 && hops.total-- > 0)
28838
+ at = canonical5(path45.isAbsolute(link) ? link : `${at}${path45.sep}${link}`, hops);
28839
+ else
28840
+ return path45.resolve(file);
28841
+ }
28842
+ return realOf(at);
28843
+ };
28603
28844
  var within = (child, parent) => {
28604
28845
  const fold = (value) => CASE_INSENSITIVE2 ? value.toLowerCase() : value;
28605
- const relative = path44.relative(fold(parent), fold(child));
28606
- return relative === "" || !relative.startsWith("..") && !path44.isAbsolute(relative);
28846
+ const relative = path45.relative(fold(parent), fold(child));
28847
+ return relative === "" || !relative.startsWith("..") && !path45.isAbsolute(relative);
28607
28848
  };
28608
28849
  var checkoutOf2 = (file) => {
28609
- for (let dir = canonical5(file);; dir = path44.dirname(dir)) {
28610
- const dotGit = path44.join(dir, ".git");
28850
+ for (let dir = canonical5(file);; dir = path45.dirname(dir)) {
28851
+ const dotGit = path45.join(dir, ".git");
28611
28852
  if (fs29.existsSync(dotGit)) {
28612
- if (!fs29.statSync(dotGit).isFile())
28613
- return { root: dir, workit: false };
28614
- const admin = /^gitdir:\s*(.+)$/mu.exec(fs29.readFileSync(dotGit, "utf8"))?.[1]?.trim();
28615
- return {
28616
- root: dir,
28617
- workit: Boolean(admin) && fs29.existsSync(path44.join(path44.resolve(dir, admin), FANOUT_TOKEN_FILE))
28618
- };
28853
+ const admin = fs29.statSync(dotGit).isFile() ? gitDirsAt(dir, null, false)?.[0] : undefined;
28854
+ return { root: dir, workit: !!admin && fs29.existsSync(path45.join(admin, FANOUT_TOKEN_FILE)) };
28619
28855
  }
28620
- if (path44.dirname(dir) === dir)
28856
+ if (path45.dirname(dir) === dir)
28621
28857
  return null;
28622
28858
  }
28623
28859
  };
@@ -28629,8 +28865,8 @@ var workitWorktreeOf = (file) => {
28629
28865
  return null;
28630
28866
  }
28631
28867
  };
28632
- var bindingDir = () => path44.join(resolveStateDir(), "worktree-bind");
28633
- var bindingFile = (session, agentId) => path44.join(bindingDir(), `${createHash20("sha256").update(`${session}\x00${agentId}`).digest("hex").slice(0, 32)}.json`);
28868
+ var bindingDir = () => path45.join(resolveStateDir(), "worktree-bind");
28869
+ var bindingFile = (session, agentId) => path45.join(bindingDir(), `${createHash21("sha256").update(`${session}\x00${agentId}`).digest("hex").slice(0, 32)}.json`);
28634
28870
  var readBinding = (file) => {
28635
28871
  try {
28636
28872
  const value = JSON.parse(fs29.readFileSync(file, "utf8"));
@@ -28655,7 +28891,7 @@ var bind = (input, worktree) => {
28655
28891
  agentId,
28656
28892
  at: new Date().toISOString()
28657
28893
  };
28658
- fs29.mkdirSync(path44.dirname(file), { recursive: true });
28894
+ fs29.mkdirSync(path45.dirname(file), { recursive: true });
28659
28895
  fs29.writeFileSync(file, JSON.stringify(binding));
28660
28896
  try {
28661
28897
  if (inWorkitWorkspace(input.cwd))
@@ -28674,31 +28910,26 @@ var hostIsolated = (cwd, agentId) => {
28674
28910
  const checkout = checkoutOf2(cwd);
28675
28911
  if (!checkout)
28676
28912
  return false;
28677
- const dotGit = path44.join(checkout.root, ".git");
28913
+ const dotGit = path45.join(checkout.root, ".git");
28678
28914
  if (!fs29.statSync(dotGit).isFile())
28679
28915
  return false;
28680
- const admin = /^gitdir:\s*(.+)$/mu.exec(fs29.readFileSync(dotGit, "utf8"))?.[1]?.trim();
28681
- if (!admin)
28682
- return false;
28683
- const adminDir = path44.resolve(checkout.root, admin);
28684
- const back = fs29.readFileSync(path44.join(adminDir, "gitdir"), "utf8").trim();
28685
- if (path44.relative(canonical5(path44.resolve(adminDir, back)), canonical5(dotGit)) !== "")
28916
+ const [adminDir, gitDir] = gitDirsAt(checkout.root, null, false) ?? [];
28917
+ const back = fs29.readFileSync(path45.join(adminDir, "gitdir"), "utf8").trim();
28918
+ if (path45.relative(canonical5(path45.resolve(adminDir, back)), canonical5(dotGit)) !== "")
28686
28919
  return false;
28687
- const common = path44.join(adminDir, "commondir");
28688
- const gitDir = fs29.existsSync(common) ? path44.resolve(adminDir, fs29.readFileSync(common, "utf8").trim()) : adminDir;
28689
- const expected = path44.join(path44.dirname(canonical5(gitDir)), ".claude", "worktrees", `agent-${agentId}`);
28690
- return path44.relative(canonical5(expected), checkout.root) === "";
28920
+ const expected = path45.join(path45.dirname(gitDir), ".claude", "worktrees", `agent-${agentId}`);
28921
+ return path45.relative(canonical5(expected), checkout.root) === "";
28691
28922
  } catch {
28692
28923
  return false;
28693
28924
  }
28694
28925
  };
28695
28926
  var runnerAt = (target) => {
28696
- const base = path44.basename(target);
28927
+ const base = path45.basename(target);
28697
28928
  return base.startsWith(OPAQUE_TARGET) ? decodeURIComponent(base.slice(OPAQUE_TARGET.length)) : null;
28698
28929
  };
28699
28930
  var shown = (target) => {
28700
- const named = /^\.workit-(?:live-target$|runs-)/.test(path44.basename(target)) ? path44.dirname(target) : target;
28701
- return path44.sep === "\\" ? named.replaceAll("/", "\\") : named;
28931
+ const named = /^\.workit-(?:live-target$|runs-)/.test(path45.basename(target)) ? path45.dirname(target) : target;
28932
+ return path45.sep === "\\" ? named.replaceAll("/", "\\") : named;
28702
28933
  };
28703
28934
  var unboundDeny = (input, target) => {
28704
28935
  const unblock = "Work only in the worktree your brief names, which the lead made with `workit fanout worktree create <slice>`: edit files under it and run one verb per call against it (`workit git --cwd <worktree> commit -m … -- <paths>`, `workit check --cwd <worktree> <name>`). If your brief names no worktree, stop and report that to the lead.";
@@ -28737,7 +28968,7 @@ var literalForm = (command, refs) => {
28737
28968
  };
28738
28969
  var unknownVarDeny = (input, worktree, targets, command) => {
28739
28970
  const refs = [
28740
- ...new Set(targets.flatMap((target) => path44.relative(UNKNOWN_VAR, path44.resolve(target)).split(path44.sep)[0].split("+").filter(Boolean).map(decodeURIComponent)))
28971
+ ...new Set(targets.flatMap((target) => path45.relative(UNKNOWN_VAR, path45.resolve(target)).split(path45.sep)[0].split("+").filter(Boolean).map(decodeURIComponent)))
28741
28972
  ];
28742
28973
  let text = command ?? "";
28743
28974
  const first = [];
@@ -28766,10 +28997,10 @@ function confineImplementer(input, targets, command) {
28766
28997
  try {
28767
28998
  if (!input.session.agentId || hostIsolated(input.cwd, input.session.agentId))
28768
28999
  return NONE5;
28769
- const unresolved = targets.filter((target) => within(path44.resolve(target), UNKNOWN_VAR));
29000
+ const unresolved = targets.filter((target) => within(path45.resolve(target), UNKNOWN_VAR));
28770
29001
  if (unresolved.length > 0)
28771
29002
  return unknownVarDeny(input, boundWorktree(input), unresolved, command);
28772
- if (targets.some((target) => within(path44.resolve(target), UNKNOWN_DIR)))
29003
+ if (targets.some((target) => within(path45.resolve(target), UNKNOWN_DIR)))
28773
29004
  return unknownDirDeny(input, boundWorktree(input));
28774
29005
  const bindings = canonical5(bindingDir());
28775
29006
  const judged = targets.map((named) => ({ named, real: canonical5(named) })).filter(({ real }) => within(real, bindings) || checkoutOf2(real) !== null);
@@ -28878,17 +29109,295 @@ var LEADS = /^(?:sudo|doas|env|command|builtin|exec|nohup|time|nice|timeout|stdb
28878
29109
  var RUNS = /^(?:sh|bash|zsh|dash|ksh|mksh|ash|python[\d.]*|node|bun|deno|ruby|perl|php|eval|source|\.|workit)$/;
28879
29110
  var INLINE = /^-[a-zA-Z]*[ceEpm]$|^--(?:eval|print|test|version|help)$|^-[hvV]$/;
28880
29111
  var VALUED = /^-[WXIrC]$|^--(?:require|import|loader|conditions|input-type)$/;
28881
- var commonDir = (root) => {
28882
- const dotGit = path44.join(root, ".git");
28883
- if (!fs29.statSync(dotGit).isFile())
28884
- return canonical5(dotGit);
28885
- const admin = path44.resolve(root, /^gitdir:\s*(.+)$/mu.exec(fs29.readFileSync(dotGit, "utf8"))?.[1]?.trim() ?? "");
28886
- const common = path44.join(admin, "commondir");
28887
- return canonical5(fs29.existsSync(common) ? path44.resolve(admin, fs29.readFileSync(common, "utf8").trim()) : admin);
28888
- };
29112
+ var commonDir = (root) => gitDirsAt(root, null, false)?.[1] ?? "";
28889
29113
  var inScratch = (real, repo) => {
28890
- const checkout = checkoutOf2(real);
28891
- return checkout !== null && within(real, path44.join(checkout.root, SCRATCH)) && (repo === null || commonDir(checkout.root) === repo);
29114
+ for (let dir = real;path45.dirname(dir) !== dir; dir = path45.dirname(dir)) {
29115
+ if (path45.basename(dir) !== SCRATCH)
29116
+ continue;
29117
+ const root = path45.dirname(dir);
29118
+ if (checkoutOf2(root)?.root === root && (repo === null || commonDir(root) === repo))
29119
+ return true;
29120
+ }
29121
+ return false;
29122
+ };
29123
+ var inGitDir = (real) => real.split(/[\\/]/).includes(".git");
29124
+ var SAFE_KEY = /^(?:core\.(?:repositoryformatversion|filemode|bare|logallrefupdates|ignorecase|precomposeunicode|symlinks)|user\..*|init\.defaultbranch|commit\.gpgsign|extensions\.(?:objectformat|refstorage)|branch\..*\.(?:remote|merge)|remote\..*\.fetch)$/;
29125
+ var literalIn = (value, repo, checkout = false) => {
29126
+ if (/[$`]/.test(value) || !path45.isAbsolute(value))
29127
+ return false;
29128
+ const real = canonical5(value);
29129
+ const root = checkout ? checkoutOf2(real)?.root : undefined;
29130
+ return inScratch(real, repo) || root !== undefined && (repo === null || commonDir(root) === repo);
29131
+ };
29132
+ var configEntries = (text) => {
29133
+ const entries = [];
29134
+ let section = "";
29135
+ for (const line of text.split(`
29136
+ `)) {
29137
+ const header = /^\s*\[\s*([\w.-]+)(?:\s+"([^"]*))?/.exec(line);
29138
+ const entry = /^\s*([\w-]+)\s*(?:=\s*"?(.*?)"?)?\s*$/.exec(line);
29139
+ if (header)
29140
+ section = header[2] === undefined ? header[1] : `${header[1]}.${header[2]}`;
29141
+ else if (entry)
29142
+ entries.push([`${section}.${entry[1]}`.toLowerCase(), entry[2] ?? "true"]);
29143
+ }
29144
+ return entries;
29145
+ };
29146
+ function gitDirsAt(dir, repo, scan = true) {
29147
+ for (let at = dir;; at = path45.dirname(at)) {
29148
+ const dotGit = path45.join(at, ".git");
29149
+ let gitDir = null;
29150
+ try {
29151
+ if (fs29.statSync(dotGit).isDirectory())
29152
+ gitDir = canonical5(dotGit);
29153
+ else {
29154
+ const named = /^gitdir:\s*(.+?)\s*$/mu.exec(fs29.readFileSync(dotGit, "utf8"))?.[1];
29155
+ if (!named)
29156
+ return null;
29157
+ gitDir = canonical5(path45.resolve(at, named));
29158
+ }
29159
+ } catch (error) {
29160
+ if (error.code !== "ENOENT")
29161
+ return null;
29162
+ if (["HEAD", "objects", "refs"].every((name) => fs29.existsSync(path45.join(at, name))))
29163
+ gitDir = canonical5(at);
29164
+ }
29165
+ if (gitDir !== null) {
29166
+ const common = path45.join(gitDir, "commondir");
29167
+ const shared = fs29.existsSync(common) ? canonical5(path45.resolve(gitDir, fs29.readFileSync(common, "utf8").trim())) : gitDir;
29168
+ const dirs = [gitDir, shared];
29169
+ for (const config of scan ? new Set([path45.join(gitDir, "config"), path45.join(shared, "config")]) : []) {
29170
+ let text = "";
29171
+ try {
29172
+ text = fs29.readFileSync(config, "utf8");
29173
+ } catch {
29174
+ continue;
29175
+ }
29176
+ for (const [key, value] of configEntries(text)) {
29177
+ if (key === "core.worktree")
29178
+ dirs.push(canonical5(path45.resolve(gitDir, value)));
29179
+ else if (/^remote\..*\.url$/.test(key) ? !literalIn(value, repo, true) : !SAFE_KEY.test(key))
29180
+ return null;
29181
+ }
29182
+ }
29183
+ return dirs;
29184
+ }
29185
+ if (path45.dirname(at) === at)
29186
+ return [];
29187
+ }
29188
+ }
29189
+ var DIFF_S = "psuRaWwbzU:S:G:l:M?C?B?D";
29190
+ var DIFF_L = "stat? numstat shortstat name-only name-status summary patch no-patch raw color? no-color word-diff? color-words? unified= ignore-all-space ignore-space-change ignore-blank-lines ignore-cr-at-eol diff-filter= find-renames? find-copies? no-renames relative? abbrev? diff-algorithm= ignore-space-at-eol word-diff-regex= full-index binary exit-code quiet minimal patience histogram src-prefix= dst-prefix= no-prefix dirstat? text check function-context no-ext-diff no-textconv output=";
29191
+ var LOG_S = "n:iEFPgL:";
29192
+ var LOG_L = "oneline format= pretty? graph decorate? no-decorate all branches? tags? remotes? since= until= after= before= author= committer= grep= all-match invert-grep regexp-ignore-case extended-regexp fixed-strings perl-regexp max-count= skip= first-parent no-merges merges reverse follow date= abbrev-commit no-abbrev-commit left-right cherry-pick cherry-mark boundary not topo-order date-order source simplify-by-decoration ancestry-path full-history notes? no-notes walk-reflogs mailmap use-mailmap";
29193
+ var GIT_VERBS = {
29194
+ log: "@d@l|@d @l",
29195
+ show: "@d@l|@d @l",
29196
+ diff: "@d|@d cached staged merge-base no-index",
29197
+ "diff-tree": "@drtcm|@d root stdin no-commit-id",
29198
+ "diff-index": "@dm|@d cached merge-base",
29199
+ status: "sbu?zv|short branch porcelain? long untracked-files? ignored? ignore-submodules? show-stash ahead-behind no-ahead-behind renames no-renames find-renames? column? no-column null verbose",
29200
+ "rev-parse": "q|verify short? abbrev-ref? symbolic symbolic-full-name show-toplevel show-prefix git-dir git-common-dir absolute-git-dir is-inside-work-tree is-inside-git-dir is-bare-repository show-cdup quiet all branches? tags? remotes? since= until= default= path-format= sq-quote",
29201
+ "rev-list": "@l|@l count objects? left-only right-only",
29202
+ "ls-files": "cdmoiskuvtzfx:X:|cached deleted modified others ignored stage unmerged killed directory no-empty-directory exclude-standard exclude= exclude-from= full-name abbrev? error-unmatch with-tree= eol deduplicate format= recurse-submodules sparse",
29203
+ "ls-tree": "rdtlz|long name-only name-status object-only full-name full-tree abbrev? format=",
29204
+ "cat-file": "tsepz|batch? batch-check? batch-all-objects follow-symlinks unordered buffer allow-unknown-type mailmap use-mailmap",
29205
+ blame: "L:lstfnepwbcM?C?|porcelain line-porcelain incremental root show-stats show-name show-number show-email abbrev= reverse= first-parent date= ignore-rev= ignore-revs-file= minimal contents=",
29206
+ describe: "|tags all long abbrev= contains always dirty? broken? match= exclude= first-parent exact-match candidates= debug",
29207
+ "merge-base": "a|all octopus independent is-ancestor fork-point",
29208
+ "for-each-ref": "|count= sort= format= color? shell perl python tcl points-at= merged? no-merged? contains? no-contains? ignore-case omit-empty exclude=",
29209
+ shortlog: "@lsnec|@l summary numbered email committer group= format=",
29210
+ "show-ref": "dsq|head verify heads tags branches hash? abbrev? quiet dereference exists",
29211
+ "name-rev": "|tags refs= exclude= all annotate-stdin name-only no-undefined always",
29212
+ grep: "aiIvnhHcEGFPlLzoWqwe:A:B:C:m:f:|cached untracked no-index no-exclude-standard exclude-standard recurse-submodules text ignore-case word-regexp invert-match line-number column count full-name extended-regexp basic-regexp fixed-strings perl-regexp files-with-matches name-only files-without-match null only-matching heading break show-function function-context max-depth= threads= and or not all-match quiet after-context= before-context= context= max-count= color? no-color",
29213
+ "format-patch": "@do:nNks|@d stdout output-directory= numbered no-numbered start-number= subject-prefix= root cover-letter thread? signoff attach? inline? suffix= base=",
29214
+ reflog: "@l|@l all expire= expire-unreachable= rewrite updateref stale-fix dry-run verbose",
29215
+ "count-objects": "vH|verbose human-readable",
29216
+ "check-ignore": "qvnz|quiet verbose stdin non-matching no-index",
29217
+ var: "l|",
29218
+ version: "|build-options",
29219
+ "ls-remote": "htbq|heads tags branches refs quiet exit-code get-url symref sort=",
29220
+ remote: "v|verbose",
29221
+ config: "lz|get get-all get-regexp list local name-only null type= default=",
29222
+ worktree: "fdqvzb:B:|force detach lock reason= orphan no-checkout checkout quiet track no-track guess-remote porcelain expire= verbose",
29223
+ branch: "dDmMcCfvraliu:|delete move copy force list all remotes verbose contains? merged? no-merged? points-at= show-current set-upstream-to= unset-upstream track? no-track sort= format= color? column? ignore-case create-reflog",
29224
+ tag: "lam:dfF:n?|list annotate message= file= delete force sort= format= contains? merged? no-merged? points-at= column? create-reflog ignore-case",
29225
+ init: "+qb:|quiet bare initial-branch= object-format= ref-format= shared? separate-git-dir=",
29226
+ add: "+AunNvf|all update intent-to-add force dry-run verbose ignore-errors ignore-removal no-all renormalize chmod= sparse",
29227
+ commit: "+m:aqsnF:C:ouv|message= all amend no-edit allow-empty allow-empty-message author= date= signoff no-verify quiet file= reuse-message= fixup= squash= only include dry-run no-gpg-sign untracked-files? cleanup= reset-author verbose",
29228
+ checkout: "+b:B:fqm|detach force orphan= quiet track? no-track merge ours theirs",
29229
+ switch: "+c:C:dfqm|create= force-create= detach discard-changes force orphan= quiet track? no-track merge",
29230
+ restore: "+s:SWq|source= staged worktree ours theirs merge quiet overlay no-overlay",
29231
+ reset: "+qN|soft mixed hard merge keep quiet no-refresh",
29232
+ rm: "+rfnq|cached force dry-run quiet ignore-unmatch",
29233
+ mv: "+fnkv|force dry-run verbose",
29234
+ merge: "+m:qvnX:|no-ff ff ff-only squash no-squash commit no-commit message= no-edit abort continue quit allow-unrelated-histories stat no-stat quiet verbose no-verify signoff strategy-option=",
29235
+ stash: "+m:ukqa|message= include-untracked keep-index quiet all index staged",
29236
+ apply: "+p:C:R3qv|check stat numstat summary index cached 3way reverse reject allow-empty exclude= include= verbose quiet whitespace= recount",
29237
+ am: "+skq3|signoff keep 3way quiet abort continue skip quit whitespace= reject",
29238
+ fetch: "+fqvptn|all depth= deepen= shallow-since= unshallow tags no-tags prune force quiet verbose dry-run update-shallow refmap=",
29239
+ clone: "+nqlsb:o:|bare no-checkout depth= branch= origin= single-branch no-single-branch no-tags quiet shared local no-local filter= separate-git-dir=",
29240
+ "cherry-pick": "+nm:sxX:|no-commit mainline= signoff abort continue skip quit allow-empty keep-redundant-commits ff strategy-option=",
29241
+ revert: "+nm:sX:|no-commit mainline= signoff abort continue skip quit strategy-option= no-edit",
29242
+ rebase: "+qvfnX:|onto= root abort continue skip quit keep-base no-ff force-rebase autosquash no-autosquash autostash no-autostash update-refs signoff quiet verbose stat no-stat committer-date-is-author-date reset-author-date rebase-merges? no-rebase-merges empty= strategy-option= apply merge",
29243
+ clean: "+dfnqxXe:|dry-run force quiet exclude=",
29244
+ bisect: "+|term-old= term-new= no-checkout first-parent"
29245
+ };
29246
+ var gitOperands = (args) => {
29247
+ const [verb = "", ...rest] = args;
29248
+ const spec = Object.hasOwn(GIT_VERBS, verb) ? GIT_VERBS[verb] : null;
29249
+ if (spec === null)
29250
+ return null;
29251
+ const [shorts, longs] = spec.split("|");
29252
+ const short = shorts.replace("@d", DIFF_S).replace("@l", LOG_S);
29253
+ const long = longs.replace("@d", DIFF_L).replace("@l", LOG_L).split(" ");
29254
+ const operands = [];
29255
+ for (let at = 0;at < rest.length; at++) {
29256
+ const arg = rest[at];
29257
+ if (arg === "--")
29258
+ return [...operands, ...rest.slice(at + 1)];
29259
+ if (!arg.startsWith("-") || arg === "-")
29260
+ operands.push(arg);
29261
+ else if (arg.startsWith("--")) {
29262
+ const [name] = arg.slice(2).split("=");
29263
+ const valued = arg.includes("=");
29264
+ if (long.includes(`${name}=`))
29265
+ at += valued ? 0 : 1;
29266
+ else if (!long.includes(`${name}?`) && (valued || !long.includes(name)))
29267
+ return null;
29268
+ } else if (!/^-\d+$/.test(arg))
29269
+ for (let index = 1;index < arg.length; index++) {
29270
+ const found = /[:?+]/.test(arg[index]) ? -1 : short.indexOf(arg[index]);
29271
+ if (found < 0)
29272
+ return null;
29273
+ const takes = short[found + 1];
29274
+ if (takes === ":" && index === arg.length - 1)
29275
+ at++;
29276
+ if (takes === ":" || takes === "?")
29277
+ break;
29278
+ }
29279
+ }
29280
+ return operands;
29281
+ };
29282
+ var gitKind = (args, local = () => true) => {
29283
+ const named = gitOperands(args);
29284
+ if (!named)
29285
+ return null;
29286
+ const [verb] = args;
29287
+ const [first = "", second] = named;
29288
+ const has = (pattern) => args.some((arg) => pattern.test(arg));
29289
+ switch (verb) {
29290
+ case "reflog":
29291
+ return /^(?:expire|delete)$/.test(first) ? "write" : "read";
29292
+ case "branch":
29293
+ case "tag":
29294
+ return leadOwnedGit(args) || named.length > 0 && !has(/^(?:-l|--list|--contains|--(?:no-)?merged|--points-at)$/) ? "write" : "read";
29295
+ case "config": {
29296
+ if (has(/^(?:-l|--list|--get-regexp)$/) || first === "list")
29297
+ return has(/^--local$/) ? "write" : null;
29298
+ if (has(/^--get/) || first === "get" || named.length === 1)
29299
+ return "read";
29300
+ const [key = "", value] = first === "set" ? named.slice(1) : named;
29301
+ return /^(?:user\.(?:name|email)|init\.defaultbranch)$/i.test(key) || /^commit\.gpgsign$/i.test(key) && value === "false" ? "write" : null;
29302
+ }
29303
+ case "worktree":
29304
+ return first === "list" ? "read" : /^(?:add|remove)$/.test(first) ? "write" : null;
29305
+ case "remote":
29306
+ return !first || first === "show" && named.length === 2 && local(second, true) ? "read" : null;
29307
+ case "ls-remote":
29308
+ return local(first || "origin", true) ? "read" : null;
29309
+ case "bisect":
29310
+ return /^(?:log|terms)$/.test(first) ? "read" : /^(?:start|good|bad|new|old|skip|reset)$/.test(first) ? "write" : null;
29311
+ case "blame": {
29312
+ const contents = args.findIndex((arg) => arg.startsWith("--contents"));
29313
+ const file = args[contents]?.slice(11) || args[contents + 1];
29314
+ return contents < 0 || local(file) ? "read" : null;
29315
+ }
29316
+ case "fetch":
29317
+ return !first || local(first, true) ? "write" : null;
29318
+ case "clone":
29319
+ return local(first) ? "write" : null;
29320
+ }
29321
+ return GIT_VERBS[verb].startsWith("+") ? "write" : "read";
29322
+ };
29323
+ var JUDGE_GIT = `a judge runs git ${Object.keys(GIT_VERBS).join(" ")} with the options each documents (no abbreviations), writing only in a scratch repo; no -c, no wrapper but timeout, nice, time, command, no env but PAGER=cat, GIT_PAGER=cat, GIT_OPTIONAL_LOCKS=0, LC_*, LANG, TZ; status outside scratch needs --no-optional-locks`;
29324
+ var remoteIn = (dir, name, repo) => {
29325
+ const shared = path45.isAbsolute(dir) ? gitDirsAt(canonical5(dir), repo, false)?.[1] : undefined;
29326
+ if (!shared)
29327
+ return false;
29328
+ const url = configEntries(fs29.readFileSync(path45.join(shared, "config"), "utf8")).find(([key]) => key === `remote.${name}.url`.toLowerCase())?.[1];
29329
+ return url !== undefined && literalIn(url, repo, true);
29330
+ };
29331
+ var judgeGit = (command, repo, depth = 0) => {
29332
+ const runsGit = /\bgit\b/.test(command);
29333
+ for (const segment of segmentsOf(command)) {
29334
+ const words = segment.words;
29335
+ let why = null;
29336
+ let at = 0;
29337
+ while (/^(?:if|then|elif|else|do|while|until|!|\{|\()$/.test(words[at] ?? ""))
29338
+ at++;
29339
+ const lead = [];
29340
+ while (/^\w+\+?=/.test(words[at] ?? ""))
29341
+ lead.push(words[at++]);
29342
+ const name = path45.basename(words[at] ?? "");
29343
+ let start = words.findIndex((word) => /(?:^|[\\/])git(?:\.exe)?(?:=|$)/.test(word));
29344
+ if (start > at) {
29345
+ if (/^(?:grep|egrep|rg|echo|printf|ls|wc|head|tail|cat|which|type|test|\[|cd|mkdir)$/.test(name) || name === "command" && /^-[vV]$/.test(words[at + 1] ?? ""))
29346
+ start = -1;
29347
+ else if (!/^(?:timeout|nice|time|command)$/.test(name) || words.slice(at + 1, start).some((word) => !/^(?:-[\w-]+|\d[\w.]*)$/.test(word)))
29348
+ why = `\`${name}\` runs git`;
29349
+ }
29350
+ if (start >= 0 && words[start].includes("="))
29351
+ why = "git is redefined";
29352
+ const run = words[start] ?? "";
29353
+ if (run.includes("/") && (!path45.isAbsolute(run) || literalIn(run, repo, true)))
29354
+ why ??= `\`${run}\` is not the system git`;
29355
+ if (segment.expands?.includes(at) && name !== "[" || /\{[^}]*,/.test(words[at] ?? ""))
29356
+ why = "the command's name is expanded by the shell";
29357
+ if (start >= 0 && (segment.expands?.length || words.some((word) => /\{[^}]*(?:,|\.\.)[^}]*\}|^~/.test(word))))
29358
+ why ??= "a word in this git command is expanded by the shell: spell it as a literal";
29359
+ if (/^(?:export|declare|local|readonly|typeset)$/.test(name))
29360
+ lead.push(...words.slice(at + 1).filter((word) => /^\w+\+?=/.test(word)));
29361
+ for (const word of runsGit ? lead : lead.filter((set) => /^(?:BASH_)?ENV=/.test(set)))
29362
+ if (!/^(?:(?:GIT_)?PAGER=cat|GIT_OPTIONAL_LOCKS=0|(?:LC_\w+|LANG|TZ)=[^$`]*)$/.test(word))
29363
+ why ??= `\`${word}\` is not allowed`;
29364
+ let index = start < 0 ? words.length : start + 1;
29365
+ let dir = "";
29366
+ let unlocked = lead.includes("GIT_OPTIONAL_LOCKS=0");
29367
+ for (;!why && words[index]?.startsWith("-") && words[index] !== "--version"; index++) {
29368
+ const word = words[index];
29369
+ const flag = /^--(git-dir|work-tree)(?:=([\s\S]*))?$/.exec(word);
29370
+ const value = flag?.[2] ?? (/^(?:-C|--git-dir|--work-tree)$/.test(word) ? words[++index] : "");
29371
+ if (word === "-C")
29372
+ dir = value;
29373
+ unlocked ||= word === "--no-optional-locks";
29374
+ if (flag ? !literalIn(value, repo) : !/^(?:-C|-P|--no-pager|--no-optional-locks)$/.test(word))
29375
+ why = `\`${word}\` is not allowed`;
29376
+ }
29377
+ const args = words[index] === "--version" ? ["version"] : words.slice(index);
29378
+ if (!why && start >= 0) {
29379
+ const local = (source, remote) => remote && /^[\w-][\w.-]*$/.test(source) ? remoteIn(dir, source, repo) : literalIn(source, repo, true);
29380
+ if (!gitKind(args, local))
29381
+ why = `\`git ${args.slice(0, 2).join(" ")}\` is not allowed`;
29382
+ else if (args[0] === "status" && !unlocked) {
29383
+ const dirs = path45.isAbsolute(dir) ? gitDirsAt(canonical5(dir), repo) : null;
29384
+ if (!dirs?.length || !dirs.every((gitDir) => inScratch(gitDir, repo)))
29385
+ why = "`git status` refreshes the index outside scratch: add --no-optional-locks";
29386
+ }
29387
+ }
29388
+ const shell = /^(?:grep|egrep|rg|echo|printf|cat)$/.test(name) ? -1 : words.findIndex((word) => /^(?:sh|bash|zsh|dash|ksh|mksh|ash)$/.test(path45.basename(word)));
29389
+ const scripts = [
29390
+ ...words.filter((_, after) => shell >= 0 && after > shell && /^-[a-zA-Z]*c[a-zA-Z]*$/.test(words[after - 1])),
29391
+ ...shell < 0 ? [] : segment.stdin ?? []
29392
+ ];
29393
+ if (shell > at && scripts.some((script) => /git/.test(script)) && (!/^(?:timeout|nice|time|command)$/.test(name) || words.slice(at + 1, shell).some((word) => !/^(?:-[\w-]+|\d[\w.]*)$/.test(word))))
29394
+ why ??= `\`${name}\` runs git`;
29395
+ for (const script of [...segment.subs ?? [], ...scripts])
29396
+ why ??= depth < 4 ? judgeGit(script, repo, depth + 1) : "scripts nest too deep for Workit to read";
29397
+ if (why)
29398
+ return why;
29399
+ }
29400
+ return null;
28892
29401
  };
28893
29402
  var JUDGE_VERBS = {
28894
29403
  check: true,
@@ -28917,7 +29426,7 @@ var judgeVerbRefused = (args) => {
28917
29426
  var CLI_RUNNERS = /^(?:npx|bunx|pnpx|npm|pnpm|yarn|bun|node|nodejs|deno|tsx|ts-node)$/;
28918
29427
  var CLI_ENTRY = /(?:^|[=\\/])(?:workit(?:\.(?:exe|cmd|[cm]?js))?|@workit-dev\/cli(?:@\S*)?)$|(?:workit-cli|@workit-dev[\\/]cli)[\\/](?:src[\\/](?:index|main)|dist[\\/]index)\.[cm]?[jt]sx?$/;
28919
29428
  var workitCalls = (command, depth = 0, aliases = new Map) => depth > 4 ? [] : commandLines(command).flatMap((words) => {
28920
- const name = path44.basename(words[0] ?? "").toLowerCase();
29429
+ const name = path45.basename(words[0] ?? "").toLowerCase();
28921
29430
  if (name === "alias")
28922
29431
  return words.flatMap((word) => {
28923
29432
  const set = /^([\w-]+)=(.*)$/s.exec(word);
@@ -28947,11 +29456,11 @@ var judgeRefusal = (command, fed, depth = 0) => {
28947
29456
  return why;
28948
29457
  }
28949
29458
  const { words } = segment;
28950
- const runs = (word = "") => RUNS.test(path44.basename(word).toLowerCase());
29459
+ const runs = (word = "") => RUNS.test(path45.basename(word).toLowerCase());
28951
29460
  let at = 0;
28952
29461
  while (at < words.length && (LEADS.test(words[at]) || /^-\w$/.test(words[at - 1] ?? "") && !runs(words[at])))
28953
29462
  at++;
28954
- const name = path44.basename(words[at] ?? "").toLowerCase();
29463
+ const name = path45.basename(words[at] ?? "").toLowerCase();
28955
29464
  const args = words.slice(at + 1);
28956
29465
  const unseen = `\`${words.join(" ").slice(0, 80)}\` runs a script Workit cannot read (piped, on stdin, a process substitution or eval): write the case to a file in ${SCRATCH} and dispatch it from a test instead`;
28957
29466
  if (/^(?:cd|chdir|pushd|popd)$/.test(name))
@@ -29030,8 +29539,8 @@ var judgeDeny = (input, what, target) => {
29030
29539
  const role = input.session.agentType?.endsWith("reviewer") ? "reviewer" : "verifier";
29031
29540
  const root = checkoutOf2(input.cwd)?.root;
29032
29541
  const candidate = target ? checkoutOf2(target)?.root : undefined;
29033
- const also = root && candidate && candidate !== root && commonDir(candidate) === commonDir(root) ? ` or ${path44.join(candidate, SCRATCH)}` : "";
29034
- const scratch = root ? `${path44.join(root, SCRATCH)}${also}` : `${SCRATCH}/ at the root of the checkout you judge`;
29542
+ const also = root && candidate && candidate !== root && commonDir(candidate) === commonDir(root) ? ` or ${path45.join(candidate, SCRATCH)}` : "";
29543
+ const scratch = root ? `${path45.join(root, SCRATCH)}${also}` : `${SCRATCH}/ at the root of the checkout you judge`;
29035
29544
  const unblock = `Write only under ${scratch} (mkdir -p it): put a generated case in a file there with a quoted heredoc (<<'EOF') and never run it in the shell. Reads, \`workit check\` and \`workit ledger verdict|finding\` stay allowed; a change the candidate needs is a finding, not an edit.`;
29036
29545
  return {
29037
29546
  kind: "deny",
@@ -29039,17 +29548,22 @@ var judgeDeny = (input, what, target) => {
29039
29548
  unblock
29040
29549
  };
29041
29550
  };
29042
- function confineJudge(input, targets) {
29551
+ function confineJudge(input, targets, placeholders = placeholdersOf(targets)) {
29043
29552
  try {
29044
29553
  if (!input.session.agentId)
29045
29554
  return NONE5;
29046
29555
  const judged = checkoutOf2(input.cwd);
29047
29556
  const repo = judged ? commonDir(judged.root) : null;
29048
29557
  for (const target of targets) {
29049
- const resolved = path44.resolve(target);
29558
+ const resolved = path45.resolve(target);
29050
29559
  if (within(resolved, UNKNOWN_VAR) || within(resolved, UNKNOWN_DIR))
29051
29560
  return judgeDeny(input, "it writes to a path Workit cannot resolve (a variable, a command substitution or `cd -`): spell the path out");
29052
- if (inScratch(canonical5(target), repo))
29561
+ const real = canonical5(target);
29562
+ const runsGit = placeholders.has(target) && /^\.workit-(?:runs-git|live-target)$/.test(path45.basename(target));
29563
+ const gitDirs = runsGit ? gitDirsAt(path45.dirname(real), repo) : [];
29564
+ if (gitDirs === null)
29565
+ return judgeDeny(input, `git in ${shown(target)} uses a git dir or config Workit cannot check`);
29566
+ if (runsGit ? gitDirs.length > 0 ? gitDirs.every((dir) => inScratch(dir, repo)) : inScratch(real, repo) : inScratch(real, repo) && !inGitDir(real))
29053
29567
  continue;
29054
29568
  const runner = runnerAt(target);
29055
29569
  return judgeDeny(input, runner === null ? `${shown(target)} is outside it` : `\`${runner}\` runs in ${shown(target)}, outside it`, target);
@@ -29070,21 +29584,31 @@ function confineJudgeShell(input, command, dialect = "posix") {
29070
29584
  } catch {
29071
29585
  refused = "Workit cannot read this command: split it into simpler ones";
29072
29586
  }
29587
+ if (!refused && dialect === "posix") {
29588
+ const judged = checkoutOf2(input.cwd);
29589
+ try {
29590
+ const why = judgeGit(command, judged ? commonDir(judged.root) : null);
29591
+ if (why)
29592
+ refused = `${why}: ${JUDGE_GIT}`;
29593
+ } catch {
29594
+ refused = "Workit cannot read this command: split it into simpler ones";
29595
+ }
29596
+ }
29073
29597
  if (refused)
29074
29598
  return judgeDeny(input, refused);
29075
29599
  if (dialect === "posix" && substitutingHeredoc(command))
29076
29600
  return judgeDeny(input, "an unquoted heredoc runs the `$(…)` or backtick command in its body: quote the delimiter (<<'EOF')");
29077
29601
  let git = [];
29078
29602
  try {
29079
- git = rawInvocations(command, dialect).flatMap(({ tool, dir, args }) => tool === "git" && (args[0] === "push" || leadOwnedGit(args)) ? [
29080
- path44.join(dir === undefined ? UNKNOWN_DIR : path44.resolve(input.cwd, dir ?? "."), `${OPAQUE_TARGET}git`)
29603
+ git = rawInvocations(command, dialect).flatMap(({ tool, dir, args }) => tool === "git" && (args[0] === "push" || leadOwnedGit(args) || gitKind(args) === "write" && !/^(?:init|clone)$/.test(args[0])) ? [
29604
+ path45.join(dir === undefined ? UNKNOWN_DIR : path45.resolve(input.cwd, dir ?? "."), `${OPAQUE_TARGET}git`)
29081
29605
  ] : []);
29082
29606
  } catch {}
29083
- return confineJudge(input, [
29084
- ...shellMutationTargets(input.cwd, command, dialect, true),
29085
- ...fed.flatMap((body) => shellMutationTargets(input.cwd, body, "posix", true)),
29086
- ...git
29087
- ]);
29607
+ const lists = [
29608
+ shellMutationTargets(input.cwd, command, dialect, true),
29609
+ ...fed.map((body) => shellMutationTargets(input.cwd, body, "posix", true))
29610
+ ];
29611
+ return confineJudge(input, [...lists.flat(), ...git], new Set([...git, ...lists.flatMap((list) => [...placeholdersOf(list)])]));
29088
29612
  } catch {
29089
29613
  return NONE5;
29090
29614
  }
@@ -29122,7 +29646,7 @@ var judgeChecksLine = (cwd) => {
29122
29646
 
29123
29647
  // packages/workit-core/src/hooks/standing.ts
29124
29648
  var readPlans = (store) => {
29125
- const dir = path45.join(store, "fanouts");
29649
+ const dir = path46.join(store, "fanouts");
29126
29650
  let names;
29127
29651
  try {
29128
29652
  names = fs30.readdirSync(dir).filter((name) => name.endsWith(".json"));
@@ -29132,7 +29656,7 @@ var readPlans = (store) => {
29132
29656
  const plans = [];
29133
29657
  for (const name of names) {
29134
29658
  try {
29135
- const raw = JSON.parse(fs30.readFileSync(path45.join(dir, name), "utf8"));
29659
+ const raw = JSON.parse(fs30.readFileSync(path46.join(dir, name), "utf8"));
29136
29660
  if (typeof raw.name !== "string" || !Array.isArray(raw.slices))
29137
29661
  continue;
29138
29662
  const texts = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string" && item !== "") : [];
@@ -29343,7 +29867,7 @@ var cdWorkitSplit = (command) => {
29343
29867
  // packages/workit-core/src/hooks/model-limit.ts
29344
29868
  import { closeSync as closeSync3, openSync as openSync3, readdirSync as readdirSync7, readSync, statSync as statSync5 } from "node:fs";
29345
29869
  import os10 from "node:os";
29346
- import path46 from "node:path";
29870
+ import path47 from "node:path";
29347
29871
  var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
29348
29872
  var WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
29349
29873
  var TIME_WORD = String.raw`(?:\d|(?:in|at|on|later|tomorrow|soon)\b|(?:${[...WEEKDAYS, ...MONTHS].join("|")})[a-z]*\b)`;
@@ -29541,17 +30065,17 @@ var firstPrompt = (file) => {
29541
30065
  var claudeProjectSlug = (cwd) => cwd.replace(/[^A-Za-z0-9]/gu, "-");
29542
30066
  var listDir = (dir) => {
29543
30067
  try {
29544
- return readdirSync7(dir).map((name) => path46.join(dir, name));
30068
+ return readdirSync7(dir).map((name) => path47.join(dir, name));
29545
30069
  } catch {
29546
30070
  return [];
29547
30071
  }
29548
30072
  };
29549
30073
  var SCAN_MS = 30 * 60000;
29550
30074
  var scanClaudeTranscripts = (cwd, env, now = new Date) => {
29551
- const projects = path46.join(env.CLAUDE_CONFIG_DIR || path46.join(env.HOME || os10.homedir(), ".claude"), "projects");
29552
- const project = path46.join(projects, claudeProjectSlug(cwd));
30075
+ const projects = path47.join(env.CLAUDE_CONFIG_DIR || path47.join(env.HOME || os10.homedir(), ".claude"), "projects");
30076
+ const project = path47.join(projects, claudeProjectSlug(cwd));
29553
30077
  const notes = [];
29554
- const files = listDir(project).flatMap((entry) => entry.endsWith(".jsonl") ? [{ file: entry, worker: false }] : listDir(path46.join(entry, "subagents")).filter((file) => file.endsWith(".jsonl")).map((file) => ({ file, worker: true })));
30078
+ const files = listDir(project).flatMap((entry) => entry.endsWith(".jsonl") ? [{ file: entry, worker: false }] : listDir(path47.join(entry, "subagents")).filter((file) => file.endsWith(".jsonl")).map((file) => ({ file, worker: true })));
29555
30079
  for (const { file, worker } of files)
29556
30080
  try {
29557
30081
  const stat = statSync5(file);
@@ -29566,7 +30090,7 @@ var scanClaudeTranscripts = (cwd, env, now = new Date) => {
29566
30090
  if (!seen)
29567
30091
  continue;
29568
30092
  notes.push(worker ? redispatchNote(seen, {
29569
- label: `worker ${path46.basename(file, ".jsonl")}`,
30093
+ label: `worker ${path47.basename(file, ".jsonl")}`,
29570
30094
  prompt: firstPrompt(file)
29571
30095
  }, now) : `Workit: this session hit a usage limit (${seen.reason}); ${seen.key} is marked exhausted until ${shortTime(seen.until)}. Claude Code runs only Anthropic models: Workit cannot switch this session, so continue on another host or after the reset.`);
29572
30096
  } catch {}
@@ -29699,7 +30223,7 @@ var namesYtrack = (text) => {
29699
30223
 
29700
30224
  // packages/workit-core/src/hooks/ytrack-guard.ts
29701
30225
  var name2 = (word = "") => (word.split(/[\\/]/).at(-1) ?? "").toLowerCase().replace(/\.(?:exe|cmd)$|@.*$/g, "");
29702
- var quote2 = (word) => /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;
30226
+ var quote3 = (word) => /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;
29703
30227
  var minutesOf = (text = "") => {
29704
30228
  if (/^\d+$/.test(text.trim()))
29705
30229
  return Number(text) > 0 ? Number(text) : null;
@@ -29791,7 +30315,7 @@ var combine = (effects) => {
29791
30315
  delete out.attach;
29792
30316
  return out;
29793
30317
  };
29794
- var pair = (flag, value) => value.startsWith("-") ? `${flag}=${quote2(value)}` : `${flag} ${quote2(value)}`;
30318
+ var pair = (flag, value) => value.startsWith("-") ? `${flag}=${quote3(value)}` : `${flag} ${quote3(value)}`;
29795
30319
  var mapWrite = (verb, args) => {
29796
30320
  const values = {};
29797
30321
  const attach = [];
@@ -29990,12 +30514,18 @@ var SHELLS3 = /^(?:sh|bash|zsh|dash|ksh|ash|mksh|yash|fish)$/;
29990
30514
  var MAX_DEPTH2 = 4;
29991
30515
  var READ = new Map;
29992
30516
  var NOT_PLAIN = gap("a ytrack call that is not a plain command of its own (a wrapper, loop, substitution or script around it can change or repeat it)");
29993
- var ungrant = (write) => write.workit ? { command: write.command, ...NOT_PLAIN } : write;
30517
+ var timeOnly = (effect) => effect?.minutes !== undefined && Object.keys(effect).every((key) => /^(?:issue|minutes|text|date)$/u.test(key));
30518
+ var ungrant = (write) => write.workit ? {
30519
+ command: write.command,
30520
+ ...NOT_PLAIN,
30521
+ ...timeOnly(write.effect) ? { hint: write.workit } : {}
30522
+ } : write;
30523
+ var hinted = (write) => write.hint ? { command: write.command, workit: write.hint } : write;
29994
30524
  var ytrackArgs = (line, found, depth, names, plain) => {
29995
30525
  const inner = (script) => void found.push(...ytrackWrites(script, "posix", depth + 1, plain));
29996
30526
  const tail = workitCheckTail(line);
29997
30527
  if (tail) {
29998
- inner("script" in tail ? tail.script : tail.argv.map(quote2).join(" "));
30528
+ inner("script" in tail ? tail.script : tail.argv.map(quote3).join(" "));
29999
30529
  return true;
30000
30530
  }
30001
30531
  const flag = SHELLS3.test(name2(line[0])) ? line.findIndex((word, index) => index > 0 && /^-[a-zA-Z]*c[a-zA-Z]*$/.test(word)) : -1;
@@ -30025,7 +30555,7 @@ var ytrackArgs = (line, found, depth, names, plain) => {
30025
30555
  const argv = [...alias ?? [], ...line.slice(at + 1)];
30026
30556
  const write = classify2(argv);
30027
30557
  if (write) {
30028
- const one = { command: ["ytrack", ...argv].map(quote2).join(" "), ...write };
30558
+ const one = { command: ["ytrack", ...argv].map(quote3).join(" "), ...write };
30029
30559
  found.push(plain ? one : ungrant(one));
30030
30560
  }
30031
30561
  return true;
@@ -30124,6 +30654,7 @@ var ytrackWrites = (command, dialect = "posix", depth = 0, plain = true) => {
30124
30654
  found = [];
30125
30655
  for (const line of commandLines(command, dialect))
30126
30656
  ytrackArgs(line, found, depth, aliases(command), false);
30657
+ found = found.map(hinted);
30127
30658
  }
30128
30659
  READ.set(key, found);
30129
30660
  if (READ.size > 64)
@@ -30131,6 +30662,8 @@ var ytrackWrites = (command, dialect = "posix", depth = 0, plain = true) => {
30131
30662
  return found;
30132
30663
  };
30133
30664
  var ytrackGate = (cwd, command, dialect, ask) => {
30665
+ if (namesTicket(command))
30666
+ return { kind: "deny", reason: TICKET_DENY, unblock: null };
30134
30667
  let writes;
30135
30668
  try {
30136
30669
  const merged = new Map;
@@ -30158,8 +30691,8 @@ var ytrackGate = (cwd, command, dialect, ask) => {
30158
30691
  reason: `${bare.join(", ")} writes to YouTrack: the user decides this call (#780).`
30159
30692
  };
30160
30693
  const why = `A raw ytrack write posts to YouTrack without the user's yes (#780).`;
30161
- const run = calls.length ? ` Run ${calls.join(", then ")} instead: it asks the user first. When it answers approval_needed, run exactly the \`workit approve <id>\` it names, now, with nothing around it (no 2>&1, pipe or echo), so the host asks the user; then rerun the workit call once.` : "";
30162
- const user = bare.length ? ` For ${bare.join(", ")}, the user decides: ask the user, and if they agree they run it in their own terminal.` : "";
30694
+ const run = calls.length ? ` Run ${calls.join(", then ")} instead, each as its own plain call: it asks the user first.` : "";
30695
+ const user = bare.length ? ask ? ` For ${bare.join(", ")}, run it as its own plain call: the host asks the user.` : ` For ${bare.join(", ")}, the user decides: ask the user, and if they agree they run it in their own terminal.` : "";
30163
30696
  const rerun = writes.some((write) => write.gap === NOT_PLAIN.gap) ? " To get the named workit youtrack call instead, rerun the ytrack call as one plain command, with no wrapper, loop, substitution or script around it." : "";
30164
30697
  return {
30165
30698
  kind: "deny",
@@ -30377,6 +30910,8 @@ function decide(input, deps) {
30377
30910
  case "write.pre": {
30378
30911
  if (!usable2(descriptor.events["write.pre"].support))
30379
30912
  return NONE6;
30913
+ if (event.text && namesTicket(event.text))
30914
+ return { kind: "deny", reason: TICKET_DENY, unblock: null };
30380
30915
  const role = agentRole(input, descriptor);
30381
30916
  if (role) {
30382
30917
  const targets = liveTargets(input.cwd, event.paths);
@@ -30455,12 +30990,12 @@ var modelKey = (model) => {
30455
30990
  };
30456
30991
 
30457
30992
  // packages/workit-core/src/hooks/budget-signal.ts
30458
- import { createHash as createHash21 } from "node:crypto";
30993
+ import { createHash as createHash22 } from "node:crypto";
30459
30994
  import fs31 from "node:fs";
30460
- import path47 from "node:path";
30461
- var hash2 = (text) => createHash21("sha256").update(text).digest("hex").slice(0, 32);
30462
- var budgetDir = (store) => path47.join(store, "budget");
30463
- var agentBase = (store, session, agentId) => path47.join(budgetDir(store), hash2(`${session}\x00${agentId ?? ""}`));
30995
+ import path48 from "node:path";
30996
+ var hash2 = (text) => createHash22("sha256").update(text).digest("hex").slice(0, 32);
30997
+ var budgetDir = (store) => path48.join(store, "budget");
30998
+ var agentBase = (store, session, agentId) => path48.join(budgetDir(store), hash2(`${session}\x00${agentId ?? ""}`));
30464
30999
  var spawnBudget = (prompt) => {
30465
31000
  const found = /^TIMEBOX:[^\n]*?\b(\d+)\s+tool calls\b/mu.exec(prompt);
30466
31001
  const n = found ? Number(found[1]) : NaN;
@@ -30480,8 +31015,8 @@ var startBudget = (store, session, agentId, n) => {
30480
31015
  const cutoff = Date.now() - 604800000;
30481
31016
  for (const name of fs31.readdirSync(dir))
30482
31017
  try {
30483
- if (fs31.statSync(path47.join(dir, name)).mtimeMs < cutoff)
30484
- fs31.rmSync(path47.join(dir, name));
31018
+ if (fs31.statSync(path48.join(dir, name)).mtimeMs < cutoff)
31019
+ fs31.rmSync(path48.join(dir, name));
30485
31020
  } catch {}
30486
31021
  const base = agentBase(store, session, agentId);
30487
31022
  fs31.writeFileSync(`${base}.json`, JSON.stringify({ limit: n, told: 0 }));
@@ -30620,11 +31155,11 @@ var unfinishedTaskOffer2 = (ctx) => {
30620
31155
  };
30621
31156
 
30622
31157
  // packages/workit-core/src/hooks/repeat-failure.ts
30623
- import { createHash as createHash22 } from "node:crypto";
31158
+ import { createHash as createHash23 } from "node:crypto";
30624
31159
  var SAME_CALL_FAILED = "Same call failed twice:";
30625
31160
  var MAX_SESSIONS = 256;
30626
31161
  var stable = (value) => JSON.stringify(value, (_key, entry) => entry && typeof entry === "object" && !Array.isArray(entry) ? Object.fromEntries(Object.entries(entry).toSorted(([a], [b]) => a.localeCompare(b))) : entry) ?? "null";
30627
- var hashOf = (call) => createHash22("sha256").update(call).digest("hex").slice(0, 32);
31162
+ var hashOf = (call) => createHash23("sha256").update(call).digest("hex").slice(0, 32);
30628
31163
  var record2 = (memo, sessionId, call, failed, next) => {
30629
31164
  const previous = memo.get(sessionId);
30630
31165
  memo.delete(sessionId);
@@ -30817,6 +31352,32 @@ ${shown.join(`
30817
31352
  };
30818
31353
  }
30819
31354
  };
31355
+ var askInline = async (words, command, event, ctx) => {
31356
+ try {
31357
+ const ask = inlineAskFor(words, ctx.cwd);
31358
+ if (!ask)
31359
+ return;
31360
+ const choice = await ctx.ui.select(ask.text, [APPROVE, REJECT]);
31361
+ if (choice !== APPROVE)
31362
+ return {
31363
+ block: true,
31364
+ reason: choice === REJECT ? `The user rejected ${ask.action}: nothing was posted. Do not retry it; report that it was not approved.` : `The user dismissed the dialog for ${ask.action}: nothing was posted.`
31365
+ };
31366
+ const { ticket } = recordInlineAsk({
31367
+ kind: ask.kind,
31368
+ argvHash: ask.argvHash,
31369
+ contentHash: ask.contentHash,
31370
+ host: "pi",
31371
+ session: ctx.sessionManager?.getSessionId() || null,
31372
+ agent: null,
31373
+ toolUseId: event.toolCallId ?? null
31374
+ });
31375
+ event.input.command = `${INLINE_TICKET_ENV}=${ticket} ${command}`;
31376
+ return;
31377
+ } catch (error) {
31378
+ return { block: true, reason: `Workit could not record the approval: ${String(error)}` };
31379
+ }
31380
+ };
30820
31381
  var enforceToolPolicy = (event, ctx) => {
30821
31382
  const gate = (hookEvent) => {
30822
31383
  const decision = handleHook(hookInput(ctx, hookEvent), {
@@ -30834,6 +31395,17 @@ var enforceToolPolicy = (event, ctx) => {
30834
31395
  return { block: true, reason: approveCallDeny(approve.fix) };
30835
31396
  if (approve?.plain && ctx.mode === "tui" && ctx.hasUI)
30836
31397
  return approveInDialog(approve.ids, event, ctx);
31398
+ const inline = typeof command === "string" ? inlineCallIn(command) : null;
31399
+ if (inline && !inline.plain)
31400
+ return { block: true, reason: inlineCallDeny(inline.fix) };
31401
+ if (inline?.plain && ctx.mode === "tui" && ctx.hasUI) {
31402
+ const gated = gate({
31403
+ kind: "shell.pre",
31404
+ command,
31405
+ toolUseId: event.toolCallId ?? null
31406
+ });
31407
+ return gated ?? askInline(inline.words, command, event, ctx);
31408
+ }
30837
31409
  return typeof command === "string" ? gate({
30838
31410
  kind: "shell.pre",
30839
31411
  command,
@@ -30855,7 +31427,8 @@ var enforceToolPolicy = (event, ctx) => {
30855
31427
  kind: "write.pre",
30856
31428
  tool: event.toolName,
30857
31429
  paths: writePaths(event.input),
30858
- toolUseId: null
31430
+ toolUseId: null,
31431
+ text: JSON.stringify(event.input ?? {})
30859
31432
  });
30860
31433
  };
30861
31434
  var observeToolResult = (event, ctx) => {
@@ -30895,14 +31468,14 @@ var observeToolResult = (event, ctx) => {
30895
31468
  var skillPromptNudge = (prompt, ctx) => process.env.WORKIT_PI_WORKER_SESSION ? null : promptNudge(hookInput(ctx, { kind: "context.turn", prompt }), prompt);
30896
31469
 
30897
31470
  // packages/workit-pi/src/launches.ts
30898
- import { mkdirSync as mkdirSync7, readFileSync as readFileSync14, readdirSync as readdirSync8, rmSync as rmSync3, writeFileSync as writeFileSync6 } from "node:fs";
31471
+ import { mkdirSync as mkdirSync7, readFileSync as readFileSync15, readdirSync as readdirSync8, rmSync as rmSync4, writeFileSync as writeFileSync6 } from "node:fs";
30899
31472
  import os11 from "node:os";
30900
- import path48 from "node:path";
31473
+ import path49 from "node:path";
30901
31474
  var launchDir = (root) => {
30902
31475
  const location = resolveStore(root);
30903
- return location instanceof Error ? null : path48.join(location.dir, "pi-launches");
31476
+ return location instanceof Error ? null : path49.join(location.dir, "pi-launches");
30904
31477
  };
30905
- var fileFor = (dir, workerId) => path48.join(dir, `${workerId.replace(/[^A-Za-z0-9-]/g, "_")}.json`);
31478
+ var fileFor = (dir, workerId) => path49.join(dir, `${workerId.replace(/[^A-Za-z0-9-]/g, "_")}.json`);
30906
31479
  var recordLaunch = (root, attempt) => {
30907
31480
  const dir = launchDir(root);
30908
31481
  if (!dir)
@@ -30923,7 +31496,7 @@ var recordLaunch = (root, attempt) => {
30923
31496
  var clearLaunch = (root, workerId) => {
30924
31497
  const dir = launchDir(root);
30925
31498
  if (dir)
30926
- rmSync3(fileFor(dir, workerId), { force: true });
31499
+ rmSync4(fileFor(dir, workerId), { force: true });
30927
31500
  };
30928
31501
  var alive = (attempt) => {
30929
31502
  if (attempt.host !== os11.hostname())
@@ -30948,7 +31521,7 @@ var abandonedLaunches = (root) => {
30948
31521
  const found = [];
30949
31522
  for (const name of names) {
30950
31523
  try {
30951
- const attempt = JSON.parse(readFileSync14(path48.join(dir, name), "utf8"));
31524
+ const attempt = JSON.parse(readFileSync15(path49.join(dir, name), "utf8"));
30952
31525
  if (typeof attempt.workerId === "string" && typeof attempt.session === "string") {
30953
31526
  if (!alive(attempt))
30954
31527
  found.push(attempt);
@@ -30961,17 +31534,17 @@ var cancelHint = (workerId) => `cancel it first: workit_worker {"action":"cancel
30961
31534
 
30962
31535
  // packages/workit-core/src/core/cli-locate.ts
30963
31536
  import { closeSync as closeSync4, existsSync as existsSync15, openSync as openSync4, readSync as readSync2 } from "node:fs";
30964
- import path49 from "node:path";
31537
+ import path50 from "node:path";
30965
31538
  var LAUNCHER_MARKER = "workit-owned-launcher";
30966
31539
  var CLI_PACKAGE_PATH = ["node_modules", "@workit-dev", "cli"];
30967
31540
  var installRoot = (env, platform = process.platform) => {
30968
31541
  if (env.WORKIT_INSTALL_ROOT)
30969
31542
  return env.WORKIT_INSTALL_ROOT;
30970
31543
  const data = dataDir(env, platform);
30971
- return platform === "win32" ? path49.join(data, "install") : data;
31544
+ return platform === "win32" ? path50.join(data, "install") : data;
30972
31545
  };
30973
- var ownedLauncherPath = (env, platform = process.platform) => path49.join(installRoot(env, platform), "bin", platform === "win32" ? "workit.cmd" : "workit");
30974
- var ownedCurrentEntry = (env, platform = process.platform) => path49.join(installRoot(env, platform), "current", ...CLI_PACKAGE_PATH, "dist", "index.js");
31546
+ var ownedLauncherPath = (env, platform = process.platform) => path50.join(installRoot(env, platform), "bin", platform === "win32" ? "workit.cmd" : "workit");
31547
+ var ownedCurrentEntry = (env, platform = process.platform) => path50.join(installRoot(env, platform), "current", ...CLI_PACKAGE_PATH, "dist", "index.js");
30975
31548
  var head = (file) => {
30976
31549
  let fd;
30977
31550
  try {
@@ -30998,7 +31571,7 @@ var locateWorkitCli = (options = {}) => {
30998
31571
  source: "owned-launcher",
30999
31572
  command: launcher,
31000
31573
  args: [],
31001
- binDir: path49.dirname(launcher)
31574
+ binDir: path50.dirname(launcher)
31002
31575
  };
31003
31576
  const current = ownedCurrentEntry(env, platform);
31004
31577
  if (exists(current))
@@ -31027,7 +31600,7 @@ var workitCliEnv = (located, env = process.env, platform = process.platform) =>
31027
31600
  if (located.binDir) {
31028
31601
  const key = pathKey(env);
31029
31602
  const delimiter = platform === "win32" ? ";" : ":";
31030
- const same = (dir) => platform === "win32" ? path49.win32.normalize(dir).toLowerCase() === path49.win32.normalize(located.binDir).toLowerCase() : path49.posix.normalize(dir) === path49.posix.normalize(located.binDir);
31603
+ const same = (dir) => platform === "win32" ? path50.win32.normalize(dir).toLowerCase() === path50.win32.normalize(located.binDir).toLowerCase() : path50.posix.normalize(dir) === path50.posix.normalize(located.binDir);
31031
31604
  const rest = (env[key] ?? "").split(delimiter).filter((dir) => dir && !same(dir));
31032
31605
  patch[key] = [located.binDir, ...rest].join(delimiter);
31033
31606
  }