@workit-dev/codex 2.29.0 → 2.29.1

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.
@@ -14300,9 +14300,9 @@ var arithmeticEnd = (command, start) => {
14300
14300
  const end = substitutionEnd(command, start);
14301
14301
  return command[end - 1] === ")" && end > start + 2 ? end : 0;
14302
14302
  };
14303
- var segmentsOf = (command, dialect = "posix") => {
14303
+ var segmentsOf = (command, dialect = "posix", options = {}) => {
14304
14304
  try {
14305
- return tokenize(command, dialect);
14305
+ return tokenize(command, dialect, options.spans === true);
14306
14306
  } catch (error) {
14307
14307
  const why = error instanceof ShellAnalysisError ? error.message : String(error);
14308
14308
  return [{ words: [], redirects: [], unanalyzable: why }];
@@ -14312,12 +14312,14 @@ var afterEnv = (words) => {
14312
14312
  const at = words.map((word) => word.split(/[\\/]/).at(-1)).lastIndexOf("env");
14313
14313
  return at >= 0 && words.slice(at + 1).every((word, index, rest) => /^-|=/.test(word) || /^-[^-]*[uCS]$|^--(?:unset|chdir|split-string)$/.test(rest[index - 1] ?? ""));
14314
14314
  };
14315
- var tokenize = (command, dialect) => {
14315
+ var tokenize = (command, dialect, spans) => {
14316
14316
  const posix = dialect === "posix";
14317
14317
  const segments = [];
14318
14318
  let current = { words: [], redirects: [] };
14319
14319
  let word = "";
14320
14320
  let inWord = false;
14321
+ let wordStart = -1;
14322
+ let cursor = 0;
14321
14323
  let expanding = false;
14322
14324
  let afterOperator = false;
14323
14325
  let pending = null;
@@ -14328,9 +14330,13 @@ var tokenize = (command, dialect) => {
14328
14330
  if (!inWord)
14329
14331
  return;
14330
14332
  const text = MARKERS.test(word) ? literal2(word) : word;
14333
+ const span = [wordStart, cursor];
14331
14334
  if (pending === "redirect") {
14332
- if (!duplicate || !/^(?:\d+-?|-)$/.test(text))
14335
+ if (!duplicate || !/^(?:\d+-?|-)$/.test(text)) {
14333
14336
  current.redirects.push(text);
14337
+ if (spans)
14338
+ (current.redirectSpans ??= []).push(span);
14339
+ }
14334
14340
  } else if (pending === "heredoc")
14335
14341
  heredocs.push({ delimiter: text.replace(/^-/, ""), owner: current });
14336
14342
  else if (pending === "herestring")
@@ -14338,17 +14344,20 @@ var tokenize = (command, dialect) => {
14338
14344
  else if (pending === "input")
14339
14345
  (current.inputs ??= []).push(text);
14340
14346
  else {
14341
- const at = current.words.length;
14347
+ const at0 = current.words.length;
14342
14348
  if (/^[^=-][^=]*=/.test(word) && afterEnv(current.words))
14343
14349
  word = word.replace(/^[^=]*/, (name) => name.replace(/\W/g, "_"));
14344
14350
  current.words.push(...MARKERS.test(word) ? expandBraces(word) : [word]);
14351
+ if (spans)
14352
+ (current.spans ??= []).push(...current.words.slice(at0).map(() => span));
14345
14353
  if (expanding || !posix && word.startsWith("@"))
14346
- (current.expands ??= []).push(...current.words.slice(at).map((_, i) => at + i));
14354
+ (current.expands ??= []).push(...current.words.slice(at0).map((_, i) => at0 + i));
14347
14355
  }
14348
14356
  pending = null;
14349
14357
  duplicate = false;
14350
14358
  word = "";
14351
14359
  inWord = false;
14360
+ wordStart = -1;
14352
14361
  expanding = false;
14353
14362
  };
14354
14363
  const flushSegment = () => {
@@ -14373,9 +14382,12 @@ var tokenize = (command, dialect) => {
14373
14382
  };
14374
14383
  const plain = posix ? PLAIN_POSIX : PLAIN_POWERSHELL;
14375
14384
  for (let index = 0;index < command.length; index++) {
14385
+ cursor = index;
14376
14386
  plain.lastIndex = index;
14377
14387
  const run = plain.exec(command);
14378
14388
  if (run) {
14389
+ if (wordStart < 0)
14390
+ wordStart = index;
14379
14391
  word += run[0];
14380
14392
  inWord = true;
14381
14393
  if (EXPANDING_RUN.test(run[0]))
@@ -14401,9 +14413,11 @@ var tokenize = (command, dialect) => {
14401
14413
  word += text;
14402
14414
  inWord = true;
14403
14415
  index = end;
14404
- } else if (posix && char === "$" && next === '"')
14416
+ } else if (posix && char === "$" && next === '"') {
14417
+ if (wordStart < 0)
14418
+ wordStart = index;
14405
14419
  continue;
14406
- else if (char === "'" || char === '"') {
14420
+ } else if (char === "'" || char === '"') {
14407
14421
  const end = closingQuote(command, index, dialect);
14408
14422
  const body = command.slice(index + 1, end < 0 ? undefined : end);
14409
14423
  if (posix && char === '"' && /\$\(|`/.test(body))
@@ -14444,6 +14458,7 @@ var tokenize = (command, dialect) => {
14444
14458
  index = end;
14445
14459
  } else if (posix && char === "(" && (pending === "input" || pending === "redirect")) {
14446
14460
  const sign = pending === "input" ? "<" : ">";
14461
+ wordStart = index - 1;
14447
14462
  pending = null;
14448
14463
  const end = substitutionEnd(command, index);
14449
14464
  const inner = command.slice(index + 1, end);
@@ -14456,8 +14471,10 @@ var tokenize = (command, dialect) => {
14456
14471
  if (char === "(" && inWord && word.endsWith("$")) {
14457
14472
  word = word.slice(0, -1);
14458
14473
  inWord = word !== "";
14459
- if (!inWord)
14474
+ if (!inWord) {
14460
14475
  expanding = false;
14476
+ wordStart = -1;
14477
+ }
14461
14478
  }
14462
14479
  group(char === "(" ? "open" : "close");
14463
14480
  } else if (!posix && (char === "{" || char === "}")) {
@@ -14492,6 +14509,7 @@ var tokenize = (command, dialect) => {
14492
14509
  if (inWord && /^\d$/.test(word)) {
14493
14510
  word = "";
14494
14511
  inWord = false;
14512
+ wordStart = -1;
14495
14513
  } else
14496
14514
  flushWord();
14497
14515
  if (command[index + 1] === ">")
@@ -14523,7 +14541,10 @@ var tokenize = (command, dialect) => {
14523
14541
  word += char;
14524
14542
  inWord = true;
14525
14543
  }
14544
+ if (inWord && wordStart < 0)
14545
+ wordStart = cursor;
14526
14546
  }
14547
+ cursor = command.length;
14527
14548
  flushSegment();
14528
14549
  return segments;
14529
14550
  };
@@ -20755,8 +20776,8 @@ var writeTargets = (input) => {
20755
20776
  return paths.length > 0 ? paths : null;
20756
20777
  };
20757
20778
  // packages/workit-core/src/hooks/standing.ts
20758
- import fs23 from "node:fs";
20759
- import path36 from "node:path";
20779
+ import fs24 from "node:fs";
20780
+ import path37 from "node:path";
20760
20781
 
20761
20782
  // packages/workit-core/src/approvals/store.ts
20762
20783
  var REQUEST_TTL_MS = 30 * 60000;
@@ -20809,6 +20830,185 @@ var approveCallIn = (command, dialect = "posix") => {
20809
20830
  };
20810
20831
  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.`;
20811
20832
 
20833
+ // packages/workit-core/src/hooks/cwd-normalize.ts
20834
+ var DIR = String.raw`(?:[A-Za-z0-9_./@%+:,=-]|(?<=[A-Za-z0-9])~)+|'[^'$${"`"}\n]*'|"(?:[^"$${"`"}\\!\n]|\\(?=[^"$${"`"}\\!\n]))*"`;
20835
+ var COMPOUND2 = new RegExp(String.raw`^\s*cd\s+(${DIR})\s*&&\s*(workit(?:\s[\s\S]*)?)$`, "u");
20836
+ var UNSAFE = /[\p{Cf}\p{Zl}\p{Zp}]|[^\P{Cc}\n]/u;
20837
+ var newlines = (text) => text.split(`
20838
+ `).length - 1;
20839
+ var writtenWord = (command, segment, index) => {
20840
+ const span = segment.spans?.[index];
20841
+ if (!span)
20842
+ return null;
20843
+ const glued = (other) => other !== undefined && other !== span && (other[1] === span[0] || other[0] === span[1]);
20844
+ if (glued(segment.spans?.[index - 1]) || glued(segment.spans?.[index + 1]))
20845
+ return null;
20846
+ const text = command.slice(span[0], span[1]);
20847
+ const value = segment.words[index] ?? "";
20848
+ return UNSAFE.test(text) || newlines(text) !== newlines(value) ? null : text;
20849
+ };
20850
+ var writtenWords = (command, segment, indexes) => {
20851
+ const texts = [];
20852
+ let last;
20853
+ for (const index of indexes) {
20854
+ const span = segment.spans?.[index];
20855
+ if (span && span === last)
20856
+ continue;
20857
+ last = span;
20858
+ const text = writtenWord(command, segment, index);
20859
+ if (text === null)
20860
+ return null;
20861
+ texts.push(text);
20862
+ }
20863
+ return texts;
20864
+ };
20865
+ var cwdIndependent = (text, colons = false) => {
20866
+ let quoted = false;
20867
+ for (let index = 0;index < text.length; index += 1) {
20868
+ const char = text[index] ?? "";
20869
+ if (char === "\\")
20870
+ index += 1;
20871
+ else if (char === "'" && !quoted) {
20872
+ const end = text.indexOf("'", index + 1);
20873
+ if (end < 0)
20874
+ return false;
20875
+ index = end;
20876
+ } else if (char === '"')
20877
+ quoted = !quoted;
20878
+ else if (char === "$" || char === "`")
20879
+ return false;
20880
+ else if (quoted)
20881
+ continue;
20882
+ else if (/[*?[]/u.test(char) || /[<>]/u.test(char) && text[index + 1] === "(")
20883
+ return false;
20884
+ else if (char === "~") {
20885
+ const start = index === 0 || colons && text[index - 1] === ":";
20886
+ if (!start || !/^(?:\/|:|$)/u.test(text.slice(index + 1, index + 2)))
20887
+ return false;
20888
+ }
20889
+ }
20890
+ return !quoted;
20891
+ };
20892
+ var NOT_A_PATH = /^(?:\d*|true|false|yes|no|on|off|-[\w-]*(?:=\d+)?)$/iu;
20893
+ var cwdFreeAssignment = (text, value) => {
20894
+ const written = text.replace(/^[A-Za-z_]\w*=/u, "");
20895
+ if (!cwdIndependent(written, true))
20896
+ return false;
20897
+ const quotes = /['"\\]/u.test(written);
20898
+ const parts = value.replace(/^[A-Za-z_]\w*=/u, "").split(":");
20899
+ return parts.every((part) => part.startsWith("/") || !quotes && /^~(?:\/|$)/u.test(part) || (part !== "" || parts.length === 1) && NOT_A_PATH.test(part));
20900
+ };
20901
+ var plainQuotedExpansions = (text) => {
20902
+ const bare = text.replaceAll(/\\./gu, "").replaceAll(/\$(?:[A-Za-z_]\w*|\{[A-Za-z_]\w*\})/gu, "");
20903
+ return !bare.includes("$") && !bare.includes("`");
20904
+ };
20905
+ var certainDir = (text, value) => value !== "" && !value.startsWith("-") && (/^(?:"(?:[^"\\]|\\.)*"|'[^']*')$/u.test(text) && (text.startsWith("'") || plainQuotedExpansions(text)) || cwdIndependent(text) && !/[{}]/u.test(text.replaceAll(/'[^']*'|"(?:[^"\\]|\\.)*"|\\./gu, "")));
20906
+ var namesSet = (segments) => {
20907
+ const names = new Set;
20908
+ for (const { words } of segments) {
20909
+ const at = /^(?:export|declare|typeset|local|readonly)$/u.test(words[0] ?? "") ? 1 : 0;
20910
+ const assigns = words.slice(at).filter((word) => /^[A-Za-z_]\w*=/u.test(word));
20911
+ if (at === 1 || assigns.length === words.length)
20912
+ for (const word of assigns)
20913
+ names.add(word.slice(0, word.indexOf("=")));
20914
+ if (words[0] === "read" || words[0] === "mapfile") {
20915
+ for (const word of words.slice(1))
20916
+ if (/^[A-Za-z_]\w*$/u.test(word))
20917
+ names.add(word);
20918
+ }
20919
+ }
20920
+ return names;
20921
+ };
20922
+ var NO_PATH = /^(?:\d+|-[A-Za-z0-9-]*)$/u;
20923
+ var cwdFreeTail = (texts, check = false) => {
20924
+ const [command = "", ...args] = texts;
20925
+ if (command.includes("/") && !command.startsWith("/"))
20926
+ return false;
20927
+ return check || args.every((text) => NO_PATH.test(text) || /^(?:\/|~(?:\/|$))/u.test(text));
20928
+ };
20929
+ var GLOBALS_FIRST = new RegExp(String.raw`^(\s*workit)((?:\s+(?:--json|--cwd(?:=|\s+)(?:${DIR})))+)\s+([a-z][a-z-]*)(?=\s|$)`, "u");
20930
+ var VERB_FIRST = /^((?:--json\s+)*)([a-z][a-z-]*)(?=\s|$)/u;
20931
+ var VERBS = new Set(WORKIT_ALLOWED_VERBS);
20932
+ var FILTERS = new Set(["tail", "head", "grep"]);
20933
+ var clean = (s) => !s.unanalyzable && !s.group && !s.subs?.length && !s.stdin?.length && !s.redirects.length;
20934
+ var stdinOnly = (words) => {
20935
+ const [name, ...args] = words;
20936
+ const operands = args.filter((w) => !w.startsWith("-"));
20937
+ if (name === "grep")
20938
+ return operands.length <= 1 && !args.some((w) => /^-[^-]*[rRf]|^--(recursive|file)/u.test(w));
20939
+ return operands.every((w) => /^\d+$/u.test(w)) && !args.some((w) => w.startsWith("--output"));
20940
+ };
20941
+ var cwdRewrite = (command) => {
20942
+ const match = COMPOUND2.exec(command);
20943
+ const dir = match?.[1];
20944
+ const rest = match?.[2];
20945
+ if (!dir || !rest || dir.startsWith("-"))
20946
+ return null;
20947
+ if (/[&;<>`\n]/u.test(rest.replaceAll("2>&1", "").replaceAll(/'[^']*'|"([^"\\]|\\.)*"/gu, "")))
20948
+ return null;
20949
+ const segments = segmentsOf(rest);
20950
+ const [head, ...filters] = segments;
20951
+ if (!head || head.words[0] !== "workit")
20952
+ return null;
20953
+ if (!segments.every(clean))
20954
+ return null;
20955
+ if (!segments.slice(0, -1).every((s) => s.pipe))
20956
+ return null;
20957
+ if (!filters.every((s) => FILTERS.has(s.words[0] ?? "") && stdinOnly(s.words)))
20958
+ return null;
20959
+ const at = head.words.indexOf("--cwd");
20960
+ if (at >= 0) {
20961
+ const bare = dir.replace(/^(['"])(.*)\1$/u, "$2");
20962
+ return bare[0] === "/" && head.words[at + 1] === bare ? rest : null;
20963
+ }
20964
+ if (head.words.some((w) => w.startsWith("--cwd=")))
20965
+ return null;
20966
+ const args = rest.slice("workit".length).trimStart();
20967
+ const verb = VERB_FIRST.exec(args);
20968
+ if (!verb?.[2] || !VERBS.has(verb[2]))
20969
+ return `workit --cwd ${dir} ${args}`.trimEnd();
20970
+ const json = verb[1] ? " --json" : "";
20971
+ return `workit ${verb[2]} --cwd ${dir}${json}${args.slice(verb[0].length)}`.trimEnd();
20972
+ };
20973
+ var verbFirst = (command) => {
20974
+ const match = GLOBALS_FIRST.exec(command);
20975
+ const [whole, lead, globals, verb] = match ?? [];
20976
+ if (!whole || !verb || !VERBS.has(verb) || !globals?.includes("--cwd"))
20977
+ return null;
20978
+ const segments = segmentsOf(command);
20979
+ if (segments.length !== 1 || !segments.every(clean))
20980
+ return null;
20981
+ return `${lead} ${verb}${globals}${command.slice(whole.length)}`;
20982
+ };
20983
+ var NPX = new RegExp(String.raw`^(\s*(?:cd\s+(?:${DIR})\s*&&\s*)?)npx(?:\s+(?:-y|--yes))*\s+@workit-dev\/cli(?:@[\w.-]+)?(?=\s|$)`, "u");
20984
+ var npxWorkit = (command) => {
20985
+ const match = NPX.exec(command);
20986
+ if (!match)
20987
+ return null;
20988
+ const call = `${match[1]}workit${command.slice(match[0].length)}`;
20989
+ const left = segmentsOf(call).some((s) => s.unanalyzable || s.words.some((w) => /^(npx|@workit-dev\/cli(@\S*)?)$/u.test(w)));
20990
+ return left ? null : cwdRewrite(call) ?? verbFirst(call) ?? call;
20991
+ };
20992
+ var MUTATING_GIT2 = /^git( -\S+| -[Cc] \S+)* (commit|push|add|switch|checkout|merge|rebase|reset|cherry-pick|revert|branch .*(-[dDmM]|--delete|--move)\b|tag (?!-l\b|--list)|stash(?! (list|show)\b))/u;
20993
+ var cdWorkitSplit = (command) => {
20994
+ const match = COMPOUND2.exec(command);
20995
+ const dir = match?.[1];
20996
+ const rest = match?.[2];
20997
+ if (!dir || !rest || cwdRewrite(command) !== null)
20998
+ return null;
20999
+ const whole = segmentsOf(rest);
21000
+ const boundary = (head) => segmentsOf(head).every((s, at) => s.words.join("\x00") === whole[at]?.words.join("\x00"));
21001
+ for (const op of rest.matchAll(/\|\||;/gu)) {
21002
+ const head = rest.slice(0, op.index).trimEnd();
21003
+ const call = cwdRewrite(`cd ${dir} && ${head}`);
21004
+ if (!call || !boundary(head))
21005
+ continue;
21006
+ const next = segmentsOf(rest.slice(op.index + op[0].length))[0];
21007
+ return next && MUTATING_GIT2.test(next.words.join(" ")) ? call : null;
21008
+ }
21009
+ return null;
21010
+ };
21011
+
20812
21012
  // packages/workit-core/src/approvals/youtrack-ask.ts
20813
21013
  var TIME = "markdown file minutes text date";
20814
21014
  var FLAGS = {
@@ -20820,8 +21020,8 @@ var FLAGS = {
20820
21020
  };
20821
21021
 
20822
21022
  // packages/workit-core/src/approvals/inline.ts
20823
- var DIR = "<dir>";
20824
- var OPAQUE_RELEASE_FIX = `workit release --cwd ${DIR} notes approve <version>`;
21023
+ var DIR2 = "<dir>";
21024
+ var OPAQUE_RELEASE_FIX = `workit release --cwd ${DIR2} notes approve <version>`;
20825
21025
 
20826
21026
  // packages/workit-core/src/hooks/hosts/claude-code.ts
20827
21027
  var CLAUDE_CODE_DESCRIPTOR = {
@@ -21466,86 +21666,562 @@ function neededChecks(lane, configured) {
21466
21666
 
21467
21667
  // packages/workit-core/src/hooks/worktree-confine.ts
21468
21668
  import { createHash as createHash16 } from "node:crypto";
21469
- import fs22 from "node:fs";
21669
+ import fs23 from "node:fs";
21470
21670
  import os10 from "node:os";
21671
+ import path36 from "node:path";
21672
+
21673
+ // packages/workit-core/src/hooks/identity-env.ts
21674
+ import fs22 from "node:fs";
21471
21675
  import path35 from "node:path";
21472
- var FANOUT_TOKEN_FILE = "workit-fanout-token";
21473
- var NONE5 = { kind: "none" };
21474
- var CASE_INSENSITIVE2 = process.platform === "darwin" || process.platform === "win32";
21475
- var realOf = (file) => {
21476
- let rest = "";
21477
- for (let dir = file;; dir = path35.dirname(dir)) {
21676
+ var NAMES = "WORKIT_(?:AGENT_ID|HOST|SESSION_ID|SESSION_TOKEN)";
21677
+ var IDENTITY = new RegExp(`^${NAMES}$`, "u");
21678
+ var HOST_NAMES = "(?:OPENCODE_SESSION_ID|PI_SESSION_ID|CODEX_THREAD_ID|CLAUDECODE|CLAUDE_CODE_ENTRYPOINT)";
21679
+ var HOST_VARIABLE = new RegExp(`^${HOST_NAMES}$`, "u");
21680
+ var IDENTITY_ANY = new RegExp(NAMES, "iu");
21681
+ var STATE_NAMES = "(?:WORKIT_(?:STATE_DIR|CONFIG(?:_DIR)?)|XDG_(?:STATE|CONFIG|DATA)_HOME|HOME|USERPROFILE|(?:LOCAL)?APPDATA)";
21682
+ var STATE2 = new RegExp(`^${STATE_NAMES}$`, "u");
21683
+ var STATE_ANY = new RegExp(STATE_NAMES, "iu");
21684
+ var powershell = (names) => new RegExp([
21685
+ `\\$\\{?env:${names}\\}?\\s*(?:[-+*/]|\\?\\?)?=(?!=)`,
21686
+ `${PS_ITEM}[^;|\\n]*?(?<![$\\w{])env:[\\\\/]?${names}\\b`,
21687
+ `SetEnvironmentVariable\\(\\s*['"]${names}\\b`
21688
+ ].join("|"), "iu");
21689
+ var PS_ITEM = "\\b(?:(?:Set|New|Remove|Clear|Rename|Move|Copy)-Item(?:Property)?|(?:Set|Add|Clear)-Content|si|ni|ri|rm|del|erase|rd|rmdir|cli|sc|ac|clc|rni|mi|move|mv|cpi|copy|cp|ren)\\b";
21690
+ var POWERSHELL = powershell(NAMES);
21691
+ var POWERSHELL_STATE = powershell(STATE_NAMES);
21692
+ var POWERSHELL_HOST = powershell(HOST_NAMES);
21693
+ var POWERSHELL_OPAQUE = new RegExp([
21694
+ `SetEnvironmentVariable\\(\\s*(?:[^'"\\s]|"[^"]*\\$)`,
21695
+ `${PS_ITEM}[^;|\\n]*?(?<![$\\w{])env:[\\\\/]?["']?[$(]`,
21696
+ `(?:^|[;&|{(\\n])\\s*\\.\\s+[^\\s.]`,
21697
+ `\\b(?:iex|Invoke-Expression)\\b`
21698
+ ].join("|"), "iu");
21699
+ var cmdSet = (names) => new RegExp(`(?:^|[&|(\\s"])set\\s+(?:/[ap]\\s+)?"?(${names})\\s*\\+?=`, "iu");
21700
+ var CMD_IDENTITY = cmdSet(NAMES);
21701
+ var CMD_STATE = cmdSet(STATE_NAMES);
21702
+ var CMD_HOST = cmdSet(HOST_NAMES);
21703
+ var RUNS_TEXT = /\bworkit(?:-cli)?\b|@workit-dev[\\/]cli/iu;
21704
+ var DECLARES = new Set(["export", "unset", "declare", "typeset", "local", "readonly"]);
21705
+ var OPAQUE = new Set([
21706
+ "watch",
21707
+ "strace",
21708
+ "chroot",
21709
+ "flock",
21710
+ "ssh",
21711
+ "su",
21712
+ "runuser",
21713
+ "script",
21714
+ "parallel"
21715
+ ]);
21716
+ var ENV_VALUED = new Set(["u", "C", "S", "a", "P"]);
21717
+ var ENV_FLAGS = new Set(["i", "0", "v"]);
21718
+ var ENV_LONG_VALUED = new Set(["--unset", "--chdir", "--split-string", "--argv0"]);
21719
+ var ENV_LONG_FLAGS = /^--(?:ignore-environment|null|debug|(?:block|default|ignore)-signal(?:=.*)?)$/u;
21720
+ var base = (word) => (word?.split(/[\\/]/u).at(-1) ?? "").replace(/\.exe$/iu, "");
21721
+ var ASSIGN = /^[A-Za-z_]\w*\+?=/u;
21722
+ var nameOf = (word) => (word?.split("=")[0] ?? "").replace(/\+$/u, "");
21723
+ var named = (word) => IDENTITY.test(nameOf(word));
21724
+ var stateNamed = (word) => STATE2.test(nameOf(word));
21725
+ var isWorkit = (word) => /^workit(?:-cli)?(?:\.[cm]?js)?$/u.test(base(word)) || /@workit-dev[\\/]cli\b|workit-cli[\\/](?:dist|src)[\\/]/u.test(word ?? "");
21726
+ var linksToWorkit = (word, cwd) => {
21727
+ const places = /[\\/]/u.test(word) ? [path35.resolve(cwd ?? process.cwd(), word)] : (process.env.PATH ?? "").split(path35.delimiter).map((dir) => path35.join(dir, word));
21728
+ for (const place of places) {
21478
21729
  try {
21479
- return path35.join(fs22.realpathSync.native(dir), rest);
21480
- } catch {
21481
- if (path35.dirname(dir) === dir)
21482
- return file;
21483
- rest = rest ? path35.join(path35.basename(dir), rest) : path35.basename(dir);
21484
- }
21730
+ const real = fs22.realpathSync(place);
21731
+ return isWorkit(real);
21732
+ } catch {}
21485
21733
  }
21734
+ return false;
21486
21735
  };
21487
- var canonical6 = (file, hops = { chain: 40, total: 1000 }) => {
21488
- const start = path35.isAbsolute(file) ? file : `${process.cwd()}${path35.sep}${file}`;
21489
- const { root } = path35.parse(start);
21490
- let at = root;
21491
- let missing = false;
21492
- for (const part of start.slice(root.length).split(/[\\/]+/)) {
21493
- if (part === "" || part === ".")
21494
- continue;
21495
- if (part === "..") {
21496
- at = path35.dirname(at);
21497
- continue;
21498
- }
21499
- const next = path35.join(at, part);
21500
- let link = null;
21501
- if (!missing)
21502
- try {
21503
- link = fs22.readlinkSync(next);
21504
- } catch (error) {
21505
- missing = error.code !== "EINVAL";
21506
- }
21507
- if (link === null) {
21508
- at = next;
21509
- hops.chain = 40;
21510
- } else if (hops.chain-- > 0 && hops.total-- > 0)
21511
- at = canonical6(path35.isAbsolute(link) ? link : `${at}${path35.sep}${link}`, hops);
21736
+ var newSeg = () => ({ identity: null, scoped: null, runs: false, words: [] });
21737
+ var UNREADABLE = "env/unset arguments Workit cannot read";
21738
+ var note = (scan, seg, word) => {
21739
+ if (scan.identity && named(word)) {
21740
+ if (seg)
21741
+ seg.identity ??= nameOf(word);
21512
21742
  else
21513
- return path35.resolve(file);
21743
+ scan.hit ??= nameOf(word);
21514
21744
  }
21515
- return realOf(at);
21516
- };
21517
- var within = (child, parent) => {
21518
- const fold = (value) => CASE_INSENSITIVE2 ? value.toLowerCase() : value;
21519
- const relative = path35.relative(fold(parent), fold(child));
21520
- return relative === "" || !relative.startsWith("..") && !path35.isAbsolute(relative);
21745
+ if (!stateNamed(word) && !(scan.identity && HOST_VARIABLE.test(nameOf(word))))
21746
+ return;
21747
+ if (seg)
21748
+ seg.scoped ??= nameOf(word);
21749
+ else
21750
+ scan.shell ??= nameOf(word);
21521
21751
  };
21522
- var checkoutOf2 = (file) => {
21523
- for (let dir = canonical6(file);; dir = path35.dirname(dir)) {
21524
- const dotGit = path35.join(dir, ".git");
21525
- if (fs22.existsSync(dotGit)) {
21526
- const admin = fs22.statSync(dotGit).isFile() ? gitDirsAt(dir, null, false)?.[0] : undefined;
21527
- return { root: dir, workit: !!admin && fs22.existsSync(path35.join(admin, FANOUT_TOKEN_FILE)) };
21752
+ var mayBeWorkit = (words, cwd) => words.some(({ word, built }) => built || linksToWorkit(word, cwd));
21753
+ var scanEnv = (words, at, expands, scan, seg, depth) => {
21754
+ const risky = (what) => void (scan.risky ??= what);
21755
+ const unset = (name) => note(scan, seg, name);
21756
+ const split = (line, rest, built) => {
21757
+ if (line === undefined || depth >= 4)
21758
+ return risky(UNREADABLE);
21759
+ if (built || /[$`]/u.test(line))
21760
+ risky(UNREADABLE);
21761
+ const tokens = [];
21762
+ const expanded = new Set;
21763
+ try {
21764
+ for (const segment of segmentsOf(line)) {
21765
+ for (const index of segment.expands ?? [])
21766
+ expanded.add(tokens.length + index);
21767
+ tokens.push(...segment.words);
21768
+ }
21769
+ } catch {
21770
+ return risky(UNREADABLE);
21528
21771
  }
21529
- if (path35.dirname(dir) === dir)
21530
- return null;
21531
- }
21532
- };
21533
- var workitWorktreeOf = (file) => {
21534
- try {
21535
- const checkout = checkoutOf2(file);
21536
- return checkout?.workit ? checkout.root : null;
21537
- } catch {
21538
- return null;
21539
- }
21540
- };
21541
- var bindingDir = () => path35.join(resolveStateDir(), "worktree-bind");
21542
- var bindingFile = (session, agentId) => path35.join(bindingDir(), `${createHash16("sha256").update(`${session}\x00${agentId}`).digest("hex").slice(0, 32)}.json`);
21543
- var readBinding = (file) => {
21544
- try {
21545
- const value = JSON.parse(fs22.readFileSync(file, "utf8"));
21546
- return typeof value.worktree === "string" ? value : null;
21547
- } catch {
21548
- return null;
21772
+ scanEnv([...tokens, ...words.slice(rest)], 0, expanded, scan, seg, depth + 1);
21773
+ };
21774
+ let options = true;
21775
+ for (let index = at;index < words.length; index += 1) {
21776
+ const word = words[index] ?? "";
21777
+ if (expands.has(index)) {
21778
+ risky(UNREADABLE);
21779
+ const built = options ? /^(?:--split-string=|-[\w]*S)(.+)$/su.exec(word) : null;
21780
+ if (built)
21781
+ return split(built[1], index + 1, true);
21782
+ continue;
21783
+ }
21784
+ if (options && word === "--") {
21785
+ options = false;
21786
+ continue;
21787
+ }
21788
+ if (options && word === "-") {
21789
+ risky("env -i");
21790
+ continue;
21791
+ }
21792
+ if (options && word.startsWith("--")) {
21793
+ const [name = "", value] = word.split(/=(.*)/su);
21794
+ if (name === "--ignore-environment")
21795
+ risky("env -i");
21796
+ else if (name === "--unset")
21797
+ unset(value ?? words[index += 1]);
21798
+ else if (name === "--split-string")
21799
+ return split(value ?? words[index + 1], index + (value === undefined ? 2 : 1), expands.has(index + (value === undefined ? 1 : 0)));
21800
+ else if (ENV_LONG_VALUED.has(name))
21801
+ index += value === undefined ? 1 : 0;
21802
+ else if (!ENV_LONG_FLAGS.test(word))
21803
+ risky(UNREADABLE);
21804
+ continue;
21805
+ }
21806
+ if (options && word.startsWith("-") && word.length > 1) {
21807
+ for (let at2 = 1;at2 < word.length; at2 += 1) {
21808
+ const letter = word[at2] ?? "";
21809
+ if (letter === "i")
21810
+ risky("env -i");
21811
+ else if (ENV_FLAGS.has(letter))
21812
+ continue;
21813
+ else if (ENV_VALUED.has(letter)) {
21814
+ const glued = word.slice(at2 + 1);
21815
+ if (!glued)
21816
+ index += 1;
21817
+ const value = glued || words[index];
21818
+ if (letter === "u")
21819
+ unset(value);
21820
+ if (letter === "S")
21821
+ return split(value, index + 1, expands.has(index));
21822
+ break;
21823
+ } else {
21824
+ risky(UNREADABLE);
21825
+ break;
21826
+ }
21827
+ }
21828
+ continue;
21829
+ }
21830
+ if (ASSIGN.test(word)) {
21831
+ unset(word);
21832
+ continue;
21833
+ }
21834
+ return commandAt(words.slice(index), scan, seg, new Set([...expands].filter((at2) => at2 >= index).map((at2) => at2 - index)));
21835
+ }
21836
+ };
21837
+ var commandAt = (words, scan, seg, expands = new Set, from = 0) => {
21838
+ let index = from;
21839
+ while (index < words.length) {
21840
+ while (ASSIGN.test(words[index] ?? "")) {
21841
+ note(scan, seg, words[index]);
21842
+ index += 1;
21843
+ }
21844
+ const name = base(words[index]).toLowerCase();
21845
+ if (name === "env")
21846
+ return scanEnv(words, index + 1, expands, scan, seg, 0);
21847
+ if (OPAQUE.has(name))
21848
+ return opaque(words.slice(index + 1), scan, seg, true);
21849
+ if (name === "busybox" || name === "toybox") {
21850
+ index += 1;
21851
+ continue;
21852
+ }
21853
+ const takes = WRAPPERS3[name];
21854
+ if (takes === undefined)
21855
+ break;
21856
+ index = pastOptions(words, index + 1, takes);
21857
+ }
21858
+ const word = words[index];
21859
+ if (word === undefined)
21860
+ return;
21861
+ seg.words.push({ word, built: expands.has(index) });
21862
+ const rest = words.slice(index + 1);
21863
+ if (isWorkit(word) || rest.some(isWorkit))
21864
+ seg.runs = true;
21865
+ if (!isWorkit(word) && rest.some((next) => base(next).toLowerCase() === "env"))
21866
+ opaque(rest, scan, seg, false);
21867
+ const program = base(word).toLowerCase();
21868
+ const shell = program === "pwsh" || program === "powershell";
21869
+ if (program === "cmd" || shell) {
21870
+ const at = rest.findIndex((next) => shell ? /^-(?:c|command)$/iu.test(next) : /^\/[ck]$/iu.test(next));
21871
+ if (at >= 0) {
21872
+ const script = rest.slice(at + 1).join(" ");
21873
+ const change = shell ? powershellChange(script, scan.identity) : cmdChange(script, scan);
21874
+ if (change)
21875
+ scan.hit ??= change;
21876
+ }
21877
+ }
21878
+ };
21879
+ var opaque = (rest, scan, seg, assigns) => {
21880
+ if (!rest.some(isWorkit))
21881
+ return;
21882
+ seg.runs = true;
21883
+ const changes = (word) => base(word).toLowerCase() === "env" || DECLARES.has(word) || assigns && ASSIGN.test(word);
21884
+ if (rest.some(changes))
21885
+ scan.risky ??= UNREADABLE;
21886
+ if (rest.some((word) => base(word).toLowerCase() === "env"))
21887
+ for (const word of rest)
21888
+ note(scan, seg, word);
21889
+ };
21890
+ var LOGIN_VALUED = {
21891
+ su: /[sgGwc]/u,
21892
+ runuser: /[sgGwuc]/u,
21893
+ script: /[cEIOBTmot]/u
21894
+ };
21895
+ var loginScript = (words) => {
21896
+ const at = words.findIndex((word) => /^(?:su|runuser|script)$/u.test(base(word)));
21897
+ if (at < 0)
21898
+ return null;
21899
+ const valued = LOGIN_VALUED[base(words[at])] ?? /c/u;
21900
+ for (let index = at + 1;index < words.length; index += 1) {
21901
+ const word = words[index] ?? "";
21902
+ if (word === "--command")
21903
+ return words[index + 1] ?? null;
21904
+ if (word.startsWith("--command="))
21905
+ return word.slice("--command=".length);
21906
+ if (!/^-[^-]/u.test(word))
21907
+ continue;
21908
+ const ends = word.slice(1).search(valued) + 1;
21909
+ if (ends > 0 && word[ends] === "c")
21910
+ return word.slice(ends + 1) || (words[index + 1] ?? null);
21911
+ }
21912
+ return null;
21913
+ };
21914
+ var scanCommand = (command, dialect, depth, scan) => {
21915
+ let segments;
21916
+ try {
21917
+ segments = segmentsOf(command, dialect);
21918
+ } catch {
21919
+ return;
21920
+ }
21921
+ for (const { words, expands = [] } of segments) {
21922
+ const expanded = new Set(expands);
21923
+ const seg = newSeg();
21924
+ let at = 0;
21925
+ while (ASSIGN.test(words[at] ?? ""))
21926
+ at += 1;
21927
+ for (const word of words.slice(0, at))
21928
+ note(scan, at === words.length ? null : seg, word);
21929
+ let declare = at;
21930
+ if (["builtin", "command"].includes(words[declare] ?? ""))
21931
+ declare += 1;
21932
+ if (DECLARES.has(words[declare] ?? "")) {
21933
+ for (let index = declare + 1;index < words.length; index += 1) {
21934
+ note(scan, null, words[index]);
21935
+ if (expanded.has(index))
21936
+ scan.risky ??= UNREADABLE;
21937
+ }
21938
+ continue;
21939
+ }
21940
+ commandAt(words, scan, seg, expanded, at);
21941
+ const script = depth < 4 ? shellScript2(words) ?? loginScript(words) : null;
21942
+ if (script) {
21943
+ const before = scan.runs;
21944
+ scan.runs = false;
21945
+ scanCommand(script, dialect, depth + 1, scan);
21946
+ seg.runs ||= scan.runs;
21947
+ scan.runs ||= before;
21948
+ }
21949
+ scan.words.push(...seg.words);
21950
+ const reaches = () => seg.runs || mayBeWorkit(seg.words, scan.cwd);
21951
+ if (seg.identity && reaches())
21952
+ scan.hit ??= seg.identity;
21953
+ if (seg.scoped && reaches())
21954
+ scan.state ??= seg.scoped;
21955
+ scan.runs ||= seg.runs;
21956
+ }
21957
+ };
21958
+ var cmdChange = (script, scan) => (scan.identity ? CMD_IDENTITY.exec(script)?.[1] : null) ?? (RUNS_TEXT.test(script) ? CMD_STATE.exec(script)?.[1] ?? (scan.identity ? CMD_HOST.exec(script)?.[1] : null) ?? null : null);
21959
+ var powershellChange = (command, identity) => {
21960
+ const hit = identity ? POWERSHELL.exec(command)?.[0] : null;
21961
+ if (hit)
21962
+ return hit;
21963
+ if (!RUNS_TEXT.test(command) && !/&\s*[$(]/u.test(command))
21964
+ return null;
21965
+ const state = POWERSHELL_STATE.exec(command)?.[0] ?? (identity ? POWERSHELL_HOST.exec(command)?.[0] : null) ?? cmdChange(command, { identity });
21966
+ if (state)
21967
+ return state;
21968
+ return POWERSHELL_OPAQUE.test(command) ? UNREADABLE : null;
21969
+ };
21970
+ var identityEnvChange = (command, dialect = "posix", options = {}) => {
21971
+ const identity = options.identity ?? true;
21972
+ if (dialect === "powershell")
21973
+ return powershellChange(command, identity);
21974
+ if (!/WORKIT_|XDG_|HOME|USERPROFILE|APPDATA|OPENCODE_SESSION_ID|PI_SESSION_ID|CODEX_THREAD_ID|CLAUDE|EnvironmentVariable|\b(?:env|unset|export|declare|typeset|local|readonly)\b/iu.test(command))
21975
+ return null;
21976
+ const scan = {
21977
+ identity,
21978
+ cwd: options.cwd,
21979
+ hit: null,
21980
+ state: null,
21981
+ shell: null,
21982
+ risky: null,
21983
+ runs: false,
21984
+ words: []
21985
+ };
21986
+ scanCommand(command, dialect, 0, scan);
21987
+ if (scan.hit)
21988
+ return scan.hit;
21989
+ if (scan.state)
21990
+ return scan.state;
21991
+ if (scan.shell && (scan.runs || mayBeWorkit(scan.words, scan.cwd)))
21992
+ return scan.shell;
21993
+ return scan.runs ? scan.risky : null;
21994
+ };
21995
+ var identityEnvDeny = (change) => {
21996
+ if (change === UNREADABLE || IDENTITY_ANY.test(change) || !STATE_ANY.test(change))
21997
+ return `workit identity: ${change === UNREADABLE ? `this command runs workit with ${UNREADABLE}` : `this command changes ${change}`}. The host sets WORKIT_HOST, WORKIT_SESSION_ID, WORKIT_AGENT_ID and its own session variables, and Workit acts as who they name; run it without changing them (a verifier or reviewer passes the --session and --token its start text names).`;
21998
+ return `workit identity: this command runs workit with ${change} changed. Workit reads issued sessions, grants and its ledger trust from the state and config dirs the host's environment names, so a workit call may not move them (#980); run it without setting, unsetting or emptying ${change}.`;
21999
+ };
22000
+
22001
+ // packages/workit-core/src/hooks/exit-pipe.ts
22002
+ var EXIT_VERBS = [
22003
+ ["ci", "wait"],
22004
+ ["check"],
22005
+ ["pr", "merge"],
22006
+ ["release"],
22007
+ ["verify-delivery"]
22008
+ ];
22009
+ var base2 = (word = "") => word.split(/[\\/]/u).at(-1) ?? "";
22010
+ var verbPath = (words) => {
22011
+ const path = [];
22012
+ for (let at = 0;at < words.length && path.length < 2; at += 1) {
22013
+ const word = words[at];
22014
+ if (word === "--")
22015
+ break;
22016
+ if (word === "--cwd")
22017
+ at += 1;
22018
+ else if (!word.startsWith("-"))
22019
+ path.push(word);
22020
+ }
22021
+ return path;
22022
+ };
22023
+ var identityAssignment = (name) => identityEnvChange(`${name}=x workit`) !== null;
22024
+ var identityWhy = (names) => names.length ? `
22025
+ Why: the retry leaves out ${names.join(", ")}: the identity guard refuses a workit call that sets ${names.length === 1 ? "it" : "them"}.` : "";
22026
+ var exitCall = (segment, first) => {
22027
+ const { words } = segment;
22028
+ let at = first;
22029
+ while (at < words.length && /^[A-Za-z_]\w*=/u.test(words[at]))
22030
+ at += 1;
22031
+ if (!/^workit(?:-cli)?$/u.test(base2(words[at])))
22032
+ return null;
22033
+ const path = verbPath(words.slice(at + 1));
22034
+ return EXIT_VERBS.some((verb) => verb.every((word, index) => path[index] === word)) ? { segment, first, at } : null;
22035
+ };
22036
+ var backgrounded = (command, segment) => {
22037
+ const ends = [...segment.spans ?? [], ...segment.redirectSpans ?? []].map(([, end]) => end);
22038
+ return /^[ \t]*&(?![&>])/u.test(command.slice(Math.max(0, ...ends)));
22039
+ };
22040
+ var setsPipefail = (words) => words[0] === "set" && words.some((word, at) => word === "pipefail" && /^-[a-z]*o$/u.test(words[at - 1] ?? ""));
22041
+ var range = (from, to) => Array.from({ length: to - from }, (_, i) => from + i);
22042
+ var absoluteCwd = (text, value) => cwdIndependent(text) && (/^(?:\/|[A-Za-z]:[\\/])/u.test(value) || /^~(?:\/|$)/u.test(text));
22043
+ var retryOf = (command, found) => {
22044
+ const { segment, first, at, cd, set } = found;
22045
+ const { words } = segment;
22046
+ const dropped = [];
22047
+ const env = range(first, at).filter((index) => {
22048
+ const name = words[index].slice(0, words[index].indexOf("="));
22049
+ if (!identityAssignment(name))
22050
+ return true;
22051
+ dropped.push(name);
22052
+ return false;
22053
+ });
22054
+ const envText = writtenWords(command, segment, env);
22055
+ const callText = writtenWords(command, segment, range(at + 1, words.length));
22056
+ const dir = cd ? writtenWord(command, cd, 1) : "";
22057
+ if (!envText || !callText || cd === undefined || dir === null)
22058
+ return { retry: null, dropped };
22059
+ const reads = [dir, ...envText, ...callText].flatMap((text) => [...text.matchAll(/\$\{?(\w+)/gu)].map((match) => match[1] ?? "")).find((name) => set.has(name));
22060
+ if (reads)
22061
+ return { retry: null, dropped, reads };
22062
+ const call = words.slice(at + 1);
22063
+ const verbAt = call[0]?.startsWith("-") ? 0 : 1;
22064
+ const plain = (body) => [...envText, "workit", ...body].join(" ");
22065
+ if (!cd)
22066
+ return { retry: plain(callText), dropped };
22067
+ const check = verbPath(call)[0] === "check";
22068
+ const cwds = range(at + 1, words.length).filter((index) => words.slice(at + 1, index).every((word) => word !== "--") && (words[index - 1] === "--cwd" || words[index].startsWith("--cwd=")));
22069
+ const moves = certainDir(dir, cd.words[1] ?? "") && env.every((index, n) => cwdFreeAssignment(envText[n] ?? "", words[index])) && callText.every((text) => cwdIndependent(text)) && (!call.includes("--") || callText.includes("--") && cwdFreeTail(callText.slice(callText.indexOf("--") + 1), check)) && cwds.every((index) => {
22070
+ const text = writtenWord(command, segment, index) ?? "";
22071
+ return absoluteCwd(text.replace(/^--cwd=/u, ""), words[index].replace(/^--cwd=/u, ""));
22072
+ });
22073
+ if (!moves)
22074
+ return { retry: `cd ${dir} && ${plain(callText)}`, dropped };
22075
+ if (cwds.length)
22076
+ return { retry: plain(callText), dropped };
22077
+ return {
22078
+ retry: plain([...callText.slice(0, verbAt), "--cwd", dir, ...callText.slice(verbAt)]),
22079
+ dropped
22080
+ };
22081
+ };
22082
+ function exitPipeGate(command, dialect = "posix") {
22083
+ if (!/\bworkit/u.test(command) || !/\b(?:tail|head)\b/u.test(command))
22084
+ return null;
22085
+ const groups = [];
22086
+ let carry = null;
22087
+ let pipefail = false;
22088
+ let cd = null;
22089
+ const seen = [];
22090
+ const chained = !command.includes("||");
22091
+ for (const segment of segmentsOf(command, dialect, { spans: true })) {
22092
+ if (segment.unanalyzable)
22093
+ return null;
22094
+ let words = segment.words;
22095
+ let closes = segment.group === "close";
22096
+ if (segment.group === "open") {
22097
+ groups.push(null);
22098
+ continue;
22099
+ }
22100
+ if (words[0] === "{") {
22101
+ groups.push(null);
22102
+ words = words.slice(1);
22103
+ } else if (words[0] === "}") {
22104
+ closes = true;
22105
+ words = words.slice(1);
22106
+ }
22107
+ if (closes) {
22108
+ const inner = groups.pop() ?? null;
22109
+ if (segment.group === "close" && cd)
22110
+ cd = undefined;
22111
+ if (inner && groups.length)
22112
+ groups[groups.length - 1] = inner;
22113
+ carry = segment.pipe ? inner ?? carry : null;
22114
+ continue;
22115
+ }
22116
+ if (!words.length && !segment.stdin && !segment.subs)
22117
+ continue;
22118
+ if (setsPipefail(words))
22119
+ pipefail = true;
22120
+ const filter = base2(words[0]);
22121
+ if (carry && !pipefail && (filter === "tail" || filter === "head")) {
22122
+ const { retry, dropped, reads } = retryOf(command, carry);
22123
+ const verb = verbPath(carry.segment.words.slice(carry.at + 1)).join(" ");
22124
+ const why = reads ? `Why: an earlier step sets $${reads}, which the call reads: run the same command without the \`| ${filter}\`, that step kept.` : `Why: run the same call without the \`| ${filter}\`, its words as you wrote them.`;
22125
+ return {
22126
+ kind: "deny",
22127
+ reason: `workit exit-pipe: piping \`workit ${verb}\` into ${filter} hides its exit code.
22128
+ ${retry ? `Retry as: ${retry}` : why}${identityWhy(dropped)}`,
22129
+ unblock: retry
22130
+ };
22131
+ }
22132
+ const call = exitCall(segment, segment.words.length - words.length);
22133
+ const found = call ? { ...call, cd, set: namesSet(seen) } : null;
22134
+ seen.push(segment);
22135
+ if (found && groups.length)
22136
+ groups[groups.length - 1] = found;
22137
+ carry = segment.pipe ? found ?? carry : null;
22138
+ const clean = chained && words === segment.words && words.length === 2 && !segment.pipe && !backgrounded(command, segment);
22139
+ if (words[0] === "cd")
22140
+ cd = clean && cd === null ? segment : undefined;
22141
+ else if (cd)
22142
+ cd = undefined;
22143
+ }
22144
+ return null;
22145
+ }
22146
+
22147
+ // packages/workit-core/src/hooks/worktree-confine.ts
22148
+ var FANOUT_TOKEN_FILE = "workit-fanout-token";
22149
+ var NONE5 = { kind: "none" };
22150
+ var CASE_INSENSITIVE2 = process.platform === "darwin" || process.platform === "win32";
22151
+ var realOf = (file) => {
22152
+ let rest = "";
22153
+ for (let dir = file;; dir = path36.dirname(dir)) {
22154
+ try {
22155
+ return path36.join(fs23.realpathSync.native(dir), rest);
22156
+ } catch {
22157
+ if (path36.dirname(dir) === dir)
22158
+ return file;
22159
+ rest = rest ? path36.join(path36.basename(dir), rest) : path36.basename(dir);
22160
+ }
22161
+ }
22162
+ };
22163
+ var canonical6 = (file, hops = { chain: 40, total: 1000 }) => {
22164
+ const start = path36.isAbsolute(file) ? file : `${process.cwd()}${path36.sep}${file}`;
22165
+ const { root } = path36.parse(start);
22166
+ let at = root;
22167
+ let missing = false;
22168
+ for (const part of start.slice(root.length).split(/[\\/]+/)) {
22169
+ if (part === "" || part === ".")
22170
+ continue;
22171
+ if (part === "..") {
22172
+ at = path36.dirname(at);
22173
+ continue;
22174
+ }
22175
+ const next = path36.join(at, part);
22176
+ let link = null;
22177
+ if (!missing)
22178
+ try {
22179
+ link = fs23.readlinkSync(next);
22180
+ } catch (error) {
22181
+ missing = error.code !== "EINVAL";
22182
+ }
22183
+ if (link === null) {
22184
+ at = next;
22185
+ hops.chain = 40;
22186
+ } else if (hops.chain-- > 0 && hops.total-- > 0)
22187
+ at = canonical6(path36.isAbsolute(link) ? link : `${at}${path36.sep}${link}`, hops);
22188
+ else
22189
+ return path36.resolve(file);
22190
+ }
22191
+ return realOf(at);
22192
+ };
22193
+ var within = (child, parent) => {
22194
+ const fold = (value) => CASE_INSENSITIVE2 ? value.toLowerCase() : value;
22195
+ const relative = path36.relative(fold(parent), fold(child));
22196
+ return relative === "" || !relative.startsWith("..") && !path36.isAbsolute(relative);
22197
+ };
22198
+ var checkoutOf2 = (file) => {
22199
+ for (let dir = canonical6(file);; dir = path36.dirname(dir)) {
22200
+ const dotGit = path36.join(dir, ".git");
22201
+ if (fs23.existsSync(dotGit)) {
22202
+ const admin = fs23.statSync(dotGit).isFile() ? gitDirsAt(dir, null, false)?.[0] : undefined;
22203
+ return { root: dir, workit: !!admin && fs23.existsSync(path36.join(admin, FANOUT_TOKEN_FILE)) };
22204
+ }
22205
+ if (path36.dirname(dir) === dir)
22206
+ return null;
22207
+ }
22208
+ };
22209
+ var workitWorktreeOf = (file) => {
22210
+ try {
22211
+ const checkout = checkoutOf2(file);
22212
+ return checkout?.workit ? checkout.root : null;
22213
+ } catch {
22214
+ return null;
22215
+ }
22216
+ };
22217
+ var bindingDir = () => path36.join(resolveStateDir(), "worktree-bind");
22218
+ var bindingFile = (session, agentId) => path36.join(bindingDir(), `${createHash16("sha256").update(`${session}\x00${agentId}`).digest("hex").slice(0, 32)}.json`);
22219
+ var readBinding = (file) => {
22220
+ try {
22221
+ const value = JSON.parse(fs23.readFileSync(file, "utf8"));
22222
+ return typeof value.worktree === "string" ? value : null;
22223
+ } catch {
22224
+ return null;
21549
22225
  }
21550
22226
  };
21551
22227
  var boundWorktree = (input) => {
@@ -21564,8 +22240,8 @@ var bind = (input, worktree) => {
21564
22240
  agentId,
21565
22241
  at: new Date().toISOString()
21566
22242
  };
21567
- fs22.mkdirSync(path35.dirname(file), { recursive: true });
21568
- fs22.writeFileSync(file, JSON.stringify(binding));
22243
+ fs23.mkdirSync(path36.dirname(file), { recursive: true });
22244
+ fs23.writeFileSync(file, JSON.stringify(binding));
21569
22245
  try {
21570
22246
  if (inWorkitWorkspace(input.cwd))
21571
22247
  appendHookObserved(input.cwd, {
@@ -21583,42 +22259,117 @@ var hostIsolated = (cwd, agentId) => {
21583
22259
  const checkout = checkoutOf2(cwd);
21584
22260
  if (!checkout)
21585
22261
  return false;
21586
- const dotGit = path35.join(checkout.root, ".git");
21587
- if (!fs22.statSync(dotGit).isFile())
22262
+ const dotGit = path36.join(checkout.root, ".git");
22263
+ if (!fs23.statSync(dotGit).isFile())
21588
22264
  return false;
21589
22265
  const [adminDir, gitDir] = gitDirsAt(checkout.root, null, false) ?? [];
21590
- const back = fs22.readFileSync(path35.join(adminDir, "gitdir"), "utf8").trim();
21591
- if (path35.relative(canonical6(path35.resolve(adminDir, back)), canonical6(dotGit)) !== "")
22266
+ const back = fs23.readFileSync(path36.join(adminDir, "gitdir"), "utf8").trim();
22267
+ if (path36.relative(canonical6(path36.resolve(adminDir, back)), canonical6(dotGit)) !== "")
21592
22268
  return false;
21593
- const expected = path35.join(path35.dirname(gitDir), ".claude", "worktrees", `agent-${agentId}`);
21594
- return path35.relative(canonical6(expected), checkout.root) === "";
22269
+ const expected = path36.join(path36.dirname(gitDir), ".claude", "worktrees", `agent-${agentId}`);
22270
+ return path36.relative(canonical6(expected), checkout.root) === "";
21595
22271
  } catch {
21596
22272
  return false;
21597
22273
  }
21598
22274
  };
21599
22275
  var runnerAt = (target) => {
21600
- const base = path35.basename(target);
22276
+ const base = path36.basename(target);
21601
22277
  return base.startsWith(OPAQUE_TARGET) ? decodeURIComponent(base.slice(OPAQUE_TARGET.length)) : null;
21602
22278
  };
21603
22279
  var shown = (target) => {
21604
- const named = /^\.workit-(?:live-target$|runs-)/.test(path35.basename(target)) ? path35.dirname(target) : target;
21605
- return path35.sep === "\\" ? named.replaceAll("/", "\\") : named;
22280
+ const named = /^\.workit-(?:live-target$|runs-)/.test(path36.basename(target)) ? path36.dirname(target) : target;
22281
+ return path36.sep === "\\" ? named.replaceAll("/", "\\") : named;
22282
+ };
22283
+ var plainWorkitCall = (command, dialect) => {
22284
+ if (dialect !== "posix")
22285
+ return null;
22286
+ const segments = segmentsOf(command, dialect, { spans: true });
22287
+ const [only] = segments;
22288
+ if (segments.length !== 1 || !only || only.unanalyzable || only.group || only.pipe)
22289
+ return null;
22290
+ if (only.redirects.length || only.subs?.length || only.stdin?.length || only.inputs?.length)
22291
+ return null;
22292
+ const { words } = only;
22293
+ let at = 0;
22294
+ while (at < words.length && /^[A-Za-z_]\w*=/.test(words[at]))
22295
+ at++;
22296
+ if (words[at] !== "workit" || (only.expands ?? []).some((index) => index >= at))
22297
+ return null;
22298
+ return { segment: only, at, cwd: skipWorkitGlobals(words.slice(at + 1)).cwd };
22299
+ };
22300
+ var workitCallDir = (command, dialect) => {
22301
+ const call = plainWorkitCall(command, dialect);
22302
+ return call?.cwd && path36.isAbsolute(call.cwd) ? call.cwd : null;
22303
+ };
22304
+ var shellWord = (dir) => /^[\w@%+=:,./-]+$/u.test(dir) ? dir : `'${dir.replaceAll("'", `'\\''`)}'`;
22305
+ var cwdAt = (words, index) => words[index] === "--cwd" && words[index + 1] !== undefined ? 2 : words[index]?.startsWith("--cwd=") ? 1 : 0;
22306
+ var plainRetry = (dir, command) => {
22307
+ const call = plainWorkitCall(command, "posix");
22308
+ if (!call)
22309
+ return null;
22310
+ const { segment, at } = call;
22311
+ const { words } = segment;
22312
+ const dropped = [];
22313
+ const env = [];
22314
+ for (let index = 0;index < at; index++) {
22315
+ const name = words[index].slice(0, words[index].indexOf("="));
22316
+ if (identityAssignment(name))
22317
+ dropped.push(name);
22318
+ else
22319
+ env.push(index);
22320
+ }
22321
+ const globals = [];
22322
+ let index = at + 1;
22323
+ for (;index < words.length; index++) {
22324
+ const skip = cwdAt(words, index);
22325
+ if (skip)
22326
+ index += skip - 1;
22327
+ else if (/^--(?:session|token|as)$/u.test(words[index]) && words[index + 1] !== undefined)
22328
+ globals.push(index, ++index);
22329
+ else if (/^--(?:session|token|as)=|^--json$/u.test(words[index]))
22330
+ globals.push(index);
22331
+ else
22332
+ break;
22333
+ }
22334
+ const verb = index;
22335
+ const rest = [];
22336
+ for (index += 1;index < words.length; index++) {
22337
+ if (words[index] === "--") {
22338
+ for (;index < words.length; index++)
22339
+ rest.push(index);
22340
+ break;
22341
+ }
22342
+ const skip = cwdAt(words, index);
22343
+ if (skip)
22344
+ index += skip - 1;
22345
+ else
22346
+ rest.push(index);
22347
+ }
22348
+ const text = (indexes) => writtenWords(command, segment, indexes);
22349
+ const parts = [text(env), text(globals), text(verb < words.length ? [verb] : []), text(rest)];
22350
+ if (parts.includes(null))
22351
+ return null;
22352
+ const [envText, globalText, verbText, restText] = parts;
22353
+ const cwd = ["--cwd", shellWord(dir)];
22354
+ const body = [...globalText, ...verbText, ...cwd, ...restText];
22355
+ return { retry: [...envText, "workit", ...body].join(" "), dropped };
21606
22356
  };
21607
22357
  var runFrom = (dir, command) => `cd ${dir} && ${command.replace(/^\s*cd\s+\S+\s*(?:&&|;)\s*/, "")}`;
21608
- var deny2 = (what, unblock) => ({
22358
+ var deny2 = (what, unblock, note = "") => ({
21609
22359
  kind: "deny",
21610
22360
  reason: `${what}.
21611
- ${unblock}`,
22361
+ ${unblock}${note}`,
21612
22362
  unblock
21613
22363
  });
21614
22364
  var unboundDeny = (input, target) => deny2(`workit worktree confinement: implementer ${input.session.agentId} is not working in a Workit worktree yet, and ${shown(target)} is outside every one`, "Why: work only in your brief's worktree (`workit fanout worktree create <slice>`); with none, tell the lead.");
21615
22365
  var outsideDeny = (input, worktree, target, command) => {
21616
22366
  const runner = runnerAt(target);
21617
- return deny2(`workit worktree confinement: implementer ${input.session.agentId} is bound to the worktree ${worktree}, and ${runner === null ? `${shown(target)} is` : `\`${runner}\` runs in ${shown(target)},`} outside it`, runner !== null && command ? `Retry as: ${runFrom(worktree, command)}` : `Why: edit only under ${worktree}, git one verb per call (\`workit git --cwd ${worktree} commit -m … -- <paths>\`); the rest is a follow-up.`);
22367
+ const plain = runner !== null && command ? plainRetry(worktree, command) : null;
22368
+ return deny2(`workit worktree confinement: implementer ${input.session.agentId} is bound to the worktree ${worktree}, and ${runner === null ? `${shown(target)} is` : `\`${runner}\` runs in ${shown(target)},`} outside it`, runner !== null && command ? `Retry as: ${plain?.retry ?? runFrom(worktree, command)}` : `Why: edit only under ${worktree}, git one verb per call (\`workit git --cwd ${worktree} commit -m … -- <paths>\`); the rest is a follow-up.`, identityWhy(plain?.dropped ?? []));
21618
22369
  };
21619
22370
  var unknownDirDeny = (input, worktree) => deny2(`workit worktree confinement: implementer ${input.session.agentId} writes after a directory change Workit cannot resolve (\`cd -\`, \`cd "$X"\`, \`popd\`)`, `Why: write by absolute path, \`git -C ${worktree ?? "<worktree>"}\` or \`workit <verb> --cwd\`.`);
21620
22371
  var refsOf = (targets) => [
21621
- ...new Set(targets.flatMap((target) => path35.relative(UNKNOWN_VAR, path35.resolve(target)).split(path35.sep)[0].split("+").filter(Boolean).map(decodeURIComponent)))
22372
+ ...new Set(targets.flatMap((target) => path36.relative(UNKNOWN_VAR, path36.resolve(target)).split(path36.sep)[0].split("+").filter(Boolean).map(decodeURIComponent)))
21622
22373
  ];
21623
22374
  var literalForm = (command, refs) => {
21624
22375
  let text = command;
@@ -21651,10 +22402,10 @@ function confineImplementer(input, targets, command) {
21651
22402
  try {
21652
22403
  if (!input.session.agentId || hostIsolated(input.cwd, input.session.agentId))
21653
22404
  return NONE5;
21654
- const unresolved = targets.filter((target) => within(path35.resolve(target), UNKNOWN_VAR));
22405
+ const unresolved = targets.filter((target) => within(path36.resolve(target), UNKNOWN_VAR));
21655
22406
  if (unresolved.length > 0)
21656
22407
  return unknownVarDeny(input, unresolved, command);
21657
- if (targets.some((target) => within(path35.resolve(target), UNKNOWN_DIR)))
22408
+ if (targets.some((target) => within(path36.resolve(target), UNKNOWN_DIR)))
21658
22409
  return unknownDirDeny(input, boundWorktree(input));
21659
22410
  const bindings = canonical6(bindingDir());
21660
22411
  const judged = targets.map((named) => ({ named, real: canonical6(named) })).filter(({ real }) => within(real, bindings) || checkoutOf2(real) !== null);
@@ -21746,7 +22497,7 @@ function confineImplementerShell(input, command, dialect = "posix") {
21746
22497
  if (rawInvocations(command, dialect).some((invocation) => invocation.tool === "git" && leadOwnedGit(invocation.args)) || workitInvocations(command, dialect).some(leadOwnedWorkit))
21747
22498
  return leadOwnedDeny(input, command);
21748
22499
  } catch {}
21749
- return confineImplementer(input, shellMutationTargets(input.cwd, command, dialect, true), command);
22500
+ return confineImplementer(input, shellMutationTargets(workitCallDir(command, dialect) ?? input.cwd, command, dialect, true), command);
21750
22501
  }
21751
22502
  var LITERAL_SET = /^\s*([A-Za-z_]\w*)=(['"]?)((?:[\w@%+=:./\\-]|(?<=[^\s:=])~)*)\2[ \t]*(?:;|&&|\n)\s*/;
21752
22503
  var SPELLED = /^(?:[A-Za-z]|wt|wd|dir|repo|root|base|sha|ref|branch|file|out|scratch|worktree|WT|WD|DIR|REPO|ROOT|BASE|SHA|REF|BRANCH|FILE|OUT|SCRATCH|WORKTREE)$/;
@@ -21761,10 +22512,10 @@ var INLINE = /^-[a-zA-Z]*[ceEpm]$|^--(?:eval|print)(?:=|$)|^--(?:test|version|he
21761
22512
  var VALUED2 = /^-[WXIrC]$|^--(?:require|import|loader|conditions|input-type)$/;
21762
22513
  var commonDir = (root) => gitDirsAt(root, null, false)?.[1] ?? "";
21763
22514
  var inScratch = (real, repo) => {
21764
- for (let dir = real;path35.dirname(dir) !== dir; dir = path35.dirname(dir)) {
21765
- if (path35.basename(dir) !== SCRATCH)
22515
+ for (let dir = real;path36.dirname(dir) !== dir; dir = path36.dirname(dir)) {
22516
+ if (path36.basename(dir) !== SCRATCH)
21766
22517
  continue;
21767
- const root = path35.dirname(dir);
22518
+ const root = path36.dirname(dir);
21768
22519
  const checkout = checkoutOf2(root);
21769
22520
  if (checkout?.root === root && (repo === null || checkout.workit || commonDir(root) === repo))
21770
22521
  return true;
@@ -21774,7 +22525,7 @@ var inScratch = (real, repo) => {
21774
22525
  var inGitDir = (real) => real.split(/[\\/]/).includes(".git");
21775
22526
  var SAFE_KEY = /^(?:core\.(?:repositoryformatversion|filemode|bare|logallrefupdates|ignorecase|precomposeunicode|symlinks)|user\..*|init\.defaultbranch|commit\.gpgsign|extensions\.(?:objectformat|refstorage)|branch\..*\.(?:remote|merge)|remote\..*\.fetch)$/;
21776
22527
  var literalIn = (value, repo, checkout = false) => {
21777
- if (/[$`]/.test(value) || !path35.isAbsolute(value))
22528
+ if (/[$`]/.test(value) || !path36.isAbsolute(value))
21778
22529
  return false;
21779
22530
  const real = canonical6(value);
21780
22531
  const root = checkout ? checkoutOf2(real)?.root : undefined;
@@ -21795,45 +22546,45 @@ var configEntries = (text) => {
21795
22546
  return entries;
21796
22547
  };
21797
22548
  function gitDirsAt(dir, repo, scan = true) {
21798
- for (let at = dir;; at = path35.dirname(at)) {
21799
- const dotGit = path35.join(at, ".git");
22549
+ for (let at = dir;; at = path36.dirname(at)) {
22550
+ const dotGit = path36.join(at, ".git");
21800
22551
  let gitDir = null;
21801
22552
  try {
21802
- if (fs22.statSync(dotGit).isDirectory())
22553
+ if (fs23.statSync(dotGit).isDirectory())
21803
22554
  gitDir = canonical6(dotGit);
21804
22555
  else {
21805
- const named = /^gitdir:\s*(.+?)\s*$/mu.exec(fs22.readFileSync(dotGit, "utf8"))?.[1];
22556
+ const named = /^gitdir:\s*(.+?)\s*$/mu.exec(fs23.readFileSync(dotGit, "utf8"))?.[1];
21806
22557
  if (!named)
21807
22558
  return null;
21808
- gitDir = canonical6(path35.resolve(at, named));
22559
+ gitDir = canonical6(path36.resolve(at, named));
21809
22560
  }
21810
22561
  } catch (error) {
21811
22562
  if (error.code !== "ENOENT")
21812
22563
  return null;
21813
- if (["HEAD", "objects", "refs"].every((name) => fs22.existsSync(path35.join(at, name))))
22564
+ if (["HEAD", "objects", "refs"].every((name) => fs23.existsSync(path36.join(at, name))))
21814
22565
  gitDir = canonical6(at);
21815
22566
  }
21816
22567
  if (gitDir !== null) {
21817
- const common = path35.join(gitDir, "commondir");
21818
- const shared = fs22.existsSync(common) ? canonical6(path35.resolve(gitDir, fs22.readFileSync(common, "utf8").trim())) : gitDir;
22568
+ const common = path36.join(gitDir, "commondir");
22569
+ const shared = fs23.existsSync(common) ? canonical6(path36.resolve(gitDir, fs23.readFileSync(common, "utf8").trim())) : gitDir;
21819
22570
  const dirs = [gitDir, shared];
21820
- for (const config of scan ? new Set([path35.join(gitDir, "config"), path35.join(shared, "config")]) : []) {
22571
+ for (const config of scan ? new Set([path36.join(gitDir, "config"), path36.join(shared, "config")]) : []) {
21821
22572
  let text = "";
21822
22573
  try {
21823
- text = fs22.readFileSync(config, "utf8");
22574
+ text = fs23.readFileSync(config, "utf8");
21824
22575
  } catch {
21825
22576
  continue;
21826
22577
  }
21827
22578
  for (const [key, value] of configEntries(text)) {
21828
22579
  if (key === "core.worktree")
21829
- dirs.push(canonical6(path35.resolve(gitDir, value)));
22580
+ dirs.push(canonical6(path36.resolve(gitDir, value)));
21830
22581
  else if (/^remote\..*\.url$/.test(key) ? !literalIn(value, repo, true) : !SAFE_KEY.test(key))
21831
22582
  return null;
21832
22583
  }
21833
22584
  }
21834
22585
  return dirs;
21835
22586
  }
21836
- if (path35.dirname(at) === at)
22587
+ if (path36.dirname(at) === at)
21837
22588
  return [];
21838
22589
  }
21839
22590
  }
@@ -21973,10 +22724,10 @@ var gitKind = (args, local = () => true) => {
21973
22724
  return GIT_VERBS[verb].startsWith("+") ? "write" : "read";
21974
22725
  };
21975
22726
  var remoteIn = (dir, name, repo) => {
21976
- const shared = path35.isAbsolute(dir) ? gitDirsAt(canonical6(dir), repo, false)?.[1] : undefined;
22727
+ const shared = path36.isAbsolute(dir) ? gitDirsAt(canonical6(dir), repo, false)?.[1] : undefined;
21977
22728
  if (!shared)
21978
22729
  return false;
21979
- const url = configEntries(fs22.readFileSync(path35.join(shared, "config"), "utf8")).find(([key]) => key === `remote.${name}.url`.toLowerCase())?.[1];
22730
+ const url = configEntries(fs23.readFileSync(path36.join(shared, "config"), "utf8")).find(([key]) => key === `remote.${name}.url`.toLowerCase())?.[1];
21980
22731
  return url !== undefined && literalIn(url, repo, true);
21981
22732
  };
21982
22733
  var judgeEnvAllowed = (word) => {
@@ -22005,7 +22756,7 @@ var judgeGit = (command, repo, cwd, depth = 0) => {
22005
22756
  at = after;
22006
22757
  }
22007
22758
  }
22008
- const name = path35.basename(words[at] ?? "");
22759
+ const name = path36.basename(words[at] ?? "");
22009
22760
  let start = words.findIndex((word) => /(?:^|[\\/])git(?:\.exe)?(?:=|$)/.test(word));
22010
22761
  if (start > at) {
22011
22762
  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] ?? ""))
@@ -22016,7 +22767,7 @@ var judgeGit = (command, repo, cwd, depth = 0) => {
22016
22767
  if (start >= 0 && words[start].includes("="))
22017
22768
  why = "git is redefined";
22018
22769
  const run = words[start] ?? "";
22019
- if (run.includes("/") && (!path35.isAbsolute(run) || literalIn(run, repo, true)))
22770
+ if (run.includes("/") && (!path36.isAbsolute(run) || literalIn(run, repo, true)))
22020
22771
  why ??= `\`${run}\` is not the system git`;
22021
22772
  if (segment.expands?.includes(at) && name !== "[" || /\{[^}]*,/.test(words[at] ?? ""))
22022
22773
  why = "the command's name is expanded by the shell";
@@ -22041,13 +22792,13 @@ var judgeGit = (command, repo, cwd, depth = 0) => {
22041
22792
  const args = words[index] === "--version" ? ["version"] : words.slice(index);
22042
22793
  if (!why && start >= 0) {
22043
22794
  const local = (source, remote) => remote && /^[\w-][\w.-]*$/.test(source) ? remoteIn(dir, source, repo) : literalIn(source, repo, true);
22044
- const runsIn = path35.isAbsolute(dir) ? dir : cwd && path35.resolve(cwd, dir);
22795
+ const runsIn = path36.isAbsolute(dir) ? dir : cwd && path36.resolve(cwd, dir);
22045
22796
  const home = runsIn && checkoutOf2(runsIn);
22046
22797
  const fetches = args[0] === "fetch" && plainFetch(args.slice(1)) && home && (home.workit || commonDir(home.root) === repo) && !words.some((word) => /^--[gw]/.test(word));
22047
22798
  if (!fetches && !gitKind(args, local))
22048
22799
  why = `\`git ${args.slice(0, 2).join(" ")}\` is not allowed`;
22049
22800
  }
22050
- const shell = /^(?:grep|egrep|rg|echo|printf|cat)$/.test(name) ? -1 : words.findIndex((word) => /^(?:sh|bash|zsh|dash|ksh|mksh|ash)$/.test(path35.basename(word)));
22801
+ const shell = /^(?:grep|egrep|rg|echo|printf|cat)$/.test(name) ? -1 : words.findIndex((word) => /^(?:sh|bash|zsh|dash|ksh|mksh|ash)$/.test(path36.basename(word)));
22051
22802
  const scripts = [
22052
22803
  ...words.filter((_, after) => shell >= 0 && after > shell && /^-[a-zA-Z]*c[a-zA-Z]*$/.test(words[after - 1])),
22053
22804
  ...shell < 0 ? [] : segment.stdin ?? []
@@ -22092,7 +22843,7 @@ var judgeVerbRefused = (args) => {
22092
22843
  var CLI_RUNNERS = /^(?:npx|bunx|pnpx|npm|pnpm|yarn|bun|node|nodejs|deno|tsx|ts-node)$/;
22093
22844
  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?$/;
22094
22845
  var workitCalls = (command, depth = 0, aliases = new Map) => depth > 4 ? [] : commandLines(command).flatMap((words) => {
22095
- const name = path35.basename(words[0] ?? "").toLowerCase();
22846
+ const name = path36.basename(words[0] ?? "").toLowerCase();
22096
22847
  if (name === "alias")
22097
22848
  return words.flatMap((word) => {
22098
22849
  const set = /^([\w-]+)=(.*)$/s.exec(word);
@@ -22121,11 +22872,11 @@ var judgeRefusal = (command, fed, depth = 0) => {
22121
22872
  return why;
22122
22873
  }
22123
22874
  const { words } = segment;
22124
- const runs = (word = "") => RUNS.test(path35.basename(word).toLowerCase());
22875
+ const runs = (word = "") => RUNS.test(path36.basename(word).toLowerCase());
22125
22876
  let at = 0;
22126
22877
  while (at < words.length && (LEADS.test(words[at]) || /^-\w$/.test(words[at - 1] ?? "") && !runs(words[at])))
22127
22878
  at++;
22128
- const name = path35.basename(words[at] ?? "").toLowerCase();
22879
+ const name = path36.basename(words[at] ?? "").toLowerCase();
22129
22880
  const args = words.slice(at + 1);
22130
22881
  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`;
22131
22882
  if (/^(?:cd|chdir|pushd|popd)$/.test(name))
@@ -22207,10 +22958,10 @@ var judgeDeny = (input, what, target, retry, why = "write only there (mkdir -p i
22207
22958
  const role = input.session.agentType?.endsWith("reviewer") ? "reviewer" : "verifier";
22208
22959
  const root = checkoutOf2(input.cwd)?.root;
22209
22960
  const candidate = target ? checkoutOf2(target)?.root : undefined;
22210
- const other = root && candidate && candidate !== root && commonDir(candidate) === commonDir(root) ? path35.join(candidate, SCRATCH) : undefined;
22211
- const scratch = root ? `${path35.join(root, SCRATCH)}${other ? ` or ${other}` : ""}` : `${SCRATCH}/ at the root of the checkout you judge`;
22212
- const call = root ? retry?.((other ?? path35.join(root, SCRATCH)).replaceAll("\\", "/")) : null;
22213
- const unblock = call ? `Retry as: ${call}` : `Why: ${why.replaceAll("<scratch>", other ?? (root ? path35.join(root, SCRATCH) : SCRATCH))}`;
22961
+ const other = root && candidate && candidate !== root && commonDir(candidate) === commonDir(root) ? path36.join(candidate, SCRATCH) : undefined;
22962
+ const scratch = root ? `${path36.join(root, SCRATCH)}${other ? ` or ${other}` : ""}` : `${SCRATCH}/ at the root of the checkout you judge`;
22963
+ const call = root ? retry?.((other ?? path36.join(root, SCRATCH)).replaceAll("\\", "/")) : null;
22964
+ const unblock = call ? `Retry as: ${call}` : `Why: ${why.replaceAll("<scratch>", other ?? (root ? path36.join(root, SCRATCH) : SCRATCH))}`;
22214
22965
  return {
22215
22966
  kind: "deny",
22216
22967
  reason: `workit scratch confinement: ${role} ${input.session.agentId} may write only in its scratch dir ${scratch}, and ${what}.
@@ -22220,9 +22971,9 @@ ${unblock}`,
22220
22971
  };
22221
22972
  var movedInto = (command, cwd, target, dir) => {
22222
22973
  for (const { words, redirects } of segmentsOf(command))
22223
- for (const word of [...redirects, ...path35.basename(words[0] ?? "") === "tee" ? words : []])
22224
- if (path35.resolve(cwd, word) === path35.resolve(cwd, target)) {
22225
- const moved = command.replace(new RegExp(`((?:>>?\\|?|\\btee(?:\\s+-a)?)\\s*)(['"]?)${word.replace(/[$()*+.?[\\\]^{|}]/g, "\\$&")}\\2(?![^\\s;&|)])`), (_, lead) => `${lead}${dir}/${path35.basename(word)}`);
22974
+ for (const word of [...redirects, ...path36.basename(words[0] ?? "") === "tee" ? words : []])
22975
+ if (path36.resolve(cwd, word) === path36.resolve(cwd, target)) {
22976
+ const moved = command.replace(new RegExp(`((?:>>?\\|?|\\btee(?:\\s+-a)?)\\s*)(['"]?)${word.replace(/[$()*+.?[\\\]^{|}]/g, "\\$&")}\\2(?![^\\s;&|)])`), (_, lead) => `${lead}${dir}/${path36.basename(word)}`);
22226
22977
  return moved === command ? null : moved;
22227
22978
  }
22228
22979
  return null;
@@ -22234,19 +22985,19 @@ function confineJudge(input, targets, placeholders = placeholdersOf(targets), co
22234
22985
  const judged = checkoutOf2(input.cwd);
22235
22986
  const repo = judged ? commonDir(judged.root) : null;
22236
22987
  const scratch = (real) => inScratch(real, repo) || [os10.tmpdir(), "/tmp"].some((dir) => {
22237
- const [host, , session] = path35.relative(canonical6(dir), real).split(path35.sep);
22988
+ const [host, , session] = path36.relative(canonical6(dir), real).split(path36.sep);
22238
22989
  return /^claude-\d+$/.test(host) && session === input.session.id;
22239
22990
  });
22240
22991
  for (const target of targets) {
22241
- const resolved = path35.resolve(target);
22992
+ const resolved = path36.resolve(target);
22242
22993
  if (within(resolved, UNKNOWN_VAR) || within(resolved, UNKNOWN_DIR))
22243
22994
  return judgeDeny(input, "it writes to a path Workit cannot resolve", undefined, () => {
22244
22995
  const literal = command && literalForm(command, refsOf([target]));
22245
22996
  return literal === command ? null : literal;
22246
22997
  });
22247
22998
  const real = canonical6(target);
22248
- const runsGit = placeholders.has(target) && /^\.workit-(?:runs-git|live-target)$/.test(path35.basename(target));
22249
- const gitDirs = runsGit ? gitDirsAt(path35.dirname(real), repo) : [];
22999
+ const runsGit = placeholders.has(target) && /^\.workit-(?:runs-git|live-target)$/.test(path36.basename(target));
23000
+ const gitDirs = runsGit ? gitDirsAt(path36.dirname(real), repo) : [];
22250
23001
  if (gitDirs === null)
22251
23002
  return judgeDeny(input, `git in ${shown(target)} uses a git dir or config Workit cannot check`);
22252
23003
  if (runsGit ? gitDirs.length > 0 ? gitDirs.every(scratch) : scratch(real) : scratch(real) && !inGitDir(real))
@@ -22314,7 +23065,7 @@ function confineJudgeShell(input, command, dialect = "posix") {
22314
23065
  let git = [];
22315
23066
  try {
22316
23067
  git = rawInvocations(command, dialect).flatMap(({ tool, dir, args }) => tool === "git" && (args[0] === "push" || leadOwnedGit(args) || gitKind(args) === "write" && !/^(?:init|clone)$/.test(args[0]) && !(args[0] === "fetch" && plainFetch(args.slice(1)))) ? [
22317
- path35.join(dir === undefined ? UNKNOWN_DIR : path35.resolve(input.cwd, dir ?? "."), `${OPAQUE_TARGET}git`)
23068
+ path36.join(dir === undefined ? UNKNOWN_DIR : path36.resolve(input.cwd, dir ?? "."), `${OPAQUE_TARGET}git`)
22318
23069
  ] : []);
22319
23070
  } catch {}
22320
23071
  const lists = [
@@ -22359,17 +23110,17 @@ var judgeChecksLine = (cwd) => {
22359
23110
 
22360
23111
  // packages/workit-core/src/hooks/standing.ts
22361
23112
  var readPlans = (store) => {
22362
- const dir = path36.join(store, "fanouts");
23113
+ const dir = path37.join(store, "fanouts");
22363
23114
  let names;
22364
23115
  try {
22365
- names = fs23.readdirSync(dir).filter((name) => name.endsWith(".json"));
23116
+ names = fs24.readdirSync(dir).filter((name) => name.endsWith(".json"));
22366
23117
  } catch {
22367
23118
  return [];
22368
23119
  }
22369
23120
  const plans = [];
22370
23121
  for (const name of names) {
22371
23122
  try {
22372
- const raw = JSON.parse(fs23.readFileSync(path36.join(dir, name), "utf8"));
23123
+ const raw = JSON.parse(fs24.readFileSync(path37.join(dir, name), "utf8"));
22373
23124
  if (typeof raw.name !== "string" || !Array.isArray(raw.slices))
22374
23125
  continue;
22375
23126
  const texts = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string" && item !== "") : [];
@@ -22491,100 +23242,14 @@ var standingDelta = (input) => {
22491
23242
  }
22492
23243
  };
22493
23244
  var sinceStart = new Map;
22494
- // packages/workit-core/src/hooks/cwd-normalize.ts
22495
- var DIR2 = String.raw`(?:[A-Za-z0-9_./@%+:,=-]|(?<=[A-Za-z0-9])~)+|'[^'$${"`"}\n]*'|"(?:[^"$${"`"}\\!\n]|\\(?=[^"$${"`"}\\!\n]))*"`;
22496
- var COMPOUND2 = new RegExp(String.raw`^\s*cd\s+(${DIR2})\s*&&\s*(workit(?:\s[\s\S]*)?)$`, "u");
22497
- var GLOBALS_FIRST = new RegExp(String.raw`^(\s*workit)((?:\s+(?:--json|--cwd(?:=|\s+)(?:${DIR2})))+)\s+([a-z][a-z-]*)(?=\s|$)`, "u");
22498
- var VERB_FIRST = /^((?:--json\s+)*)([a-z][a-z-]*)(?=\s|$)/u;
22499
- var VERBS = new Set(WORKIT_ALLOWED_VERBS);
22500
- var FILTERS = new Set(["tail", "head", "grep"]);
22501
- var clean = (s) => !s.unanalyzable && !s.group && !s.subs?.length && !s.stdin?.length && !s.redirects.length;
22502
- var stdinOnly = (words) => {
22503
- const [name, ...args] = words;
22504
- const operands = args.filter((w) => !w.startsWith("-"));
22505
- if (name === "grep")
22506
- return operands.length <= 1 && !args.some((w) => /^-[^-]*[rRf]|^--(recursive|file)/u.test(w));
22507
- return operands.every((w) => /^\d+$/u.test(w)) && !args.some((w) => w.startsWith("--output"));
22508
- };
22509
- var cwdRewrite = (command) => {
22510
- const match = COMPOUND2.exec(command);
22511
- const dir = match?.[1];
22512
- const rest = match?.[2];
22513
- if (!dir || !rest || dir.startsWith("-"))
22514
- return null;
22515
- if (/[&;<>`\n]/u.test(rest.replaceAll("2>&1", "").replaceAll(/'[^']*'|"([^"\\]|\\.)*"/gu, "")))
22516
- return null;
22517
- const segments = segmentsOf(rest);
22518
- const [head, ...filters] = segments;
22519
- if (!head || head.words[0] !== "workit")
22520
- return null;
22521
- if (!segments.every(clean))
22522
- return null;
22523
- if (!segments.slice(0, -1).every((s) => s.pipe))
22524
- return null;
22525
- if (!filters.every((s) => FILTERS.has(s.words[0] ?? "") && stdinOnly(s.words)))
22526
- return null;
22527
- const at = head.words.indexOf("--cwd");
22528
- if (at >= 0) {
22529
- const bare = dir.replace(/^(['"])(.*)\1$/u, "$2");
22530
- return bare[0] === "/" && head.words[at + 1] === bare ? rest : null;
22531
- }
22532
- if (head.words.some((w) => w.startsWith("--cwd=")))
22533
- return null;
22534
- const args = rest.slice("workit".length).trimStart();
22535
- const verb = VERB_FIRST.exec(args);
22536
- if (!verb?.[2] || !VERBS.has(verb[2]))
22537
- return `workit --cwd ${dir} ${args}`.trimEnd();
22538
- const json = verb[1] ? " --json" : "";
22539
- return `workit ${verb[2]} --cwd ${dir}${json}${args.slice(verb[0].length)}`.trimEnd();
22540
- };
22541
- var verbFirst = (command) => {
22542
- const match = GLOBALS_FIRST.exec(command);
22543
- const [whole, lead, globals, verb] = match ?? [];
22544
- if (!whole || !verb || !VERBS.has(verb) || !globals?.includes("--cwd"))
22545
- return null;
22546
- const segments = segmentsOf(command);
22547
- if (segments.length !== 1 || !segments.every(clean))
22548
- return null;
22549
- return `${lead} ${verb}${globals}${command.slice(whole.length)}`;
22550
- };
22551
- var NPX = new RegExp(String.raw`^(\s*(?:cd\s+(?:${DIR2})\s*&&\s*)?)npx(?:\s+(?:-y|--yes))*\s+@workit-dev\/cli(?:@[\w.-]+)?(?=\s|$)`, "u");
22552
- var npxWorkit = (command) => {
22553
- const match = NPX.exec(command);
22554
- if (!match)
22555
- return null;
22556
- const call = `${match[1]}workit${command.slice(match[0].length)}`;
22557
- const left = segmentsOf(call).some((s) => s.unanalyzable || s.words.some((w) => /^(npx|@workit-dev\/cli(@\S*)?)$/u.test(w)));
22558
- return left ? null : cwdRewrite(call) ?? verbFirst(call) ?? call;
22559
- };
22560
- var MUTATING_GIT2 = /^git( -\S+| -[Cc] \S+)* (commit|push|add|switch|checkout|merge|rebase|reset|cherry-pick|revert|branch .*(-[dDmM]|--delete|--move)\b|tag (?!-l\b|--list)|stash(?! (list|show)\b))/u;
22561
- var cdWorkitSplit = (command) => {
22562
- const match = COMPOUND2.exec(command);
22563
- const dir = match?.[1];
22564
- const rest = match?.[2];
22565
- if (!dir || !rest || cwdRewrite(command) !== null)
22566
- return null;
22567
- const whole = segmentsOf(rest);
22568
- const boundary = (head) => segmentsOf(head).every((s, at) => s.words.join("\x00") === whole[at]?.words.join("\x00"));
22569
- for (const op of rest.matchAll(/\|\||;/gu)) {
22570
- const head = rest.slice(0, op.index).trimEnd();
22571
- const call = cwdRewrite(`cd ${dir} && ${head}`);
22572
- if (!call || !boundary(head))
22573
- continue;
22574
- const next = segmentsOf(rest.slice(op.index + op[0].length))[0];
22575
- return next && MUTATING_GIT2.test(next.words.join(" ")) ? call : null;
22576
- }
22577
- return null;
22578
- };
22579
-
22580
23245
  // packages/workit-core/src/hooks/spawn-gate.ts
22581
- import fs24 from "node:fs";
22582
- import path38 from "node:path";
23246
+ import fs25 from "node:fs";
23247
+ import path39 from "node:path";
22583
23248
 
22584
23249
  // packages/workit-core/src/hooks/model-limit.ts
22585
23250
  import { closeSync as closeSync3, openSync as openSync3, readdirSync as readdirSync5, readSync, statSync as statSync5 } from "node:fs";
22586
23251
  import os11 from "node:os";
22587
- import path37 from "node:path";
23252
+ import path38 from "node:path";
22588
23253
  var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
22589
23254
  var WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
22590
23255
  var TIME_WORD = String.raw`(?:\d|(?:in|at|on|later|tomorrow|soon)\b|(?:${[...WEEKDAYS, ...MONTHS].join("|")})[a-z]*\b)`;
@@ -22782,17 +23447,17 @@ var firstPrompt = (file) => {
22782
23447
  var claudeProjectSlug = (cwd) => cwd.replace(/[^A-Za-z0-9]/gu, "-");
22783
23448
  var listDir = (dir) => {
22784
23449
  try {
22785
- return readdirSync5(dir).map((name) => path37.join(dir, name));
23450
+ return readdirSync5(dir).map((name) => path38.join(dir, name));
22786
23451
  } catch {
22787
23452
  return [];
22788
23453
  }
22789
23454
  };
22790
23455
  var SCAN_MS = 30 * 60000;
22791
23456
  var scanClaudeTranscripts = (cwd, env, now = new Date) => {
22792
- const projects = path37.join(env.CLAUDE_CONFIG_DIR || path37.join(env.HOME || os11.homedir(), ".claude"), "projects");
22793
- const project = path37.join(projects, claudeProjectSlug(cwd));
23457
+ const projects = path38.join(env.CLAUDE_CONFIG_DIR || path38.join(env.HOME || os11.homedir(), ".claude"), "projects");
23458
+ const project = path38.join(projects, claudeProjectSlug(cwd));
22794
23459
  const notes = [];
22795
- const files = listDir(project).flatMap((entry) => entry.endsWith(".jsonl") ? [{ file: entry, worker: false }] : listDir(path37.join(entry, "subagents")).filter((file) => file.endsWith(".jsonl")).map((file) => ({ file, worker: true })));
23460
+ const files = listDir(project).flatMap((entry) => entry.endsWith(".jsonl") ? [{ file: entry, worker: false }] : listDir(path38.join(entry, "subagents")).filter((file) => file.endsWith(".jsonl")).map((file) => ({ file, worker: true })));
22796
23461
  for (const { file, worker } of files)
22797
23462
  try {
22798
23463
  const stat = statSync5(file);
@@ -22807,7 +23472,7 @@ var scanClaudeTranscripts = (cwd, env, now = new Date) => {
22807
23472
  if (!seen)
22808
23473
  continue;
22809
23474
  notes.push(worker ? redispatchNote(seen, {
22810
- label: `worker ${path37.basename(file, ".jsonl")}`,
23475
+ label: `worker ${path38.basename(file, ".jsonl")}`,
22811
23476
  prompt: firstPrompt(file)
22812
23477
  }, 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.`);
22813
23478
  } catch {}
@@ -22906,13 +23571,13 @@ var agentModelDecision = (cwd, tool, options = {}) => {
22906
23571
  var MADE_WORKTREE = /^WORKTREE:[ \t]*(?!not made yet)\S(?![^\n]*not made yet)/mu;
22907
23572
  var namesMade = (word) => {
22908
23573
  try {
22909
- const stat = fs24.statSync(word);
23574
+ const stat = fs25.statSync(word);
22910
23575
  if (stat.isFile())
22911
- return stat.size < 1e6 && MADE_WORKTREE.test(fs24.readFileSync(word, "utf8"));
22912
- const dotGit = path38.join(word, ".git");
22913
- const link = fs24.statSync(dotGit);
22914
- const admin = link.isFile() && link.size <= 4096 && /^gitdir: *(.+)/u.exec(fs24.readFileSync(dotGit, "utf8"));
22915
- return !!admin && fs24.existsSync(path38.resolve(word, admin[1].trim(), FANOUT_TOKEN_FILE));
23576
+ return stat.size < 1e6 && MADE_WORKTREE.test(fs25.readFileSync(word, "utf8"));
23577
+ const dotGit = path39.join(word, ".git");
23578
+ const link = fs25.statSync(dotGit);
23579
+ const admin = link.isFile() && link.size <= 4096 && /^gitdir: *(.+)/u.exec(fs25.readFileSync(dotGit, "utf8"));
23580
+ return !!admin && fs25.existsSync(path39.resolve(word, admin[1].trim(), FANOUT_TOKEN_FILE));
22916
23581
  } catch {
22917
23582
  return false;
22918
23583
  }
@@ -22958,8 +23623,8 @@ var spawnDecision = (descriptor, cwd, tool, permissionMode = null) => {
22958
23623
 
22959
23624
  // packages/workit-core/src/hooks/teardown.ts
22960
23625
  import { spawn } from "node:child_process";
22961
- import fs25 from "node:fs";
22962
- import path39 from "node:path";
23626
+ import fs26 from "node:fs";
23627
+ import path40 from "node:path";
22963
23628
  var REAP_INTERVAL_MS = 10 * 60000;
22964
23629
  var LOG_MAX_BYTES = 1 << 20;
22965
23630
  var ENDS = {
@@ -22970,9 +23635,9 @@ var ENDS = {
22970
23635
  };
22971
23636
  var SAFE_SESSION = /^[\w.@+][\w.:@/+-]{0,127}$/u;
22972
23637
  var HOST_SESSION_VARS = ["OPENCODE_SESSION_ID", "PI_SESSION_ID", "CODEX_THREAD_ID"];
22973
- var teardownDir = (env) => path39.join(stateDir3(env), "procs");
22974
- var teardownLog = (env) => path39.join(teardownDir(env), "teardown.log");
22975
- var reapStamp = (env) => path39.join(teardownDir(env), "reap-at-start.stamp");
23638
+ var teardownDir = (env) => path40.join(stateDir3(env), "procs");
23639
+ var teardownLog = (env) => path40.join(teardownDir(env), "teardown.log");
23640
+ var reapStamp = (env) => path40.join(teardownDir(env), "reap-at-start.stamp");
22976
23641
  function spawnDetached(request) {
22977
23642
  try {
22978
23643
  const shell = process.platform === "win32" && !/\.exe$/iu.test(request.command);
@@ -22999,13 +23664,13 @@ var teardownDeps = {
22999
23664
  var openLog = (env, args) => {
23000
23665
  try {
23001
23666
  const file = teardownLog(env);
23002
- fs25.mkdirSync(path39.dirname(file), { recursive: true });
23667
+ fs26.mkdirSync(path40.dirname(file), { recursive: true });
23003
23668
  let size = 0;
23004
23669
  try {
23005
- size = fs25.statSync(file).size;
23670
+ size = fs26.statSync(file).size;
23006
23671
  } catch {}
23007
- const fd = fs25.openSync(file, size > LOG_MAX_BYTES ? "w" : "a", 384);
23008
- fs25.writeSync(fd, `${new Date(teardownDeps.now()).toISOString()} workit ${args.join(" ")}
23672
+ const fd = fs26.openSync(file, size > LOG_MAX_BYTES ? "w" : "a", 384);
23673
+ fs26.writeSync(fd, `${new Date(teardownDeps.now()).toISOString()} workit ${args.join(" ")}
23009
23674
  `);
23010
23675
  return fd;
23011
23676
  } catch {
@@ -23017,7 +23682,7 @@ function runCli(args, env) {
23017
23682
  try {
23018
23683
  const cli = locateWorkitCli2({ env });
23019
23684
  const cwd = teardownDir(env);
23020
- fs25.mkdirSync(cwd, { recursive: true });
23685
+ fs26.mkdirSync(cwd, { recursive: true });
23021
23686
  log = openLog(env, args);
23022
23687
  const started = teardownDeps.spawn({
23023
23688
  command: cli.command,
@@ -23027,7 +23692,7 @@ function runCli(args, env) {
23027
23692
  log
23028
23693
  });
23029
23694
  if (!started && log !== null)
23030
- fs25.writeSync(log, ` not started
23695
+ fs26.writeSync(log, ` not started
23031
23696
  `);
23032
23697
  return started;
23033
23698
  } catch {
@@ -23035,7 +23700,7 @@ function runCli(args, env) {
23035
23700
  } finally {
23036
23701
  if (log !== null)
23037
23702
  try {
23038
- fs25.closeSync(log);
23703
+ fs26.closeSync(log);
23039
23704
  } catch {}
23040
23705
  }
23041
23706
  }
@@ -23054,24 +23719,24 @@ function endSession(end, env = process.env) {
23054
23719
  var claim2 = (file, now) => {
23055
23720
  for (let attempt = 0;attempt < 2; attempt += 1)
23056
23721
  try {
23057
- fs25.writeFileSync(file, String(now), { flag: "wx", mode: 384 });
23722
+ fs26.writeFileSync(file, String(now), { flag: "wx", mode: 384 });
23058
23723
  return true;
23059
23724
  } catch (error) {
23060
23725
  if (error.code !== "EEXIST")
23061
23726
  return false;
23062
23727
  let held = Number.NaN;
23063
23728
  try {
23064
- held = Number(fs25.readFileSync(file, "utf8"));
23729
+ held = Number(fs26.readFileSync(file, "utf8"));
23065
23730
  } catch {}
23066
23731
  if (now - held < REAP_INTERVAL_MS)
23067
23732
  return false;
23068
- fs25.rmSync(file, { force: true });
23733
+ fs26.rmSync(file, { force: true });
23069
23734
  }
23070
23735
  return false;
23071
23736
  };
23072
23737
  var fresh = (stamp, now) => {
23073
23738
  try {
23074
- const last = Number(fs25.readFileSync(stamp, "utf8"));
23739
+ const last = Number(fs26.readFileSync(stamp, "utf8"));
23075
23740
  return now - last < REAP_INTERVAL_MS && last <= now;
23076
23741
  } catch {
23077
23742
  return false;
@@ -23084,7 +23749,7 @@ function reapAtStart(_cwd, env = process.env) {
23084
23749
  try {
23085
23750
  if (fresh(stamp, now))
23086
23751
  return false;
23087
- fs25.mkdirSync(path39.dirname(stamp), { recursive: true });
23752
+ fs26.mkdirSync(path40.dirname(stamp), { recursive: true });
23088
23753
  if (!claim2(lock, now))
23089
23754
  return false;
23090
23755
  } catch {
@@ -23097,12 +23762,12 @@ function reapAtStart(_cwd, env = process.env) {
23097
23762
  started = runCli(["stop", "--orphans", "--reason", "session-start"], env);
23098
23763
  if (started) {
23099
23764
  const temp = `${stamp}.${process.pid}`;
23100
- fs25.writeFileSync(temp, String(now), { mode: 384 });
23101
- fs25.renameSync(temp, stamp);
23765
+ fs26.writeFileSync(temp, String(now), { mode: 384 });
23766
+ fs26.renameSync(temp, stamp);
23102
23767
  }
23103
23768
  } catch {} finally {
23104
23769
  try {
23105
- fs25.rmSync(lock, { force: true });
23770
+ fs26.rmSync(lock, { force: true });
23106
23771
  } catch {}
23107
23772
  }
23108
23773
  return started;
@@ -23664,119 +24329,27 @@ var ytrackGate = (cwd, command, dialect, ask) => {
23664
24329
  const calls = writes.flatMap((write) => write.workit ? [`\`${write.workit}\``] : []);
23665
24330
  const bare = writes.filter((write) => !write.workit).map((write) => `\`${write.command}\` (${write.gap ? `Workit cannot carry ${write.gap} into a workit youtrack call` : "no workit youtrack verb covers it"})`);
23666
24331
  if (!calls.length && ask)
23667
- return {
23668
- kind: "ask",
23669
- reason: `${bare.join(", ")} writes to YouTrack: the user decides this call (#780).`
23670
- };
23671
- const why = `A raw ytrack write posts to YouTrack without the user's yes (#780).`;
23672
- const run = calls.length ? ` Run ${calls.join(", then ")} instead, each as its own plain call: it asks the user first.` : "";
23673
- 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.` : "";
23674
- 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." : "";
23675
- const retry = writes.find((write) => write.workit)?.workit ?? (rerun ? writes.find((write) => write.gap === NOT_PLAIN.gap)?.command : undefined);
23676
- return {
23677
- kind: "deny",
23678
- reason: `${why}${run}${user}${rerun}${retry ? `
23679
- Retry as: ${retry}` : ""}`,
23680
- unblock: writes[0]?.workit ?? null
23681
- };
23682
- };
23683
-
23684
- // packages/workit-core/src/hooks/exit-pipe.ts
23685
- var EXIT_VERBS = [
23686
- ["ci", "wait"],
23687
- ["check"],
23688
- ["pr", "merge"],
23689
- ["release"],
23690
- ["verify-delivery"]
23691
- ];
23692
- var base = (word = "") => word.split(/[\\/]/u).at(-1) ?? "";
23693
- var quote3 = (word) => /^[\w@%+=:,./-]+$/u.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;
23694
- var verbPath = (words) => {
23695
- const path = [];
23696
- for (let at = 0;at < words.length && path.length < 2; at += 1) {
23697
- const word = words[at];
23698
- if (word === "--")
23699
- break;
23700
- if (word === "--cwd")
23701
- at += 1;
23702
- else if (!word.startsWith("-"))
23703
- path.push(word);
23704
- }
23705
- return path;
23706
- };
23707
- var exitCall = (words) => {
23708
- let at = 0;
23709
- while (at < words.length && /^[A-Za-z_]\w*=/u.test(words[at]))
23710
- at += 1;
23711
- if (!/^workit(?:-cli)?$/u.test(base(words[at])))
23712
- return null;
23713
- const path = verbPath(words.slice(at + 1));
23714
- return EXIT_VERBS.some((verb) => verb.every((word, index) => path[index] === word)) ? words.slice(at) : null;
23715
- };
23716
- var setsPipefail = (words) => words[0] === "set" && words.some((word, at) => word === "pipefail" && /^-[a-z]*o$/u.test(words[at - 1] ?? ""));
23717
- var retryOf = ({ call, dir }) => {
23718
- const at = call[1]?.startsWith("-") ? 1 : 2;
23719
- const words = dir && !call.includes("--cwd") ? [...call.slice(0, at), "--cwd", dir, ...call.slice(at)] : call;
23720
- return ["workit", ...words.slice(1)].map(quote3).join(" ");
23721
- };
23722
- function exitPipeGate(command, dialect = "posix") {
23723
- if (!/\bworkit/u.test(command) || !/\b(?:tail|head)\b/u.test(command))
23724
- return null;
23725
- const groups = [];
23726
- let carry = null;
23727
- let pipefail = false;
23728
- let dir = null;
23729
- for (const segment of segmentsOf(command, dialect)) {
23730
- if (segment.unanalyzable)
23731
- return null;
23732
- let words = segment.words;
23733
- let closes = segment.group === "close";
23734
- if (segment.group === "open") {
23735
- groups.push(null);
23736
- continue;
23737
- }
23738
- if (words[0] === "{") {
23739
- groups.push(null);
23740
- words = words.slice(1);
23741
- } else if (words[0] === "}") {
23742
- closes = true;
23743
- words = words.slice(1);
23744
- }
23745
- if (closes) {
23746
- const inner = groups.pop() ?? null;
23747
- if (inner && groups.length)
23748
- groups[groups.length - 1] = inner;
23749
- carry = segment.pipe ? inner ?? carry : null;
23750
- continue;
23751
- }
23752
- if (!words.length && !segment.stdin && !segment.subs)
23753
- continue;
23754
- if (setsPipefail(words))
23755
- pipefail = true;
23756
- const filter = base(words[0]);
23757
- if (carry && !pipefail && (filter === "tail" || filter === "head")) {
23758
- const retry = retryOf(carry);
23759
- return {
23760
- kind: "deny",
23761
- reason: `workit exit-pipe: piping \`workit ${verbPath(carry.call.slice(1)).join(" ")}\` into ${filter} hides its exit code.
23762
- Retry as: ${retry}`,
23763
- unblock: retry
23764
- };
23765
- }
23766
- const call = exitCall(words);
23767
- const found = call ? { call, dir } : null;
23768
- if (found && groups.length)
23769
- groups[groups.length - 1] = found;
23770
- carry = segment.pipe ? found ?? carry : null;
23771
- dir = words.length === 2 && words[0] === "cd" && !segment.expands?.length ? words[1] : null;
23772
- }
23773
- return null;
23774
- }
24332
+ return {
24333
+ kind: "ask",
24334
+ reason: `${bare.join(", ")} writes to YouTrack: the user decides this call (#780).`
24335
+ };
24336
+ const why = `A raw ytrack write posts to YouTrack without the user's yes (#780).`;
24337
+ const run = calls.length ? ` Run ${calls.join(", then ")} instead, each as its own plain call: it asks the user first.` : "";
24338
+ 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.` : "";
24339
+ 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." : "";
24340
+ const retry = writes.find((write) => write.workit)?.workit ?? (rerun ? writes.find((write) => write.gap === NOT_PLAIN.gap)?.command : undefined);
24341
+ return {
24342
+ kind: "deny",
24343
+ reason: `${why}${run}${user}${rerun}${retry ? `
24344
+ Retry as: ${retry}` : ""}`,
24345
+ unblock: writes[0]?.workit ?? null
24346
+ };
24347
+ };
23775
24348
 
23776
24349
  // packages/workit-core/src/agent-stamp.ts
23777
24350
  import { randomBytes as randomBytes4 } from "node:crypto";
23778
- import fs26 from "node:fs";
23779
- import path40 from "node:path";
24351
+ import fs27 from "node:fs";
24352
+ import path41 from "node:path";
23780
24353
  var STAMP_TTL_MS = 120000;
23781
24354
  var AGENT_ID = /^[\w-]{1,64}$/u;
23782
24355
  var workitCalls2 = (command, dialect = "posix") => {
@@ -23800,12 +24373,12 @@ var noteAgentStamps = (env, session, agentId, command, options = {}) => {
23800
24373
  const call = options.toolUseId ? callTag2(options.toolUseId) : randomBytes4(4).toString("hex");
23801
24374
  try {
23802
24375
  const dir = stampDir2(env, session);
23803
- fs26.mkdirSync(dir, { recursive: true, mode: 448 });
24376
+ fs27.mkdirSync(dir, { recursive: true, mode: 448 });
23804
24377
  const now = Date.now();
23805
- for (const name of fs26.readdirSync(dir))
23806
- if (now - fs26.statSync(path40.join(dir, name)).mtimeMs > STAMP_TTL_MS)
23807
- fs26.rmSync(path40.join(dir, name), { force: true });
23808
- calls.forEach((argv, index) => fs26.writeFileSync(path40.join(dir, `${stampHash2(argv.join("\x00"))}.${agentId ?? ""}.${call}-${index}`), ""));
24378
+ for (const name of fs27.readdirSync(dir))
24379
+ if (now - fs27.statSync(path41.join(dir, name)).mtimeMs > STAMP_TTL_MS)
24380
+ fs27.rmSync(path41.join(dir, name), { force: true });
24381
+ calls.forEach((argv, index) => fs27.writeFileSync(path41.join(dir, `${stampHash2(argv.join("\x00"))}.${agentId ?? ""}.${call}-${index}`), ""));
23809
24382
  } catch {}
23810
24383
  };
23811
24384
  var dropAgentStamps = (env, session, toolUseId, command) => {
@@ -23815,7 +24388,7 @@ var dropAgentStamps = (env, session, toolUseId, command) => {
23815
24388
 
23816
24389
  // packages/workit-core/src/hooks/hook-entry.ts
23817
24390
  import { existsSync as existsSync14, readFileSync as readFileSync11, realpathSync as realpathSync10 } from "node:fs";
23818
- import path41 from "node:path";
24391
+ import path42 from "node:path";
23819
24392
  var ENTRY_NAMES = /^(?:workit-hook(?:-[\w-]+)?\.(?:m?js|ts)|cursor-session-start\.js|workit-(?:codex|cursor)-hook|workit-cursor-session-start)(?:\.(?:cmd|ps1|exe))?$/iu;
23820
24393
  var PACKAGE_ENTRIES = {
23821
24394
  "claude-code": /^(?:bin\/workit-hook\.mjs|src\/(?:run|hook)\.ts|dist\/workit-hook\.js)$/u,
@@ -23840,744 +24413,416 @@ var RUNNERS = new Set([
23840
24413
  "."
23841
24414
  ]);
23842
24415
  var PACKAGE_RUNNERS2 = new Set(["npx", "bunx", "pnpx"]);
23843
- var NO_RUN = new Set([
23844
- "build",
23845
- "test",
23846
- "fmt",
23847
- "lint",
23848
- "check",
23849
- "doc",
23850
- "info",
23851
- "install",
23852
- "add",
23853
- "pm"
23854
- ]);
23855
- var MORE_WRAPPERS = new Set(["strace", "ltrace", "watch", "unshare", "firejail", "xargs", "&"]);
23856
- var baseName3 = (word) => (word.split(/[\\/]/u).at(-1) ?? "").replace(/\.exe$/iu, "").toLowerCase();
23857
- var packageAt = (dir) => {
23858
- try {
23859
- const name = JSON.parse(readFileSync11(path41.join(dir, "package.json"), "utf8")).name;
23860
- const short = /^@workit-dev\/(claude-code|codex|cursor|core)$/u.exec(String(name))?.[1];
23861
- if (short)
23862
- return short;
23863
- } catch {}
23864
- for (const [manifest, short] of [
23865
- [".claude-plugin", "claude-code"],
23866
- [".codex-plugin", "codex"],
23867
- [".cursor-plugin", "cursor"]
23868
- ]) {
23869
- try {
23870
- const name = JSON.parse(readFileSync11(path41.join(dir, manifest, "plugin.json"), "utf8")).name;
23871
- if (name === "workit")
23872
- return short;
23873
- } catch {}
23874
- }
23875
- return null;
23876
- };
23877
- var entryByPath = (file) => {
23878
- let dir = path41.dirname(file);
23879
- for (let depth = 0;depth < 4; depth += 1, dir = path41.dirname(dir)) {
23880
- const short = packageAt(dir);
23881
- if (short)
23882
- return PACKAGE_ENTRIES[short]?.test(path41.relative(dir, file).split(path41.sep).join("/")) ?? false;
23883
- if (existsSync14(path41.join(dir, "package.json")))
23884
- return false;
23885
- }
23886
- return false;
23887
- };
23888
- var literalSub = (match, inner) => {
23889
- try {
23890
- const [only, ...rest] = segmentsOf(inner);
23891
- const [verb = "", ...args] = only?.words ?? [];
23892
- const last = args.findLast((arg) => !arg.startsWith("-"));
23893
- return rest.length === 0 && /^(?:echo|printf|ls|realpath|readlink)$/u.test(baseName3(verb)) && last ? last : match;
23894
- } catch {
23895
- return match;
23896
- }
23897
- };
23898
- var expand = (word, vars) => word.replace(/\$\(([^()]*)\)|`([^`]*)`/gu, (match, sub, tick) => literalSub(match, sub ?? tick ?? "")).replace(/\$\{(\w+)\}|\$(\w+)/gu, (match, braced, bare) => {
23899
- const name = braced ?? bare ?? "";
23900
- return vars.get(name) ?? process.env[name] ?? match;
23901
- }).replace(/^~(?=[\\/]|$)/u, userHome2(process.env));
23902
- var entryNamed = (word, scan) => {
23903
- if (!word)
23904
- return null;
23905
- const text = expand(word, scan.vars);
23906
- if (ENTRY_NAMES.test(baseName3(text)))
23907
- return text;
23908
- const fd = /^\/(?:dev|proc\/self)\/fd\/(\d+)$/u.exec(text)?.[1];
23909
- if (fd !== undefined && scan.fds.has(fd))
23910
- return text;
23911
- if (scan.dir === null && !path41.isAbsolute(text))
23912
- return null;
23913
- for (const file of expandGlob(path41.resolve(scan.dir ?? "/", text))) {
23914
- if (scan.links.has(file) || entryByPath(file))
23915
- return text;
23916
- let real;
23917
- try {
23918
- real = realpathSync10(file);
23919
- } catch {
23920
- continue;
23921
- }
23922
- if (ENTRY_NAMES.test(baseName3(real)) || entryByPath(real))
23923
- return text;
23924
- }
23925
- return null;
23926
- };
23927
- var noteLink = (words, scan) => {
23928
- if (!/^(?:ln|cp|install)$/u.test(baseName3(words[0] ?? "")) || scan.dir === null)
23929
- return;
23930
- const names = words.slice(1).filter((word) => !word.startsWith("-"));
23931
- const dest = names.at(-1);
23932
- if (dest === undefined || names.length < 2)
23933
- return;
23934
- for (const source of names.slice(0, -1).filter((name) => entryNamed(name, scan))) {
23935
- const to = path41.resolve(scan.dir, expand(dest, scan.vars));
23936
- scan.links.add(to);
23937
- scan.links.add(path41.join(to, path41.basename(source)));
23938
- }
23939
- };
23940
- var runsEntry = (words, inputs, scan) => {
23941
- const named = (word) => entryNamed(word, scan);
23942
- let at = 0;
23943
- while (at < words.length) {
23944
- while (/^[A-Za-z_]\w*=/u.test(words[at] ?? ""))
23945
- at += 1;
23946
- const word = words[at];
23947
- if (word === undefined)
23948
- return null;
23949
- const entry = named(word);
23950
- if (entry)
23951
- return entry;
23952
- const name = baseName3(word);
23953
- const split = name === "env" ? words.findIndex((w) => /^(?:-\w*S|--split-string)/u.test(w)) : -1;
23954
- if (split > at) {
23955
- const line = /^(?:-\w*S|--split-string=?)(.*)$/su.exec(words[split] ?? "")?.[1] || words[split + 1];
23956
- const rest = words.slice(split + (line === words[split + 1] ? 2 : 1));
23957
- return runsEntry([...(line ?? "").split(/\s+/u).filter(Boolean), ...rest], inputs, scan);
23958
- }
23959
- if (MORE_WRAPPERS.has(name)) {
23960
- at = pastOptions(words, at + 1, "");
23961
- continue;
23962
- }
23963
- const takes = WRAPPERS3[name];
23964
- if (takes !== undefined && !PACKAGE_RUNNERS2.has(name)) {
23965
- at = pastOptions(words, at + 1, takes, name === "env" || name === "sudo");
23966
- continue;
23967
- }
23968
- if (name === "busybox" || name === "toybox") {
23969
- at += 1;
23970
- continue;
23971
- }
23972
- const runner = PACKAGE_RUNNERS2.has(name) || name === "bun" && words[at + 1] === "x" || /^(?:pnpm|yarn|npm)$/u.test(name) && /^(?:dlx|exec|x)$/u.test(words[at + 1] ?? "");
23973
- if (runner) {
23974
- at += PACKAGE_RUNNERS2.has(name) ? 1 : 2;
23975
- while (words[at]?.startsWith("-"))
23976
- at += /^(?:-p|--package|-c|--call)$/u.test(words[at] ?? "") ? 2 : 1;
23977
- if (/^@workit-dev\/(?:claude-code|codex|cursor)(?:@|$)/u.test(words[at] ?? ""))
23978
- return words[at] ?? null;
23979
- continue;
23980
- }
23981
- if (!RUNNERS.has(name))
23982
- return null;
23983
- if ((name === "bun" || name === "deno") && NO_RUN.has(words[at + 1] ?? ""))
23984
- return null;
23985
- for (const arg of [...words.slice(at + 1), ...inputs]) {
23986
- const hit = named(arg);
23987
- if (hit)
23988
- return hit;
23989
- }
23990
- return null;
23991
- }
23992
- return null;
23993
- };
23994
- var KEYWORDS3 = new Set([
23995
- "{",
23996
- "}",
23997
- "if",
23998
- "then",
23999
- "elif",
24000
- "else",
24001
- "fi",
24002
- "while",
24003
- "until",
24004
- "do",
24005
- "done",
24006
- "esac",
24007
- "!"
24008
- ]);
24009
- var pastKeywords = (words) => {
24010
- let at = 0;
24011
- for (;; ) {
24012
- if (words[at] === "function")
24013
- at += 2;
24014
- else if (KEYWORDS3.has(words[at] ?? ""))
24015
- at += 1;
24016
- else
24017
- break;
24018
- }
24019
- return /^(?:for|case|select)$/u.test(words[at] ?? "") ? [] : words.slice(at);
24020
- };
24021
- var READERS2 = new Set(("cat less more head tail ls dir stat file wc grep egrep fgrep rg ag diff cmp sha256sum md5sum " + "shasum du bat echo printf cp mv rm chmod touch mkdir realpath readlink dirname basename tee " + "oxfmt oxlint prettier eslint tsc gh jq sort uniq cut tr nl od xxd hexdump strings code vim " + "nano sed get-content gc type select-string get-childitem test-path").split(" "));
24022
- var TOKENS2 = /[\s'"`(),[\]{};|&<>=!]+/u;
24023
- var ENTRY_SAMPLES = [
24024
- "workit-hook.mjs",
24025
- "workit-hook.js",
24026
- "workit-hook.ts",
24027
- "cursor-session-start.js"
24028
- ];
24029
- var tokenEntry = (token, scan) => {
24030
- if (!/[\\/]/u.test(token) && !existsSync14(path41.resolve(scan.dir ?? "/", token)))
24031
- return null;
24032
- return entryNamed(token, scan);
24033
- };
24034
- var opaqueEntry = (words, inputs, scan) => {
24035
- let at = 0;
24036
- while (/^[A-Za-z_]\w*=/u.test(words[at] ?? ""))
24037
- at += 1;
24038
- const head = baseName3(words[at] ?? "");
24039
- if (READERS2.has(head))
24040
- return null;
24041
- if ((head === "bun" || head === "deno") && NO_RUN.has(words[at + 1] ?? ""))
24042
- return null;
24043
- if (head === "git" && !words.some((word) => word.includes("alias.")))
24044
- return null;
24045
- if (head === "workit" || head === "workit-cli")
24046
- return null;
24047
- const tokens = words.flatMap((word) => word.split(TOKENS2)).filter(Boolean);
24048
- const runner = (token) => RUNNERS.has(baseName3(token)) && !/^(?:\.|source)$/u.test(token) || PACKAGE_RUNNERS2.has(baseName3(token));
24049
- if (!tokens.some(runner))
24050
- return null;
24051
- if (scan.fed)
24052
- return scan.fed;
24053
- for (const token of tokens) {
24054
- const hit = tokenEntry(token, scan);
24055
- if (hit)
24056
- return hit;
24057
- }
24058
- if (head === "find")
24059
- for (const [index, word] of words.entries()) {
24060
- const named = /^-i?name$/u.test(words[index - 1] ?? "") && /^[^*?[]/u.test(word);
24061
- const pattern = named ? globPattern(word) : null;
24062
- if (pattern && ENTRY_SAMPLES.some((sample) => pattern.test(sample)))
24063
- return word;
24064
- }
24065
- if (/^(?:xargs|parallel)$/u.test(head) || tokens.includes("xargs"))
24066
- for (const input of inputs) {
24067
- try {
24068
- const file = path41.resolve(scan.dir ?? "/", expand(input, scan.vars));
24069
- const text = readFileSync11(file, "utf8").slice(0, 65536);
24070
- for (const token of text.split(/\s+/u).filter(Boolean)) {
24071
- const hit = tokenEntry(token, scan);
24072
- if (hit)
24073
- return hit;
24074
- }
24075
- } catch {}
24076
- }
24077
- return null;
24078
- };
24079
- var expandedCommand = (words, scan) => {
24080
- let at = 0;
24081
- while (/^[A-Za-z_]\w*=/u.test(words[at] ?? ""))
24082
- at += 1;
24083
- if (!/[$`]/u.test(words[at] ?? ""))
24084
- return null;
24085
- for (const word of words.slice(at + 1)) {
24086
- const hit = entryNamed(word, scan);
24087
- if (hit)
24088
- return hit;
24416
+ var NO_RUN = new Set([
24417
+ "build",
24418
+ "test",
24419
+ "fmt",
24420
+ "lint",
24421
+ "check",
24422
+ "doc",
24423
+ "info",
24424
+ "install",
24425
+ "add",
24426
+ "pm"
24427
+ ]);
24428
+ var MORE_WRAPPERS = new Set(["strace", "ltrace", "watch", "unshare", "firejail", "xargs", "&"]);
24429
+ var baseName3 = (word) => (word.split(/[\\/]/u).at(-1) ?? "").replace(/\.exe$/iu, "").toLowerCase();
24430
+ var packageAt = (dir) => {
24431
+ try {
24432
+ const name = JSON.parse(readFileSync11(path42.join(dir, "package.json"), "utf8")).name;
24433
+ const short = /^@workit-dev\/(claude-code|codex|cursor|core)$/u.exec(String(name))?.[1];
24434
+ if (short)
24435
+ return short;
24436
+ } catch {}
24437
+ for (const [manifest, short] of [
24438
+ [".claude-plugin", "claude-code"],
24439
+ [".codex-plugin", "codex"],
24440
+ [".cursor-plugin", "cursor"]
24441
+ ]) {
24442
+ try {
24443
+ const name = JSON.parse(readFileSync11(path42.join(dir, manifest, "plugin.json"), "utf8")).name;
24444
+ if (name === "workit")
24445
+ return short;
24446
+ } catch {}
24089
24447
  }
24090
24448
  return null;
24091
24449
  };
24092
- var optionsEntry = (words, scan) => {
24093
- for (const word of words) {
24094
- const value = /^(?:NODE_OPTIONS|BUN_OPTIONS)=(.*)$/su.exec(word)?.[1];
24095
- if (value === undefined)
24096
- continue;
24097
- for (const token of value.split(TOKENS2).filter(Boolean)) {
24098
- const hit = tokenEntry(token, scan);
24099
- if (hit)
24100
- return hit;
24101
- }
24450
+ var entryByPath = (file) => {
24451
+ let dir = path42.dirname(file);
24452
+ for (let depth = 0;depth < 4; depth += 1, dir = path42.dirname(dir)) {
24453
+ const short = packageAt(dir);
24454
+ if (short)
24455
+ return PACKAGE_ENTRIES[short]?.test(path42.relative(dir, file).split(path42.sep).join("/")) ?? false;
24456
+ if (existsSync14(path42.join(dir, "package.json")))
24457
+ return false;
24102
24458
  }
24103
- return null;
24459
+ return false;
24104
24460
  };
24105
- var scanCommand = (command, dialect, scan) => {
24106
- let segments;
24461
+ var literalSub = (match, inner) => {
24107
24462
  try {
24108
- segments = segmentsOf(command, dialect);
24463
+ const [only, ...rest] = segmentsOf(inner);
24464
+ const [verb = "", ...args] = only?.words ?? [];
24465
+ const last = args.findLast((arg) => !arg.startsWith("-"));
24466
+ return rest.length === 0 && /^(?:echo|printf|ls|realpath|readlink)$/u.test(baseName3(verb)) && last ? last : match;
24109
24467
  } catch {
24110
- return null;
24111
- }
24112
- for (const [index, segment] of segments.entries()) {
24113
- if (segment.unanalyzable)
24114
- continue;
24115
- bindLoop(segment.words, segments.slice(index + 1), scan);
24116
- const words = pastKeywords(segment.words);
24117
- const fed = scan.fed;
24118
- scan.fed = null;
24119
- const hit = segmentEntry(segment, words, dialect, scan, fed);
24120
- if (hit)
24121
- return hit;
24122
- }
24123
- return null;
24124
- };
24125
- var bindLoop = (raw, after, scan) => {
24126
- const at = raw.findIndex((word) => !KEYWORDS3.has(word));
24127
- const verb = raw[at];
24128
- if ((verb === "for" || verb === "select") && raw[at + 2] === "in") {
24129
- const name = raw[at + 1] ?? "";
24130
- const items = raw.slice(at + 3);
24131
- const item = items.find((word) => entryNamed(word, scan)) ?? items[0];
24132
- if (/^[A-Za-z_]\w*$/u.test(name) && item !== undefined)
24133
- scan.vars.set(name, expand(item, scan.vars));
24134
- return;
24135
- }
24136
- const read = raw.indexOf("read");
24137
- if (read < 0 || !raw.slice(0, read).some((word) => word === "while" || word === "until"))
24138
- return;
24139
- const fed = after.find((segment) => segment.words[0] === "done")?.stdin?.[0];
24140
- const line = fed?.split(`
24141
- `)[0]?.trim();
24142
- const name = raw.slice(read + 1).find((word) => /^[A-Za-z_]\w*$/u.test(word));
24143
- if (name && line)
24144
- scan.vars.set(name, line);
24145
- };
24146
- var segmentEntry = (segment, words, dialect, scan, fed) => {
24147
- const verb = baseName3(words[0] ?? "");
24148
- if (["cd", "pushd", "chdir", "set-location", "sl"].includes(verb)) {
24149
- const target = words.slice(1).find((word) => !word.startsWith("-") || word === "-");
24150
- const moved = target === undefined ? userHome2(process.env) : expand(target, scan.vars);
24151
- scan.dir = moved === "-" || /[$`]/u.test(moved) ? null : path41.isAbsolute(moved) ? moved : scan.dir && path41.resolve(scan.dir, moved);
24152
- if (scan.dir === null)
24153
- scan.vars.delete("PWD");
24154
- else
24155
- scan.vars.set("PWD", scan.dir);
24156
- return null;
24157
- }
24158
- if (verb === "popd") {
24159
- scan.dir = null;
24160
- return null;
24161
- }
24162
- const declares = ["export", "declare", "typeset", "local", "readonly"].includes(verb);
24163
- const assigns = declares ? words.slice(1) : words.every((word) => /^[A-Za-z_]\w*=/u.test(word)) ? words : [];
24164
- for (const word of assigns) {
24165
- const [name = "", value] = word.split(/=(.*)/su);
24166
- if (value !== undefined && /^[A-Za-z_]\w*$/u.test(name))
24167
- scan.vars.set(name, expand(value.replace(/^(['"])(.*)\1$/su, "$2"), scan.vars));
24168
- }
24169
- const options = optionsEntry(declares ? words.slice(1) : words, scan);
24170
- if (options)
24171
- return options;
24172
- if (verb === "exec" && words.slice(1).every((word) => /^\d+$/u.test(word))) {
24173
- for (const input of segment.inputs ?? [])
24174
- if (entryNamed(input, scan))
24175
- for (const fd of words.slice(1))
24176
- scan.fds.add(fd);
24177
- }
24178
- const inputs = segment.inputs ?? [];
24179
- const entry = runsEntry(words, inputs, scan) ?? expandedCommand(words, scan) ?? opaqueEntry(words, inputs, { ...scan, fed });
24180
- if (entry)
24181
- return entry;
24182
- if (segment.pipe)
24183
- scan.fed = words.slice(1).flatMap((word) => word.split(TOKENS2)).map((token) => token ? tokenEntry(token, scan) : null).find(Boolean) ?? null;
24184
- noteLink(words, scan);
24185
- if (scan.depth >= 4)
24186
- return null;
24187
- const nested = (script) => scanCommand(script, dialect, {
24188
- ...scan,
24189
- vars: new Map(scan.vars),
24190
- fed: null,
24191
- depth: scan.depth + 1
24192
- });
24193
- const scripts = [...segment.subs ?? []];
24194
- const script = shellScript2(words) ?? cmdScript2(words) ?? workitScript(words);
24195
- if (script)
24196
- scripts.push(script);
24197
- if (!script && /^(?:ba|z|da|k)?sh$/u.test(verb) && words.slice(1).every((word) => word.startsWith("-")) || verb === "at" || verb === "batch")
24198
- scripts.push(...segment.stdin ?? []);
24199
- for (const text of scripts) {
24200
- const hit = nested(text);
24201
- if (hit)
24202
- return hit;
24468
+ return match;
24203
24469
  }
24204
- return null;
24205
24470
  };
24206
- var cmdScript2 = (words) => {
24207
- const name = baseName3(words[0] ?? "");
24208
- if (!/^(?:cmd|pwsh|powershell)$/u.test(name))
24471
+ var expand = (word, vars) => word.replace(/\$\(([^()]*)\)|`([^`]*)`/gu, (match, sub, tick) => literalSub(match, sub ?? tick ?? "")).replace(/\$\{(\w+)\}|\$(\w+)/gu, (match, braced, bare) => {
24472
+ const name = braced ?? bare ?? "";
24473
+ return vars.get(name) ?? process.env[name] ?? match;
24474
+ }).replace(/^~(?=[\\/]|$)/u, userHome2(process.env));
24475
+ var entryNamed = (word, scan) => {
24476
+ if (!word)
24209
24477
  return null;
24210
- const flag = words.findIndex((word, at) => at > 0 && /^[/-](?:c|k|command)$/iu.test(word));
24211
- return flag < 0 ? null : words.slice(flag + 1).join(" ").replaceAll("\\", "/") || null;
24212
- };
24213
- var workitScript = (words) => {
24214
- if (!/^workit(?:-cli)?$/u.test(baseName3(words[0] ?? "")))
24478
+ const text = expand(word, scan.vars);
24479
+ if (ENTRY_NAMES.test(baseName3(text)))
24480
+ return text;
24481
+ const fd = /^\/(?:dev|proc\/self)\/fd\/(\d+)$/u.exec(text)?.[1];
24482
+ if (fd !== undefined && scan.fds.has(fd))
24483
+ return text;
24484
+ if (scan.dir === null && !path42.isAbsolute(text))
24215
24485
  return null;
24216
- const dash = words.indexOf("--");
24217
- return dash < 0 ? null : words.slice(dash + 1).join(" ") || null;
24218
- };
24219
- var substitutions2 = (command) => {
24220
- const found = [];
24221
- for (let at = command.indexOf("$(");at >= 0 && found.length < 32; at = command.indexOf("$(", at + 1)) {
24222
- if (command[at + 2] === "(")
24223
- continue;
24224
- let depth = 1;
24225
- let end = at + 2;
24226
- for (;end < command.length && depth > 0; end += 1)
24227
- if (command[end] === "(")
24228
- depth += 1;
24229
- else if (command[end] === ")")
24230
- depth -= 1;
24231
- found.push(command.slice(at + 2, end - 1));
24232
- }
24233
- return found;
24234
- };
24235
- var hookEntryRun = (cwd, command, dialect = "posix") => {
24236
- const scan = (text) => scanCommand(text, dialect, {
24237
- dir: cwd,
24238
- vars: new Map([["PWD", cwd]]),
24239
- links: new Set,
24240
- fds: new Set,
24241
- fed: null,
24242
- depth: 0
24243
- });
24244
- const texts = dialect === "posix" && /[A-Za-z]:\\/u.test(command) ? [command, command.replaceAll("\\", "/")] : [command];
24245
- for (const text of texts) {
24246
- const hit = scan(text) ?? substitutions2(text).map(scan).find(Boolean);
24247
- if (hit)
24248
- return hit;
24249
- }
24250
- return null;
24251
- };
24252
- var hookEntryDeny = (entry) => `workit hook guard: this command runs Workit's hook entry ${entry}. Only the host runs Workit's hooks, with the payload it builds; a payload written in a shell would act as a session, subagent or agent that never existed. Use the workit CLI for what you need (\`workit doctor\` probes the installed hooks).`;
24253
-
24254
- // packages/workit-core/src/hooks/identity-env.ts
24255
- import fs27 from "node:fs";
24256
- import path42 from "node:path";
24257
- var NAMES = "WORKIT_(?:AGENT_ID|HOST|SESSION_ID|SESSION_TOKEN)";
24258
- var IDENTITY = new RegExp(`^${NAMES}$`, "u");
24259
- var HOST_NAMES = "(?:OPENCODE_SESSION_ID|PI_SESSION_ID|CODEX_THREAD_ID|CLAUDECODE|CLAUDE_CODE_ENTRYPOINT)";
24260
- var HOST_VARIABLE = new RegExp(`^${HOST_NAMES}$`, "u");
24261
- var IDENTITY_ANY = new RegExp(NAMES, "iu");
24262
- var STATE_NAMES = "(?:WORKIT_(?:STATE_DIR|CONFIG(?:_DIR)?)|XDG_(?:STATE|CONFIG|DATA)_HOME|HOME|USERPROFILE|(?:LOCAL)?APPDATA)";
24263
- var STATE2 = new RegExp(`^${STATE_NAMES}$`, "u");
24264
- var STATE_ANY = new RegExp(STATE_NAMES, "iu");
24265
- var powershell = (names) => new RegExp([
24266
- `\\$\\{?env:${names}\\}?\\s*(?:[-+*/]|\\?\\?)?=(?!=)`,
24267
- `${PS_ITEM}[^;|\\n]*?(?<![$\\w{])env:[\\\\/]?${names}\\b`,
24268
- `SetEnvironmentVariable\\(\\s*['"]${names}\\b`
24269
- ].join("|"), "iu");
24270
- var PS_ITEM = "\\b(?:(?:Set|New|Remove|Clear|Rename|Move|Copy)-Item(?:Property)?|(?:Set|Add|Clear)-Content|si|ni|ri|rm|del|erase|rd|rmdir|cli|sc|ac|clc|rni|mi|move|mv|cpi|copy|cp|ren)\\b";
24271
- var POWERSHELL = powershell(NAMES);
24272
- var POWERSHELL_STATE = powershell(STATE_NAMES);
24273
- var POWERSHELL_HOST = powershell(HOST_NAMES);
24274
- var POWERSHELL_OPAQUE = new RegExp([
24275
- `SetEnvironmentVariable\\(\\s*(?:[^'"\\s]|"[^"]*\\$)`,
24276
- `${PS_ITEM}[^;|\\n]*?(?<![$\\w{])env:[\\\\/]?["']?[$(]`,
24277
- `(?:^|[;&|{(\\n])\\s*\\.\\s+[^\\s.]`,
24278
- `\\b(?:iex|Invoke-Expression)\\b`
24279
- ].join("|"), "iu");
24280
- var cmdSet = (names) => new RegExp(`(?:^|[&|(\\s"])set\\s+(?:/[ap]\\s+)?"?(${names})\\s*\\+?=`, "iu");
24281
- var CMD_IDENTITY = cmdSet(NAMES);
24282
- var CMD_STATE = cmdSet(STATE_NAMES);
24283
- var CMD_HOST = cmdSet(HOST_NAMES);
24284
- var RUNS_TEXT = /\bworkit(?:-cli)?\b|@workit-dev[\\/]cli/iu;
24285
- var DECLARES = new Set(["export", "unset", "declare", "typeset", "local", "readonly"]);
24286
- var OPAQUE = new Set([
24287
- "watch",
24288
- "strace",
24289
- "chroot",
24290
- "flock",
24291
- "ssh",
24292
- "su",
24293
- "runuser",
24294
- "script",
24295
- "parallel"
24296
- ]);
24297
- var ENV_VALUED = new Set(["u", "C", "S", "a", "P"]);
24298
- var ENV_FLAGS = new Set(["i", "0", "v"]);
24299
- var ENV_LONG_VALUED = new Set(["--unset", "--chdir", "--split-string", "--argv0"]);
24300
- var ENV_LONG_FLAGS = /^--(?:ignore-environment|null|debug|(?:block|default|ignore)-signal(?:=.*)?)$/u;
24301
- var base2 = (word) => (word?.split(/[\\/]/u).at(-1) ?? "").replace(/\.exe$/iu, "");
24302
- var ASSIGN = /^[A-Za-z_]\w*\+?=/u;
24303
- var nameOf = (word) => (word?.split("=")[0] ?? "").replace(/\+$/u, "");
24304
- var named = (word) => IDENTITY.test(nameOf(word));
24305
- var stateNamed = (word) => STATE2.test(nameOf(word));
24306
- var isWorkit = (word) => /^workit(?:-cli)?(?:\.[cm]?js)?$/u.test(base2(word)) || /@workit-dev[\\/]cli\b|workit-cli[\\/](?:dist|src)[\\/]/u.test(word ?? "");
24307
- var linksToWorkit = (word, cwd) => {
24308
- const places = /[\\/]/u.test(word) ? [path42.resolve(cwd ?? process.cwd(), word)] : (process.env.PATH ?? "").split(path42.delimiter).map((dir) => path42.join(dir, word));
24309
- for (const place of places) {
24486
+ for (const file of expandGlob(path42.resolve(scan.dir ?? "/", text))) {
24487
+ if (scan.links.has(file) || entryByPath(file))
24488
+ return text;
24489
+ let real;
24310
24490
  try {
24311
- const real = fs27.realpathSync(place);
24312
- return isWorkit(real);
24313
- } catch {}
24491
+ real = realpathSync10(file);
24492
+ } catch {
24493
+ continue;
24494
+ }
24495
+ if (ENTRY_NAMES.test(baseName3(real)) || entryByPath(real))
24496
+ return text;
24314
24497
  }
24315
- return false;
24498
+ return null;
24316
24499
  };
24317
- var newSeg = () => ({ identity: null, scoped: null, runs: false, words: [] });
24318
- var UNREADABLE = "env/unset arguments Workit cannot read";
24319
- var note = (scan, seg, word) => {
24320
- if (scan.identity && named(word)) {
24321
- if (seg)
24322
- seg.identity ??= nameOf(word);
24323
- else
24324
- scan.hit ??= nameOf(word);
24325
- }
24326
- if (!stateNamed(word) && !(scan.identity && HOST_VARIABLE.test(nameOf(word))))
24500
+ var noteLink = (words, scan) => {
24501
+ if (!/^(?:ln|cp|install)$/u.test(baseName3(words[0] ?? "")) || scan.dir === null)
24327
24502
  return;
24328
- if (seg)
24329
- seg.scoped ??= nameOf(word);
24330
- else
24331
- scan.shell ??= nameOf(word);
24503
+ const names = words.slice(1).filter((word) => !word.startsWith("-"));
24504
+ const dest = names.at(-1);
24505
+ if (dest === undefined || names.length < 2)
24506
+ return;
24507
+ for (const source of names.slice(0, -1).filter((name) => entryNamed(name, scan))) {
24508
+ const to = path42.resolve(scan.dir, expand(dest, scan.vars));
24509
+ scan.links.add(to);
24510
+ scan.links.add(path42.join(to, path42.basename(source)));
24511
+ }
24332
24512
  };
24333
- var mayBeWorkit = (words, cwd) => words.some(({ word, built }) => built || linksToWorkit(word, cwd));
24334
- var scanEnv = (words, at, expands, scan, seg, depth) => {
24335
- const risky = (what) => void (scan.risky ??= what);
24336
- const unset = (name) => note(scan, seg, name);
24337
- const split = (line, rest, built) => {
24338
- if (line === undefined || depth >= 4)
24339
- return risky(UNREADABLE);
24340
- if (built || /[$`]/u.test(line))
24341
- risky(UNREADABLE);
24342
- const tokens = [];
24343
- const expanded = new Set;
24344
- try {
24345
- for (const segment of segmentsOf(line)) {
24346
- for (const index of segment.expands ?? [])
24347
- expanded.add(tokens.length + index);
24348
- tokens.push(...segment.words);
24349
- }
24350
- } catch {
24351
- return risky(UNREADABLE);
24352
- }
24353
- scanEnv([...tokens, ...words.slice(rest)], 0, expanded, scan, seg, depth + 1);
24354
- };
24355
- let options = true;
24356
- for (let index = at;index < words.length; index += 1) {
24357
- const word = words[index] ?? "";
24358
- if (expands.has(index)) {
24359
- risky(UNREADABLE);
24360
- const built = options ? /^(?:--split-string=|-[\w]*S)(.+)$/su.exec(word) : null;
24361
- if (built)
24362
- return split(built[1], index + 1, true);
24363
- continue;
24513
+ var runsEntry = (words, inputs, scan) => {
24514
+ const named = (word) => entryNamed(word, scan);
24515
+ let at = 0;
24516
+ while (at < words.length) {
24517
+ while (/^[A-Za-z_]\w*=/u.test(words[at] ?? ""))
24518
+ at += 1;
24519
+ const word = words[at];
24520
+ if (word === undefined)
24521
+ return null;
24522
+ const entry = named(word);
24523
+ if (entry)
24524
+ return entry;
24525
+ const name = baseName3(word);
24526
+ const split = name === "env" ? words.findIndex((w) => /^(?:-\w*S|--split-string)/u.test(w)) : -1;
24527
+ if (split > at) {
24528
+ const line = /^(?:-\w*S|--split-string=?)(.*)$/su.exec(words[split] ?? "")?.[1] || words[split + 1];
24529
+ const rest = words.slice(split + (line === words[split + 1] ? 2 : 1));
24530
+ return runsEntry([...(line ?? "").split(/\s+/u).filter(Boolean), ...rest], inputs, scan);
24364
24531
  }
24365
- if (options && word === "--") {
24366
- options = false;
24532
+ if (MORE_WRAPPERS.has(name)) {
24533
+ at = pastOptions(words, at + 1, "");
24367
24534
  continue;
24368
24535
  }
24369
- if (options && word === "-") {
24370
- risky("env -i");
24536
+ const takes = WRAPPERS3[name];
24537
+ if (takes !== undefined && !PACKAGE_RUNNERS2.has(name)) {
24538
+ at = pastOptions(words, at + 1, takes, name === "env" || name === "sudo");
24371
24539
  continue;
24372
24540
  }
24373
- if (options && word.startsWith("--")) {
24374
- const [name = "", value] = word.split(/=(.*)/su);
24375
- if (name === "--ignore-environment")
24376
- risky("env -i");
24377
- else if (name === "--unset")
24378
- unset(value ?? words[index += 1]);
24379
- else if (name === "--split-string")
24380
- return split(value ?? words[index + 1], index + (value === undefined ? 2 : 1), expands.has(index + (value === undefined ? 1 : 0)));
24381
- else if (ENV_LONG_VALUED.has(name))
24382
- index += value === undefined ? 1 : 0;
24383
- else if (!ENV_LONG_FLAGS.test(word))
24384
- risky(UNREADABLE);
24541
+ if (name === "busybox" || name === "toybox") {
24542
+ at += 1;
24385
24543
  continue;
24386
24544
  }
24387
- if (options && word.startsWith("-") && word.length > 1) {
24388
- for (let at2 = 1;at2 < word.length; at2 += 1) {
24389
- const letter = word[at2] ?? "";
24390
- if (letter === "i")
24391
- risky("env -i");
24392
- else if (ENV_FLAGS.has(letter))
24393
- continue;
24394
- else if (ENV_VALUED.has(letter)) {
24395
- const glued = word.slice(at2 + 1);
24396
- if (!glued)
24397
- index += 1;
24398
- const value = glued || words[index];
24399
- if (letter === "u")
24400
- unset(value);
24401
- if (letter === "S")
24402
- return split(value, index + 1, expands.has(index));
24403
- break;
24404
- } else {
24405
- risky(UNREADABLE);
24406
- break;
24407
- }
24408
- }
24545
+ const runner = PACKAGE_RUNNERS2.has(name) || name === "bun" && words[at + 1] === "x" || /^(?:pnpm|yarn|npm)$/u.test(name) && /^(?:dlx|exec|x)$/u.test(words[at + 1] ?? "");
24546
+ if (runner) {
24547
+ at += PACKAGE_RUNNERS2.has(name) ? 1 : 2;
24548
+ while (words[at]?.startsWith("-"))
24549
+ at += /^(?:-p|--package|-c|--call)$/u.test(words[at] ?? "") ? 2 : 1;
24550
+ if (/^@workit-dev\/(?:claude-code|codex|cursor)(?:@|$)/u.test(words[at] ?? ""))
24551
+ return words[at] ?? null;
24409
24552
  continue;
24410
24553
  }
24411
- if (ASSIGN.test(word)) {
24412
- unset(word);
24413
- continue;
24554
+ if (!RUNNERS.has(name))
24555
+ return null;
24556
+ if ((name === "bun" || name === "deno") && NO_RUN.has(words[at + 1] ?? ""))
24557
+ return null;
24558
+ for (const arg of [...words.slice(at + 1), ...inputs]) {
24559
+ const hit = named(arg);
24560
+ if (hit)
24561
+ return hit;
24414
24562
  }
24415
- return commandAt(words.slice(index), scan, seg, new Set([...expands].filter((at2) => at2 >= index).map((at2) => at2 - index)));
24563
+ return null;
24416
24564
  }
24565
+ return null;
24417
24566
  };
24418
- var commandAt = (words, scan, seg, expands = new Set, from = 0) => {
24419
- let index = from;
24420
- while (index < words.length) {
24421
- while (ASSIGN.test(words[index] ?? "")) {
24422
- note(scan, seg, words[index]);
24423
- index += 1;
24424
- }
24425
- const name = base2(words[index]).toLowerCase();
24426
- if (name === "env")
24427
- return scanEnv(words, index + 1, expands, scan, seg, 0);
24428
- if (OPAQUE.has(name))
24429
- return opaque(words.slice(index + 1), scan, seg, true);
24430
- if (name === "busybox" || name === "toybox") {
24431
- index += 1;
24432
- continue;
24433
- }
24434
- const takes = WRAPPERS3[name];
24435
- if (takes === undefined)
24567
+ var KEYWORDS3 = new Set([
24568
+ "{",
24569
+ "}",
24570
+ "if",
24571
+ "then",
24572
+ "elif",
24573
+ "else",
24574
+ "fi",
24575
+ "while",
24576
+ "until",
24577
+ "do",
24578
+ "done",
24579
+ "esac",
24580
+ "!"
24581
+ ]);
24582
+ var pastKeywords = (words) => {
24583
+ let at = 0;
24584
+ for (;; ) {
24585
+ if (words[at] === "function")
24586
+ at += 2;
24587
+ else if (KEYWORDS3.has(words[at] ?? ""))
24588
+ at += 1;
24589
+ else
24436
24590
  break;
24437
- index = pastOptions(words, index + 1, takes);
24438
24591
  }
24439
- const word = words[index];
24440
- if (word === undefined)
24441
- return;
24442
- seg.words.push({ word, built: expands.has(index) });
24443
- const rest = words.slice(index + 1);
24444
- if (isWorkit(word) || rest.some(isWorkit))
24445
- seg.runs = true;
24446
- if (!isWorkit(word) && rest.some((next) => base2(next).toLowerCase() === "env"))
24447
- opaque(rest, scan, seg, false);
24448
- const program = base2(word).toLowerCase();
24449
- const shell = program === "pwsh" || program === "powershell";
24450
- if (program === "cmd" || shell) {
24451
- const at = rest.findIndex((next) => shell ? /^-(?:c|command)$/iu.test(next) : /^\/[ck]$/iu.test(next));
24452
- if (at >= 0) {
24453
- const script = rest.slice(at + 1).join(" ");
24454
- const change = shell ? powershellChange(script, scan.identity) : cmdChange(script, scan);
24455
- if (change)
24456
- scan.hit ??= change;
24592
+ return /^(?:for|case|select)$/u.test(words[at] ?? "") ? [] : words.slice(at);
24593
+ };
24594
+ var READERS2 = new Set(("cat less more head tail ls dir stat file wc grep egrep fgrep rg ag diff cmp sha256sum md5sum " + "shasum du bat echo printf cp mv rm chmod touch mkdir realpath readlink dirname basename tee " + "oxfmt oxlint prettier eslint tsc gh jq sort uniq cut tr nl od xxd hexdump strings code vim " + "nano sed get-content gc type select-string get-childitem test-path").split(" "));
24595
+ var TOKENS2 = /[\s'"`(),[\]{};|&<>=!]+/u;
24596
+ var ENTRY_SAMPLES = [
24597
+ "workit-hook.mjs",
24598
+ "workit-hook.js",
24599
+ "workit-hook.ts",
24600
+ "cursor-session-start.js"
24601
+ ];
24602
+ var tokenEntry = (token, scan) => {
24603
+ if (!/[\\/]/u.test(token) && !existsSync14(path42.resolve(scan.dir ?? "/", token)))
24604
+ return null;
24605
+ return entryNamed(token, scan);
24606
+ };
24607
+ var opaqueEntry = (words, inputs, scan) => {
24608
+ let at = 0;
24609
+ while (/^[A-Za-z_]\w*=/u.test(words[at] ?? ""))
24610
+ at += 1;
24611
+ const head = baseName3(words[at] ?? "");
24612
+ if (READERS2.has(head))
24613
+ return null;
24614
+ if ((head === "bun" || head === "deno") && NO_RUN.has(words[at + 1] ?? ""))
24615
+ return null;
24616
+ if (head === "git" && !words.some((word) => word.includes("alias.")))
24617
+ return null;
24618
+ if (head === "workit" || head === "workit-cli")
24619
+ return null;
24620
+ const tokens = words.flatMap((word) => word.split(TOKENS2)).filter(Boolean);
24621
+ const runner = (token) => RUNNERS.has(baseName3(token)) && !/^(?:\.|source)$/u.test(token) || PACKAGE_RUNNERS2.has(baseName3(token));
24622
+ if (!tokens.some(runner))
24623
+ return null;
24624
+ if (scan.fed)
24625
+ return scan.fed;
24626
+ for (const token of tokens) {
24627
+ const hit = tokenEntry(token, scan);
24628
+ if (hit)
24629
+ return hit;
24630
+ }
24631
+ if (head === "find")
24632
+ for (const [index, word] of words.entries()) {
24633
+ const named = /^-i?name$/u.test(words[index - 1] ?? "") && /^[^*?[]/u.test(word);
24634
+ const pattern = named ? globPattern(word) : null;
24635
+ if (pattern && ENTRY_SAMPLES.some((sample) => pattern.test(sample)))
24636
+ return word;
24637
+ }
24638
+ if (/^(?:xargs|parallel)$/u.test(head) || tokens.includes("xargs"))
24639
+ for (const input of inputs) {
24640
+ try {
24641
+ const file = path42.resolve(scan.dir ?? "/", expand(input, scan.vars));
24642
+ const text = readFileSync11(file, "utf8").slice(0, 65536);
24643
+ for (const token of text.split(/\s+/u).filter(Boolean)) {
24644
+ const hit = tokenEntry(token, scan);
24645
+ if (hit)
24646
+ return hit;
24647
+ }
24648
+ } catch {}
24457
24649
  }
24458
- }
24459
- };
24460
- var opaque = (rest, scan, seg, assigns) => {
24461
- if (!rest.some(isWorkit))
24462
- return;
24463
- seg.runs = true;
24464
- const changes = (word) => base2(word).toLowerCase() === "env" || DECLARES.has(word) || assigns && ASSIGN.test(word);
24465
- if (rest.some(changes))
24466
- scan.risky ??= UNREADABLE;
24467
- if (rest.some((word) => base2(word).toLowerCase() === "env"))
24468
- for (const word of rest)
24469
- note(scan, seg, word);
24470
- };
24471
- var LOGIN_VALUED = {
24472
- su: /[sgGwc]/u,
24473
- runuser: /[sgGwuc]/u,
24474
- script: /[cEIOBTmot]/u
24650
+ return null;
24475
24651
  };
24476
- var loginScript = (words) => {
24477
- const at = words.findIndex((word) => /^(?:su|runuser|script)$/u.test(base2(word)));
24478
- if (at < 0)
24652
+ var expandedCommand = (words, scan) => {
24653
+ let at = 0;
24654
+ while (/^[A-Za-z_]\w*=/u.test(words[at] ?? ""))
24655
+ at += 1;
24656
+ if (!/[$`]/u.test(words[at] ?? ""))
24479
24657
  return null;
24480
- const valued = LOGIN_VALUED[base2(words[at])] ?? /c/u;
24481
- for (let index = at + 1;index < words.length; index += 1) {
24482
- const word = words[index] ?? "";
24483
- if (word === "--command")
24484
- return words[index + 1] ?? null;
24485
- if (word.startsWith("--command="))
24486
- return word.slice("--command=".length);
24487
- if (!/^-[^-]/u.test(word))
24658
+ for (const word of words.slice(at + 1)) {
24659
+ const hit = entryNamed(word, scan);
24660
+ if (hit)
24661
+ return hit;
24662
+ }
24663
+ return null;
24664
+ };
24665
+ var optionsEntry = (words, scan) => {
24666
+ for (const word of words) {
24667
+ const value = /^(?:NODE_OPTIONS|BUN_OPTIONS)=(.*)$/su.exec(word)?.[1];
24668
+ if (value === undefined)
24488
24669
  continue;
24489
- const ends = word.slice(1).search(valued) + 1;
24490
- if (ends > 0 && word[ends] === "c")
24491
- return word.slice(ends + 1) || (words[index + 1] ?? null);
24670
+ for (const token of value.split(TOKENS2).filter(Boolean)) {
24671
+ const hit = tokenEntry(token, scan);
24672
+ if (hit)
24673
+ return hit;
24674
+ }
24492
24675
  }
24493
24676
  return null;
24494
24677
  };
24495
- var scanCommand2 = (command, dialect, depth, scan) => {
24678
+ var scanCommand2 = (command, dialect, scan) => {
24496
24679
  let segments;
24497
24680
  try {
24498
24681
  segments = segmentsOf(command, dialect);
24499
24682
  } catch {
24500
- return;
24683
+ return null;
24501
24684
  }
24502
- for (const { words, expands = [] } of segments) {
24503
- const expanded = new Set(expands);
24504
- const seg = newSeg();
24505
- let at = 0;
24506
- while (ASSIGN.test(words[at] ?? ""))
24507
- at += 1;
24508
- for (const word of words.slice(0, at))
24509
- note(scan, at === words.length ? null : seg, word);
24510
- let declare = at;
24511
- if (["builtin", "command"].includes(words[declare] ?? ""))
24512
- declare += 1;
24513
- if (DECLARES.has(words[declare] ?? "")) {
24514
- for (let index = declare + 1;index < words.length; index += 1) {
24515
- note(scan, null, words[index]);
24516
- if (expanded.has(index))
24517
- scan.risky ??= UNREADABLE;
24518
- }
24685
+ for (const [index, segment] of segments.entries()) {
24686
+ if (segment.unanalyzable)
24519
24687
  continue;
24520
- }
24521
- commandAt(words, scan, seg, expanded, at);
24522
- const script = depth < 4 ? shellScript2(words) ?? loginScript(words) : null;
24523
- if (script) {
24524
- const before = scan.runs;
24525
- scan.runs = false;
24526
- scanCommand2(script, dialect, depth + 1, scan);
24527
- seg.runs ||= scan.runs;
24528
- scan.runs ||= before;
24529
- }
24530
- scan.words.push(...seg.words);
24531
- const reaches = () => seg.runs || mayBeWorkit(seg.words, scan.cwd);
24532
- if (seg.identity && reaches())
24533
- scan.hit ??= seg.identity;
24534
- if (seg.scoped && reaches())
24535
- scan.state ??= seg.scoped;
24536
- scan.runs ||= seg.runs;
24688
+ bindLoop(segment.words, segments.slice(index + 1), scan);
24689
+ const words = pastKeywords(segment.words);
24690
+ const fed = scan.fed;
24691
+ scan.fed = null;
24692
+ const hit = segmentEntry(segment, words, dialect, scan, fed);
24693
+ if (hit)
24694
+ return hit;
24537
24695
  }
24696
+ return null;
24538
24697
  };
24539
- var cmdChange = (script, scan) => (scan.identity ? CMD_IDENTITY.exec(script)?.[1] : null) ?? (RUNS_TEXT.test(script) ? CMD_STATE.exec(script)?.[1] ?? (scan.identity ? CMD_HOST.exec(script)?.[1] : null) ?? null : null);
24540
- var powershellChange = (command, identity) => {
24541
- const hit = identity ? POWERSHELL.exec(command)?.[0] : null;
24542
- if (hit)
24543
- return hit;
24544
- if (!RUNS_TEXT.test(command) && !/&\s*[$(]/u.test(command))
24698
+ var bindLoop = (raw, after, scan) => {
24699
+ const at = raw.findIndex((word) => !KEYWORDS3.has(word));
24700
+ const verb = raw[at];
24701
+ if ((verb === "for" || verb === "select") && raw[at + 2] === "in") {
24702
+ const name = raw[at + 1] ?? "";
24703
+ const items = raw.slice(at + 3);
24704
+ const item = items.find((word) => entryNamed(word, scan)) ?? items[0];
24705
+ if (/^[A-Za-z_]\w*$/u.test(name) && item !== undefined)
24706
+ scan.vars.set(name, expand(item, scan.vars));
24707
+ return;
24708
+ }
24709
+ const read = raw.indexOf("read");
24710
+ if (read < 0 || !raw.slice(0, read).some((word) => word === "while" || word === "until"))
24711
+ return;
24712
+ const fed = after.find((segment) => segment.words[0] === "done")?.stdin?.[0];
24713
+ const line = fed?.split(`
24714
+ `)[0]?.trim();
24715
+ const name = raw.slice(read + 1).find((word) => /^[A-Za-z_]\w*$/u.test(word));
24716
+ if (name && line)
24717
+ scan.vars.set(name, line);
24718
+ };
24719
+ var segmentEntry = (segment, words, dialect, scan, fed) => {
24720
+ const verb = baseName3(words[0] ?? "");
24721
+ if (["cd", "pushd", "chdir", "set-location", "sl"].includes(verb)) {
24722
+ const target = words.slice(1).find((word) => !word.startsWith("-") || word === "-");
24723
+ const moved = target === undefined ? userHome2(process.env) : expand(target, scan.vars);
24724
+ scan.dir = moved === "-" || /[$`]/u.test(moved) ? null : path42.isAbsolute(moved) ? moved : scan.dir && path42.resolve(scan.dir, moved);
24725
+ if (scan.dir === null)
24726
+ scan.vars.delete("PWD");
24727
+ else
24728
+ scan.vars.set("PWD", scan.dir);
24545
24729
  return null;
24546
- const state = POWERSHELL_STATE.exec(command)?.[0] ?? (identity ? POWERSHELL_HOST.exec(command)?.[0] : null) ?? cmdChange(command, { identity });
24547
- if (state)
24548
- return state;
24549
- return POWERSHELL_OPAQUE.test(command) ? UNREADABLE : null;
24730
+ }
24731
+ if (verb === "popd") {
24732
+ scan.dir = null;
24733
+ return null;
24734
+ }
24735
+ const declares = ["export", "declare", "typeset", "local", "readonly"].includes(verb);
24736
+ const assigns = declares ? words.slice(1) : words.every((word) => /^[A-Za-z_]\w*=/u.test(word)) ? words : [];
24737
+ for (const word of assigns) {
24738
+ const [name = "", value] = word.split(/=(.*)/su);
24739
+ if (value !== undefined && /^[A-Za-z_]\w*$/u.test(name))
24740
+ scan.vars.set(name, expand(value.replace(/^(['"])(.*)\1$/su, "$2"), scan.vars));
24741
+ }
24742
+ const options = optionsEntry(declares ? words.slice(1) : words, scan);
24743
+ if (options)
24744
+ return options;
24745
+ if (verb === "exec" && words.slice(1).every((word) => /^\d+$/u.test(word))) {
24746
+ for (const input of segment.inputs ?? [])
24747
+ if (entryNamed(input, scan))
24748
+ for (const fd of words.slice(1))
24749
+ scan.fds.add(fd);
24750
+ }
24751
+ const inputs = segment.inputs ?? [];
24752
+ const entry = runsEntry(words, inputs, scan) ?? expandedCommand(words, scan) ?? opaqueEntry(words, inputs, { ...scan, fed });
24753
+ if (entry)
24754
+ return entry;
24755
+ if (segment.pipe)
24756
+ scan.fed = words.slice(1).flatMap((word) => word.split(TOKENS2)).map((token) => token ? tokenEntry(token, scan) : null).find(Boolean) ?? null;
24757
+ noteLink(words, scan);
24758
+ if (scan.depth >= 4)
24759
+ return null;
24760
+ const nested = (script) => scanCommand2(script, dialect, {
24761
+ ...scan,
24762
+ vars: new Map(scan.vars),
24763
+ fed: null,
24764
+ depth: scan.depth + 1
24765
+ });
24766
+ const scripts = [...segment.subs ?? []];
24767
+ const script = shellScript2(words) ?? cmdScript2(words) ?? workitScript(words);
24768
+ if (script)
24769
+ scripts.push(script);
24770
+ if (!script && /^(?:ba|z|da|k)?sh$/u.test(verb) && words.slice(1).every((word) => word.startsWith("-")) || verb === "at" || verb === "batch")
24771
+ scripts.push(...segment.stdin ?? []);
24772
+ for (const text of scripts) {
24773
+ const hit = nested(text);
24774
+ if (hit)
24775
+ return hit;
24776
+ }
24777
+ return null;
24550
24778
  };
24551
- var identityEnvChange = (command, dialect = "posix", options = {}) => {
24552
- const identity = options.identity ?? true;
24553
- if (dialect === "powershell")
24554
- return powershellChange(command, identity);
24555
- if (!/WORKIT_|XDG_|HOME|USERPROFILE|APPDATA|OPENCODE_SESSION_ID|PI_SESSION_ID|CODEX_THREAD_ID|CLAUDE|EnvironmentVariable|\b(?:env|unset|export|declare|typeset|local|readonly)\b/iu.test(command))
24779
+ var cmdScript2 = (words) => {
24780
+ const name = baseName3(words[0] ?? "");
24781
+ if (!/^(?:cmd|pwsh|powershell)$/u.test(name))
24556
24782
  return null;
24557
- const scan = {
24558
- identity,
24559
- cwd: options.cwd,
24560
- hit: null,
24561
- state: null,
24562
- shell: null,
24563
- risky: null,
24564
- runs: false,
24565
- words: []
24566
- };
24567
- scanCommand2(command, dialect, 0, scan);
24568
- if (scan.hit)
24569
- return scan.hit;
24570
- if (scan.state)
24571
- return scan.state;
24572
- if (scan.shell && (scan.runs || mayBeWorkit(scan.words, scan.cwd)))
24573
- return scan.shell;
24574
- return scan.runs ? scan.risky : null;
24783
+ const flag = words.findIndex((word, at) => at > 0 && /^[/-](?:c|k|command)$/iu.test(word));
24784
+ return flag < 0 ? null : words.slice(flag + 1).join(" ").replaceAll("\\", "/") || null;
24575
24785
  };
24576
- var identityEnvDeny = (change) => {
24577
- if (change === UNREADABLE || IDENTITY_ANY.test(change) || !STATE_ANY.test(change))
24578
- return `workit identity: ${change === UNREADABLE ? `this command runs workit with ${UNREADABLE}` : `this command changes ${change}`}. The host sets WORKIT_HOST, WORKIT_SESSION_ID, WORKIT_AGENT_ID and its own session variables, and Workit acts as who they name; run it without changing them (a verifier or reviewer passes the --session and --token its start text names).`;
24579
- return `workit identity: this command runs workit with ${change} changed. Workit reads issued sessions, grants and its ledger trust from the state and config dirs the host's environment names, so a workit call may not move them (#980); run it without setting, unsetting or emptying ${change}.`;
24786
+ var workitScript = (words) => {
24787
+ if (!/^workit(?:-cli)?$/u.test(baseName3(words[0] ?? "")))
24788
+ return null;
24789
+ const dash = words.indexOf("--");
24790
+ return dash < 0 ? null : words.slice(dash + 1).join(" ") || null;
24791
+ };
24792
+ var substitutions2 = (command) => {
24793
+ const found = [];
24794
+ for (let at = command.indexOf("$(");at >= 0 && found.length < 32; at = command.indexOf("$(", at + 1)) {
24795
+ if (command[at + 2] === "(")
24796
+ continue;
24797
+ let depth = 1;
24798
+ let end = at + 2;
24799
+ for (;end < command.length && depth > 0; end += 1)
24800
+ if (command[end] === "(")
24801
+ depth += 1;
24802
+ else if (command[end] === ")")
24803
+ depth -= 1;
24804
+ found.push(command.slice(at + 2, end - 1));
24805
+ }
24806
+ return found;
24807
+ };
24808
+ var hookEntryRun = (cwd, command, dialect = "posix") => {
24809
+ const scan = (text) => scanCommand2(text, dialect, {
24810
+ dir: cwd,
24811
+ vars: new Map([["PWD", cwd]]),
24812
+ links: new Set,
24813
+ fds: new Set,
24814
+ fed: null,
24815
+ depth: 0
24816
+ });
24817
+ const texts = dialect === "posix" && /[A-Za-z]:\\/u.test(command) ? [command, command.replaceAll("\\", "/")] : [command];
24818
+ for (const text of texts) {
24819
+ const hit = scan(text) ?? substitutions2(text).map(scan).find(Boolean);
24820
+ if (hit)
24821
+ return hit;
24822
+ }
24823
+ return null;
24580
24824
  };
24825
+ var hookEntryDeny = (entry) => `workit hook guard: this command runs Workit's hook entry ${entry}. Only the host runs Workit's hooks, with the payload it builds; a payload written in a shell would act as a session, subagent or agent that never existed. Use the workit CLI for what you need (\`workit doctor\` probes the installed hooks).`;
24581
24826
 
24582
24827
  // packages/workit-core/src/hooks/handle.ts
24583
24828
  var usable2 = (value) => value === "native" || value === "partial";