@workit-dev/codex 2.29.0 → 2.29.2

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.
@@ -71,12 +71,12 @@ var capabilitiesFor = (descriptor, observed = {}) => descriptor.capabilities.map
71
71
  };
72
72
  });
73
73
  // packages/workit-core/src/hooks/context.ts
74
- import { createHash as createHash11 } from "node:crypto";
74
+ import { createHash as createHash12 } from "node:crypto";
75
75
  import fs15 from "node:fs";
76
- import path20 from "node:path";
76
+ import path21 from "node:path";
77
77
 
78
78
  // packages/workit-core/src/core/branch.ts
79
- import { createHash as createHash4 } from "node:crypto";
79
+ import { createHash as createHash5 } from "node:crypto";
80
80
 
81
81
  // packages/workit-core/src/core/branch-policy.ts
82
82
  import { spawnSync } from "node:child_process";
@@ -295,9 +295,9 @@ var releaseTagPrefixOf = (workspaceRoot, policyPrefix) => {
295
295
 
296
296
  // packages/workit-core/src/core/workspaces.ts
297
297
  import { spawnSync as spawnSync5 } from "node:child_process";
298
- import { createHash as createHash2 } from "node:crypto";
299
- import { existsSync as existsSync3, lstatSync as lstatSync2, readFileSync as readFileSync4, realpathSync as realpathSync3 } from "node:fs";
300
- import path5 from "node:path";
298
+ import { createHash as createHash3 } from "node:crypto";
299
+ import { existsSync as existsSync3, lstatSync as lstatSync2, readFileSync as readFileSync5, realpathSync as realpathSync3 } from "node:fs";
300
+ import path6 from "node:path";
301
301
 
302
302
  // node_modules/zod/v4/core/util.js
303
303
  function getEnumValues(entries) {
@@ -4041,6 +4041,103 @@ var pushTarget = (cwd, remote, replay = {}) => {
4041
4041
  return { remotes };
4042
4042
  };
4043
4043
 
4044
+ // packages/workit-core/src/core/grant-seal.ts
4045
+ import { createHash as createHash2 } from "node:crypto";
4046
+ import { readFileSync as readFileSync4 } from "node:fs";
4047
+ import path5 from "node:path";
4048
+ var SEAL_FILE = "workspaces.json.seal";
4049
+ var SEAL_VERSION = 2;
4050
+ var isSealVersion = (value) => value === 1 || value === 2;
4051
+ var SEAL_COMMAND = "workit workspace seal";
4052
+ var pick3 = (value, keys) => {
4053
+ if (!value || typeof value !== "object" || Array.isArray(value))
4054
+ return;
4055
+ const out = Object.fromEntries(keys.flatMap((key) => {
4056
+ const item = value[key];
4057
+ return item === undefined ? [] : [[key, item]];
4058
+ }));
4059
+ return Object.keys(out).length > 0 ? out : undefined;
4060
+ };
4061
+ var ENTRY_KEYS = [
4062
+ "name",
4063
+ "glob",
4064
+ "remotes",
4065
+ "externalRepos",
4066
+ "additiveRiskPaths",
4067
+ "vcs",
4068
+ "autonomy",
4069
+ "autoApprove",
4070
+ "defaultEndpoint",
4071
+ "verification",
4072
+ "youtrack"
4073
+ ];
4074
+ var RELEASE_KEYS = [
4075
+ "releaseNotes",
4076
+ "releaseTagPrefix",
4077
+ "branchPolicy",
4078
+ "profiles",
4079
+ "defaultProfile",
4080
+ "releaseTracks",
4081
+ "releasePackages"
4082
+ ];
4083
+ var keysOf = (version) => version >= 2 ? [...ENTRY_KEYS, ...RELEASE_KEYS] : ENTRY_KEYS;
4084
+ var IDENTITY_KEYS = ["provider", "account", "tokenFile", "host"];
4085
+ var sealProjection = (entries, version = SEAL_VERSION) => entries.map((entry) => {
4086
+ const keys = keysOf(version);
4087
+ const all = pick3(entry, keys) ?? {};
4088
+ return pick3({
4089
+ ...all,
4090
+ vcs: pick3(all.vcs, IDENTITY_KEYS),
4091
+ youtrack: pick3(all.youtrack, ["writes", "autoHosts"]),
4092
+ ...version >= 2 ? releaseLineMapping(entry, true) : {}
4093
+ }, keys);
4094
+ });
4095
+ var canonical2 = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : item);
4096
+ var sealDigest = (projection) => createHash2("sha256").update(canonical2(projection)).digest("hex");
4097
+ var broken = (reason, sealed = null, version) => ({
4098
+ state: "broken",
4099
+ reason,
4100
+ sealed,
4101
+ ...version ? { version } : {}
4102
+ });
4103
+ var PARTIAL_KEYS = ["releaseTracks", "branchPolicy", "profiles", "defaultProfile"];
4104
+ var sealedEntries = (projection, file) => {
4105
+ const partial = projection.map((entry) => pick3(entry, PARTIAL_KEYS));
4106
+ const validated = validateWorkspacesDocument({
4107
+ workspaces: projection.map((entry) => {
4108
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
4109
+ return entry;
4110
+ const rest = { ...entry };
4111
+ for (const key of PARTIAL_KEYS)
4112
+ delete rest[key];
4113
+ return rest;
4114
+ })
4115
+ }, file);
4116
+ if (validated.status !== "valid" || validated.entries.length !== projection.length)
4117
+ return null;
4118
+ return validated.entries.map((entry, at) => partial[at] === undefined ? entry : { ...entry, ...partial[at] });
4119
+ };
4120
+ function checkSeal(dir) {
4121
+ const file = path5.join(dir, SEAL_FILE);
4122
+ let seal;
4123
+ try {
4124
+ seal = JSON.parse(readFileSync4(file, "utf8"));
4125
+ } catch (error) {
4126
+ if (error.code === "ENOENT")
4127
+ return { state: "none" };
4128
+ return broken(`${SEAL_FILE} cannot be read`);
4129
+ }
4130
+ if (!isSealVersion(seal?.version) || !Array.isArray(seal.projection) || seal.sha256 !== sealDigest(seal.projection))
4131
+ return broken(`${SEAL_FILE} is malformed`);
4132
+ const version = seal.version;
4133
+ const sealed = sealedEntries(seal.projection, file);
4134
+ if (!sealed)
4135
+ return broken(`${SEAL_FILE} is malformed`, null, version);
4136
+ const current = readWorkspacesResult(dir);
4137
+ const ok = current.status === "valid" || current.status === "missing";
4138
+ return ok && sealDigest(sealProjection(current.entries, version)) === seal.sha256 ? { state: "valid", version } : broken("workspaces.json changed since it was sealed", sealed, version);
4139
+ }
4140
+
4044
4141
  // packages/workit-core/src/core/workspaces.ts
4045
4142
  var nonBlank = string2().check(refine((value) => value.trim().length > 0, "must not be blank"));
4046
4143
  var branchPreset = custom((value) => typeof value === "string" && Object.hasOwn(PRESETS, value), "unsupported branch preset");
@@ -4106,7 +4203,7 @@ var releaseTrackSchema = looseObject({
4106
4203
  });
4107
4204
  }
4108
4205
  }
4109
- if (track.versionSource?.kind === "package-json" && (path5.posix.isAbsolute(track.versionSource.path.replaceAll("\\", "/")) || /^[A-Za-z]:\//u.test(track.versionSource.path.replaceAll("\\", "/")) || track.versionSource.path.replaceAll("\\", "/").split("/").includes(".."))) {
4206
+ if (track.versionSource?.kind === "package-json" && (path6.posix.isAbsolute(track.versionSource.path.replaceAll("\\", "/")) || /^[A-Za-z]:\//u.test(track.versionSource.path.replaceAll("\\", "/")) || track.versionSource.path.replaceAll("\\", "/").split("/").includes(".."))) {
4110
4207
  context.addIssue({
4111
4208
  code: "custom",
4112
4209
  path: ["versionSource", "path"],
@@ -4205,7 +4302,7 @@ var workspacesFileSchema = looseObject({
4205
4302
  names.add(workspace.name);
4206
4303
  }
4207
4304
  }));
4208
- var workspacesRevision = (contents) => createHash2("sha256").update(contents ?? "<missing>").digest("hex");
4305
+ var workspacesRevision = (contents) => createHash3("sha256").update(contents ?? "<missing>").digest("hex");
4209
4306
  var validateWorkspacesDocument = (parsed, file) => {
4210
4307
  if (!isConfigObject(parsed)) {
4211
4308
  return {
@@ -4251,10 +4348,10 @@ var validateWorkspacesDocument = (parsed, file) => {
4251
4348
  };
4252
4349
  };
4253
4350
  var readWorkspacesResult = (dir = configDir()) => {
4254
- const file = path5.join(dir, "workspaces.json");
4351
+ const file = path6.join(dir, "workspaces.json");
4255
4352
  let raw;
4256
4353
  try {
4257
- raw = readFileSync4(file, "utf8");
4354
+ raw = readFileSync5(file, "utf8");
4258
4355
  } catch (error) {
4259
4356
  if (error.code === "ENOENT")
4260
4357
  return {
@@ -4355,9 +4452,9 @@ var probeCheckout = (cwd) => {
4355
4452
  const cached = probes.get(cwd);
4356
4453
  if (cached !== undefined)
4357
4454
  return cached;
4358
- let dir = path5.resolve(cwd);
4359
- while (!existsSync3(path5.join(dir, ".git"))) {
4360
- if (["HEAD", "objects", "refs"].every((name) => existsSync3(path5.join(dir, name)))) {
4455
+ let dir = path6.resolve(cwd);
4456
+ while (!existsSync3(path6.join(dir, ".git"))) {
4457
+ if (["HEAD", "objects", "refs"].every((name) => existsSync3(path6.join(dir, name)))) {
4361
4458
  const real = realpathOf(dir);
4362
4459
  const owner = ownInternals(real) === true ? gitDirOwner(real) : null;
4363
4460
  if (owner === null)
@@ -4366,7 +4463,7 @@ var probeCheckout = (cwd) => {
4366
4463
  probes.set(cwd, probe);
4367
4464
  return probe;
4368
4465
  }
4369
- const up = path5.dirname(dir);
4466
+ const up = path6.dirname(dir);
4370
4467
  if (up === dir)
4371
4468
  return null;
4372
4469
  dir = up;
@@ -4395,9 +4492,9 @@ var probeCheckout = (cwd) => {
4395
4492
  if (!gitDir || !common)
4396
4493
  return failed;
4397
4494
  let main = null;
4398
- if (path5.resolve(gitDir) === path5.resolve(common)) {
4495
+ if (path6.resolve(gitDir) === path6.resolve(common)) {
4399
4496
  const real = realpathOf(common);
4400
- if (!ownGitDir(path5.join(dir, ".git"), real)) {
4497
+ if (!ownGitDir(path6.join(dir, ".git"), real)) {
4401
4498
  const owner = gitDirOwner(real);
4402
4499
  if (owner === null)
4403
4500
  return Error(`${cwd} uses the repository at ${real}, owned by no checkout workit can name`);
@@ -4416,7 +4513,7 @@ var probeCheckout = (cwd) => {
4416
4513
  const list = git(["worktree", "list", "--porcelain"]);
4417
4514
  if (list === null)
4418
4515
  return failed;
4419
- main = /^worktree (.+)$/mu.exec(list)?.[1]?.trim() || (path5.basename(common) === ".git" ? path5.dirname(common) : common);
4516
+ main = /^worktree (.+)$/mu.exec(list)?.[1]?.trim() || (path6.basename(common) === ".git" ? path6.dirname(common) : common);
4420
4517
  }
4421
4518
  const probe = { main, superproject: superproject || null };
4422
4519
  probes.set(cwd, probe);
@@ -4433,7 +4530,7 @@ var INTERNALS = ["refs", "objects", "config", "packed-refs", "commondir"];
4433
4530
  var ownInternals = (real) => {
4434
4531
  let lender = null;
4435
4532
  for (const name of INTERNALS) {
4436
- const at = path5.join(real, name);
4533
+ const at = path6.join(real, name);
4437
4534
  try {
4438
4535
  lstatSync2(at);
4439
4536
  } catch {
@@ -4445,10 +4542,10 @@ var ownInternals = (real) => {
4445
4542
  } catch {
4446
4543
  return false;
4447
4544
  }
4448
- const rel = path5.relative(real, resolved);
4449
- if (rel && !rel.startsWith("..") && !path5.isAbsolute(rel))
4545
+ const rel = path6.relative(real, resolved);
4546
+ if (rel && !rel.startsWith("..") && !path6.isAbsolute(rel))
4450
4547
  continue;
4451
- const owner = path5.basename(resolved) === name ? gitDirOwner(path5.dirname(resolved)) : null;
4548
+ const owner = path6.basename(resolved) === name ? gitDirOwner(path6.dirname(resolved)) : null;
4452
4549
  if (owner === null || lender !== null && lender !== owner)
4453
4550
  return false;
4454
4551
  lender = owner;
@@ -4462,7 +4559,7 @@ var gitDirOwner = (real) => {
4462
4559
  return null;
4463
4560
  const rest = parts.slice(at + 1);
4464
4561
  const module = rest[0] === "modules" || rest[0] === "worktrees" && rest[2] === "modules";
4465
- return rest.length === 0 || module ? parts.slice(0, at).join(path5.sep) || path5.sep : null;
4562
+ return rest.length === 0 || module ? parts.slice(0, at).join(path6.sep) || path6.sep : null;
4466
4563
  };
4467
4564
  var mainCheckoutOf = (cwd) => {
4468
4565
  const probe = probeCheckout(cwd);
@@ -4586,11 +4683,11 @@ var resolveRuntimeWorkspaceVcs = (cwd) => resolveRuntimeWorkspaceCandidate(cwd,
4586
4683
  var runtimeWorkspaceIndexSchema = looseObject({
4587
4684
  workspaces: optional(array(looseObject({ name: nonBlank, glob: nonBlank })))
4588
4685
  });
4589
- var matchRuntimeWorkspace = (cwd, dir = configDir()) => {
4590
- const file = path5.join(dir, "workspaces.json");
4686
+ var matchRuntimeWorkspace = (cwd, dir = configDir(), workspaceName = namedWorkspace()) => {
4687
+ const file = path6.join(dir, "workspaces.json");
4591
4688
  let raw;
4592
4689
  try {
4593
- raw = readFileSync4(file, "utf8");
4690
+ raw = readFileSync5(file, "utf8");
4594
4691
  } catch (error) {
4595
4692
  if (error.code === "ENOENT")
4596
4693
  return null;
@@ -4613,13 +4710,21 @@ var matchRuntimeWorkspace = (cwd, dir = configDir()) => {
4613
4710
  if (!glob.ok)
4614
4711
  throw new WorkspaceConfigError(`${file} workspace ${entry.name}: ${glob.error}`);
4615
4712
  }
4616
- const workspaceName = process.env.WORKIT_WORKSPACE_NAME?.trim() || undefined;
4617
- const selected = resolveWorkspaceFromEntries(cwd, entries ?? [], workspaceName, true);
4713
+ const matched = matchAmong(cwd, entries ?? [], workspaceName);
4714
+ return matched ? { file, ...matched } : null;
4715
+ };
4716
+ var namedWorkspace = () => process.env.WORKIT_WORKSPACE_NAME?.trim() || null;
4717
+ var matchAmong = (cwd, entries, workspaceName = namedWorkspace()) => {
4718
+ const selected = resolveWorkspaceFromEntries(cwd, entries, workspaceName ?? undefined, true);
4618
4719
  if (!selected)
4619
4720
  return null;
4620
- const matches = matchingEntries(cwd, entries ?? []);
4621
- return { file, selected, matches: matches.length ? matches : [selected] };
4721
+ const matches = matchingEntries(cwd, entries);
4722
+ return { selected, matches: matches.length ? matches : [selected] };
4622
4723
  };
4724
+ var chainOf = (matched) => matched ? [
4725
+ matched.selected,
4726
+ ...matched.matches.filter((entry) => entry !== matched.selected).toSorted((a, b) => globSpecificity(b.glob) - globSpecificity(a.glob))
4727
+ ] : [];
4623
4728
  var resolveRuntimeReleaseTracks = (cwd) => {
4624
4729
  const matched = matchRuntimeWorkspace(cwd);
4625
4730
  return matched ? {
@@ -4636,11 +4741,9 @@ var inheritedSetting = (cwd, dir, has) => {
4636
4741
  }
4637
4742
  if (!matched)
4638
4743
  return null;
4639
- const { selected, matches } = matched;
4640
- const enclosing = matches.filter((entry) => entry !== selected).toSorted((a, b) => globSpecificity(b.glob) - globSpecificity(a.glob));
4641
4744
  return {
4642
- workspace: selected.name,
4643
- source: [selected, ...enclosing].find(has) ?? null
4745
+ workspace: matched.selected.name,
4746
+ source: chainOf(matched).find(has) ?? null
4644
4747
  };
4645
4748
  };
4646
4749
  var resolveRuntimeReleasePackages = (cwd, dir) => {
@@ -4670,6 +4773,47 @@ var changelogPathOf = (value) => {
4670
4773
  return null;
4671
4774
  return parts.includes("..") ? null : parts.join("/");
4672
4775
  };
4776
+ var isPlainRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4777
+ var pickSet = (value, keys) => isPlainRecord(value) ? Object.fromEntries(keys.filter((key) => value[key] !== undefined).map((key) => [key, value[key]])) : {};
4778
+ var mapRecord = (value, map) => Object.fromEntries(Object.entries(value).map(([name, item]) => [name, map(item)]));
4779
+ var TRACK_LINE_KEYS = [
4780
+ "tagNamespace",
4781
+ "productionBranch",
4782
+ "integrationBranch",
4783
+ "baseBranch",
4784
+ "mergeBackBranches",
4785
+ "pullRequestTarget",
4786
+ "naming",
4787
+ "strategy"
4788
+ ];
4789
+ var releaseLineMapping = (entry, notes = false) => {
4790
+ if (!isPlainRecord(entry))
4791
+ return;
4792
+ const out = {};
4793
+ if (notes && entry.releaseNotes !== undefined)
4794
+ out.releaseNotes = entry.releaseNotes;
4795
+ if (entry.releaseTagPrefix !== undefined)
4796
+ out.releaseTagPrefix = entry.releaseTagPrefix;
4797
+ if (entry.defaultProfile !== undefined)
4798
+ out.defaultProfile = entry.defaultProfile;
4799
+ const policy = pickSet(entry.branchPolicy, ["releaseTagPrefix"]);
4800
+ if (Object.keys(policy).length)
4801
+ out.branchPolicy = policy;
4802
+ const profiles = Object.fromEntries(Object.entries(isPlainRecord(entry.profiles) ? entry.profiles : {}).flatMap(([name, profile]) => {
4803
+ const prefix = pickSet(isPlainRecord(profile) ? profile.branchPolicy : undefined, [
4804
+ "releaseTagPrefix"
4805
+ ]);
4806
+ return Object.keys(prefix).length ? [[name, { branchPolicy: prefix }]] : [];
4807
+ }));
4808
+ if (Object.keys(profiles).length)
4809
+ out.profiles = profiles;
4810
+ const trackKeys = notes ? [...TRACK_LINE_KEYS, "releaseNotes"] : TRACK_LINE_KEYS;
4811
+ if (entry.releaseTracks !== undefined)
4812
+ out.releaseTracks = isPlainRecord(entry.releaseTracks) ? mapRecord(entry.releaseTracks, (track) => pickSet(track, trackKeys)) : entry.releaseTracks;
4813
+ if (entry.releasePackages !== undefined)
4814
+ out.releasePackages = isPlainRecord(entry.releasePackages) ? mapRecord(entry.releasePackages, (pkg) => pickSet(pkg, ["tagNamespace"])) : entry.releasePackages;
4815
+ return Object.keys(out).length ? out : undefined;
4816
+ };
4673
4817
  var modelSources = (cwd, dir) => {
4674
4818
  const out = [];
4675
4819
  try {
@@ -4686,7 +4830,7 @@ var modelSources = (cwd, dir) => {
4686
4830
  }
4687
4831
  } catch {}
4688
4832
  try {
4689
- const document = JSON.parse(readFileSync4(path5.join(dir ?? configDir(), "workspaces.json"), "utf8"));
4833
+ const document = JSON.parse(readFileSync5(path6.join(dir ?? configDir(), "workspaces.json"), "utf8"));
4690
4834
  if (document && typeof document === "object" && !Array.isArray(document))
4691
4835
  out.push({
4692
4836
  name: "global",
@@ -4751,10 +4895,10 @@ function workspaceDefaultTarget(cwd, globalDefault) {
4751
4895
 
4752
4896
  // packages/workit-core/src/core/vcs-config.ts
4753
4897
  import fs3 from "node:fs";
4754
- import path6 from "node:path";
4898
+ import path7 from "node:path";
4755
4899
 
4756
4900
  // packages/workit-core/src/core/release-tracks.ts
4757
- import { createHash as createHash3 } from "node:crypto";
4901
+ import { createHash as createHash4 } from "node:crypto";
4758
4902
  import { spawnSync as spawnSync6 } from "node:child_process";
4759
4903
  class ReleaseTrackError extends Error {
4760
4904
  }
@@ -5137,7 +5281,7 @@ function resolveTrackFor(cwd, options) {
5137
5281
  ]) ?? "",
5138
5282
  git2(cwd, ["config", "--get", recordedBaseKey(branch)]) ?? ""
5139
5283
  ] : [];
5140
- key = createHash3("sha256").update(JSON.stringify({ cwd, input, refs, head, own })).digest("hex");
5284
+ key = createHash4("sha256").update(JSON.stringify({ cwd, input, refs, head, own })).digest("hex");
5141
5285
  const hit = memo2.get(key);
5142
5286
  if (hit)
5143
5287
  return hit;
@@ -5152,7 +5296,7 @@ function resolveTrackFor(cwd, options) {
5152
5296
  }
5153
5297
 
5154
5298
  // packages/workit-core/src/core/vcs-config.ts
5155
- var workspacesPath = () => path6.join(configDir(), "workspaces.json");
5299
+ var workspacesPath = () => path7.join(configDir(), "workspaces.json");
5156
5300
  var vcsCwd = (cwd) => cwd ?? process.env.WORKIT_WORKSPACE_ROOT ?? process.cwd();
5157
5301
  var remoteProvider = (cwd) => {
5158
5302
  const url = originUrl(cwd) ?? "";
@@ -5291,7 +5435,7 @@ function vcsConfig(mode, cwd, options = {}) {
5291
5435
  const prov = cfg[provider] ?? {};
5292
5436
  const out = {
5293
5437
  ok: true,
5294
- configPath: path6.resolve(cfgPath),
5438
+ configPath: path7.resolve(cfgPath),
5295
5439
  provider,
5296
5440
  defaultTargetBranch: workspaceDefault,
5297
5441
  pr: cfg.pr ?? {},
@@ -5444,7 +5588,7 @@ var branchPolicySnapshotFor = (workspaceRoot) => {
5444
5588
  const source = resolved.provenance.branchPolicy;
5445
5589
  const allowed = branchPolicy.allowed.map((pattern) => `${pattern.source}/${pattern.flags}`).toSorted();
5446
5590
  const protectedRefs = [...branchPolicy.protected].map((name) => name.toLowerCase()).toSorted();
5447
- const fingerprint = createHash4("sha256").update(JSON.stringify({ allowed, protectedRefs, source })).digest("hex");
5591
+ const fingerprint = createHash5("sha256").update(JSON.stringify({ allowed, protectedRefs, source })).digest("hex");
5448
5592
  return {
5449
5593
  branchPolicy,
5450
5594
  namePolicy: { allowed: branchPolicy.allowed, protected: branchPolicy.protected },
@@ -5535,9 +5679,9 @@ var isProtectedTarget = (root, name) => {
5535
5679
  };
5536
5680
 
5537
5681
  // packages/workit-core/src/core/model-fallback.ts
5538
- import { createHash as createHash5 } from "node:crypto";
5539
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync5, renameSync, writeFileSync as writeFileSync2 } from "node:fs";
5540
- import path7 from "node:path";
5682
+ import { createHash as createHash6 } from "node:crypto";
5683
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync6, renameSync, writeFileSync as writeFileSync2 } from "node:fs";
5684
+ import path8 from "node:path";
5541
5685
 
5542
5686
  // packages/workit-core/src/core/logger.ts
5543
5687
  import os3 from "node:os";
@@ -5605,10 +5749,10 @@ var providerOf = (model, host) => {
5605
5749
  return null;
5606
5750
  };
5607
5751
  var empty = () => ({ exhausted: {}, seen: {}, redispatched: {} });
5608
- var storePath = (stateDir) => path7.join(stateDir ?? resolveStateDir(), LIMITS_FILE);
5752
+ var storePath = (stateDir) => path8.join(stateDir ?? resolveStateDir(), LIMITS_FILE);
5609
5753
  var readStore = (stateDir) => {
5610
5754
  try {
5611
- const parsed = JSON.parse(readFileSync5(storePath(stateDir), "utf8"));
5755
+ const parsed = JSON.parse(readFileSync6(storePath(stateDir), "utf8"));
5612
5756
  const store = empty();
5613
5757
  for (const key of ["exhausted", "seen", "redispatched"])
5614
5758
  if (parsed[key] && typeof parsed[key] === "object")
@@ -5629,7 +5773,7 @@ var writeStore = (store, now, stateDir) => {
5629
5773
  delete store.exhausted[id];
5630
5774
  try {
5631
5775
  const file = storePath(stateDir);
5632
- mkdirSync2(path7.dirname(file), { recursive: true });
5776
+ mkdirSync2(path8.dirname(file), { recursive: true });
5633
5777
  const temp = `${file}.${process.pid}.tmp`;
5634
5778
  writeFileSync2(temp, `${JSON.stringify(store, null, 2)}
5635
5779
  `);
@@ -5665,7 +5809,7 @@ var firstSighting = (id, now = new Date, stateDir) => {
5665
5809
  writeStore(store, now, stateDir);
5666
5810
  return true;
5667
5811
  };
5668
- var promptKey = (prompt) => createHash5("sha256").update(prompt.trim()).digest("hex").slice(0, 16);
5812
+ var promptKey = (prompt) => createHash6("sha256").update(prompt.trim()).digest("hex").slice(0, 16);
5669
5813
  var claimRedispatch = (key, now = new Date, stateDir) => {
5670
5814
  const store = readStore(stateDir);
5671
5815
  if (store.redispatched[key])
@@ -6083,14 +6227,14 @@ ${table}` : bootstrap;
6083
6227
 
6084
6228
  // packages/workit-core/src/store/paths.ts
6085
6229
  import { spawnSync as spawnSync7 } from "node:child_process";
6086
- import { createHash as createHash6 } from "node:crypto";
6230
+ import { createHash as createHash7 } from "node:crypto";
6087
6231
  import fs5 from "node:fs";
6088
- import path9 from "node:path";
6232
+ import path10 from "node:path";
6089
6233
 
6090
6234
  // packages/workit-core/src/store/folder-store.ts
6091
6235
  import fs4 from "node:fs";
6092
6236
  import os4 from "node:os";
6093
- import path8 from "node:path";
6237
+ import path9 from "node:path";
6094
6238
  var FOLDER_CONFIG = new Set(["checks.json", "risk-paths"]);
6095
6239
  var MOVED_POINTER = "MOVED-TO-STATE.txt";
6096
6240
  var V2_LEFTOVERS = new Set(["recovery", "index.json"]);
@@ -6099,7 +6243,7 @@ var MARKER = "workspace.json";
6099
6243
  var v2Workspace = (workit) => {
6100
6244
  let bytes;
6101
6245
  try {
6102
- bytes = fs4.readFileSync(path8.join(workit, MARKER), "utf8");
6246
+ bytes = fs4.readFileSync(path9.join(workit, MARKER), "utf8");
6103
6247
  } catch {
6104
6248
  return null;
6105
6249
  }
@@ -6148,7 +6292,7 @@ var strayEntries = (workit) => {
6148
6292
  } catch {
6149
6293
  return [];
6150
6294
  }
6151
- return names.filter((name) => !FOLDER_CONFIG.has(name) && !V2_LEFTOVERS.has(name) && name !== MOVED_POINTER && name !== MARKER && !(name === ".gitignore" && generatedIgnore(path8.join(workit, name))) && !(name === "tasks" && onlyStubs(path8.join(workit, name))));
6295
+ return names.filter((name) => !FOLDER_CONFIG.has(name) && !V2_LEFTOVERS.has(name) && name !== MOVED_POINTER && name !== MARKER && !(name === ".gitignore" && generatedIgnore(path9.join(workit, name))) && !(name === "tasks" && onlyStubs(path9.join(workit, name))));
6152
6296
  };
6153
6297
  var folderStoreIo = {
6154
6298
  rename: (from, to) => fs4.renameSync(from, to),
@@ -6156,13 +6300,13 @@ var folderStoreIo = {
6156
6300
  judgedStale: () => {}
6157
6301
  };
6158
6302
  var tempSeq = 0;
6159
- var tempBeside = (file) => path8.join(path8.dirname(file), `.${path8.basename(file)}.workit-move-${process.pid}-${tempSeq += 1}`);
6303
+ var tempBeside = (file) => path9.join(path9.dirname(file), `.${path9.basename(file)}.workit-move-${process.pid}-${tempSeq += 1}`);
6160
6304
  var copyInto = (from, to) => {
6161
6305
  const stat = fs4.lstatSync(from);
6162
6306
  if (stat.isDirectory()) {
6163
6307
  fs4.mkdirSync(to, { recursive: true });
6164
6308
  for (const name of fs4.readdirSync(from))
6165
- copyInto(path8.join(from, name), path8.join(to, name));
6309
+ copyInto(path9.join(from, name), path9.join(to, name));
6166
6310
  return;
6167
6311
  }
6168
6312
  if (exists(to))
@@ -6213,7 +6357,7 @@ var merge2 = (from, to, rel, moved) => {
6213
6357
  }
6214
6358
  if (!isDir(from) || !isDir(to))
6215
6359
  return [rel];
6216
- const kept = fs4.readdirSync(from).flatMap((name) => merge2(path8.join(from, name), path8.join(to, name), `${rel}/${name}`, moved));
6360
+ const kept = fs4.readdirSync(from).flatMap((name) => merge2(path9.join(from, name), path9.join(to, name), `${rel}/${name}`, moved));
6217
6361
  try {
6218
6362
  if (fs4.readdirSync(from).length === 0)
6219
6363
  fs4.rmdirSync(from);
@@ -6292,38 +6436,38 @@ var takeMoveLock = (target) => {
6292
6436
  pause(25);
6293
6437
  }
6294
6438
  };
6295
- var canonical2 = (dir) => {
6439
+ var canonical3 = (dir) => {
6296
6440
  try {
6297
6441
  return fs4.realpathSync.native(dir);
6298
6442
  } catch {
6299
- return path8.resolve(dir);
6443
+ return path9.resolve(dir);
6300
6444
  }
6301
6445
  };
6302
6446
  var below = (parent, child) => {
6303
- const rel = path8.relative(parent, child);
6304
- return rel !== "" && !rel.startsWith("..") && !path8.isAbsolute(rel);
6447
+ const rel = path9.relative(parent, child);
6448
+ return rel !== "" && !rel.startsWith("..") && !path9.isAbsolute(rel);
6305
6449
  };
6306
- var insideTempDir = (dir, tempDir = os4.tmpdir()) => below(canonical2(tempDir), canonical2(dir));
6450
+ var insideTempDir = (dir, tempDir = os4.tmpdir()) => below(canonical3(tempDir), canonical3(dir));
6307
6451
  var TEST_RUN_REFUSALS = "folder-store-refusals.log";
6308
6452
  var testRunFolderRefusal = (folder, hasStray, env = process.env, tempDir = os4.tmpdir()) => {
6309
6453
  if (env.WORKIT_TEST_RUN === undefined || !hasStray)
6310
6454
  return null;
6311
- const real = canonical2(folder);
6312
- const tmp = canonical2(tempDir);
6455
+ const real = canonical3(folder);
6456
+ const tmp = canonical3(tempDir);
6313
6457
  if (insideTempDir(folder, tempDir))
6314
6458
  return null;
6315
- return `workit test run (WORKIT_TEST_RUN): refusing to move ${path8.join(real, ".workit")} into the run's throwaway state dir; a test must work in a fresh dir inside ${tmp}, never the temp dir itself, a parent of it or a folder outside it (#892)`;
6459
+ return `workit test run (WORKIT_TEST_RUN): refusing to move ${path9.join(real, ".workit")} into the run's throwaway state dir; a test must work in a fresh dir inside ${tmp}, never the temp dir itself, a parent of it or a folder outside it (#892)`;
6316
6460
  };
6317
6461
  function migrateFolderStore(folder, target, note = (line) => process.stderr.write(`${line}
6318
6462
  `)) {
6319
- const workit = path8.join(folder, ".workit");
6463
+ const workit = path9.join(folder, ".workit");
6320
6464
  const names = strayEntries(workit);
6321
6465
  const refusal = testRunFolderRefusal(folder, names.length > 0);
6322
6466
  if (refusal) {
6323
6467
  const run = process.env.WORKIT_TEST_RUN ?? "";
6324
- if (path8.isAbsolute(run))
6468
+ if (path9.isAbsolute(run))
6325
6469
  try {
6326
- fs4.appendFileSync(path8.join(run, TEST_RUN_REFUSALS), `${refusal}
6470
+ fs4.appendFileSync(path9.join(run, TEST_RUN_REFUSALS), `${refusal}
6327
6471
  `);
6328
6472
  } catch {}
6329
6473
  throw new Error(refusal);
@@ -6331,7 +6475,7 @@ function migrateFolderStore(folder, target, note = (line) => process.stderr.writ
6331
6475
  if (names.length === 0 || v2Workspace(workit) === true)
6332
6476
  return null;
6333
6477
  try {
6334
- fs4.mkdirSync(path8.dirname(target), { recursive: true });
6478
+ fs4.mkdirSync(path9.dirname(target), { recursive: true });
6335
6479
  } catch {
6336
6480
  return null;
6337
6481
  }
@@ -6355,7 +6499,7 @@ function moveLocked(workit, target, note) {
6355
6499
  }
6356
6500
  const result = { from: workit, to: target, moved: [], kept: [] };
6357
6501
  for (const name of names) {
6358
- result.kept.push(...merge2(path8.join(workit, name), path8.join(target, name), name, result.moved));
6502
+ result.kept.push(...merge2(path9.join(workit, name), path9.join(target, name), name, result.moved));
6359
6503
  }
6360
6504
  const left = (() => {
6361
6505
  try {
@@ -6364,13 +6508,13 @@ function moveLocked(workit, target, note) {
6364
6508
  return [];
6365
6509
  }
6366
6510
  })();
6367
- const v2Left = left.some((name) => V2_LEFTOVERS.has(name) || name === "tasks" && isDir(path8.join(workit, name)));
6511
+ const v2Left = left.some((name) => V2_LEFTOVERS.has(name) || name === "tasks" && isDir(path9.join(workit, name)));
6368
6512
  if (!v2Left && result.kept.length === 0) {
6369
- fs4.rmSync(path8.join(workit, MARKER), { force: true });
6370
- if (generatedIgnore(path8.join(workit, ".gitignore")))
6371
- fs4.rmSync(path8.join(workit, ".gitignore"), { force: true });
6513
+ fs4.rmSync(path9.join(workit, MARKER), { force: true });
6514
+ if (generatedIgnore(path9.join(workit, ".gitignore")))
6515
+ fs4.rmSync(path9.join(workit, ".gitignore"), { force: true });
6372
6516
  }
6373
- const pointer = path8.join(workit, MOVED_POINTER);
6517
+ const pointer = path9.join(workit, MOVED_POINTER);
6374
6518
  let wrote = false;
6375
6519
  if (result.kept.length > 0) {
6376
6520
  const text = `Workit keeps this folder's state in ${target}.
@@ -6420,7 +6564,7 @@ var gitRun = (cwd, args) => {
6420
6564
  missing: error?.code === "ENOENT"
6421
6565
  };
6422
6566
  };
6423
- var shortHash = (value) => createHash6("sha256").update(value).digest("hex").slice(0, 12);
6567
+ var shortHash = (value) => createHash7("sha256").update(value).digest("hex").slice(0, 12);
6424
6568
  var real = (file) => {
6425
6569
  try {
6426
6570
  return fs5.realpathSync.native(file);
@@ -6437,14 +6581,14 @@ var DISCOVERY_ENV = [
6437
6581
  ];
6438
6582
  var isGitDir = (dir) => {
6439
6583
  try {
6440
- return fs5.statSync(path9.join(dir, "HEAD")).isFile() && fs5.statSync(path9.join(dir, "objects")).isDirectory() && fs5.statSync(path9.join(dir, "refs")).isDirectory();
6584
+ return fs5.statSync(path10.join(dir, "HEAD")).isFile() && fs5.statSync(path10.join(dir, "objects")).isDirectory() && fs5.statSync(path10.join(dir, "refs")).isDirectory();
6441
6585
  } catch {
6442
6586
  return false;
6443
6587
  }
6444
6588
  };
6445
6589
  var reftableRefs = (common) => {
6446
6590
  try {
6447
- return /^\s*refstorage\s*=\s*reftable\s*$/imu.test(fs5.readFileSync(path9.join(common, "config"), "utf8"));
6591
+ return /^\s*refstorage\s*=\s*reftable\s*$/imu.test(fs5.readFileSync(path10.join(common, "config"), "utf8"));
6448
6592
  } catch {
6449
6593
  return false;
6450
6594
  }
@@ -6464,7 +6608,7 @@ function fastGit(root) {
6464
6608
  if (device !== null && stat.dev !== device)
6465
6609
  return { kind: "none" };
6466
6610
  device = stat.dev;
6467
- const dotGit = path9.join(dir, ".git");
6611
+ const dotGit = path10.join(dir, ".git");
6468
6612
  let entry = null;
6469
6613
  try {
6470
6614
  entry = fs5.statSync(dotGit);
@@ -6485,19 +6629,19 @@ function fastGit(root) {
6485
6629
  const match = /^gitdir: (.+)$/mu.exec(text);
6486
6630
  if (!match)
6487
6631
  return null;
6488
- gitDir = path9.resolve(dir, match[1].trim());
6632
+ gitDir = path10.resolve(dir, match[1].trim());
6489
6633
  } else
6490
6634
  return null;
6491
- if (!fs5.existsSync(path9.join(gitDir, "HEAD")))
6635
+ if (!fs5.existsSync(path10.join(gitDir, "HEAD")))
6492
6636
  return null;
6493
6637
  } else if (isGitDir(dir))
6494
6638
  gitDir = dir;
6495
6639
  if (gitDir) {
6496
6640
  let common = gitDir;
6497
6641
  try {
6498
- common = path9.resolve(gitDir, fs5.readFileSync(path9.join(gitDir, "commondir"), "utf8").trim());
6642
+ common = path10.resolve(gitDir, fs5.readFileSync(path10.join(gitDir, "commondir"), "utf8").trim());
6499
6643
  } catch {}
6500
- if (!fs5.existsSync(path9.join(common, "objects")))
6644
+ if (!fs5.existsSync(path10.join(common, "objects")))
6501
6645
  return null;
6502
6646
  return {
6503
6647
  kind: "repo",
@@ -6507,7 +6651,7 @@ function fastGit(root) {
6507
6651
  reftable: reftableRefs(common)
6508
6652
  };
6509
6653
  }
6510
- const parent = path9.dirname(dir);
6654
+ const parent = path10.dirname(dir);
6511
6655
  if (parent === dir)
6512
6656
  return { kind: "none" };
6513
6657
  dir = parent;
@@ -6519,7 +6663,7 @@ var outsideGit = (root) => {
6519
6663
  return { dir, shared: false, top: null };
6520
6664
  };
6521
6665
  function resolveStore(root) {
6522
- root = path9.resolve(root);
6666
+ root = path10.resolve(root);
6523
6667
  let stat = null;
6524
6668
  try {
6525
6669
  stat = fs5.statSync(root);
@@ -6527,13 +6671,13 @@ function resolveStore(root) {
6527
6671
  if (!stat)
6528
6672
  return new Error(`cannot locate the workit store: ${root} does not exist (removed while workit ran?); nothing is recorded under a missing directory`);
6529
6673
  if (!stat.isDirectory())
6530
- return { dir: path9.join(root, ".workit"), shared: false, top: null };
6674
+ return { dir: path10.join(root, ".workit"), shared: false, top: null };
6531
6675
  const fast = fastGit(root);
6532
6676
  if (fast?.kind === "none")
6533
6677
  return outsideGit(root);
6534
6678
  if (fast?.kind === "repo")
6535
6679
  return {
6536
- dir: path9.join(fast.common, "workit"),
6680
+ dir: path10.join(fast.common, "workit"),
6537
6681
  shared: true,
6538
6682
  top: fast.top,
6539
6683
  git: { gitDir: fast.gitDir, top: fast.top, reftable: fast.reftable }
@@ -6543,7 +6687,7 @@ function resolveStore(root) {
6543
6687
  if (run.ok && common) {
6544
6688
  const top = gitRun(root, ["rev-parse", "--path-format=absolute", "--show-toplevel"]);
6545
6689
  return {
6546
- dir: path9.join(real(path9.resolve(root, common)), "workit"),
6690
+ dir: path10.join(real(path10.resolve(root, common)), "workit"),
6547
6691
  shared: true,
6548
6692
  top: top.ok && top.stdout.trim() ? real(top.stdout.trim()) : null
6549
6693
  };
@@ -6556,7 +6700,7 @@ function resolveStore(root) {
6556
6700
  var rebasingBranch = (gitDir) => {
6557
6701
  for (const state of ["rebase-merge", "rebase-apply"]) {
6558
6702
  try {
6559
- const ref = fs5.readFileSync(path9.join(gitDir, state, "head-name"), "utf8").trim();
6703
+ const ref = fs5.readFileSync(path10.join(gitDir, state, "head-name"), "utf8").trim();
6560
6704
  const match = /^refs\/heads\/(.+)$/u.exec(ref);
6561
6705
  if (match)
6562
6706
  return match[1];
@@ -6571,7 +6715,7 @@ function resolveTaskKey(root, location) {
6571
6715
  if (location.git && !location.git.reftable) {
6572
6716
  let head = "";
6573
6717
  try {
6574
- head = fs5.readFileSync(path9.join(location.git.gitDir, "HEAD"), "utf8").trim();
6718
+ head = fs5.readFileSync(path10.join(location.git.gitDir, "HEAD"), "utf8").trim();
6575
6719
  } catch {}
6576
6720
  const ref = /^ref: refs\/heads\/(.+)$/u.exec(head);
6577
6721
  if (ref && ref[1] !== ".invalid")
@@ -6602,7 +6746,7 @@ function resolveTaskKey(root, location) {
6602
6746
  return { key: `detached-${shortHash(real(worktree))}`, kind: "detached", branch: null };
6603
6747
  }
6604
6748
  function checkoutRootOf(root, location) {
6605
- const resolved = path9.resolve(root);
6749
+ const resolved = path10.resolve(root);
6606
6750
  let canonical = resolved;
6607
6751
  try {
6608
6752
  canonical = fs5.realpathSync(resolved);
@@ -6633,13 +6777,13 @@ function branchRenames(location) {
6633
6777
  }
6634
6778
  for (const entry of entries)
6635
6779
  if (entry.isDirectory())
6636
- walk(path9.join(dir, entry.name));
6780
+ walk(path10.join(dir, entry.name));
6637
6781
  else
6638
- files.push(path9.join(dir, entry.name));
6782
+ files.push(path10.join(dir, entry.name));
6639
6783
  };
6640
- walk(path9.join(path9.dirname(location.dir), "logs", "refs", "heads"));
6784
+ walk(path10.join(path10.dirname(location.dir), "logs", "refs", "heads"));
6641
6785
  if (location.git)
6642
- files.push(path9.join(location.git.gitDir, "logs", "HEAD"));
6786
+ files.push(path10.join(location.git.gitDir, "logs", "HEAD"));
6643
6787
  const seen = new Set;
6644
6788
  const renames = [];
6645
6789
  for (const file of files) {
@@ -6673,7 +6817,7 @@ function followRenames(key, boundAt, renames) {
6673
6817
  var checkoutSlug = (root) => folderSlug2(root);
6674
6818
 
6675
6819
  // packages/workit-core/src/core/task-contract.ts
6676
- import { createHash as createHash7, randomUUID } from "node:crypto";
6820
+ import { createHash as createHash8, randomUUID } from "node:crypto";
6677
6821
 
6678
6822
  // packages/workit-core/src/core/scope-glob.ts
6679
6823
  var GLOB = /[*?[\]{}]/u;
@@ -7235,7 +7379,7 @@ function resolveIdRef(kind, ref, ids) {
7235
7379
  return failure2("not_found", `${kind} not found`);
7236
7380
  return failure2("invalid_input", `${kind} prefix ${ref} is ambiguous; candidates: ${matches.join(", ")}`);
7237
7381
  }
7238
- function canonical3(value, seen) {
7382
+ function canonical4(value, seen) {
7239
7383
  if (value === null || typeof value === "boolean" || typeof value === "string") {
7240
7384
  if (typeof value === "string" && invalidUnicode(value))
7241
7385
  throw new TypeError("invalid Unicode");
@@ -7257,7 +7401,7 @@ function canonical3(value, seen) {
7257
7401
  if (!(index in value))
7258
7402
  throw new TypeError("sparse array");
7259
7403
  }
7260
- result = value.map((item) => canonical3(item, seen));
7404
+ result = value.map((item) => canonical4(item, seen));
7261
7405
  } else {
7262
7406
  if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)
7263
7407
  throw new TypeError("value is not a JSON object");
@@ -7265,18 +7409,18 @@ function canonical3(value, seen) {
7265
7409
  throw new TypeError("symbol key is not JSON");
7266
7410
  if (Object.keys(value).some((key) => invalidUnicode(key)))
7267
7411
  throw new TypeError("invalid Unicode");
7268
- result = Object.fromEntries(Object.keys(value).toSorted().map((key) => [key, canonical3(value[key], seen)]));
7412
+ result = Object.fromEntries(Object.keys(value).toSorted().map((key) => [key, canonical4(value[key], seen)]));
7269
7413
  }
7270
7414
  seen.delete(value);
7271
7415
  return result;
7272
7416
  }
7273
7417
  function canonicalJson(value) {
7274
- return JSON.stringify(canonical3(value, new Set));
7418
+ return JSON.stringify(canonical4(value, new Set));
7275
7419
  }
7276
7420
  function sha256(value) {
7277
7421
  if (typeof value === "string" && invalidUnicode(value))
7278
7422
  throw new TypeError("invalid Unicode");
7279
- return createHash7("sha256").update(typeof value === "string" ? value : canonicalJson(value), "utf8").digest("hex");
7423
+ return createHash8("sha256").update(typeof value === "string" ? value : canonicalJson(value), "utf8").digest("hex");
7280
7424
  }
7281
7425
  function newId() {
7282
7426
  return randomUUID().toLowerCase();
@@ -7311,15 +7455,15 @@ function candidateDigest(input) {
7311
7455
  }
7312
7456
 
7313
7457
  // packages/workit-core/src/core/task-evaluation.ts
7314
- import { createHash as createHash10 } from "node:crypto";
7458
+ import { createHash as createHash11 } from "node:crypto";
7315
7459
  import * as fs14 from "node:fs";
7316
7460
  import { spawnSync as spawnSync12 } from "node:child_process";
7317
- import path19 from "node:path";
7461
+ import path20 from "node:path";
7318
7462
 
7319
7463
  // packages/workit-core/src/core/task-read.ts
7320
7464
  import { randomUUID as randomUUID3 } from "node:crypto";
7321
7465
  import * as fs11 from "node:fs";
7322
- import path14 from "node:path";
7466
+ import path15 from "node:path";
7323
7467
 
7324
7468
  // node_modules/@openclaw/fs-safe/dist/errors.js
7325
7469
  var OPERATIONAL_CODES = new Set([
@@ -7370,7 +7514,7 @@ function sameFileIdentity(left, right, platform = process.platform) {
7370
7514
  // node_modules/@openclaw/fs-safe/dist/sidecar-lock-reclaim.js
7371
7515
  import { randomBytes } from "node:crypto";
7372
7516
  import fsSync from "node:fs";
7373
- import path10 from "node:path";
7517
+ import path11 from "node:path";
7374
7518
 
7375
7519
  // node_modules/@openclaw/fs-safe/dist/bounded-read.js
7376
7520
  import fs6 from "node:fs";
@@ -7460,13 +7604,13 @@ ${ownershipToken}
7460
7604
  return { raw, ownershipToken };
7461
7605
  }
7462
7606
  function relativeSidecarLockPath(lockRoot, lockPath) {
7463
- const resolved = path10.resolve(lockPath);
7464
- const lexicalRelative = path10.relative(lockRoot.rootDir, resolved);
7465
- const relative = lexicalRelative !== ".." && !lexicalRelative.startsWith(`..${path10.sep}`) && !path10.isAbsolute(lexicalRelative) ? lexicalRelative : path10.relative(lockRoot.rootReal, resolved);
7466
- if (!relative || relative === ".." || relative.startsWith(`..${path10.sep}`) || path10.isAbsolute(relative)) {
7607
+ const resolved = path11.resolve(lockPath);
7608
+ const lexicalRelative = path11.relative(lockRoot.rootDir, resolved);
7609
+ const relative = lexicalRelative !== ".." && !lexicalRelative.startsWith(`..${path11.sep}`) && !path11.isAbsolute(lexicalRelative) ? lexicalRelative : path11.relative(lockRoot.rootReal, resolved);
7610
+ if (!relative || relative === ".." || relative.startsWith(`..${path11.sep}`) || path11.isAbsolute(relative)) {
7467
7611
  throw new FsSafeError("outside-workspace", "sidecar lock path is outside lockRoot");
7468
7612
  }
7469
- return relative.split(path10.sep).join(path10.posix.sep);
7613
+ return relative.split(path11.sep).join(path11.posix.sep);
7470
7614
  }
7471
7615
  function parseSidecarLockPayload(raw, parser) {
7472
7616
  if (parser) {
@@ -7613,7 +7757,7 @@ function getFsSafeLockConfig() {
7613
7757
 
7614
7758
  // node_modules/@openclaw/fs-safe/dist/file-lock-sync.js
7615
7759
  import fs8 from "node:fs";
7616
- import path11 from "node:path";
7760
+ import path12 from "node:path";
7617
7761
 
7618
7762
  // node_modules/@openclaw/fs-safe/dist/timing.js
7619
7763
  function sleepSync(ms) {
@@ -7704,26 +7848,26 @@ function canonicalLockParentSync(parent) {
7704
7848
  return process.platform === "win32" ? fs8.realpathSync.native(parent) : fs8.realpathSync(parent);
7705
7849
  }
7706
7850
  function normalizeTargetPath(targetPath) {
7707
- const resolved = path11.resolve(targetPath);
7708
- fs8.mkdirSync(path11.dirname(resolved), { recursive: true });
7851
+ const resolved = path12.resolve(targetPath);
7852
+ fs8.mkdirSync(path12.dirname(resolved), { recursive: true });
7709
7853
  try {
7710
- return path11.join(canonicalLockParentSync(path11.dirname(resolved)), path11.basename(resolved));
7854
+ return path12.join(canonicalLockParentSync(path12.dirname(resolved)), path12.basename(resolved));
7711
7855
  } catch {
7712
7856
  return resolved;
7713
7857
  }
7714
7858
  }
7715
7859
  function boundedLockPath(lockPath, lockRoot) {
7716
- const resolved = path11.resolve(lockPath);
7860
+ const resolved = path12.resolve(lockPath);
7717
7861
  if (!lockRoot)
7718
7862
  return resolved;
7719
7863
  relativeSidecarLockPath(lockRoot, resolved);
7720
- const parent = path11.dirname(resolved);
7864
+ const parent = path12.dirname(resolved);
7721
7865
  const parentReal = canonicalLockParentSync(parent);
7722
- const parentRelative = path11.relative(lockRoot.rootReal, parentReal);
7723
- if (parentRelative === ".." || parentRelative.startsWith(`..${path11.sep}`) || path11.isAbsolute(parentRelative)) {
7866
+ const parentRelative = path12.relative(lockRoot.rootReal, parentReal);
7867
+ if (parentRelative === ".." || parentRelative.startsWith(`..${path12.sep}`) || path12.isAbsolute(parentRelative)) {
7724
7868
  throw new FsSafeError("outside-workspace", "sidecar lock parent is outside lockRoot");
7725
7869
  }
7726
- return path11.join(parentReal, path11.basename(resolved));
7870
+ return path12.join(parentReal, path12.basename(resolved));
7727
7871
  }
7728
7872
  function defaultShouldReclaim(snapshot, staleMs, nowMs) {
7729
7873
  const createdAtMs = sidecarLockPayloadCreatedAtMs(snapshot.payload);
@@ -7924,13 +8068,13 @@ function acquireFileLockSync(targetPath, options) {
7924
8068
  }
7925
8069
  // packages/workit-core/src/core/package-root.ts
7926
8070
  import { existsSync as existsSync4 } from "node:fs";
7927
- import path12 from "node:path";
8071
+ import path13 from "node:path";
7928
8072
  import { fileURLToPath } from "node:url";
7929
8073
  var packageRoot = () => {
7930
- let dir = path12.dirname(fileURLToPath(import.meta.url));
8074
+ let dir = path13.dirname(fileURLToPath(import.meta.url));
7931
8075
  while (true) {
7932
- const parent = path12.dirname(dir);
7933
- if (existsSync4(path12.join(dir, "package.json")) || parent === dir)
8076
+ const parent = path13.dirname(dir);
8077
+ if (existsSync4(path13.join(dir, "package.json")) || parent === dir)
7934
8078
  return dir;
7935
8079
  dir = parent;
7936
8080
  }
@@ -8088,7 +8232,7 @@ var clearAbandonedReclaimGuard = (lockPath, nowMs = Date.now()) => {
8088
8232
  // packages/workit-core/src/store/event-log.ts
8089
8233
  import { randomUUID as randomUUID2 } from "node:crypto";
8090
8234
  import fs10 from "node:fs";
8091
- import path13 from "node:path";
8235
+ import path14 from "node:path";
8092
8236
  var EVENT_VERSION = 1;
8093
8237
 
8094
8238
  class LogDamage extends Error {
@@ -8189,7 +8333,7 @@ function replaceFile(file, bytes, durable) {
8189
8333
  }
8190
8334
  renameWithRetry(temporary, file);
8191
8335
  if (durable)
8192
- fsyncDirectory(path13.dirname(file));
8336
+ fsyncDirectory(path14.dirname(file));
8193
8337
  } catch (error) {
8194
8338
  try {
8195
8339
  fs10.unlinkSync(temporary);
@@ -8426,7 +8570,7 @@ var cachedRuntimeVersion = null;
8426
8570
  var runtimeVersion = () => {
8427
8571
  if (cachedRuntimeVersion === null) {
8428
8572
  try {
8429
- const pkg = JSON.parse(fs11.readFileSync(path14.join(packageRoot(), "package.json"), "utf8"));
8573
+ const pkg = JSON.parse(fs11.readFileSync(path15.join(packageRoot(), "package.json"), "utf8"));
8430
8574
  cachedRuntimeVersion = typeof pkg.version === "string" && pkg.version ? pkg.version : "0.0.0";
8431
8575
  } catch {
8432
8576
  cachedRuntimeVersion = "0.0.0";
@@ -8455,7 +8599,7 @@ var readText2 = (file) => {
8455
8599
  };
8456
8600
  var REFLOG_LINE = /^[0-9a-f]+ ([0-9a-f]+) .* (\d+) [+-]\d{4}\t(.*)$/u;
8457
8601
  var branchStart = (location, branch, aliases) => {
8458
- const first = readText2(path14.join(path14.dirname(location.dir), "logs", "refs", "heads", branch)).split(`
8602
+ const first = readText2(path15.join(path15.dirname(location.dir), "logs", "refs", "heads", branch)).split(`
8459
8603
  `, 1)[0];
8460
8604
  const created = REFLOG_LINE.exec(first);
8461
8605
  const start = created && /^branch: Created from (\S+)$/u.exec(created[3])?.[1];
@@ -8465,7 +8609,7 @@ var branchStart = (location, branch, aliases) => {
8465
8609
  return start;
8466
8610
  if (!location.git)
8467
8611
  return null;
8468
- for (const line of readText2(path14.join(location.git.gitDir, "logs", "HEAD")).split(`
8612
+ for (const line of readText2(path15.join(location.git.gitDir, "logs", "HEAD")).split(`
8469
8613
  `)) {
8470
8614
  const entry = REFLOG_LINE.exec(line);
8471
8615
  const moved = entry && /^checkout: moving from (\S+) to (\S+)$/u.exec(entry[3]);
@@ -8475,14 +8619,14 @@ var branchStart = (location, branch, aliases) => {
8475
8619
  }
8476
8620
  return null;
8477
8621
  };
8478
- var refExists2 = (common, ref) => fs11.existsSync(path14.join(common, ref)) || readText2(path14.join(common, "packed-refs")).includes(` ${ref}
8622
+ var refExists2 = (common, ref) => fs11.existsSync(path15.join(common, ref)) || readText2(path15.join(common, "packed-refs")).includes(` ${ref}
8479
8623
  `);
8480
8624
  var origins = new Map;
8481
8625
  var sameDirectoryIdentity = (left, right) => {
8482
- if (!path14.isAbsolute(left) || !path14.isAbsolute(right))
8626
+ if (!path15.isAbsolute(left) || !path15.isAbsolute(right))
8483
8627
  return false;
8484
- const normalizedLeft = path14.resolve(left);
8485
- const normalizedRight = path14.resolve(right);
8628
+ const normalizedLeft = path15.resolve(left);
8629
+ const normalizedRight = path15.resolve(right);
8486
8630
  try {
8487
8631
  const a = fs11.statSync(normalizedLeft, { bigint: true });
8488
8632
  const b = fs11.statSync(normalizedRight, { bigint: true });
@@ -8516,14 +8660,14 @@ class TaskReader {
8516
8660
  located;
8517
8661
  migrationChecked = false;
8518
8662
  constructor(root, options = {}) {
8519
- const resolved = path14.resolve(root);
8663
+ const resolved = path15.resolve(root);
8520
8664
  this.origin = fs11.existsSync(resolved) ? fs11.realpathSync(resolved) : resolved;
8521
8665
  this.located = resolveStore(this.origin);
8522
8666
  this.root = checkoutRootOf(this.origin, this.located);
8523
8667
  this.lockTimeoutMs = options.lockTimeoutMs ?? defaultLockTimeout();
8524
8668
  }
8525
8669
  location() {
8526
- if (this.located !== undefined && !(this.located instanceof Error) && !this.located.shared && fs11.existsSync(path14.join(this.root, ".git"))) {
8670
+ if (this.located !== undefined && !(this.located instanceof Error) && !this.located.shared && fs11.existsSync(path15.join(this.root, ".git"))) {
8527
8671
  this.located = undefined;
8528
8672
  this.migrationChecked = false;
8529
8673
  }
@@ -8681,14 +8825,14 @@ class TaskReader {
8681
8825
  const branch = key.ok ? key.data.branch : null;
8682
8826
  if (!branch || !location.ok)
8683
8827
  return success(null, null, null);
8684
- const common = path14.dirname(location.data.dir);
8685
- const heads = path14.join(common, "logs", "refs", "heads");
8686
- const headLog = location.data.git ? path14.join(location.data.git.gitDir, "logs", "HEAD") : "";
8828
+ const common = path15.dirname(location.data.dir);
8829
+ const heads = path15.join(common, "logs", "refs", "heads");
8830
+ const headLog = location.data.git ? path15.join(location.data.git.gitDir, "logs", "HEAD") : "";
8687
8831
  const signatures = [
8688
- path14.join(heads, branch),
8832
+ path15.join(heads, branch),
8689
8833
  headLog,
8690
8834
  heads,
8691
- path14.join(common, "packed-refs")
8835
+ path15.join(common, "packed-refs")
8692
8836
  ].map((file) => fileSignature(file) ?? "-");
8693
8837
  const slot = `${location.data.dir}\x00${headLog}\x00${branch}`;
8694
8838
  let resolved = origins.get(slot);
@@ -8700,7 +8844,7 @@ class TaskReader {
8700
8844
  aliases.push(rename.from);
8701
8845
  const start = branchStart(location.data, branch, aliases);
8702
8846
  const slash = start?.indexOf("/") ?? -1;
8703
- const remote = slash > 0 && !refExists2(common, `refs/heads/${start}`) && (refExists2(common, `refs/remotes/${start}`) || readText2(path14.join(common, "config")).includes(`[remote "${start.slice(0, slash)}"]`));
8847
+ const remote = slash > 0 && !refExists2(common, `refs/heads/${start}`) && (refExists2(common, `refs/remotes/${start}`) || readText2(path15.join(common, "config")).includes(`[remote "${start.slice(0, slash)}"]`));
8704
8848
  const name = start && (remote ? start.slice(slash + 1) : start);
8705
8849
  resolved = {
8706
8850
  signature: signatures.join("|"),
@@ -8720,27 +8864,27 @@ class TaskReader {
8720
8864
  }
8721
8865
  paths() {
8722
8866
  const location = this.location();
8723
- const dir = location.ok ? location.data.dir : path14.join(this.root, ".workit");
8724
- const checkout = path14.join(dir, "checkouts", checkoutSlug(this.root));
8867
+ const dir = location.ok ? location.data.dir : path15.join(this.root, ".workit");
8868
+ const checkout = path15.join(dir, "checkouts", checkoutSlug(this.root));
8725
8869
  return {
8726
8870
  dir,
8727
8871
  shared: location.ok ? location.data.shared : false,
8728
- marker: path14.join(dir, "store.json"),
8872
+ marker: path15.join(dir, "store.json"),
8729
8873
  checkout,
8730
- workspace: path14.join(checkout, "workspace.json"),
8731
- checkoutLock: path14.join(checkout, "metadata.lock"),
8732
- tasks: path14.join(dir, "tasks"),
8733
- index: path14.join(dir, "task-index.json"),
8734
- blobs: path14.join(dir, "blobs", "candidates"),
8735
- legacy: path14.join(dir, "legacy", checkoutSlug(this.root), "v2"),
8736
- v2: path14.join(this.root, ".workit")
8874
+ workspace: path15.join(checkout, "workspace.json"),
8875
+ checkoutLock: path15.join(checkout, "metadata.lock"),
8876
+ tasks: path15.join(dir, "tasks"),
8877
+ index: path15.join(dir, "task-index.json"),
8878
+ blobs: path15.join(dir, "blobs", "candidates"),
8879
+ legacy: path15.join(dir, "legacy", checkoutSlug(this.root), "v2"),
8880
+ v2: path15.join(this.root, ".workit")
8737
8881
  };
8738
8882
  }
8739
8883
  eventsPath(taskId) {
8740
- return path14.join(this.paths().tasks, taskId, "events.jsonl");
8884
+ return path15.join(this.paths().tasks, taskId, "events.jsonl");
8741
8885
  }
8742
8886
  snapshotPath(taskId) {
8743
- return path14.join(this.paths().tasks, taskId, "snapshot.json");
8887
+ return path15.join(this.paths().tasks, taskId, "snapshot.json");
8744
8888
  }
8745
8889
  ready(write = false) {
8746
8890
  const location = this.location();
@@ -8775,7 +8919,7 @@ class TaskReader {
8775
8919
  return {
8776
8920
  read: (digest) => {
8777
8921
  try {
8778
- return JSON.parse(fs11.readFileSync(path14.join(dir, `${digest}.json`), "utf8"));
8922
+ return JSON.parse(fs11.readFileSync(path15.join(dir, `${digest}.json`), "utf8"));
8779
8923
  } catch (error) {
8780
8924
  throw new LogDamage(`stored candidate ${digest} is missing or unreadable: ${String(error)}`);
8781
8925
  }
@@ -8941,11 +9085,11 @@ class TaskReader {
8941
9085
  return failure2("recovery_required", `${label} record does not satisfy its schema`);
8942
9086
  }
8943
9087
  v2Dirs() {
8944
- return [...new Set([this.root, this.origin])].map((dir) => path14.join(dir, ".workit"));
9088
+ return [...new Set([this.root, this.origin])].map((dir) => path15.join(dir, ".workit"));
8945
9089
  }
8946
9090
  pendingMigrations() {
8947
9091
  return this.v2Dirs().filter((dir) => {
8948
- const raw = this.readV2Workspace(path14.join(dir, "workspace.json"));
9092
+ const raw = this.readV2Workspace(path15.join(dir, "workspace.json"));
8949
9093
  return raw !== null && raw !== TOMBSTONE;
8950
9094
  });
8951
9095
  }
@@ -8961,7 +9105,7 @@ class TaskReader {
8961
9105
  }
8962
9106
  adoptStoreFrom(local) {
8963
9107
  const dirs = this.paths();
8964
- const marker = path14.join(local, "store.json");
9108
+ const marker = path15.join(local, "store.json");
8965
9109
  if (!fs11.existsSync(marker))
8966
9110
  return success(null, null, null);
8967
9111
  return this.withLock(dirs.checkoutLock, () => {
@@ -8971,7 +9115,7 @@ class TaskReader {
8971
9115
  try {
8972
9116
  const merge = (from, to) => {
8973
9117
  if (!fs11.existsSync(to)) {
8974
- fs11.mkdirSync(path14.dirname(to), { recursive: true });
9118
+ fs11.mkdirSync(path15.dirname(to), { recursive: true });
8975
9119
  try {
8976
9120
  fs11.renameSync(from, to);
8977
9121
  } catch {
@@ -8982,24 +9126,24 @@ class TaskReader {
8982
9126
  }
8983
9127
  if (fs11.lstatSync(from).isDirectory() && fs11.lstatSync(to).isDirectory())
8984
9128
  for (const name of fs11.readdirSync(from))
8985
- merge(path14.join(from, name), path14.join(to, name));
9129
+ merge(path15.join(from, name), path15.join(to, name));
8986
9130
  };
8987
9131
  for (const sub of ["tasks", "checkouts", "blobs", "legacy"]) {
8988
- const from = path14.join(local, sub);
9132
+ const from = path15.join(local, sub);
8989
9133
  if (!fs11.existsSync(from))
8990
9134
  continue;
8991
9135
  if (sub === "tasks") {
8992
9136
  for (const name of fs11.readdirSync(from))
8993
- if (validId(name) && !fs11.existsSync(path14.join(dirs.dir, sub, name)))
9137
+ if (validId(name) && !fs11.existsSync(path15.join(dirs.dir, sub, name)))
8994
9138
  tasks += 1;
8995
9139
  }
8996
- merge(from, path14.join(dirs.dir, sub));
9140
+ merge(from, path15.join(dirs.dir, sub));
8997
9141
  }
8998
- const ledger = path14.join(local, "ledger");
8999
- if (fs11.existsSync(ledger) && !fs11.existsSync(path14.join(dirs.dir, "ledger")))
9000
- merge(ledger, path14.join(dirs.dir, "ledger"));
9001
- fs11.rmSync(path14.join(local, "task-index.json"), { force: true });
9002
- fs11.renameSync(marker, path14.join(local, "store.moved.json"));
9142
+ const ledger = path15.join(local, "ledger");
9143
+ if (fs11.existsSync(ledger) && !fs11.existsSync(path15.join(dirs.dir, "ledger")))
9144
+ merge(ledger, path15.join(dirs.dir, "ledger"));
9145
+ fs11.rmSync(path15.join(local, "task-index.json"), { force: true });
9146
+ fs11.renameSync(marker, path15.join(local, "store.moved.json"));
9003
9147
  } catch (error) {
9004
9148
  return failure2("storage_error", `cannot move ${local} into ${dirs.dir}: ${String(error)}`, {
9005
9149
  path: local
@@ -9037,7 +9181,7 @@ class TaskReader {
9037
9181
  schemaVersion: SCHEMA_VERSION,
9038
9182
  id: workspaceId ?? newId(),
9039
9183
  revision: newRevision(),
9040
- root: path14.dirname(v2),
9184
+ root: path15.dirname(v2),
9041
9185
  runtime: { createdWith: version, updatedWith: version },
9042
9186
  writer: null,
9043
9187
  store: {
@@ -9049,11 +9193,11 @@ class TaskReader {
9049
9193
  critical: ["store"]
9050
9194
  };
9051
9195
  fs11.mkdirSync(v2, { recursive: true });
9052
- const ignore = path14.join(v2, ".gitignore");
9196
+ const ignore = path15.join(v2, ".gitignore");
9053
9197
  if (!fs11.existsSync(ignore))
9054
9198
  fs11.writeFileSync(ignore, `*
9055
9199
  `);
9056
- replaceFile(path14.join(v2, "workspace.json"), `${JSON.stringify(marker, null, 2)}
9200
+ replaceFile(path15.join(v2, "workspace.json"), `${JSON.stringify(marker, null, 2)}
9057
9201
  `, true);
9058
9202
  }
9059
9203
  initializeStorage() {
@@ -9112,7 +9256,7 @@ class TaskReader {
9112
9256
  withLock(lockPath, operation) {
9113
9257
  try {
9114
9258
  this.initializeStorage();
9115
- fs11.mkdirSync(path14.dirname(lockPath), { recursive: true });
9259
+ fs11.mkdirSync(path15.dirname(lockPath), { recursive: true });
9116
9260
  } catch (error) {
9117
9261
  return failure2("storage_error", `unable to initialize store: ${String(error)}`, {
9118
9262
  path: this.paths().dir
@@ -9175,7 +9319,7 @@ class TaskReader {
9175
9319
  if (isTransientWindowsError(error) && !this.lockHolderPresent(lockPath) && !this.lockDirWritable(lockPath))
9176
9320
  return failure2("storage_error", `cannot create the workit lock (${code}); no other Workit call holds it`, {
9177
9321
  path: lockPath,
9178
- guidance: `Check permissions and the read-only attribute on ${path14.dirname(lockPath)}.`
9322
+ guidance: `Check permissions and the read-only attribute on ${path15.dirname(lockPath)}.`
9179
9323
  });
9180
9324
  if (code === "EEXIST" || code === "file_lock_timeout" || code === "file_lock_stale" || isTransientWindowsError(error)) {
9181
9325
  let lock = null;
@@ -9195,13 +9339,13 @@ class TaskReader {
9195
9339
 
9196
9340
  // packages/workit-core/src/core/policy/derive.ts
9197
9341
  import { existsSync as existsSync7 } from "node:fs";
9198
- import path18 from "node:path";
9342
+ import path19 from "node:path";
9199
9343
 
9200
9344
  // packages/workit-core/src/ledger.ts
9201
9345
  import { spawnSync as spawnSync11 } from "node:child_process";
9202
- import { createHash as createHash9, randomBytes as randomBytes3 } from "node:crypto";
9346
+ import { createHash as createHash10, randomBytes as randomBytes3 } from "node:crypto";
9203
9347
  import fs13 from "node:fs";
9204
- import path17 from "node:path";
9348
+ import path18 from "node:path";
9205
9349
 
9206
9350
  // packages/workit-core/src/core/policy/bookkeeping.ts
9207
9351
  import { spawnSync as spawnSync9 } from "node:child_process";
@@ -9281,8 +9425,8 @@ function bookkeepingPaths(cwd, input) {
9281
9425
  }
9282
9426
 
9283
9427
  // packages/workit-core/src/core/policy/lane.ts
9284
- import { existsSync as existsSync6, readFileSync as readFileSync7 } from "node:fs";
9285
- import path15 from "node:path";
9428
+ import { existsSync as existsSync6, readFileSync as readFileSync8 } from "node:fs";
9429
+ import path16 from "node:path";
9286
9430
 
9287
9431
  // packages/workit-core/src/git/default-base.ts
9288
9432
  import { spawnSync as spawnSync10 } from "node:child_process";
@@ -10673,7 +10817,7 @@ function computeLane(input) {
10673
10817
  }
10674
10818
  function untrackedStat(cwd, file) {
10675
10819
  try {
10676
- const bytes = readFileSync7(path15.join(cwd, file));
10820
+ const bytes = readFileSync8(path16.join(cwd, file));
10677
10821
  if (bytes.includes(0))
10678
10822
  return { path: file, added: 0, deleted: 0, binary: true };
10679
10823
  const text = bytes.toString("utf8");
@@ -10705,7 +10849,7 @@ function cosmeticFiles(cwd, fork, head) {
10705
10849
  let after = blobs.get(entry.newBlob);
10706
10850
  if (!after && head === null && ABSENT.test(entry.newBlob))
10707
10851
  try {
10708
- after = readFileSync7(path15.join(cwd, entry.path));
10852
+ after = readFileSync8(path16.join(cwd, entry.path));
10709
10853
  } catch {
10710
10854
  after = undefined;
10711
10855
  }
@@ -10860,9 +11004,9 @@ function verdictDrift(cwd, input) {
10860
11004
  }
10861
11005
 
10862
11006
  // packages/workit-core/src/host-session.ts
10863
- import { createHash as createHash8, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
11007
+ import { createHash as createHash9, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
10864
11008
  import fs12 from "node:fs";
10865
- import path16 from "node:path";
11009
+ import path17 from "node:path";
10866
11010
  var STAMPING_HOSTS = new Set([
10867
11011
  "claude_code",
10868
11012
  "codex_cli",
@@ -10870,13 +11014,13 @@ var STAMPING_HOSTS = new Set([
10870
11014
  ]);
10871
11015
  var ISSUED_PER_LEAD = 64;
10872
11016
  var ISSUED_SESSIONS_MARKER = "workit-issued-sessions/3";
10873
- var hash = (value) => createHash8("sha256").update(value).digest("hex").slice(0, 32);
11017
+ var hash = (value) => createHash9("sha256").update(value).digest("hex").slice(0, 32);
10874
11018
  var PIN_FILE = "issued-registry";
10875
11019
  var pinFiles = new Map;
10876
11020
  var pinFile = (cwd) => {
10877
11021
  if (cwd === undefined)
10878
11022
  return null;
10879
- const key = path16.resolve(cwd);
11023
+ const key = path17.resolve(cwd);
10880
11024
  const known = pinFiles.get(key);
10881
11025
  if (known !== undefined)
10882
11026
  return known;
@@ -10884,7 +11028,7 @@ var pinFile = (cwd) => {
10884
11028
  const location = resolveStore(key);
10885
11029
  if (location instanceof Error)
10886
11030
  return null;
10887
- const file = location.shared ? path16.join(location.dir, "ledger", PIN_FILE) : null;
11031
+ const file = location.shared ? path17.join(location.dir, "ledger", PIN_FILE) : null;
10888
11032
  pinFiles.set(key, file);
10889
11033
  return file;
10890
11034
  } catch {
@@ -10897,32 +11041,32 @@ var pinnedStateDir = (cwd) => {
10897
11041
  return null;
10898
11042
  try {
10899
11043
  const pinned = fs12.readFileSync(file, "utf8").trim();
10900
- return path16.isAbsolute(pinned) ? pinned : null;
11044
+ return path17.isAbsolute(pinned) ? pinned : null;
10901
11045
  } catch {
10902
11046
  return null;
10903
11047
  }
10904
11048
  };
10905
11049
  var registryDir = (cwd) => pinnedStateDir(cwd) ?? resolveStateDir();
10906
- var testRunSkipsPin = (file) => process.env.WORKIT_TEST_RUN !== undefined && !insideTempDir(path16.dirname(path16.dirname(path16.dirname(file))));
11050
+ var testRunSkipsPin = (file) => process.env.WORKIT_TEST_RUN !== undefined && !insideTempDir(path17.dirname(path17.dirname(path17.dirname(file))));
10907
11051
  function pinIssuedRegistry(cwd) {
10908
11052
  const file = pinFile(cwd);
10909
11053
  if (file === null)
10910
11054
  return;
10911
- const state = path16.resolve(resolveStateDir());
11055
+ const state = path17.resolve(resolveStateDir());
10912
11056
  if (pinnedStateDir(cwd) === state)
10913
11057
  return;
10914
11058
  if (testRunSkipsPin(file))
10915
11059
  return;
10916
11060
  try {
10917
- fs12.mkdirSync(path16.dirname(file), { recursive: true });
11061
+ fs12.mkdirSync(path17.dirname(file), { recursive: true });
10918
11062
  const temp = `${file}.${process.pid}.tmp`;
10919
11063
  fs12.writeFileSync(temp, `${state}
10920
11064
  `, { mode: 420 });
10921
11065
  fs12.renameSync(temp, file);
10922
11066
  } catch {}
10923
11067
  }
10924
- var userIssuedRoot = (cwd) => path16.join(registryDir(cwd), "issued");
10925
- var userTokenRoot = (cwd) => path16.join(registryDir(cwd), "issued-tokens");
11068
+ var userIssuedRoot = (cwd) => path17.join(registryDir(cwd), "issued");
11069
+ var userTokenRoot = (cwd) => path17.join(registryDir(cwd), "issued-tokens");
10926
11070
  function migrateRepoIssued(cwd) {
10927
11071
  if (cwd === undefined)
10928
11072
  return;
@@ -10931,7 +11075,7 @@ function migrateRepoIssued(cwd) {
10931
11075
  const location = resolveStore(cwd);
10932
11076
  if (location instanceof Error)
10933
11077
  return;
10934
- old = path16.join(location.dir, "hooks", "issued");
11078
+ old = path17.join(location.dir, "hooks", "issued");
10935
11079
  if (!fs12.existsSync(old))
10936
11080
  return;
10937
11081
  } catch {
@@ -10939,19 +11083,19 @@ function migrateRepoIssued(cwd) {
10939
11083
  }
10940
11084
  for (const lead of safeList(old)) {
10941
11085
  try {
10942
- const from = path16.join(old, lead);
11086
+ const from = path17.join(old, lead);
10943
11087
  if (!fs12.statSync(from).isDirectory())
10944
11088
  continue;
10945
- const to = path16.join(userIssuedRoot(cwd), lead);
11089
+ const to = path17.join(userIssuedRoot(cwd), lead);
10946
11090
  fs12.mkdirSync(to, { recursive: true, mode: 448 });
10947
11091
  for (const id of fs12.readdirSync(from)) {
10948
11092
  try {
10949
- fs12.copyFileSync(path16.join(from, id), path16.join(to, id), fs12.constants.COPYFILE_EXCL);
11093
+ fs12.copyFileSync(path17.join(from, id), path17.join(to, id), fs12.constants.COPYFILE_EXCL);
10950
11094
  } catch (error) {
10951
11095
  if (error.code !== "EEXIST")
10952
11096
  throw error;
10953
11097
  }
10954
- fs12.rmSync(path16.join(from, id), { force: true });
11098
+ fs12.rmSync(path17.join(from, id), { force: true });
10955
11099
  }
10956
11100
  removeIfEmpty(from);
10957
11101
  } catch {}
@@ -10970,7 +11114,7 @@ var removeIfEmpty = (dir) => {
10970
11114
  fs12.rmdirSync(dir);
10971
11115
  } catch {}
10972
11116
  };
10973
- var tokenHash = (token) => createHash8("sha256").update(token).digest("hex");
11117
+ var tokenHash = (token) => createHash9("sha256").update(token).digest("hex");
10974
11118
  function recordIssuedSession(cwd, lead, issued) {
10975
11119
  const token = randomBytes2(18).toString("hex");
10976
11120
  try {
@@ -10978,13 +11122,13 @@ function recordIssuedSession(cwd, lead, issued) {
10978
11122
  migrateRepoIssued(cwd);
10979
11123
  const own = hash(issued);
10980
11124
  const state = resolveStateDir();
10981
- const tokens = path16.join(state, "issued-tokens", hash(lead));
11125
+ const tokens = path17.join(state, "issued-tokens", hash(lead));
10982
11126
  fs12.mkdirSync(tokens, { recursive: true, mode: 448 });
10983
- fs12.writeFileSync(path16.join(tokens, own), `${tokenHash(token)}
11127
+ fs12.writeFileSync(path17.join(tokens, own), `${tokenHash(token)}
10984
11128
  `, { mode: 384, flag: "wx" });
10985
- const dir = path16.join(state, "issued", hash(lead));
11129
+ const dir = path17.join(state, "issued", hash(lead));
10986
11130
  fs12.mkdirSync(dir, { recursive: true, mode: 448 });
10987
- fs12.writeFileSync(path16.join(dir, own), `${ISSUED_SESSIONS_MARKER}
11131
+ fs12.writeFileSync(path17.join(dir, own), `${ISSUED_SESSIONS_MARKER}
10988
11132
  `, { mode: 384 });
10989
11133
  pruneIssued(dir, own, tokens);
10990
11134
  return token;
@@ -11014,10 +11158,10 @@ function pruneIssued(dir, own, tokens) {
11014
11158
  const entries = fs12.readdirSync(dir);
11015
11159
  if (entries.length <= ISSUED_PER_LEAD)
11016
11160
  return;
11017
- const byAge = entries.filter((name) => name !== own).map((name) => ({ name, at: fs12.statSync(path16.join(dir, name)).mtimeMs })).toSorted((a, b) => a.at - b.at);
11161
+ const byAge = entries.filter((name) => name !== own).map((name) => ({ name, at: fs12.statSync(path17.join(dir, name)).mtimeMs })).toSorted((a, b) => a.at - b.at);
11018
11162
  for (const { name } of byAge.slice(0, entries.length - ISSUED_PER_LEAD)) {
11019
- fs12.rmSync(path16.join(dir, name), { force: true });
11020
- fs12.rmSync(path16.join(tokens, name), { force: true });
11163
+ fs12.rmSync(path17.join(dir, name), { force: true });
11164
+ fs12.rmSync(path17.join(tokens, name), { force: true });
11021
11165
  }
11022
11166
  } catch {}
11023
11167
  }
@@ -11027,7 +11171,7 @@ var issuedRecord = (cwd, claimed) => {
11027
11171
  return null;
11028
11172
  migrateRepoIssued(cwd);
11029
11173
  try {
11030
- return fs12.readFileSync(path16.join(userIssuedRoot(cwd), hash(claimed.slice(0, cut)), hash(claimed)), "utf8");
11174
+ return fs12.readFileSync(path17.join(userIssuedRoot(cwd), hash(claimed.slice(0, cut)), hash(claimed)), "utf8");
11031
11175
  } catch {
11032
11176
  return null;
11033
11177
  }
@@ -11037,9 +11181,9 @@ var issuedToken = (cwd, claimed) => {
11037
11181
  const cut = claimed.lastIndexOf(":");
11038
11182
  if (cut <= 0)
11039
11183
  return { stored: null, leadBound: false };
11040
- const dir = path16.join(userTokenRoot(cwd), hash(claimed.slice(0, cut)));
11184
+ const dir = path17.join(userTokenRoot(cwd), hash(claimed.slice(0, cut)));
11041
11185
  try {
11042
- const text = fs12.readFileSync(path16.join(dir, hash(claimed)), "utf8");
11186
+ const text = fs12.readFileSync(path17.join(dir, hash(claimed)), "utf8");
11043
11187
  return { stored: TOKEN_HASH.exec(text)?.[1] ?? null, leadBound: true };
11044
11188
  } catch {
11045
11189
  return { stored: null, leadBound: safeList(dir).length > 0 };
@@ -11133,7 +11277,7 @@ var binaryRangeDiff = (cwd, base, head) => {
11133
11277
  return diff.ok && diff.stdout ? diff.stdout : null;
11134
11278
  };
11135
11279
  var hashOfDiff = (diff) => {
11136
- const hash = createHash9("sha256");
11280
+ const hash = createHash10("sha256");
11137
11281
  for (const line of diff.split(`
11138
11282
  `)) {
11139
11283
  if (line.startsWith("index "))
@@ -11166,14 +11310,14 @@ function cleanRebase(cwd, range) {
11166
11310
  return Boolean(tree) && tree === git3(cwd, ["rev-parse", "--verify", "-q", `${range.to}^{tree}`]);
11167
11311
  }
11168
11312
  function storeRoot(cwd) {
11169
- const location = resolveStore(path17.resolve(cwd));
11313
+ const location = resolveStore(path18.resolve(cwd));
11170
11314
  if (location instanceof Error)
11171
11315
  return err("unavailable", location.message.replace(/; fix the repository.*$/u, ""), / does not exist /u.test(location.message) ? "run workit from a directory that exists" : "fix the repository (git status should work here) or run from a non-git directory");
11172
11316
  return { ok: true, value: { root: location.dir, shared: location.shared } };
11173
11317
  }
11174
11318
  function ledgerPath(cwd) {
11175
11319
  const root = storeRoot(cwd);
11176
- return root.ok ? { ok: true, value: path17.join(root.value.root, "ledger", "ledger.jsonl") } : root;
11320
+ return root.ok ? { ok: true, value: path18.join(root.value.root, "ledger", "ledger.jsonl") } : root;
11177
11321
  }
11178
11322
  var newId2 = () => `${Date.now().toString(36)}-${randomBytes3(6).toString("hex")}`;
11179
11323
  var NETWORK_FS_TYPES = new Set([
@@ -11203,13 +11347,13 @@ var LOCK_STALE_MS2 = 30000;
11203
11347
  var LOCK_OWNER = "owner";
11204
11348
  var lockToken = (lock) => {
11205
11349
  try {
11206
- return fs13.readFileSync(path17.join(lock, LOCK_OWNER), "utf8");
11350
+ return fs13.readFileSync(path18.join(lock, LOCK_OWNER), "utf8");
11207
11351
  } catch {
11208
11352
  return null;
11209
11353
  }
11210
11354
  };
11211
11355
  var lockAgeMs = (lock) => {
11212
- for (const target of [path17.join(lock, LOCK_OWNER), lock]) {
11356
+ for (const target of [path18.join(lock, LOCK_OWNER), lock]) {
11213
11357
  try {
11214
11358
  return Date.now() - fs13.statSync(target).mtimeMs;
11215
11359
  } catch {}
@@ -11226,7 +11370,7 @@ var ledgerLock = {
11226
11370
  throw error;
11227
11371
  }
11228
11372
  const token = `${process.pid}-${randomBytes3(8).toString("hex")}`;
11229
- fs13.writeFileSync(path17.join(lock, LOCK_OWNER), token);
11373
+ fs13.writeFileSync(path18.join(lock, LOCK_OWNER), token);
11230
11374
  return token;
11231
11375
  },
11232
11376
  release(lock, token) {
@@ -11289,7 +11433,7 @@ function withLedgerLock(file, fn, waitMs = hostAwareLockTimeout(LOCK_WAIT_MS2))
11289
11433
  ledgerLock.release(lock, token);
11290
11434
  }
11291
11435
  }
11292
- var sha2562 = (text) => createHash9("sha256").update(text).digest("hex");
11436
+ var sha2562 = (text) => createHash10("sha256").update(text).digest("hex");
11293
11437
  var chainHash = (prevHash, body) => sha2562(`${prevHash ?? ""}
11294
11438
  ${body}`);
11295
11439
  var TAIL_BYTES = 64 * 1024;
@@ -11351,8 +11495,8 @@ ${line.value}`);
11351
11495
  }
11352
11496
  };
11353
11497
  try {
11354
- fs13.mkdirSync(path17.dirname(file), { recursive: true });
11355
- if (options.heldLock || !options.forceLock && !onNetworkFs(path17.dirname(file)))
11498
+ fs13.mkdirSync(path18.dirname(file), { recursive: true });
11499
+ if (options.heldLock || !options.forceLock && !onNetworkFs(path18.dirname(file)))
11356
11500
  return write();
11357
11501
  const locked = withLedgerLock(file, write);
11358
11502
  return locked ?? err("busy", `ledger lock ${file}.lock is held`, "retry; remove the .lock directory if no workit process is running");
@@ -11369,7 +11513,7 @@ var sealed = (row, id, at, previous) => {
11369
11513
  ` };
11370
11514
  };
11371
11515
  function appendRaw(cwd, row, options) {
11372
- const file = options.store ? { ok: true, value: path17.join(options.store.root, "ledger", "ledger.jsonl") } : ledgerPath(cwd);
11516
+ const file = options.store ? { ok: true, value: path18.join(options.store.root, "ledger", "ledger.jsonl") } : ledgerPath(cwd);
11373
11517
  if (!file.ok)
11374
11518
  return file;
11375
11519
  const id = newId2();
@@ -12025,7 +12169,7 @@ function remoteIdentity(cwd, hop = 0) {
12025
12169
  return null;
12026
12170
  if (hop === 0 && !/^[\w+.-]+:\/\/|^[^/\\]+@[^/\\]+:/u.test(raw)) {
12027
12171
  const local = raw.replace(/^file:\/\//u, "");
12028
- const resolved = path17.isAbsolute(local) ? local : path17.resolve(cwd, local);
12172
+ const resolved = path18.isAbsolute(local) ? local : path18.resolve(cwd, local);
12029
12173
  if (fs13.existsSync(resolved))
12030
12174
  return remoteIdentity(resolved, 1);
12031
12175
  }
@@ -12046,8 +12190,8 @@ function verdictMirrorPath(cwd) {
12046
12190
  }
12047
12191
  if (!identity)
12048
12192
  return null;
12049
- const key = createHash9("sha256").update(identity).digest("hex").slice(0, 32);
12050
- return path17.join(resolveStateDir(), "verdicts", key, "ledger.jsonl");
12193
+ const key = createHash10("sha256").update(identity).digest("hex").slice(0, 32);
12194
+ return path18.join(resolveStateDir(), "verdicts", key, "ledger.jsonl");
12051
12195
  }
12052
12196
  var importedStamp = new Map;
12053
12197
  function importMirroredVerdicts(cwd, branch) {
@@ -12070,7 +12214,7 @@ function importMirroredVerdicts(cwd, branch) {
12070
12214
  const candidates = mirror.value.rows.filter((row) => (row.type === "verdict" || row.type === VOID_TYPE) && row.branch === branch && row.integrity === "verified");
12071
12215
  const added = new Set;
12072
12216
  try {
12073
- fs13.mkdirSync(path17.dirname(local.value), { recursive: true });
12217
+ fs13.mkdirSync(path18.dirname(local.value), { recursive: true });
12074
12218
  } catch {
12075
12219
  return [];
12076
12220
  }
@@ -12186,7 +12330,7 @@ var productDecision = (task, ledger) => {
12186
12330
  };
12187
12331
  };
12188
12332
  var planRecorded = (task, root) => {
12189
- const cited = (latestJudgment(task)?.refs ?? []).find((ref) => ref.kind === "external" || ref.kind === "file" && existsSync7(path18.resolve(root, ref.path)));
12333
+ const cited = (latestJudgment(task)?.refs ?? []).find((ref) => ref.kind === "external" || ref.kind === "file" && existsSync7(path19.resolve(root, ref.path)));
12190
12334
  if (cited)
12191
12335
  return {
12192
12336
  met: true,
@@ -12263,15 +12407,15 @@ function writeBlockers(task, root) {
12263
12407
  }
12264
12408
 
12265
12409
  // packages/workit-core/src/core/task-evaluation.ts
12266
- var digestBytes = (value) => createHash10("sha256").update(value).digest("hex");
12267
- var inside = (root, candidate) => candidate === root || candidate.startsWith(`${root}${path19.sep}`);
12268
- var relative = (root, candidate) => path19.relative(root, candidate).split(path19.sep).join("/") || ".";
12410
+ var digestBytes = (value) => createHash11("sha256").update(value).digest("hex");
12411
+ var inside = (root, candidate) => candidate === root || candidate.startsWith(`${root}${path20.sep}`);
12412
+ var relative = (root, candidate) => path20.relative(root, candidate).split(path20.sep).join("/") || ".";
12269
12413
  var canonicalPath = (value) => {
12270
12414
  if (typeof value !== "string" || !value)
12271
12415
  return null;
12272
12416
  if (value.includes("\\") || value.split("/").includes(".."))
12273
12417
  return null;
12274
- const normalized = path19.posix.normalize(value);
12418
+ const normalized = path20.posix.normalize(value);
12275
12419
  if (normalized === ".." || normalized.startsWith("../") || normalized.startsWith("/"))
12276
12420
  return null;
12277
12421
  return normalized === "." ? "." : normalized.replace(/\/$/, "");
@@ -12319,14 +12463,14 @@ var gitPaths = (root) => {
12319
12463
  git: !/not a git repository/i.test(stderr)
12320
12464
  };
12321
12465
  }
12322
- const paths = result.stdout ? result.stdout.toString("utf8").split("\x00").filter(Boolean).map((item) => item.split(path19.sep).join("/")) : [];
12466
+ const paths = result.stdout ? result.stdout.toString("utf8").split("\x00").filter(Boolean).map((item) => item.split(path20.sep).join("/")) : [];
12323
12467
  const stagedDeleted = spawnSync12("git", ["diff", "--cached", "--name-only", "--diff-filter=D", "-z"], { cwd: root, encoding: "buffer" });
12324
12468
  if (stagedDeleted.status !== 0) {
12325
12469
  const stderr = stagedDeleted.stderr?.toString("utf8") ?? "";
12326
12470
  if (!/not a git repository/i.test(stderr))
12327
12471
  return { paths, uncertain: true, git: true };
12328
12472
  } else if (stagedDeleted.stdout) {
12329
- paths.push(...stagedDeleted.stdout.toString("utf8").split("\x00").filter(Boolean).map((item) => item.split(path19.sep).join("/")));
12473
+ paths.push(...stagedDeleted.stdout.toString("utf8").split("\x00").filter(Boolean).map((item) => item.split(path20.sep).join("/")));
12330
12474
  }
12331
12475
  return { paths: [...new Set(paths)], uncertain: false, git: true };
12332
12476
  };
@@ -12341,7 +12485,7 @@ var walk = (root, directory, output) => {
12341
12485
  for (const name of names) {
12342
12486
  if (name === ".git" || name === ".workit")
12343
12487
  continue;
12344
- const target = path19.join(directory, name);
12488
+ const target = path20.join(directory, name);
12345
12489
  let stat;
12346
12490
  try {
12347
12491
  stat = fs14.lstatSync(target);
@@ -12359,12 +12503,12 @@ var walk = (root, directory, output) => {
12359
12503
  var scopeRoots = (root, scope) => {
12360
12504
  const roots = [];
12361
12505
  for (const item of scope.paths.length ? scope.paths : ["."]) {
12362
- const target = path19.resolve(root, item);
12506
+ const target = path20.resolve(root, item);
12363
12507
  if (!inside(root, target))
12364
12508
  return failure2("invalid_input", `candidate scope escapes checkout: ${item} — keep one task per repository and coordinate a separate linked task in the other checkout`, { fields: [{ path: "scope.paths", reason: `${item} is outside the checkout` }] });
12365
12509
  let ancestor = target;
12366
12510
  while (!fs14.existsSync(ancestor) && ancestor !== root)
12367
- ancestor = path19.dirname(ancestor);
12511
+ ancestor = path20.dirname(ancestor);
12368
12512
  try {
12369
12513
  if (!inside(root, fs14.realpathSync(ancestor)))
12370
12514
  return failure2("invalid_input", `candidate scope escapes checkout through a symlink: ${item} — keep one task per repository and coordinate a separate linked task in the other checkout`, { fields: [{ path: "scope.paths", reason: `${item} resolves outside the checkout` }] });
@@ -12416,7 +12560,7 @@ function captureCandidate(root, scope, environment = []) {
12416
12560
  for (const item of [...names].toSorted()) {
12417
12561
  if (!scopeMatches(item, normalizedScope))
12418
12562
  continue;
12419
- const target = path19.join(checkout, item);
12563
+ const target = path20.join(checkout, item);
12420
12564
  try {
12421
12565
  const stat = fs14.lstatSync(target);
12422
12566
  if (stat.isSymbolicLink()) {
@@ -12585,23 +12729,23 @@ var verifyDecisionContentAtRoot = (checkoutRoot, binding) => {
12585
12729
  continue;
12586
12730
  if (!reference.digest)
12587
12731
  return failure2("invalid_input", "document references require a byte digest");
12588
- const target = path19.resolve(root, reference.path);
12589
- if (target !== root && !target.startsWith(`${root}${path19.sep}`))
12732
+ const target = path20.resolve(root, reference.path);
12733
+ if (target !== root && !target.startsWith(`${root}${path20.sep}`))
12590
12734
  return failure2("invalid_input", "document reference escapes checkout; cite it as an external file:// reference instead", {
12591
12735
  fields: [
12592
12736
  { path: "contentRefs.path", reason: `${reference.path} is outside the checkout` }
12593
12737
  ]
12594
12738
  });
12595
12739
  try {
12596
- const below = path19.relative(root, target);
12740
+ const below = path20.relative(root, target);
12597
12741
  let current = root;
12598
- for (const segment of below.split(path19.sep)) {
12742
+ for (const segment of below.split(path20.sep)) {
12599
12743
  if (!segment)
12600
12744
  continue;
12601
- current = path19.join(current, segment);
12745
+ current = path20.join(current, segment);
12602
12746
  const stat = fs14.lstatSync(current);
12603
12747
  const real = fs14.realpathSync(current);
12604
- if (real !== root && !real.startsWith(`${root}${path19.sep}`))
12748
+ if (real !== root && !real.startsWith(`${root}${path20.sep}`))
12605
12749
  return failure2("invalid_input", "document reference escapes checkout; cite it as an external file:// reference instead", {
12606
12750
  fields: [
12607
12751
  {
@@ -13099,7 +13243,7 @@ function entryCompactContext(store, entry, session, context) {
13099
13243
  current: () => recentSignal(store.root)
13100
13244
  };
13101
13245
  const observed = task?.data.evidence.some(isObservedCheck) ?? false;
13102
- const files = (task?.data.decisions ?? []).flatMap((decision) => decision.data.binding.contentRefs.flatMap((ref) => ref.kind === "file" ? [path20.resolve(store.root, ref.path)] : []));
13246
+ const files = (task?.data.decisions ?? []).flatMap((decision) => decision.data.binding.contentRefs.flatMap((ref) => ref.kind === "file" ? [path21.resolve(store.root, ref.path)] : []));
13103
13247
  const observedFiles = filesKey(files);
13104
13248
  const compact = compactContext(store, context, entry?.id ?? null, freshness, origin && { origin: origin.origin, taskId: origin.entry.id });
13105
13249
  if (!compact.ok || !compact.data)
@@ -13158,17 +13302,17 @@ ${options.addendum}` : ""}
13158
13302
  </workit-contract>`;
13159
13303
  };
13160
13304
  var checkoutAt = (cwd) => {
13161
- for (let dir = path20.resolve(cwd);; dir = path20.dirname(dir)) {
13162
- const dotGit = path20.join(dir, ".git");
13305
+ for (let dir = path21.resolve(cwd);; dir = path21.dirname(dir)) {
13306
+ const dotGit = path21.join(dir, ".git");
13163
13307
  if (fs15.existsSync(dotGit)) {
13164
- const admin = fs15.statSync(dotGit).isFile() ? path20.resolve(dir, /^gitdir:\s*(.+)$/mu.exec(fs15.readFileSync(dotGit, "utf8"))?.[1]?.trim() ?? "") : dotGit;
13165
- const head = fs15.readFileSync(path20.join(admin, "HEAD"), "utf8").trim();
13308
+ const admin = fs15.statSync(dotGit).isFile() ? path21.resolve(dir, /^gitdir:\s*(.+)$/mu.exec(fs15.readFileSync(dotGit, "utf8"))?.[1]?.trim() ?? "") : dotGit;
13309
+ const head = fs15.readFileSync(path21.join(admin, "HEAD"), "utf8").trim();
13166
13310
  return {
13167
13311
  root: dir,
13168
13312
  branch: /^ref: refs\/heads\/(.+)$/u.exec(head)?.[1] ?? null
13169
13313
  };
13170
13314
  }
13171
- if (path20.dirname(dir) === dir)
13315
+ if (path21.dirname(dir) === dir)
13172
13316
  return null;
13173
13317
  }
13174
13318
  };
@@ -13179,7 +13323,7 @@ var whereLine = (cwd) => {
13179
13323
  return null;
13180
13324
  const allowed = branchPolicySnapshotFor(cwd).namePolicy.allowed;
13181
13325
  const kinds = allowed.some((pattern) => pattern.source === "^.*$") ? "any" : allowedKinds(allowed).join(", ") || "see `workit help git`";
13182
- const place = checkout.root === path20.resolve(cwd) ? "" : ` in ${checkout.root}`;
13326
+ const place = checkout.root === path21.resolve(cwd) ? "" : ` in ${checkout.root}`;
13183
13327
  return `cwd ${cwd}${place} on ${checkout.branch ?? "detached HEAD"}; branch kinds: ${kinds}`;
13184
13328
  } catch {
13185
13329
  return null;
@@ -13197,7 +13341,7 @@ var turnContextText = (input, descriptor) => {
13197
13341
  }
13198
13342
  };
13199
13343
  var TURN_TTL_MS = 7 * 24 * 60 * 60 * 1000;
13200
- var digestOf = (text) => createHash11("sha256").update(text).digest("hex");
13344
+ var digestOf = (text) => createHash12("sha256").update(text).digest("hex");
13201
13345
  var turnMarker = (input) => {
13202
13346
  if (!input.session.id)
13203
13347
  return null;
@@ -13206,14 +13350,14 @@ var turnMarker = (input) => {
13206
13350
  if (location instanceof Error)
13207
13351
  return null;
13208
13352
  const session = [input.host, input.session.id, input.session.agentId ?? ""].join("\x00");
13209
- return path20.join(location.dir, "hooks", `turn-${digestOf(session).slice(0, 32)}.json`);
13353
+ return path21.join(location.dir, "hooks", `turn-${digestOf(session).slice(0, 32)}.json`);
13210
13354
  } catch {
13211
13355
  return null;
13212
13356
  }
13213
13357
  };
13214
13358
  var writeTurnDigest = (file, digest) => {
13215
13359
  try {
13216
- fs15.mkdirSync(path20.dirname(file), { recursive: true });
13360
+ fs15.mkdirSync(path21.dirname(file), { recursive: true });
13217
13361
  fs15.writeFileSync(file, `${JSON.stringify({ digest })}
13218
13362
  `);
13219
13363
  } catch {}
@@ -13228,7 +13372,7 @@ var pruneTurnDigests = (dir, now) => {
13228
13372
  for (const name of fs15.readdirSync(dir)) {
13229
13373
  if (!name.startsWith("turn-"))
13230
13374
  continue;
13231
- const file = path20.join(dir, name);
13375
+ const file = path21.join(dir, name);
13232
13376
  try {
13233
13377
  if (now - fs15.statSync(file).mtimeMs > TURN_TTL_MS)
13234
13378
  fs15.rmSync(file, { force: true });
@@ -13258,7 +13402,7 @@ var seedTurnContext = (input, descriptor, text = turnContextText(input, descript
13258
13402
  const file = turnMarker(input);
13259
13403
  if (!file)
13260
13404
  return;
13261
- pruneTurnDigests(path20.dirname(file), Date.now());
13405
+ pruneTurnDigests(path21.dirname(file), Date.now());
13262
13406
  if (text)
13263
13407
  writeTurnDigest(file, digestOf(text));
13264
13408
  else
@@ -13283,20 +13427,20 @@ import path23 from "node:path";
13283
13427
  // packages/workit-core/src/core/eval-world.ts
13284
13428
  import { existsSync as existsSync9, realpathSync as realpathSync7 } from "node:fs";
13285
13429
  import os5 from "node:os";
13286
- import path21 from "node:path";
13430
+ import path22 from "node:path";
13287
13431
  var EVAL_WORLD_ENV = "WORKIT_EVAL_WORLD";
13288
13432
  var EVAL_WORLD_MARKER = ".workit-eval-world";
13289
13433
  var inside2 = (dir, file) => {
13290
- const rel = path21.relative(dir, file);
13291
- return !rel.startsWith("..") && !path21.isAbsolute(rel);
13434
+ const rel = path22.relative(dir, file);
13435
+ return !rel.startsWith("..") && !path22.isAbsolute(rel);
13292
13436
  };
13293
13437
  var evalWorld = (cwd) => {
13294
13438
  const raw = process.env[EVAL_WORLD_ENV];
13295
- if (!raw || !path21.isAbsolute(raw))
13439
+ if (!raw || !path22.isAbsolute(raw))
13296
13440
  return null;
13297
13441
  try {
13298
13442
  const world = realpathSync7(raw);
13299
- return inside2(realpathSync7(os5.tmpdir()), world) && inside2(world, realpathSync7(cwd)) && existsSync9(path21.join(world, EVAL_WORLD_MARKER)) ? world : null;
13443
+ return inside2(realpathSync7(os5.tmpdir()), world) && inside2(world, realpathSync7(cwd)) && existsSync9(path22.join(world, EVAL_WORLD_MARKER)) ? world : null;
13300
13444
  } catch {
13301
13445
  return null;
13302
13446
  }
@@ -13304,77 +13448,12 @@ var evalWorld = (cwd) => {
13304
13448
  var evalWorldEntry = (cwd) => {
13305
13449
  const world = evalWorld(cwd);
13306
13450
  try {
13307
- return world ? loadWorkspacesFrom(path21.join(world, "config"))[0] ?? null : null;
13451
+ return world ? loadWorkspacesFrom(path22.join(world, "config"))[0] ?? null : null;
13308
13452
  } catch {
13309
13453
  return null;
13310
13454
  }
13311
13455
  };
13312
13456
 
13313
- // packages/workit-core/src/core/grant-seal.ts
13314
- import { createHash as createHash12 } from "node:crypto";
13315
- import { readFileSync as readFileSync9 } from "node:fs";
13316
- import path22 from "node:path";
13317
- var SEAL_FILE = "workspaces.json.seal";
13318
- var SEAL_VERSION = 1;
13319
- var SEAL_COMMAND = "workit workspace seal";
13320
- var pick3 = (value, keys) => {
13321
- if (!value || typeof value !== "object" || Array.isArray(value))
13322
- return;
13323
- const out = Object.fromEntries(keys.flatMap((key) => {
13324
- const item = value[key];
13325
- return item === undefined ? [] : [[key, item]];
13326
- }));
13327
- return Object.keys(out).length > 0 ? out : undefined;
13328
- };
13329
- var ENTRY_KEYS = [
13330
- "name",
13331
- "glob",
13332
- "remotes",
13333
- "externalRepos",
13334
- "additiveRiskPaths",
13335
- "vcs",
13336
- "autonomy",
13337
- "autoApprove",
13338
- "defaultEndpoint",
13339
- "verification",
13340
- "youtrack"
13341
- ];
13342
- var IDENTITY_KEYS = ["provider", "account", "tokenFile", "host"];
13343
- var sealProjection = (entries) => entries.map((entry) => {
13344
- const all = pick3(entry, ENTRY_KEYS) ?? {};
13345
- return pick3({
13346
- ...all,
13347
- vcs: pick3(all.vcs, IDENTITY_KEYS),
13348
- youtrack: pick3(all.youtrack, ["writes", "autoHosts"])
13349
- }, ENTRY_KEYS);
13350
- });
13351
- var canonical4 = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : item);
13352
- var sealDigest = (projection) => createHash12("sha256").update(canonical4(projection)).digest("hex");
13353
- var broken = (reason, sealed = null) => ({
13354
- state: "broken",
13355
- reason,
13356
- sealed
13357
- });
13358
- function checkSeal(dir) {
13359
- const file = path22.join(dir, SEAL_FILE);
13360
- let seal;
13361
- try {
13362
- seal = JSON.parse(readFileSync9(file, "utf8"));
13363
- } catch (error) {
13364
- if (error.code === "ENOENT")
13365
- return { state: "none" };
13366
- return broken(`${SEAL_FILE} cannot be read`);
13367
- }
13368
- if (seal?.version !== SEAL_VERSION || !Array.isArray(seal.projection) || seal.sha256 !== sealDigest(seal.projection))
13369
- return broken(`${SEAL_FILE} is malformed`);
13370
- const sealed = validateWorkspacesDocument({ workspaces: seal.projection }, file);
13371
- if (sealed.status !== "valid")
13372
- return broken(`${SEAL_FILE} is malformed`);
13373
- const current = readWorkspacesResult(dir);
13374
- const ok = current.status === "valid" || current.status === "missing";
13375
- return ok && sealDigest(sealProjection(current.entries)) === seal.sha256 ? { state: "valid" } : broken("workspaces.json changed since it was sealed", sealed.entries);
13376
- }
13377
-
13378
13457
  // packages/workit-core/src/forge/redact.ts
13379
13458
  var NAME = "[A-Za-z0-9_.-]";
13380
13459
  var KEY = String.raw`(?<!${NAME})(?=${NAME}*?(?:token|secret|password|passwd|pwd|api[_-]?key|access[_-]?key|account[_-]?key|private[_-]?key|client[_-]?secret|credentials?|authorization|cookie|signature))${NAME}+`;
@@ -13455,7 +13534,7 @@ var sealOf = () => {
13455
13534
  var SEAL_UNBLOCK = `if the user made this change, ask them to run, in their own terminal: ${SEAL_COMMAND}`;
13456
13535
  var NO_SEAL_UNBLOCK = `ask the user to review and seal the grants, in their own terminal: ${SEAL_COMMAND}`;
13457
13536
  var NO_SEAL_NOTE = `workspaces.json has no seal yet (${SEAL_COMMAND} has never run), so grants, endpoint, verification and youtrack.writes stay at or below the D4 defaults; ${NO_SEAL_UNBLOCK}`;
13458
- var sealNote = (seal = sealOf()) => seal.state === "broken" ? `workspaces.json does not match its seal (${seal.reason}), so grants, endpoint, verification and youtrack.writes are the stricter of their current and last sealed values; ${SEAL_UNBLOCK}` : null;
13537
+ var sealNote = (seal = sealOf()) => seal.state === "broken" ? `workspaces.json does not match its seal (${seal.reason}), so grants, endpoint, verification and youtrack.writes are the stricter of their current and last sealed values, and a sealed releaseNotes review stays; ${SEAL_UNBLOCK}` : null;
13459
13538
  var ASK = { mode: "ask" };
13460
13539
  var youtrackOf = (entry) => entry?.youtrack;
13461
13540
  var autoHostsOf = (entry) => {
@@ -13871,7 +13950,14 @@ var SCOPE_FIELDS = new Set([
13871
13950
  "autoApprove",
13872
13951
  "defaultEndpoint",
13873
13952
  "verification",
13874
- "youtrack"
13953
+ "youtrack",
13954
+ "releaseNotes",
13955
+ "releaseTagPrefix",
13956
+ "branchPolicy",
13957
+ "profiles",
13958
+ "defaultProfile",
13959
+ "releaseTracks",
13960
+ "releasePackages"
13875
13961
  ]);
13876
13962
 
13877
13963
  // packages/workit-core/src/core/release-packages.ts
@@ -14300,9 +14386,9 @@ var arithmeticEnd = (command, start) => {
14300
14386
  const end = substitutionEnd(command, start);
14301
14387
  return command[end - 1] === ")" && end > start + 2 ? end : 0;
14302
14388
  };
14303
- var segmentsOf = (command, dialect = "posix") => {
14389
+ var segmentsOf = (command, dialect = "posix", options = {}) => {
14304
14390
  try {
14305
- return tokenize(command, dialect);
14391
+ return tokenize(command, dialect, options.spans === true);
14306
14392
  } catch (error) {
14307
14393
  const why = error instanceof ShellAnalysisError ? error.message : String(error);
14308
14394
  return [{ words: [], redirects: [], unanalyzable: why }];
@@ -14312,12 +14398,14 @@ var afterEnv = (words) => {
14312
14398
  const at = words.map((word) => word.split(/[\\/]/).at(-1)).lastIndexOf("env");
14313
14399
  return at >= 0 && words.slice(at + 1).every((word, index, rest) => /^-|=/.test(word) || /^-[^-]*[uCS]$|^--(?:unset|chdir|split-string)$/.test(rest[index - 1] ?? ""));
14314
14400
  };
14315
- var tokenize = (command, dialect) => {
14401
+ var tokenize = (command, dialect, spans) => {
14316
14402
  const posix = dialect === "posix";
14317
14403
  const segments = [];
14318
14404
  let current = { words: [], redirects: [] };
14319
14405
  let word = "";
14320
14406
  let inWord = false;
14407
+ let wordStart = -1;
14408
+ let cursor = 0;
14321
14409
  let expanding = false;
14322
14410
  let afterOperator = false;
14323
14411
  let pending = null;
@@ -14328,9 +14416,13 @@ var tokenize = (command, dialect) => {
14328
14416
  if (!inWord)
14329
14417
  return;
14330
14418
  const text = MARKERS.test(word) ? literal2(word) : word;
14419
+ const span = [wordStart, cursor];
14331
14420
  if (pending === "redirect") {
14332
- if (!duplicate || !/^(?:\d+-?|-)$/.test(text))
14421
+ if (!duplicate || !/^(?:\d+-?|-)$/.test(text)) {
14333
14422
  current.redirects.push(text);
14423
+ if (spans)
14424
+ (current.redirectSpans ??= []).push(span);
14425
+ }
14334
14426
  } else if (pending === "heredoc")
14335
14427
  heredocs.push({ delimiter: text.replace(/^-/, ""), owner: current });
14336
14428
  else if (pending === "herestring")
@@ -14338,17 +14430,20 @@ var tokenize = (command, dialect) => {
14338
14430
  else if (pending === "input")
14339
14431
  (current.inputs ??= []).push(text);
14340
14432
  else {
14341
- const at = current.words.length;
14433
+ const at0 = current.words.length;
14342
14434
  if (/^[^=-][^=]*=/.test(word) && afterEnv(current.words))
14343
14435
  word = word.replace(/^[^=]*/, (name) => name.replace(/\W/g, "_"));
14344
14436
  current.words.push(...MARKERS.test(word) ? expandBraces(word) : [word]);
14437
+ if (spans)
14438
+ (current.spans ??= []).push(...current.words.slice(at0).map(() => span));
14345
14439
  if (expanding || !posix && word.startsWith("@"))
14346
- (current.expands ??= []).push(...current.words.slice(at).map((_, i) => at + i));
14440
+ (current.expands ??= []).push(...current.words.slice(at0).map((_, i) => at0 + i));
14347
14441
  }
14348
14442
  pending = null;
14349
14443
  duplicate = false;
14350
14444
  word = "";
14351
14445
  inWord = false;
14446
+ wordStart = -1;
14352
14447
  expanding = false;
14353
14448
  };
14354
14449
  const flushSegment = () => {
@@ -14373,9 +14468,12 @@ var tokenize = (command, dialect) => {
14373
14468
  };
14374
14469
  const plain = posix ? PLAIN_POSIX : PLAIN_POWERSHELL;
14375
14470
  for (let index = 0;index < command.length; index++) {
14471
+ cursor = index;
14376
14472
  plain.lastIndex = index;
14377
14473
  const run = plain.exec(command);
14378
14474
  if (run) {
14475
+ if (wordStart < 0)
14476
+ wordStart = index;
14379
14477
  word += run[0];
14380
14478
  inWord = true;
14381
14479
  if (EXPANDING_RUN.test(run[0]))
@@ -14401,9 +14499,11 @@ var tokenize = (command, dialect) => {
14401
14499
  word += text;
14402
14500
  inWord = true;
14403
14501
  index = end;
14404
- } else if (posix && char === "$" && next === '"')
14502
+ } else if (posix && char === "$" && next === '"') {
14503
+ if (wordStart < 0)
14504
+ wordStart = index;
14405
14505
  continue;
14406
- else if (char === "'" || char === '"') {
14506
+ } else if (char === "'" || char === '"') {
14407
14507
  const end = closingQuote(command, index, dialect);
14408
14508
  const body = command.slice(index + 1, end < 0 ? undefined : end);
14409
14509
  if (posix && char === '"' && /\$\(|`/.test(body))
@@ -14444,6 +14544,7 @@ var tokenize = (command, dialect) => {
14444
14544
  index = end;
14445
14545
  } else if (posix && char === "(" && (pending === "input" || pending === "redirect")) {
14446
14546
  const sign = pending === "input" ? "<" : ">";
14547
+ wordStart = index - 1;
14447
14548
  pending = null;
14448
14549
  const end = substitutionEnd(command, index);
14449
14550
  const inner = command.slice(index + 1, end);
@@ -14456,8 +14557,10 @@ var tokenize = (command, dialect) => {
14456
14557
  if (char === "(" && inWord && word.endsWith("$")) {
14457
14558
  word = word.slice(0, -1);
14458
14559
  inWord = word !== "";
14459
- if (!inWord)
14560
+ if (!inWord) {
14460
14561
  expanding = false;
14562
+ wordStart = -1;
14563
+ }
14461
14564
  }
14462
14565
  group(char === "(" ? "open" : "close");
14463
14566
  } else if (!posix && (char === "{" || char === "}")) {
@@ -14492,6 +14595,7 @@ var tokenize = (command, dialect) => {
14492
14595
  if (inWord && /^\d$/.test(word)) {
14493
14596
  word = "";
14494
14597
  inWord = false;
14598
+ wordStart = -1;
14495
14599
  } else
14496
14600
  flushWord();
14497
14601
  if (command[index + 1] === ">")
@@ -14523,7 +14627,10 @@ var tokenize = (command, dialect) => {
14523
14627
  word += char;
14524
14628
  inWord = true;
14525
14629
  }
14630
+ if (inWord && wordStart < 0)
14631
+ wordStart = cursor;
14526
14632
  }
14633
+ cursor = command.length;
14527
14634
  flushSegment();
14528
14635
  return segments;
14529
14636
  };
@@ -20755,8 +20862,8 @@ var writeTargets = (input) => {
20755
20862
  return paths.length > 0 ? paths : null;
20756
20863
  };
20757
20864
  // packages/workit-core/src/hooks/standing.ts
20758
- import fs23 from "node:fs";
20759
- import path36 from "node:path";
20865
+ import fs24 from "node:fs";
20866
+ import path37 from "node:path";
20760
20867
 
20761
20868
  // packages/workit-core/src/approvals/store.ts
20762
20869
  var REQUEST_TTL_MS = 30 * 60000;
@@ -20809,92 +20916,271 @@ var approveCallIn = (command, dialect = "posix") => {
20809
20916
  };
20810
20917
  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
20918
 
20812
- // packages/workit-core/src/approvals/youtrack-ask.ts
20813
- var TIME = "markdown file minutes text date";
20814
- var FLAGS = {
20815
- note: TIME,
20816
- time: TIME,
20817
- meeting: TIME,
20818
- update: `${TIME} attach state command`,
20819
- create: "project summary description file attach command"
20919
+ // packages/workit-core/src/hooks/cwd-normalize.ts
20920
+ var DIR = String.raw`(?:[A-Za-z0-9_./@%+:,=-]|(?<=[A-Za-z0-9])~)+|'[^'$${"`"}\n]*'|"(?:[^"$${"`"}\\!\n]|\\(?=[^"$${"`"}\\!\n]))*"`;
20921
+ var COMPOUND2 = new RegExp(String.raw`^\s*cd\s+(${DIR})\s*&&\s*(workit(?:\s[\s\S]*)?)$`, "u");
20922
+ var UNSAFE = /[\p{Cf}\p{Zl}\p{Zp}]|[^\P{Cc}\n]/u;
20923
+ var newlines = (text) => text.split(`
20924
+ `).length - 1;
20925
+ var writtenWord = (command, segment, index) => {
20926
+ const span = segment.spans?.[index];
20927
+ if (!span)
20928
+ return null;
20929
+ const glued = (other) => other !== undefined && other !== span && (other[1] === span[0] || other[0] === span[1]);
20930
+ if (glued(segment.spans?.[index - 1]) || glued(segment.spans?.[index + 1]))
20931
+ return null;
20932
+ const text = command.slice(span[0], span[1]);
20933
+ const value = segment.words[index] ?? "";
20934
+ return UNSAFE.test(text) || newlines(text) !== newlines(value) ? null : text;
20935
+ };
20936
+ var writtenWords = (command, segment, indexes) => {
20937
+ const texts = [];
20938
+ let last;
20939
+ for (const index of indexes) {
20940
+ const span = segment.spans?.[index];
20941
+ if (span && span === last)
20942
+ continue;
20943
+ last = span;
20944
+ const text = writtenWord(command, segment, index);
20945
+ if (text === null)
20946
+ return null;
20947
+ texts.push(text);
20948
+ }
20949
+ return texts;
20820
20950
  };
20821
-
20822
- // packages/workit-core/src/approvals/inline.ts
20823
- var DIR = "<dir>";
20824
- var OPAQUE_RELEASE_FIX = `workit release --cwd ${DIR} notes approve <version>`;
20825
-
20826
- // packages/workit-core/src/hooks/hosts/claude-code.ts
20827
- var CLAUDE_CODE_DESCRIPTOR = {
20828
- host: "claude_code",
20829
- label: "Claude Code",
20830
- verifiedAgainst: "claude 2.1.288 (hook zod schemas in the binary; SessionEnd: 2.1.327)",
20831
- docs: ["https://code.claude.com/docs/en/hooks"],
20832
- transport: "hook-process",
20833
- events: {
20834
- "session.start": { support: "native", native: "SessionStart" },
20835
- "session.end": { support: "native", native: "SessionEnd" },
20836
- "context.turn": { support: "native", native: "UserPromptSubmit" },
20837
- "shell.pre": { support: "native", native: "PreToolUse" },
20838
- "tool.pre": { support: "native", native: "PreToolUse" },
20839
- "write.pre": { support: "native", native: "PreToolUse" },
20840
- "shell.post": { support: "native", native: "PostToolUse" },
20841
- "subagent.start": { support: "native", native: "SubagentStart" },
20842
- "prompt.submit": { support: "native", native: "UserPromptSubmit" },
20843
- "subagent.stop": { support: "native", native: "SubagentStop" },
20844
- "compact.pre": { support: "none", native: null },
20845
- stop: { support: "native", native: "Stop" }
20846
- },
20847
- shellPolicy: {
20848
- deny: "native",
20849
- channel: "permissionDecision",
20850
- failClosed: false,
20851
- rewrite: "native"
20852
- },
20853
- context: {
20854
- sessionStart: "native",
20855
- perTurn: "native",
20856
- afterCompact: "native",
20857
- task: "session-bound",
20858
- turnResend: "on-change"
20859
- },
20860
- subagents: {
20861
- identity: "native",
20862
- parentBinding: "partial",
20863
- blockStart: "none",
20864
- worktreeIsolation: "native",
20865
- maxConcurrency: "undocumented",
20866
- agentPrefix: "workit:"
20867
- },
20868
- provenance: {
20869
- sessionId: "native",
20870
- agentIdOnTool: "native",
20871
- postToolObserve: "native"
20872
- },
20873
- interaction: { questions: "undocumented", writeBoundary: "partial" },
20874
- stopControl: "native",
20875
- shellAvailable: "native",
20876
- perEventCost: "low",
20877
- capabilities: [
20878
- {
20879
- name: "known_product_writes",
20880
- surface: "PreToolUse",
20881
- refs: ["PreToolUse"],
20882
- requires: [],
20883
- assurance: "unavailable",
20884
- reason: "file writes are host-policy; Claude Code permissions govern them"
20885
- },
20886
- {
20887
- name: "native_subagents",
20888
- surface: "SubagentStart",
20889
- refs: ["SubagentStart"],
20890
- requires: ["event:subagent.start"],
20891
- observed: ["subagent.start"],
20892
- assurance: "agent_guided",
20893
- reason: "Claude Code reports stable agent identities, but SubagentStart cannot block or bind",
20894
- unavailableReason: "Claude Code SubagentStart is unavailable"
20895
- },
20896
- {
20897
- name: "fresh-context-review",
20951
+ var cwdIndependent = (text, colons = false) => {
20952
+ let quoted = false;
20953
+ for (let index = 0;index < text.length; index += 1) {
20954
+ const char = text[index] ?? "";
20955
+ if (char === "\\")
20956
+ index += 1;
20957
+ else if (char === "'" && !quoted) {
20958
+ const end = text.indexOf("'", index + 1);
20959
+ if (end < 0)
20960
+ return false;
20961
+ index = end;
20962
+ } else if (char === '"')
20963
+ quoted = !quoted;
20964
+ else if (char === "$" || char === "`")
20965
+ return false;
20966
+ else if (quoted)
20967
+ continue;
20968
+ else if (/[*?[]/u.test(char) || /[<>]/u.test(char) && text[index + 1] === "(")
20969
+ return false;
20970
+ else if (char === "~") {
20971
+ const start = index === 0 || colons && text[index - 1] === ":";
20972
+ if (!start || !/^(?:\/|:|$)/u.test(text.slice(index + 1, index + 2)))
20973
+ return false;
20974
+ }
20975
+ }
20976
+ return !quoted;
20977
+ };
20978
+ var NOT_A_PATH = /^(?:\d*|true|false|yes|no|on|off|-[\w-]*(?:=\d+)?)$/iu;
20979
+ var cwdFreeAssignment = (text, value) => {
20980
+ const written = text.replace(/^[A-Za-z_]\w*=/u, "");
20981
+ if (!cwdIndependent(written, true))
20982
+ return false;
20983
+ const quotes = /['"\\]/u.test(written);
20984
+ const parts = value.replace(/^[A-Za-z_]\w*=/u, "").split(":");
20985
+ return parts.every((part) => part.startsWith("/") || !quotes && /^~(?:\/|$)/u.test(part) || (part !== "" || parts.length === 1) && NOT_A_PATH.test(part));
20986
+ };
20987
+ var plainQuotedExpansions = (text) => {
20988
+ const bare = text.replaceAll(/\\./gu, "").replaceAll(/\$(?:[A-Za-z_]\w*|\{[A-Za-z_]\w*\})/gu, "");
20989
+ return !bare.includes("$") && !bare.includes("`");
20990
+ };
20991
+ var certainDir = (text, value) => value !== "" && !value.startsWith("-") && (/^(?:"(?:[^"\\]|\\.)*"|'[^']*')$/u.test(text) && (text.startsWith("'") || plainQuotedExpansions(text)) || cwdIndependent(text) && !/[{}]/u.test(text.replaceAll(/'[^']*'|"(?:[^"\\]|\\.)*"|\\./gu, "")));
20992
+ var namesSet = (segments) => {
20993
+ const names = new Set;
20994
+ for (const { words } of segments) {
20995
+ const at = /^(?:export|declare|typeset|local|readonly)$/u.test(words[0] ?? "") ? 1 : 0;
20996
+ const assigns = words.slice(at).filter((word) => /^[A-Za-z_]\w*=/u.test(word));
20997
+ if (at === 1 || assigns.length === words.length)
20998
+ for (const word of assigns)
20999
+ names.add(word.slice(0, word.indexOf("=")));
21000
+ if (words[0] === "read" || words[0] === "mapfile") {
21001
+ for (const word of words.slice(1))
21002
+ if (/^[A-Za-z_]\w*$/u.test(word))
21003
+ names.add(word);
21004
+ }
21005
+ }
21006
+ return names;
21007
+ };
21008
+ var NO_PATH = /^(?:\d+|-[A-Za-z0-9-]*)$/u;
21009
+ var cwdFreeTail = (texts, check = false) => {
21010
+ const [command = "", ...args] = texts;
21011
+ if (command.includes("/") && !command.startsWith("/"))
21012
+ return false;
21013
+ return check || args.every((text) => NO_PATH.test(text) || /^(?:\/|~(?:\/|$))/u.test(text));
21014
+ };
21015
+ var GLOBALS_FIRST = new RegExp(String.raw`^(\s*workit)((?:\s+(?:--json|--cwd(?:=|\s+)(?:${DIR})))+)\s+([a-z][a-z-]*)(?=\s|$)`, "u");
21016
+ var VERB_FIRST = /^((?:--json\s+)*)([a-z][a-z-]*)(?=\s|$)/u;
21017
+ var VERBS = new Set(WORKIT_ALLOWED_VERBS);
21018
+ var FILTERS = new Set(["tail", "head", "grep"]);
21019
+ var clean = (s) => !s.unanalyzable && !s.group && !s.subs?.length && !s.stdin?.length && !s.redirects.length;
21020
+ var stdinOnly = (words) => {
21021
+ const [name, ...args] = words;
21022
+ const operands = args.filter((w) => !w.startsWith("-"));
21023
+ if (name === "grep")
21024
+ return operands.length <= 1 && !args.some((w) => /^-[^-]*[rRf]|^--(recursive|file)/u.test(w));
21025
+ return operands.every((w) => /^\d+$/u.test(w)) && !args.some((w) => w.startsWith("--output"));
21026
+ };
21027
+ var cwdRewrite = (command) => {
21028
+ const match = COMPOUND2.exec(command);
21029
+ const dir = match?.[1];
21030
+ const rest = match?.[2];
21031
+ if (!dir || !rest || dir.startsWith("-"))
21032
+ return null;
21033
+ if (/[&;<>`\n]/u.test(rest.replaceAll("2>&1", "").replaceAll(/'[^']*'|"([^"\\]|\\.)*"/gu, "")))
21034
+ return null;
21035
+ const segments = segmentsOf(rest);
21036
+ const [head, ...filters] = segments;
21037
+ if (!head || head.words[0] !== "workit")
21038
+ return null;
21039
+ if (!segments.every(clean))
21040
+ return null;
21041
+ if (!segments.slice(0, -1).every((s) => s.pipe))
21042
+ return null;
21043
+ if (!filters.every((s) => FILTERS.has(s.words[0] ?? "") && stdinOnly(s.words)))
21044
+ return null;
21045
+ const at = head.words.indexOf("--cwd");
21046
+ if (at >= 0) {
21047
+ const bare = dir.replace(/^(['"])(.*)\1$/u, "$2");
21048
+ return bare[0] === "/" && head.words[at + 1] === bare ? rest : null;
21049
+ }
21050
+ if (head.words.some((w) => w.startsWith("--cwd=")))
21051
+ return null;
21052
+ const args = rest.slice("workit".length).trimStart();
21053
+ const verb = VERB_FIRST.exec(args);
21054
+ if (!verb?.[2] || !VERBS.has(verb[2]))
21055
+ return `workit --cwd ${dir} ${args}`.trimEnd();
21056
+ const json = verb[1] ? " --json" : "";
21057
+ return `workit ${verb[2]} --cwd ${dir}${json}${args.slice(verb[0].length)}`.trimEnd();
21058
+ };
21059
+ var verbFirst = (command) => {
21060
+ const match = GLOBALS_FIRST.exec(command);
21061
+ const [whole, lead, globals, verb] = match ?? [];
21062
+ if (!whole || !verb || !VERBS.has(verb) || !globals?.includes("--cwd"))
21063
+ return null;
21064
+ const segments = segmentsOf(command);
21065
+ if (segments.length !== 1 || !segments.every(clean))
21066
+ return null;
21067
+ return `${lead} ${verb}${globals}${command.slice(whole.length)}`;
21068
+ };
21069
+ var NPX = new RegExp(String.raw`^(\s*(?:cd\s+(?:${DIR})\s*&&\s*)?)npx(?:\s+(?:-y|--yes))*\s+@workit-dev\/cli(?:@[\w.-]+)?(?=\s|$)`, "u");
21070
+ var npxWorkit = (command) => {
21071
+ const match = NPX.exec(command);
21072
+ if (!match)
21073
+ return null;
21074
+ const call = `${match[1]}workit${command.slice(match[0].length)}`;
21075
+ const left = segmentsOf(call).some((s) => s.unanalyzable || s.words.some((w) => /^(npx|@workit-dev\/cli(@\S*)?)$/u.test(w)));
21076
+ return left ? null : cwdRewrite(call) ?? verbFirst(call) ?? call;
21077
+ };
21078
+ 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;
21079
+ var cdWorkitSplit = (command) => {
21080
+ const match = COMPOUND2.exec(command);
21081
+ const dir = match?.[1];
21082
+ const rest = match?.[2];
21083
+ if (!dir || !rest || cwdRewrite(command) !== null)
21084
+ return null;
21085
+ const whole = segmentsOf(rest);
21086
+ const boundary = (head) => segmentsOf(head).every((s, at) => s.words.join("\x00") === whole[at]?.words.join("\x00"));
21087
+ for (const op of rest.matchAll(/\|\||;/gu)) {
21088
+ const head = rest.slice(0, op.index).trimEnd();
21089
+ const call = cwdRewrite(`cd ${dir} && ${head}`);
21090
+ if (!call || !boundary(head))
21091
+ continue;
21092
+ const next = segmentsOf(rest.slice(op.index + op[0].length))[0];
21093
+ return next && MUTATING_GIT2.test(next.words.join(" ")) ? call : null;
21094
+ }
21095
+ return null;
21096
+ };
21097
+
21098
+ // packages/workit-core/src/approvals/youtrack-ask.ts
21099
+ var TIME = "markdown file minutes text date";
21100
+ var FLAGS = {
21101
+ note: TIME,
21102
+ time: TIME,
21103
+ meeting: TIME,
21104
+ update: `${TIME} attach state command`,
21105
+ create: "project summary description file attach command"
21106
+ };
21107
+
21108
+ // packages/workit-core/src/approvals/inline.ts
21109
+ var DIR2 = "<dir>";
21110
+ var OPAQUE_RELEASE_FIX = `workit release --cwd ${DIR2} notes approve <version>`;
21111
+
21112
+ // packages/workit-core/src/hooks/hosts/claude-code.ts
21113
+ var CLAUDE_CODE_DESCRIPTOR = {
21114
+ host: "claude_code",
21115
+ label: "Claude Code",
21116
+ verifiedAgainst: "claude 2.1.288 (hook zod schemas in the binary; SessionEnd: 2.1.327)",
21117
+ docs: ["https://code.claude.com/docs/en/hooks"],
21118
+ transport: "hook-process",
21119
+ events: {
21120
+ "session.start": { support: "native", native: "SessionStart" },
21121
+ "session.end": { support: "native", native: "SessionEnd" },
21122
+ "context.turn": { support: "native", native: "UserPromptSubmit" },
21123
+ "shell.pre": { support: "native", native: "PreToolUse" },
21124
+ "tool.pre": { support: "native", native: "PreToolUse" },
21125
+ "write.pre": { support: "native", native: "PreToolUse" },
21126
+ "shell.post": { support: "native", native: "PostToolUse" },
21127
+ "subagent.start": { support: "native", native: "SubagentStart" },
21128
+ "prompt.submit": { support: "native", native: "UserPromptSubmit" },
21129
+ "subagent.stop": { support: "native", native: "SubagentStop" },
21130
+ "compact.pre": { support: "none", native: null },
21131
+ stop: { support: "native", native: "Stop" }
21132
+ },
21133
+ shellPolicy: {
21134
+ deny: "native",
21135
+ channel: "permissionDecision",
21136
+ failClosed: false,
21137
+ rewrite: "native"
21138
+ },
21139
+ context: {
21140
+ sessionStart: "native",
21141
+ perTurn: "native",
21142
+ afterCompact: "native",
21143
+ task: "session-bound",
21144
+ turnResend: "on-change"
21145
+ },
21146
+ subagents: {
21147
+ identity: "native",
21148
+ parentBinding: "partial",
21149
+ blockStart: "none",
21150
+ worktreeIsolation: "native",
21151
+ maxConcurrency: "undocumented",
21152
+ agentPrefix: "workit:"
21153
+ },
21154
+ provenance: {
21155
+ sessionId: "native",
21156
+ agentIdOnTool: "native",
21157
+ postToolObserve: "native"
21158
+ },
21159
+ interaction: { questions: "undocumented", writeBoundary: "partial" },
21160
+ stopControl: "native",
21161
+ shellAvailable: "native",
21162
+ perEventCost: "low",
21163
+ capabilities: [
21164
+ {
21165
+ name: "known_product_writes",
21166
+ surface: "PreToolUse",
21167
+ refs: ["PreToolUse"],
21168
+ requires: [],
21169
+ assurance: "unavailable",
21170
+ reason: "file writes are host-policy; Claude Code permissions govern them"
21171
+ },
21172
+ {
21173
+ name: "native_subagents",
21174
+ surface: "SubagentStart",
21175
+ refs: ["SubagentStart"],
21176
+ requires: ["event:subagent.start"],
21177
+ observed: ["subagent.start"],
21178
+ assurance: "agent_guided",
21179
+ reason: "Claude Code reports stable agent identities, but SubagentStart cannot block or bind",
21180
+ unavailableReason: "Claude Code SubagentStart is unavailable"
21181
+ },
21182
+ {
21183
+ name: "fresh-context-review",
20898
21184
  surface: "SubagentStart",
20899
21185
  refs: ["SubagentStart"],
20900
21186
  requires: ["event:subagent.start"],
@@ -21466,111 +21752,587 @@ function neededChecks(lane, configured) {
21466
21752
 
21467
21753
  // packages/workit-core/src/hooks/worktree-confine.ts
21468
21754
  import { createHash as createHash16 } from "node:crypto";
21469
- import fs22 from "node:fs";
21755
+ import fs23 from "node:fs";
21470
21756
  import os10 from "node:os";
21757
+ import path36 from "node:path";
21758
+
21759
+ // packages/workit-core/src/hooks/identity-env.ts
21760
+ import fs22 from "node:fs";
21471
21761
  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)) {
21762
+ var NAMES = "WORKIT_(?:AGENT_ID|HOST|SESSION_ID|SESSION_TOKEN)";
21763
+ var IDENTITY = new RegExp(`^${NAMES}$`, "u");
21764
+ var HOST_NAMES = "(?:OPENCODE_SESSION_ID|PI_SESSION_ID|CODEX_THREAD_ID|CLAUDECODE|CLAUDE_CODE_ENTRYPOINT)";
21765
+ var HOST_VARIABLE = new RegExp(`^${HOST_NAMES}$`, "u");
21766
+ var IDENTITY_ANY = new RegExp(NAMES, "iu");
21767
+ var STATE_NAMES = "(?:WORKIT_(?:STATE_DIR|CONFIG(?:_DIR)?)|XDG_(?:STATE|CONFIG|DATA)_HOME|HOME|USERPROFILE|(?:LOCAL)?APPDATA)";
21768
+ var STATE2 = new RegExp(`^${STATE_NAMES}$`, "u");
21769
+ var STATE_ANY = new RegExp(STATE_NAMES, "iu");
21770
+ var powershell = (names) => new RegExp([
21771
+ `\\$\\{?env:${names}\\}?\\s*(?:[-+*/]|\\?\\?)?=(?!=)`,
21772
+ `${PS_ITEM}[^;|\\n]*?(?<![$\\w{])env:[\\\\/]?${names}\\b`,
21773
+ `SetEnvironmentVariable\\(\\s*['"]${names}\\b`
21774
+ ].join("|"), "iu");
21775
+ 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";
21776
+ var POWERSHELL = powershell(NAMES);
21777
+ var POWERSHELL_STATE = powershell(STATE_NAMES);
21778
+ var POWERSHELL_HOST = powershell(HOST_NAMES);
21779
+ var POWERSHELL_OPAQUE = new RegExp([
21780
+ `SetEnvironmentVariable\\(\\s*(?:[^'"\\s]|"[^"]*\\$)`,
21781
+ `${PS_ITEM}[^;|\\n]*?(?<![$\\w{])env:[\\\\/]?["']?[$(]`,
21782
+ `(?:^|[;&|{(\\n])\\s*\\.\\s+[^\\s.]`,
21783
+ `\\b(?:iex|Invoke-Expression)\\b`
21784
+ ].join("|"), "iu");
21785
+ var cmdSet = (names) => new RegExp(`(?:^|[&|(\\s"])set\\s+(?:/[ap]\\s+)?"?(${names})\\s*\\+?=`, "iu");
21786
+ var CMD_IDENTITY = cmdSet(NAMES);
21787
+ var CMD_STATE = cmdSet(STATE_NAMES);
21788
+ var CMD_HOST = cmdSet(HOST_NAMES);
21789
+ var RUNS_TEXT = /\bworkit(?:-cli)?\b|@workit-dev[\\/]cli/iu;
21790
+ var DECLARES = new Set(["export", "unset", "declare", "typeset", "local", "readonly"]);
21791
+ var OPAQUE = new Set([
21792
+ "watch",
21793
+ "strace",
21794
+ "chroot",
21795
+ "flock",
21796
+ "ssh",
21797
+ "su",
21798
+ "runuser",
21799
+ "script",
21800
+ "parallel"
21801
+ ]);
21802
+ var ENV_VALUED = new Set(["u", "C", "S", "a", "P"]);
21803
+ var ENV_FLAGS = new Set(["i", "0", "v"]);
21804
+ var ENV_LONG_VALUED = new Set(["--unset", "--chdir", "--split-string", "--argv0"]);
21805
+ var ENV_LONG_FLAGS = /^--(?:ignore-environment|null|debug|(?:block|default|ignore)-signal(?:=.*)?)$/u;
21806
+ var base = (word) => (word?.split(/[\\/]/u).at(-1) ?? "").replace(/\.exe$/iu, "");
21807
+ var ASSIGN = /^[A-Za-z_]\w*\+?=/u;
21808
+ var nameOf = (word) => (word?.split("=")[0] ?? "").replace(/\+$/u, "");
21809
+ var named = (word) => IDENTITY.test(nameOf(word));
21810
+ var stateNamed = (word) => STATE2.test(nameOf(word));
21811
+ var isWorkit = (word) => /^workit(?:-cli)?(?:\.[cm]?js)?$/u.test(base(word)) || /@workit-dev[\\/]cli\b|workit-cli[\\/](?:dist|src)[\\/]/u.test(word ?? "");
21812
+ var linksToWorkit = (word, cwd) => {
21813
+ const places = /[\\/]/u.test(word) ? [path35.resolve(cwd ?? process.cwd(), word)] : (process.env.PATH ?? "").split(path35.delimiter).map((dir) => path35.join(dir, word));
21814
+ for (const place of places) {
21478
21815
  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
- }
21816
+ const real = fs22.realpathSync(place);
21817
+ return isWorkit(real);
21818
+ } catch {}
21485
21819
  }
21820
+ return false;
21486
21821
  };
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 === ".")
21822
+ var newSeg = () => ({ identity: null, scoped: null, runs: false, words: [] });
21823
+ var UNREADABLE = "env/unset arguments Workit cannot read";
21824
+ var note = (scan, seg, word) => {
21825
+ if (scan.identity && named(word)) {
21826
+ if (seg)
21827
+ seg.identity ??= nameOf(word);
21828
+ else
21829
+ scan.hit ??= nameOf(word);
21830
+ }
21831
+ if (!stateNamed(word) && !(scan.identity && HOST_VARIABLE.test(nameOf(word))))
21832
+ return;
21833
+ if (seg)
21834
+ seg.scoped ??= nameOf(word);
21835
+ else
21836
+ scan.shell ??= nameOf(word);
21837
+ };
21838
+ var mayBeWorkit = (words, cwd) => words.some(({ word, built }) => built || linksToWorkit(word, cwd));
21839
+ var scanEnv = (words, at, expands, scan, seg, depth) => {
21840
+ const risky = (what) => void (scan.risky ??= what);
21841
+ const unset = (name) => note(scan, seg, name);
21842
+ const split = (line, rest, built) => {
21843
+ if (line === undefined || depth >= 4)
21844
+ return risky(UNREADABLE);
21845
+ if (built || /[$`]/u.test(line))
21846
+ risky(UNREADABLE);
21847
+ const tokens = [];
21848
+ const expanded = new Set;
21849
+ try {
21850
+ for (const segment of segmentsOf(line)) {
21851
+ for (const index of segment.expands ?? [])
21852
+ expanded.add(tokens.length + index);
21853
+ tokens.push(...segment.words);
21854
+ }
21855
+ } catch {
21856
+ return risky(UNREADABLE);
21857
+ }
21858
+ scanEnv([...tokens, ...words.slice(rest)], 0, expanded, scan, seg, depth + 1);
21859
+ };
21860
+ let options = true;
21861
+ for (let index = at;index < words.length; index += 1) {
21862
+ const word = words[index] ?? "";
21863
+ if (expands.has(index)) {
21864
+ risky(UNREADABLE);
21865
+ const built = options ? /^(?:--split-string=|-[\w]*S)(.+)$/su.exec(word) : null;
21866
+ if (built)
21867
+ return split(built[1], index + 1, true);
21494
21868
  continue;
21495
- if (part === "..") {
21496
- at = path35.dirname(at);
21869
+ }
21870
+ if (options && word === "--") {
21871
+ options = false;
21497
21872
  continue;
21498
21873
  }
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";
21874
+ if (options && word === "-") {
21875
+ risky("env -i");
21876
+ continue;
21877
+ }
21878
+ if (options && word.startsWith("--")) {
21879
+ const [name = "", value] = word.split(/=(.*)/su);
21880
+ if (name === "--ignore-environment")
21881
+ risky("env -i");
21882
+ else if (name === "--unset")
21883
+ unset(value ?? words[index += 1]);
21884
+ else if (name === "--split-string")
21885
+ return split(value ?? words[index + 1], index + (value === undefined ? 2 : 1), expands.has(index + (value === undefined ? 1 : 0)));
21886
+ else if (ENV_LONG_VALUED.has(name))
21887
+ index += value === undefined ? 1 : 0;
21888
+ else if (!ENV_LONG_FLAGS.test(word))
21889
+ risky(UNREADABLE);
21890
+ continue;
21891
+ }
21892
+ if (options && word.startsWith("-") && word.length > 1) {
21893
+ for (let at2 = 1;at2 < word.length; at2 += 1) {
21894
+ const letter = word[at2] ?? "";
21895
+ if (letter === "i")
21896
+ risky("env -i");
21897
+ else if (ENV_FLAGS.has(letter))
21898
+ continue;
21899
+ else if (ENV_VALUED.has(letter)) {
21900
+ const glued = word.slice(at2 + 1);
21901
+ if (!glued)
21902
+ index += 1;
21903
+ const value = glued || words[index];
21904
+ if (letter === "u")
21905
+ unset(value);
21906
+ if (letter === "S")
21907
+ return split(value, index + 1, expands.has(index));
21908
+ break;
21909
+ } else {
21910
+ risky(UNREADABLE);
21911
+ break;
21912
+ }
21506
21913
  }
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);
21512
- else
21513
- return path35.resolve(file);
21914
+ continue;
21915
+ }
21916
+ if (ASSIGN.test(word)) {
21917
+ unset(word);
21918
+ continue;
21919
+ }
21920
+ return commandAt(words.slice(index), scan, seg, new Set([...expands].filter((at2) => at2 >= index).map((at2) => at2 - index)));
21514
21921
  }
21515
- return realOf(at);
21516
21922
  };
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);
21521
- };
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)) };
21923
+ var commandAt = (words, scan, seg, expands = new Set, from = 0) => {
21924
+ let index = from;
21925
+ while (index < words.length) {
21926
+ while (ASSIGN.test(words[index] ?? "")) {
21927
+ note(scan, seg, words[index]);
21928
+ index += 1;
21929
+ }
21930
+ const name = base(words[index]).toLowerCase();
21931
+ if (name === "env")
21932
+ return scanEnv(words, index + 1, expands, scan, seg, 0);
21933
+ if (OPAQUE.has(name))
21934
+ return opaque(words.slice(index + 1), scan, seg, true);
21935
+ if (name === "busybox" || name === "toybox") {
21936
+ index += 1;
21937
+ continue;
21938
+ }
21939
+ const takes = WRAPPERS3[name];
21940
+ if (takes === undefined)
21941
+ break;
21942
+ index = pastOptions(words, index + 1, takes);
21943
+ }
21944
+ const word = words[index];
21945
+ if (word === undefined)
21946
+ return;
21947
+ seg.words.push({ word, built: expands.has(index) });
21948
+ const rest = words.slice(index + 1);
21949
+ if (isWorkit(word) || rest.some(isWorkit))
21950
+ seg.runs = true;
21951
+ if (!isWorkit(word) && rest.some((next) => base(next).toLowerCase() === "env"))
21952
+ opaque(rest, scan, seg, false);
21953
+ const program = base(word).toLowerCase();
21954
+ const shell = program === "pwsh" || program === "powershell";
21955
+ if (program === "cmd" || shell) {
21956
+ const at = rest.findIndex((next) => shell ? /^-(?:c|command)$/iu.test(next) : /^\/[ck]$/iu.test(next));
21957
+ if (at >= 0) {
21958
+ const script = rest.slice(at + 1).join(" ");
21959
+ const change = shell ? powershellChange(script, scan.identity) : cmdChange(script, scan);
21960
+ if (change)
21961
+ scan.hit ??= change;
21528
21962
  }
21529
- if (path35.dirname(dir) === dir)
21530
- return null;
21531
21963
  }
21532
21964
  };
21533
- var workitWorktreeOf = (file) => {
21534
- try {
21535
- const checkout = checkoutOf2(file);
21536
- return checkout?.workit ? checkout.root : null;
21537
- } catch {
21965
+ var opaque = (rest, scan, seg, assigns) => {
21966
+ if (!rest.some(isWorkit))
21967
+ return;
21968
+ seg.runs = true;
21969
+ const changes = (word) => base(word).toLowerCase() === "env" || DECLARES.has(word) || assigns && ASSIGN.test(word);
21970
+ if (rest.some(changes))
21971
+ scan.risky ??= UNREADABLE;
21972
+ if (rest.some((word) => base(word).toLowerCase() === "env"))
21973
+ for (const word of rest)
21974
+ note(scan, seg, word);
21975
+ };
21976
+ var LOGIN_VALUED = {
21977
+ su: /[sgGwc]/u,
21978
+ runuser: /[sgGwuc]/u,
21979
+ script: /[cEIOBTmot]/u
21980
+ };
21981
+ var loginScript = (words) => {
21982
+ const at = words.findIndex((word) => /^(?:su|runuser|script)$/u.test(base(word)));
21983
+ if (at < 0)
21538
21984
  return null;
21985
+ const valued = LOGIN_VALUED[base(words[at])] ?? /c/u;
21986
+ for (let index = at + 1;index < words.length; index += 1) {
21987
+ const word = words[index] ?? "";
21988
+ if (word === "--command")
21989
+ return words[index + 1] ?? null;
21990
+ if (word.startsWith("--command="))
21991
+ return word.slice("--command=".length);
21992
+ if (!/^-[^-]/u.test(word))
21993
+ continue;
21994
+ const ends = word.slice(1).search(valued) + 1;
21995
+ if (ends > 0 && word[ends] === "c")
21996
+ return word.slice(ends + 1) || (words[index + 1] ?? null);
21539
21997
  }
21998
+ return null;
21540
21999
  };
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) => {
22000
+ var scanCommand = (command, dialect, depth, scan) => {
22001
+ let segments;
21544
22002
  try {
21545
- const value = JSON.parse(fs22.readFileSync(file, "utf8"));
21546
- return typeof value.worktree === "string" ? value : null;
22003
+ segments = segmentsOf(command, dialect);
21547
22004
  } catch {
21548
- return null;
22005
+ return;
22006
+ }
22007
+ for (const { words, expands = [] } of segments) {
22008
+ const expanded = new Set(expands);
22009
+ const seg = newSeg();
22010
+ let at = 0;
22011
+ while (ASSIGN.test(words[at] ?? ""))
22012
+ at += 1;
22013
+ for (const word of words.slice(0, at))
22014
+ note(scan, at === words.length ? null : seg, word);
22015
+ let declare = at;
22016
+ if (["builtin", "command"].includes(words[declare] ?? ""))
22017
+ declare += 1;
22018
+ if (DECLARES.has(words[declare] ?? "")) {
22019
+ for (let index = declare + 1;index < words.length; index += 1) {
22020
+ note(scan, null, words[index]);
22021
+ if (expanded.has(index))
22022
+ scan.risky ??= UNREADABLE;
22023
+ }
22024
+ continue;
22025
+ }
22026
+ commandAt(words, scan, seg, expanded, at);
22027
+ const script = depth < 4 ? shellScript2(words) ?? loginScript(words) : null;
22028
+ if (script) {
22029
+ const before = scan.runs;
22030
+ scan.runs = false;
22031
+ scanCommand(script, dialect, depth + 1, scan);
22032
+ seg.runs ||= scan.runs;
22033
+ scan.runs ||= before;
22034
+ }
22035
+ scan.words.push(...seg.words);
22036
+ const reaches = () => seg.runs || mayBeWorkit(seg.words, scan.cwd);
22037
+ if (seg.identity && reaches())
22038
+ scan.hit ??= seg.identity;
22039
+ if (seg.scoped && reaches())
22040
+ scan.state ??= seg.scoped;
22041
+ scan.runs ||= seg.runs;
21549
22042
  }
21550
22043
  };
21551
- var boundWorktree = (input) => {
21552
- const agentId = input.session.agentId;
21553
- if (!agentId)
22044
+ 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);
22045
+ var powershellChange = (command, identity) => {
22046
+ const hit = identity ? POWERSHELL.exec(command)?.[0] : null;
22047
+ if (hit)
22048
+ return hit;
22049
+ if (!RUNS_TEXT.test(command) && !/&\s*[$(]/u.test(command))
21554
22050
  return null;
21555
- const binding = readBinding(bindingFile(input.session.id, agentId));
21556
- return binding && workitWorktreeOf(binding.worktree) === binding.worktree ? binding.worktree : null;
22051
+ const state = POWERSHELL_STATE.exec(command)?.[0] ?? (identity ? POWERSHELL_HOST.exec(command)?.[0] : null) ?? cmdChange(command, { identity });
22052
+ if (state)
22053
+ return state;
22054
+ return POWERSHELL_OPAQUE.test(command) ? UNREADABLE : null;
21557
22055
  };
21558
- var bind = (input, worktree) => {
21559
- const agentId = input.session.agentId;
21560
- const file = bindingFile(input.session.id, agentId);
21561
- const binding = {
21562
- worktree,
21563
- session: input.session.id,
21564
- agentId,
21565
- at: new Date().toISOString()
21566
- };
21567
- fs22.mkdirSync(path35.dirname(file), { recursive: true });
21568
- fs22.writeFileSync(file, JSON.stringify(binding));
21569
- try {
21570
- if (inWorkitWorkspace(input.cwd))
21571
- appendHookObserved(input.cwd, {
21572
- type: "worktree.bound",
21573
- actor: { host: input.host, session: input.session.id, agentId },
22056
+ var identityEnvChange = (command, dialect = "posix", options = {}) => {
22057
+ const identity = options.identity ?? true;
22058
+ if (dialect === "powershell")
22059
+ return powershellChange(command, identity);
22060
+ 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))
22061
+ return null;
22062
+ const scan = {
22063
+ identity,
22064
+ cwd: options.cwd,
22065
+ hit: null,
22066
+ state: null,
22067
+ shell: null,
22068
+ risky: null,
22069
+ runs: false,
22070
+ words: []
22071
+ };
22072
+ scanCommand(command, dialect, 0, scan);
22073
+ if (scan.hit)
22074
+ return scan.hit;
22075
+ if (scan.state)
22076
+ return scan.state;
22077
+ if (scan.shell && (scan.runs || mayBeWorkit(scan.words, scan.cwd)))
22078
+ return scan.shell;
22079
+ return scan.runs ? scan.risky : null;
22080
+ };
22081
+ var identityEnvDeny = (change) => {
22082
+ if (change === UNREADABLE || IDENTITY_ANY.test(change) || !STATE_ANY.test(change))
22083
+ 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).`;
22084
+ 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}.`;
22085
+ };
22086
+
22087
+ // packages/workit-core/src/hooks/exit-pipe.ts
22088
+ var EXIT_VERBS = [
22089
+ ["ci", "wait"],
22090
+ ["check"],
22091
+ ["pr", "merge"],
22092
+ ["release"],
22093
+ ["verify-delivery"]
22094
+ ];
22095
+ var base2 = (word = "") => word.split(/[\\/]/u).at(-1) ?? "";
22096
+ var verbPath = (words) => {
22097
+ const path = [];
22098
+ for (let at = 0;at < words.length && path.length < 2; at += 1) {
22099
+ const word = words[at];
22100
+ if (word === "--")
22101
+ break;
22102
+ if (word === "--cwd")
22103
+ at += 1;
22104
+ else if (!word.startsWith("-"))
22105
+ path.push(word);
22106
+ }
22107
+ return path;
22108
+ };
22109
+ var identityAssignment = (name) => identityEnvChange(`${name}=x workit`) !== null;
22110
+ var identityWhy = (names) => names.length ? `
22111
+ Why: the retry leaves out ${names.join(", ")}: the identity guard refuses a workit call that sets ${names.length === 1 ? "it" : "them"}.` : "";
22112
+ var exitCall = (segment, first) => {
22113
+ const { words } = segment;
22114
+ let at = first;
22115
+ while (at < words.length && /^[A-Za-z_]\w*=/u.test(words[at]))
22116
+ at += 1;
22117
+ if (!/^workit(?:-cli)?$/u.test(base2(words[at])))
22118
+ return null;
22119
+ const path = verbPath(words.slice(at + 1));
22120
+ return EXIT_VERBS.some((verb) => verb.every((word, index) => path[index] === word)) ? { segment, first, at } : null;
22121
+ };
22122
+ var backgrounded = (command, segment) => {
22123
+ const ends = [...segment.spans ?? [], ...segment.redirectSpans ?? []].map(([, end]) => end);
22124
+ return /^[ \t]*&(?![&>])/u.test(command.slice(Math.max(0, ...ends)));
22125
+ };
22126
+ var setsPipefail = (words) => words[0] === "set" && words.some((word, at) => word === "pipefail" && /^-[a-z]*o$/u.test(words[at - 1] ?? ""));
22127
+ var range = (from, to) => Array.from({ length: to - from }, (_, i) => from + i);
22128
+ var absoluteCwd = (text, value) => cwdIndependent(text) && (/^(?:\/|[A-Za-z]:[\\/])/u.test(value) || /^~(?:\/|$)/u.test(text));
22129
+ var retryOf = (command, found) => {
22130
+ const { segment, first, at, cd, set } = found;
22131
+ const { words } = segment;
22132
+ const dropped = [];
22133
+ const env = range(first, at).filter((index) => {
22134
+ const name = words[index].slice(0, words[index].indexOf("="));
22135
+ if (!identityAssignment(name))
22136
+ return true;
22137
+ dropped.push(name);
22138
+ return false;
22139
+ });
22140
+ const envText = writtenWords(command, segment, env);
22141
+ const callText = writtenWords(command, segment, range(at + 1, words.length));
22142
+ const dir = cd ? writtenWord(command, cd, 1) : "";
22143
+ if (!envText || !callText || cd === undefined || dir === null)
22144
+ return { retry: null, dropped };
22145
+ const reads = [dir, ...envText, ...callText].flatMap((text) => [...text.matchAll(/\$\{?(\w+)/gu)].map((match) => match[1] ?? "")).find((name) => set.has(name));
22146
+ if (reads)
22147
+ return { retry: null, dropped, reads };
22148
+ const call = words.slice(at + 1);
22149
+ const verbAt = call[0]?.startsWith("-") ? 0 : 1;
22150
+ const plain = (body) => [...envText, "workit", ...body].join(" ");
22151
+ if (!cd)
22152
+ return { retry: plain(callText), dropped };
22153
+ const check = verbPath(call)[0] === "check";
22154
+ 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=")));
22155
+ 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) => {
22156
+ const text = writtenWord(command, segment, index) ?? "";
22157
+ return absoluteCwd(text.replace(/^--cwd=/u, ""), words[index].replace(/^--cwd=/u, ""));
22158
+ });
22159
+ if (!moves)
22160
+ return { retry: `cd ${dir} && ${plain(callText)}`, dropped };
22161
+ if (cwds.length)
22162
+ return { retry: plain(callText), dropped };
22163
+ return {
22164
+ retry: plain([...callText.slice(0, verbAt), "--cwd", dir, ...callText.slice(verbAt)]),
22165
+ dropped
22166
+ };
22167
+ };
22168
+ function exitPipeGate(command, dialect = "posix") {
22169
+ if (!/\bworkit/u.test(command) || !/\b(?:tail|head)\b/u.test(command))
22170
+ return null;
22171
+ const groups = [];
22172
+ let carry = null;
22173
+ let pipefail = false;
22174
+ let cd = null;
22175
+ const seen = [];
22176
+ const chained = !command.includes("||");
22177
+ for (const segment of segmentsOf(command, dialect, { spans: true })) {
22178
+ if (segment.unanalyzable)
22179
+ return null;
22180
+ let words = segment.words;
22181
+ let closes = segment.group === "close";
22182
+ if (segment.group === "open") {
22183
+ groups.push(null);
22184
+ continue;
22185
+ }
22186
+ if (words[0] === "{") {
22187
+ groups.push(null);
22188
+ words = words.slice(1);
22189
+ } else if (words[0] === "}") {
22190
+ closes = true;
22191
+ words = words.slice(1);
22192
+ }
22193
+ if (closes) {
22194
+ const inner = groups.pop() ?? null;
22195
+ if (segment.group === "close" && cd)
22196
+ cd = undefined;
22197
+ if (inner && groups.length)
22198
+ groups[groups.length - 1] = inner;
22199
+ carry = segment.pipe ? inner ?? carry : null;
22200
+ continue;
22201
+ }
22202
+ if (!words.length && !segment.stdin && !segment.subs)
22203
+ continue;
22204
+ if (setsPipefail(words))
22205
+ pipefail = true;
22206
+ const filter = base2(words[0]);
22207
+ if (carry && !pipefail && (filter === "tail" || filter === "head")) {
22208
+ const { retry, dropped, reads } = retryOf(command, carry);
22209
+ const verb = verbPath(carry.segment.words.slice(carry.at + 1)).join(" ");
22210
+ 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.`;
22211
+ return {
22212
+ kind: "deny",
22213
+ reason: `workit exit-pipe: piping \`workit ${verb}\` into ${filter} hides its exit code.
22214
+ ${retry ? `Retry as: ${retry}` : why}${identityWhy(dropped)}`,
22215
+ unblock: retry
22216
+ };
22217
+ }
22218
+ const call = exitCall(segment, segment.words.length - words.length);
22219
+ const found = call ? { ...call, cd, set: namesSet(seen) } : null;
22220
+ seen.push(segment);
22221
+ if (found && groups.length)
22222
+ groups[groups.length - 1] = found;
22223
+ carry = segment.pipe ? found ?? carry : null;
22224
+ const clean = chained && words === segment.words && words.length === 2 && !segment.pipe && !backgrounded(command, segment);
22225
+ if (words[0] === "cd")
22226
+ cd = clean && cd === null ? segment : undefined;
22227
+ else if (cd)
22228
+ cd = undefined;
22229
+ }
22230
+ return null;
22231
+ }
22232
+
22233
+ // packages/workit-core/src/hooks/worktree-confine.ts
22234
+ var FANOUT_TOKEN_FILE = "workit-fanout-token";
22235
+ var NONE5 = { kind: "none" };
22236
+ var CASE_INSENSITIVE2 = process.platform === "darwin" || process.platform === "win32";
22237
+ var realOf = (file) => {
22238
+ let rest = "";
22239
+ for (let dir = file;; dir = path36.dirname(dir)) {
22240
+ try {
22241
+ return path36.join(fs23.realpathSync.native(dir), rest);
22242
+ } catch {
22243
+ if (path36.dirname(dir) === dir)
22244
+ return file;
22245
+ rest = rest ? path36.join(path36.basename(dir), rest) : path36.basename(dir);
22246
+ }
22247
+ }
22248
+ };
22249
+ var canonical6 = (file, hops = { chain: 40, total: 1000 }) => {
22250
+ const start = path36.isAbsolute(file) ? file : `${process.cwd()}${path36.sep}${file}`;
22251
+ const { root } = path36.parse(start);
22252
+ let at = root;
22253
+ let missing = false;
22254
+ for (const part of start.slice(root.length).split(/[\\/]+/)) {
22255
+ if (part === "" || part === ".")
22256
+ continue;
22257
+ if (part === "..") {
22258
+ at = path36.dirname(at);
22259
+ continue;
22260
+ }
22261
+ const next = path36.join(at, part);
22262
+ let link = null;
22263
+ if (!missing)
22264
+ try {
22265
+ link = fs23.readlinkSync(next);
22266
+ } catch (error) {
22267
+ missing = error.code !== "EINVAL";
22268
+ }
22269
+ if (link === null) {
22270
+ at = next;
22271
+ hops.chain = 40;
22272
+ } else if (hops.chain-- > 0 && hops.total-- > 0)
22273
+ at = canonical6(path36.isAbsolute(link) ? link : `${at}${path36.sep}${link}`, hops);
22274
+ else
22275
+ return path36.resolve(file);
22276
+ }
22277
+ return realOf(at);
22278
+ };
22279
+ var within = (child, parent) => {
22280
+ const fold = (value) => CASE_INSENSITIVE2 ? value.toLowerCase() : value;
22281
+ const relative = path36.relative(fold(parent), fold(child));
22282
+ return relative === "" || !relative.startsWith("..") && !path36.isAbsolute(relative);
22283
+ };
22284
+ var checkoutOf2 = (file) => {
22285
+ for (let dir = canonical6(file);; dir = path36.dirname(dir)) {
22286
+ const dotGit = path36.join(dir, ".git");
22287
+ if (fs23.existsSync(dotGit)) {
22288
+ const admin = fs23.statSync(dotGit).isFile() ? gitDirsAt(dir, null, false)?.[0] : undefined;
22289
+ return { root: dir, workit: !!admin && fs23.existsSync(path36.join(admin, FANOUT_TOKEN_FILE)) };
22290
+ }
22291
+ if (path36.dirname(dir) === dir)
22292
+ return null;
22293
+ }
22294
+ };
22295
+ var workitWorktreeOf = (file) => {
22296
+ try {
22297
+ const checkout = checkoutOf2(file);
22298
+ return checkout?.workit ? checkout.root : null;
22299
+ } catch {
22300
+ return null;
22301
+ }
22302
+ };
22303
+ var bindingDir = () => path36.join(resolveStateDir(), "worktree-bind");
22304
+ var bindingFile = (session, agentId) => path36.join(bindingDir(), `${createHash16("sha256").update(`${session}\x00${agentId}`).digest("hex").slice(0, 32)}.json`);
22305
+ var readBinding = (file) => {
22306
+ try {
22307
+ const value = JSON.parse(fs23.readFileSync(file, "utf8"));
22308
+ return typeof value.worktree === "string" ? value : null;
22309
+ } catch {
22310
+ return null;
22311
+ }
22312
+ };
22313
+ var boundWorktree = (input) => {
22314
+ const agentId = input.session.agentId;
22315
+ if (!agentId)
22316
+ return null;
22317
+ const binding = readBinding(bindingFile(input.session.id, agentId));
22318
+ return binding && workitWorktreeOf(binding.worktree) === binding.worktree ? binding.worktree : null;
22319
+ };
22320
+ var bind = (input, worktree) => {
22321
+ const agentId = input.session.agentId;
22322
+ const file = bindingFile(input.session.id, agentId);
22323
+ const binding = {
22324
+ worktree,
22325
+ session: input.session.id,
22326
+ agentId,
22327
+ at: new Date().toISOString()
22328
+ };
22329
+ fs23.mkdirSync(path36.dirname(file), { recursive: true });
22330
+ fs23.writeFileSync(file, JSON.stringify(binding));
22331
+ try {
22332
+ if (inWorkitWorkspace(input.cwd))
22333
+ appendHookObserved(input.cwd, {
22334
+ type: "worktree.bound",
22335
+ actor: { host: input.host, session: input.session.id, agentId },
21574
22336
  agentType: input.session.agentType,
21575
22337
  worktree
21576
22338
  });
@@ -21583,42 +22345,117 @@ var hostIsolated = (cwd, agentId) => {
21583
22345
  const checkout = checkoutOf2(cwd);
21584
22346
  if (!checkout)
21585
22347
  return false;
21586
- const dotGit = path35.join(checkout.root, ".git");
21587
- if (!fs22.statSync(dotGit).isFile())
22348
+ const dotGit = path36.join(checkout.root, ".git");
22349
+ if (!fs23.statSync(dotGit).isFile())
21588
22350
  return false;
21589
22351
  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)) !== "")
22352
+ const back = fs23.readFileSync(path36.join(adminDir, "gitdir"), "utf8").trim();
22353
+ if (path36.relative(canonical6(path36.resolve(adminDir, back)), canonical6(dotGit)) !== "")
21592
22354
  return false;
21593
- const expected = path35.join(path35.dirname(gitDir), ".claude", "worktrees", `agent-${agentId}`);
21594
- return path35.relative(canonical6(expected), checkout.root) === "";
22355
+ const expected = path36.join(path36.dirname(gitDir), ".claude", "worktrees", `agent-${agentId}`);
22356
+ return path36.relative(canonical6(expected), checkout.root) === "";
21595
22357
  } catch {
21596
22358
  return false;
21597
22359
  }
21598
22360
  };
21599
22361
  var runnerAt = (target) => {
21600
- const base = path35.basename(target);
22362
+ const base = path36.basename(target);
21601
22363
  return base.startsWith(OPAQUE_TARGET) ? decodeURIComponent(base.slice(OPAQUE_TARGET.length)) : null;
21602
22364
  };
21603
22365
  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;
22366
+ const named = /^\.workit-(?:live-target$|runs-)/.test(path36.basename(target)) ? path36.dirname(target) : target;
22367
+ return path36.sep === "\\" ? named.replaceAll("/", "\\") : named;
22368
+ };
22369
+ var plainWorkitCall = (command, dialect) => {
22370
+ if (dialect !== "posix")
22371
+ return null;
22372
+ const segments = segmentsOf(command, dialect, { spans: true });
22373
+ const [only] = segments;
22374
+ if (segments.length !== 1 || !only || only.unanalyzable || only.group || only.pipe)
22375
+ return null;
22376
+ if (only.redirects.length || only.subs?.length || only.stdin?.length || only.inputs?.length)
22377
+ return null;
22378
+ const { words } = only;
22379
+ let at = 0;
22380
+ while (at < words.length && /^[A-Za-z_]\w*=/.test(words[at]))
22381
+ at++;
22382
+ if (words[at] !== "workit" || (only.expands ?? []).some((index) => index >= at))
22383
+ return null;
22384
+ return { segment: only, at, cwd: skipWorkitGlobals(words.slice(at + 1)).cwd };
22385
+ };
22386
+ var workitCallDir = (command, dialect) => {
22387
+ const call = plainWorkitCall(command, dialect);
22388
+ return call?.cwd && path36.isAbsolute(call.cwd) ? call.cwd : null;
22389
+ };
22390
+ var shellWord = (dir) => /^[\w@%+=:,./-]+$/u.test(dir) ? dir : `'${dir.replaceAll("'", `'\\''`)}'`;
22391
+ var cwdAt = (words, index) => words[index] === "--cwd" && words[index + 1] !== undefined ? 2 : words[index]?.startsWith("--cwd=") ? 1 : 0;
22392
+ var plainRetry = (dir, command) => {
22393
+ const call = plainWorkitCall(command, "posix");
22394
+ if (!call)
22395
+ return null;
22396
+ const { segment, at } = call;
22397
+ const { words } = segment;
22398
+ const dropped = [];
22399
+ const env = [];
22400
+ for (let index = 0;index < at; index++) {
22401
+ const name = words[index].slice(0, words[index].indexOf("="));
22402
+ if (identityAssignment(name))
22403
+ dropped.push(name);
22404
+ else
22405
+ env.push(index);
22406
+ }
22407
+ const globals = [];
22408
+ let index = at + 1;
22409
+ for (;index < words.length; index++) {
22410
+ const skip = cwdAt(words, index);
22411
+ if (skip)
22412
+ index += skip - 1;
22413
+ else if (/^--(?:session|token|as)$/u.test(words[index]) && words[index + 1] !== undefined)
22414
+ globals.push(index, ++index);
22415
+ else if (/^--(?:session|token|as)=|^--json$/u.test(words[index]))
22416
+ globals.push(index);
22417
+ else
22418
+ break;
22419
+ }
22420
+ const verb = index;
22421
+ const rest = [];
22422
+ for (index += 1;index < words.length; index++) {
22423
+ if (words[index] === "--") {
22424
+ for (;index < words.length; index++)
22425
+ rest.push(index);
22426
+ break;
22427
+ }
22428
+ const skip = cwdAt(words, index);
22429
+ if (skip)
22430
+ index += skip - 1;
22431
+ else
22432
+ rest.push(index);
22433
+ }
22434
+ const text = (indexes) => writtenWords(command, segment, indexes);
22435
+ const parts = [text(env), text(globals), text(verb < words.length ? [verb] : []), text(rest)];
22436
+ if (parts.includes(null))
22437
+ return null;
22438
+ const [envText, globalText, verbText, restText] = parts;
22439
+ const cwd = ["--cwd", shellWord(dir)];
22440
+ const body = [...globalText, ...verbText, ...cwd, ...restText];
22441
+ return { retry: [...envText, "workit", ...body].join(" "), dropped };
21606
22442
  };
21607
22443
  var runFrom = (dir, command) => `cd ${dir} && ${command.replace(/^\s*cd\s+\S+\s*(?:&&|;)\s*/, "")}`;
21608
- var deny2 = (what, unblock) => ({
22444
+ var deny2 = (what, unblock, note = "") => ({
21609
22445
  kind: "deny",
21610
22446
  reason: `${what}.
21611
- ${unblock}`,
22447
+ ${unblock}${note}`,
21612
22448
  unblock
21613
22449
  });
21614
22450
  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
22451
  var outsideDeny = (input, worktree, target, command) => {
21616
22452
  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.`);
22453
+ const plain = runner !== null && command ? plainRetry(worktree, command) : null;
22454
+ 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
22455
  };
21619
22456
  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
22457
  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)))
22458
+ ...new Set(targets.flatMap((target) => path36.relative(UNKNOWN_VAR, path36.resolve(target)).split(path36.sep)[0].split("+").filter(Boolean).map(decodeURIComponent)))
21622
22459
  ];
21623
22460
  var literalForm = (command, refs) => {
21624
22461
  let text = command;
@@ -21651,10 +22488,10 @@ function confineImplementer(input, targets, command) {
21651
22488
  try {
21652
22489
  if (!input.session.agentId || hostIsolated(input.cwd, input.session.agentId))
21653
22490
  return NONE5;
21654
- const unresolved = targets.filter((target) => within(path35.resolve(target), UNKNOWN_VAR));
22491
+ const unresolved = targets.filter((target) => within(path36.resolve(target), UNKNOWN_VAR));
21655
22492
  if (unresolved.length > 0)
21656
22493
  return unknownVarDeny(input, unresolved, command);
21657
- if (targets.some((target) => within(path35.resolve(target), UNKNOWN_DIR)))
22494
+ if (targets.some((target) => within(path36.resolve(target), UNKNOWN_DIR)))
21658
22495
  return unknownDirDeny(input, boundWorktree(input));
21659
22496
  const bindings = canonical6(bindingDir());
21660
22497
  const judged = targets.map((named) => ({ named, real: canonical6(named) })).filter(({ real }) => within(real, bindings) || checkoutOf2(real) !== null);
@@ -21746,7 +22583,7 @@ function confineImplementerShell(input, command, dialect = "posix") {
21746
22583
  if (rawInvocations(command, dialect).some((invocation) => invocation.tool === "git" && leadOwnedGit(invocation.args)) || workitInvocations(command, dialect).some(leadOwnedWorkit))
21747
22584
  return leadOwnedDeny(input, command);
21748
22585
  } catch {}
21749
- return confineImplementer(input, shellMutationTargets(input.cwd, command, dialect, true), command);
22586
+ return confineImplementer(input, shellMutationTargets(workitCallDir(command, dialect) ?? input.cwd, command, dialect, true), command);
21750
22587
  }
21751
22588
  var LITERAL_SET = /^\s*([A-Za-z_]\w*)=(['"]?)((?:[\w@%+=:./\\-]|(?<=[^\s:=])~)*)\2[ \t]*(?:;|&&|\n)\s*/;
21752
22589
  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 +22598,10 @@ var INLINE = /^-[a-zA-Z]*[ceEpm]$|^--(?:eval|print)(?:=|$)|^--(?:test|version|he
21761
22598
  var VALUED2 = /^-[WXIrC]$|^--(?:require|import|loader|conditions|input-type)$/;
21762
22599
  var commonDir = (root) => gitDirsAt(root, null, false)?.[1] ?? "";
21763
22600
  var inScratch = (real, repo) => {
21764
- for (let dir = real;path35.dirname(dir) !== dir; dir = path35.dirname(dir)) {
21765
- if (path35.basename(dir) !== SCRATCH)
22601
+ for (let dir = real;path36.dirname(dir) !== dir; dir = path36.dirname(dir)) {
22602
+ if (path36.basename(dir) !== SCRATCH)
21766
22603
  continue;
21767
- const root = path35.dirname(dir);
22604
+ const root = path36.dirname(dir);
21768
22605
  const checkout = checkoutOf2(root);
21769
22606
  if (checkout?.root === root && (repo === null || checkout.workit || commonDir(root) === repo))
21770
22607
  return true;
@@ -21774,7 +22611,7 @@ var inScratch = (real, repo) => {
21774
22611
  var inGitDir = (real) => real.split(/[\\/]/).includes(".git");
21775
22612
  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
22613
  var literalIn = (value, repo, checkout = false) => {
21777
- if (/[$`]/.test(value) || !path35.isAbsolute(value))
22614
+ if (/[$`]/.test(value) || !path36.isAbsolute(value))
21778
22615
  return false;
21779
22616
  const real = canonical6(value);
21780
22617
  const root = checkout ? checkoutOf2(real)?.root : undefined;
@@ -21795,45 +22632,45 @@ var configEntries = (text) => {
21795
22632
  return entries;
21796
22633
  };
21797
22634
  function gitDirsAt(dir, repo, scan = true) {
21798
- for (let at = dir;; at = path35.dirname(at)) {
21799
- const dotGit = path35.join(at, ".git");
22635
+ for (let at = dir;; at = path36.dirname(at)) {
22636
+ const dotGit = path36.join(at, ".git");
21800
22637
  let gitDir = null;
21801
22638
  try {
21802
- if (fs22.statSync(dotGit).isDirectory())
22639
+ if (fs23.statSync(dotGit).isDirectory())
21803
22640
  gitDir = canonical6(dotGit);
21804
22641
  else {
21805
- const named = /^gitdir:\s*(.+?)\s*$/mu.exec(fs22.readFileSync(dotGit, "utf8"))?.[1];
22642
+ const named = /^gitdir:\s*(.+?)\s*$/mu.exec(fs23.readFileSync(dotGit, "utf8"))?.[1];
21806
22643
  if (!named)
21807
22644
  return null;
21808
- gitDir = canonical6(path35.resolve(at, named));
22645
+ gitDir = canonical6(path36.resolve(at, named));
21809
22646
  }
21810
22647
  } catch (error) {
21811
22648
  if (error.code !== "ENOENT")
21812
22649
  return null;
21813
- if (["HEAD", "objects", "refs"].every((name) => fs22.existsSync(path35.join(at, name))))
22650
+ if (["HEAD", "objects", "refs"].every((name) => fs23.existsSync(path36.join(at, name))))
21814
22651
  gitDir = canonical6(at);
21815
22652
  }
21816
22653
  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;
22654
+ const common = path36.join(gitDir, "commondir");
22655
+ const shared = fs23.existsSync(common) ? canonical6(path36.resolve(gitDir, fs23.readFileSync(common, "utf8").trim())) : gitDir;
21819
22656
  const dirs = [gitDir, shared];
21820
- for (const config of scan ? new Set([path35.join(gitDir, "config"), path35.join(shared, "config")]) : []) {
22657
+ for (const config of scan ? new Set([path36.join(gitDir, "config"), path36.join(shared, "config")]) : []) {
21821
22658
  let text = "";
21822
22659
  try {
21823
- text = fs22.readFileSync(config, "utf8");
22660
+ text = fs23.readFileSync(config, "utf8");
21824
22661
  } catch {
21825
22662
  continue;
21826
22663
  }
21827
22664
  for (const [key, value] of configEntries(text)) {
21828
22665
  if (key === "core.worktree")
21829
- dirs.push(canonical6(path35.resolve(gitDir, value)));
22666
+ dirs.push(canonical6(path36.resolve(gitDir, value)));
21830
22667
  else if (/^remote\..*\.url$/.test(key) ? !literalIn(value, repo, true) : !SAFE_KEY.test(key))
21831
22668
  return null;
21832
22669
  }
21833
22670
  }
21834
22671
  return dirs;
21835
22672
  }
21836
- if (path35.dirname(at) === at)
22673
+ if (path36.dirname(at) === at)
21837
22674
  return [];
21838
22675
  }
21839
22676
  }
@@ -21973,10 +22810,10 @@ var gitKind = (args, local = () => true) => {
21973
22810
  return GIT_VERBS[verb].startsWith("+") ? "write" : "read";
21974
22811
  };
21975
22812
  var remoteIn = (dir, name, repo) => {
21976
- const shared = path35.isAbsolute(dir) ? gitDirsAt(canonical6(dir), repo, false)?.[1] : undefined;
22813
+ const shared = path36.isAbsolute(dir) ? gitDirsAt(canonical6(dir), repo, false)?.[1] : undefined;
21977
22814
  if (!shared)
21978
22815
  return false;
21979
- const url = configEntries(fs22.readFileSync(path35.join(shared, "config"), "utf8")).find(([key]) => key === `remote.${name}.url`.toLowerCase())?.[1];
22816
+ const url = configEntries(fs23.readFileSync(path36.join(shared, "config"), "utf8")).find(([key]) => key === `remote.${name}.url`.toLowerCase())?.[1];
21980
22817
  return url !== undefined && literalIn(url, repo, true);
21981
22818
  };
21982
22819
  var judgeEnvAllowed = (word) => {
@@ -22005,7 +22842,7 @@ var judgeGit = (command, repo, cwd, depth = 0) => {
22005
22842
  at = after;
22006
22843
  }
22007
22844
  }
22008
- const name = path35.basename(words[at] ?? "");
22845
+ const name = path36.basename(words[at] ?? "");
22009
22846
  let start = words.findIndex((word) => /(?:^|[\\/])git(?:\.exe)?(?:=|$)/.test(word));
22010
22847
  if (start > at) {
22011
22848
  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 +22853,7 @@ var judgeGit = (command, repo, cwd, depth = 0) => {
22016
22853
  if (start >= 0 && words[start].includes("="))
22017
22854
  why = "git is redefined";
22018
22855
  const run = words[start] ?? "";
22019
- if (run.includes("/") && (!path35.isAbsolute(run) || literalIn(run, repo, true)))
22856
+ if (run.includes("/") && (!path36.isAbsolute(run) || literalIn(run, repo, true)))
22020
22857
  why ??= `\`${run}\` is not the system git`;
22021
22858
  if (segment.expands?.includes(at) && name !== "[" || /\{[^}]*,/.test(words[at] ?? ""))
22022
22859
  why = "the command's name is expanded by the shell";
@@ -22041,13 +22878,13 @@ var judgeGit = (command, repo, cwd, depth = 0) => {
22041
22878
  const args = words[index] === "--version" ? ["version"] : words.slice(index);
22042
22879
  if (!why && start >= 0) {
22043
22880
  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);
22881
+ const runsIn = path36.isAbsolute(dir) ? dir : cwd && path36.resolve(cwd, dir);
22045
22882
  const home = runsIn && checkoutOf2(runsIn);
22046
22883
  const fetches = args[0] === "fetch" && plainFetch(args.slice(1)) && home && (home.workit || commonDir(home.root) === repo) && !words.some((word) => /^--[gw]/.test(word));
22047
22884
  if (!fetches && !gitKind(args, local))
22048
22885
  why = `\`git ${args.slice(0, 2).join(" ")}\` is not allowed`;
22049
22886
  }
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)));
22887
+ 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
22888
  const scripts = [
22052
22889
  ...words.filter((_, after) => shell >= 0 && after > shell && /^-[a-zA-Z]*c[a-zA-Z]*$/.test(words[after - 1])),
22053
22890
  ...shell < 0 ? [] : segment.stdin ?? []
@@ -22092,7 +22929,7 @@ var judgeVerbRefused = (args) => {
22092
22929
  var CLI_RUNNERS = /^(?:npx|bunx|pnpx|npm|pnpm|yarn|bun|node|nodejs|deno|tsx|ts-node)$/;
22093
22930
  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
22931
  var workitCalls = (command, depth = 0, aliases = new Map) => depth > 4 ? [] : commandLines(command).flatMap((words) => {
22095
- const name = path35.basename(words[0] ?? "").toLowerCase();
22932
+ const name = path36.basename(words[0] ?? "").toLowerCase();
22096
22933
  if (name === "alias")
22097
22934
  return words.flatMap((word) => {
22098
22935
  const set = /^([\w-]+)=(.*)$/s.exec(word);
@@ -22121,11 +22958,11 @@ var judgeRefusal = (command, fed, depth = 0) => {
22121
22958
  return why;
22122
22959
  }
22123
22960
  const { words } = segment;
22124
- const runs = (word = "") => RUNS.test(path35.basename(word).toLowerCase());
22961
+ const runs = (word = "") => RUNS.test(path36.basename(word).toLowerCase());
22125
22962
  let at = 0;
22126
22963
  while (at < words.length && (LEADS.test(words[at]) || /^-\w$/.test(words[at - 1] ?? "") && !runs(words[at])))
22127
22964
  at++;
22128
- const name = path35.basename(words[at] ?? "").toLowerCase();
22965
+ const name = path36.basename(words[at] ?? "").toLowerCase();
22129
22966
  const args = words.slice(at + 1);
22130
22967
  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
22968
  if (/^(?:cd|chdir|pushd|popd)$/.test(name))
@@ -22207,10 +23044,10 @@ var judgeDeny = (input, what, target, retry, why = "write only there (mkdir -p i
22207
23044
  const role = input.session.agentType?.endsWith("reviewer") ? "reviewer" : "verifier";
22208
23045
  const root = checkoutOf2(input.cwd)?.root;
22209
23046
  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))}`;
23047
+ const other = root && candidate && candidate !== root && commonDir(candidate) === commonDir(root) ? path36.join(candidate, SCRATCH) : undefined;
23048
+ const scratch = root ? `${path36.join(root, SCRATCH)}${other ? ` or ${other}` : ""}` : `${SCRATCH}/ at the root of the checkout you judge`;
23049
+ const call = root ? retry?.((other ?? path36.join(root, SCRATCH)).replaceAll("\\", "/")) : null;
23050
+ const unblock = call ? `Retry as: ${call}` : `Why: ${why.replaceAll("<scratch>", other ?? (root ? path36.join(root, SCRATCH) : SCRATCH))}`;
22214
23051
  return {
22215
23052
  kind: "deny",
22216
23053
  reason: `workit scratch confinement: ${role} ${input.session.agentId} may write only in its scratch dir ${scratch}, and ${what}.
@@ -22220,9 +23057,9 @@ ${unblock}`,
22220
23057
  };
22221
23058
  var movedInto = (command, cwd, target, dir) => {
22222
23059
  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)}`);
23060
+ for (const word of [...redirects, ...path36.basename(words[0] ?? "") === "tee" ? words : []])
23061
+ if (path36.resolve(cwd, word) === path36.resolve(cwd, target)) {
23062
+ const moved = command.replace(new RegExp(`((?:>>?\\|?|\\btee(?:\\s+-a)?)\\s*)(['"]?)${word.replace(/[$()*+.?[\\\]^{|}]/g, "\\$&")}\\2(?![^\\s;&|)])`), (_, lead) => `${lead}${dir}/${path36.basename(word)}`);
22226
23063
  return moved === command ? null : moved;
22227
23064
  }
22228
23065
  return null;
@@ -22234,19 +23071,19 @@ function confineJudge(input, targets, placeholders = placeholdersOf(targets), co
22234
23071
  const judged = checkoutOf2(input.cwd);
22235
23072
  const repo = judged ? commonDir(judged.root) : null;
22236
23073
  const scratch = (real) => inScratch(real, repo) || [os10.tmpdir(), "/tmp"].some((dir) => {
22237
- const [host, , session] = path35.relative(canonical6(dir), real).split(path35.sep);
23074
+ const [host, , session] = path36.relative(canonical6(dir), real).split(path36.sep);
22238
23075
  return /^claude-\d+$/.test(host) && session === input.session.id;
22239
23076
  });
22240
23077
  for (const target of targets) {
22241
- const resolved = path35.resolve(target);
23078
+ const resolved = path36.resolve(target);
22242
23079
  if (within(resolved, UNKNOWN_VAR) || within(resolved, UNKNOWN_DIR))
22243
23080
  return judgeDeny(input, "it writes to a path Workit cannot resolve", undefined, () => {
22244
23081
  const literal = command && literalForm(command, refsOf([target]));
22245
23082
  return literal === command ? null : literal;
22246
23083
  });
22247
23084
  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) : [];
23085
+ const runsGit = placeholders.has(target) && /^\.workit-(?:runs-git|live-target)$/.test(path36.basename(target));
23086
+ const gitDirs = runsGit ? gitDirsAt(path36.dirname(real), repo) : [];
22250
23087
  if (gitDirs === null)
22251
23088
  return judgeDeny(input, `git in ${shown(target)} uses a git dir or config Workit cannot check`);
22252
23089
  if (runsGit ? gitDirs.length > 0 ? gitDirs.every(scratch) : scratch(real) : scratch(real) && !inGitDir(real))
@@ -22314,7 +23151,7 @@ function confineJudgeShell(input, command, dialect = "posix") {
22314
23151
  let git = [];
22315
23152
  try {
22316
23153
  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`)
23154
+ path36.join(dir === undefined ? UNKNOWN_DIR : path36.resolve(input.cwd, dir ?? "."), `${OPAQUE_TARGET}git`)
22318
23155
  ] : []);
22319
23156
  } catch {}
22320
23157
  const lists = [
@@ -22359,17 +23196,17 @@ var judgeChecksLine = (cwd) => {
22359
23196
 
22360
23197
  // packages/workit-core/src/hooks/standing.ts
22361
23198
  var readPlans = (store) => {
22362
- const dir = path36.join(store, "fanouts");
23199
+ const dir = path37.join(store, "fanouts");
22363
23200
  let names;
22364
23201
  try {
22365
- names = fs23.readdirSync(dir).filter((name) => name.endsWith(".json"));
23202
+ names = fs24.readdirSync(dir).filter((name) => name.endsWith(".json"));
22366
23203
  } catch {
22367
23204
  return [];
22368
23205
  }
22369
23206
  const plans = [];
22370
23207
  for (const name of names) {
22371
23208
  try {
22372
- const raw = JSON.parse(fs23.readFileSync(path36.join(dir, name), "utf8"));
23209
+ const raw = JSON.parse(fs24.readFileSync(path37.join(dir, name), "utf8"));
22373
23210
  if (typeof raw.name !== "string" || !Array.isArray(raw.slices))
22374
23211
  continue;
22375
23212
  const texts = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string" && item !== "") : [];
@@ -22491,128 +23328,42 @@ var standingDelta = (input) => {
22491
23328
  }
22492
23329
  };
22493
23330
  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
- // packages/workit-core/src/hooks/spawn-gate.ts
22581
- import fs24 from "node:fs";
22582
- import path38 from "node:path";
22583
-
22584
- // packages/workit-core/src/hooks/model-limit.ts
22585
- import { closeSync as closeSync3, openSync as openSync3, readdirSync as readdirSync5, readSync, statSync as statSync5 } from "node:fs";
22586
- import os11 from "node:os";
22587
- import path37 from "node:path";
22588
- var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
22589
- var WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
22590
- var TIME_WORD = String.raw`(?:\d|(?:in|at|on|later|tomorrow|soon)\b|(?:${[...WEEKDAYS, ...MONTHS].join("|")})[a-z]*\b)`;
22591
- var LIMIT_END = String.raw`(?=\s*(?:\|\d{10}\b|(?:[∙·•|,:\-–—.]\s*)?(?:$|\(?(?:resets?|try again)\s+${TIME_WORD})))`;
22592
- var LIMIT_PATTERNS = [
22593
- /\byou(?:'|\u2019)?ve hit your\b[^.\n]{0,40}\blimit\b/iu,
22594
- new RegExp(String.raw`\bclaude(?: ai)? usage limit reached${LIMIT_END}`, "imu"),
22595
- new RegExp(String.raw`\b(?:5-hour|five-hour|weekly|daily|session|opus|sonnet|fable|haiku) limit reached${LIMIT_END}`, "imu"),
22596
- /\busage limit\b[^\n]{0,200}\b(?:try again|resets?) (?:in|at)\b/iu,
22597
- /\byou exceeded your current quota\b|\binsufficient_quota\b/iu
22598
- ];
22599
- var RATE_LIMIT = /\brate_limit(?:_error)?\b|"type":\s*"rate_limit|\bstatus(?:code)?["':\s]+429\b|^\s*(?:\w+Error:\s*)?429\b/imu;
22600
- var LONG_WAIT_MS = 15 * 60000;
22601
- var AT_TIME = new RegExp(String.raw`\b(?:resets?|reset at|try again at|available again at|retry at)\s+(?:at\s+|on\s+)?` + String.raw`(?:(?:${WEEKDAYS.join("|")})[a-z]*,?\s+)?` + String.raw`(?:(${MONTHS.join("|")})[a-z]*\.?\s+(\d{1,2})(?:st|nd|rd|th)?,?\s+(?:at\s+)?)?` + String.raw`(\d{1,2})(?::(\d{2}))?\s*(am|pm)?(?:\s*\(([A-Za-z_]+(?:/[A-Za-z_+-]+)*)\))?`, "iu");
22602
- var IN_DURATION = /\b(?:try again|resets?|retry|available again)\s+in\s+((?:\d+(?:\.\d+)?\s*(?:days?|d|hours?|hrs?|h|minutes?|mins?|m|seconds?|secs?|s)\b[\s,]*(?:and\s+)?)+)/iu;
22603
- var RETRY_AFTER = /\bretry[- ]after\b["':\s]+(\d+)/iu;
22604
- var EPOCH = /\|(\d{10})\b/u;
22605
- var UNIT_MS = [
22606
- [/^d/u, 86400000],
22607
- [/^h/u, 3600000],
22608
- [/^m/u, 60000],
22609
- [/^s/u, 1000]
22610
- ];
22611
- var durationMs = (text) => {
22612
- let total = 0;
22613
- for (const [, amount, unit] of text.matchAll(/(\d+(?:\.\d+)?)\s*([a-z]+)/giu))
22614
- total += Number(amount) * (UNIT_MS.find(([re]) => re.test(unit.toLowerCase()))?.[1] ?? 0);
22615
- return total;
23331
+ // packages/workit-core/src/hooks/spawn-gate.ts
23332
+ import fs25 from "node:fs";
23333
+ import path39 from "node:path";
23334
+
23335
+ // packages/workit-core/src/hooks/model-limit.ts
23336
+ import { closeSync as closeSync3, openSync as openSync3, readdirSync as readdirSync5, readSync, statSync as statSync5 } from "node:fs";
23337
+ import os11 from "node:os";
23338
+ import path38 from "node:path";
23339
+ var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
23340
+ var WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
23341
+ var TIME_WORD = String.raw`(?:\d|(?:in|at|on|later|tomorrow|soon)\b|(?:${[...WEEKDAYS, ...MONTHS].join("|")})[a-z]*\b)`;
23342
+ var LIMIT_END = String.raw`(?=\s*(?:\|\d{10}\b|(?:[∙·•|,:\-–—.]\s*)?(?:$|\(?(?:resets?|try again)\s+${TIME_WORD})))`;
23343
+ var LIMIT_PATTERNS = [
23344
+ /\byou(?:'|\u2019)?ve hit your\b[^.\n]{0,40}\blimit\b/iu,
23345
+ new RegExp(String.raw`\bclaude(?: ai)? usage limit reached${LIMIT_END}`, "imu"),
23346
+ new RegExp(String.raw`\b(?:5-hour|five-hour|weekly|daily|session|opus|sonnet|fable|haiku) limit reached${LIMIT_END}`, "imu"),
23347
+ /\busage limit\b[^\n]{0,200}\b(?:try again|resets?) (?:in|at)\b/iu,
23348
+ /\byou exceeded your current quota\b|\binsufficient_quota\b/iu
23349
+ ];
23350
+ var RATE_LIMIT = /\brate_limit(?:_error)?\b|"type":\s*"rate_limit|\bstatus(?:code)?["':\s]+429\b|^\s*(?:\w+Error:\s*)?429\b/imu;
23351
+ var LONG_WAIT_MS = 15 * 60000;
23352
+ var AT_TIME = new RegExp(String.raw`\b(?:resets?|reset at|try again at|available again at|retry at)\s+(?:at\s+|on\s+)?` + String.raw`(?:(?:${WEEKDAYS.join("|")})[a-z]*,?\s+)?` + String.raw`(?:(${MONTHS.join("|")})[a-z]*\.?\s+(\d{1,2})(?:st|nd|rd|th)?,?\s+(?:at\s+)?)?` + String.raw`(\d{1,2})(?::(\d{2}))?\s*(am|pm)?(?:\s*\(([A-Za-z_]+(?:/[A-Za-z_+-]+)*)\))?`, "iu");
23353
+ var IN_DURATION = /\b(?:try again|resets?|retry|available again)\s+in\s+((?:\d+(?:\.\d+)?\s*(?:days?|d|hours?|hrs?|h|minutes?|mins?|m|seconds?|secs?|s)\b[\s,]*(?:and\s+)?)+)/iu;
23354
+ var RETRY_AFTER = /\bretry[- ]after\b["':\s]+(\d+)/iu;
23355
+ var EPOCH = /\|(\d{10})\b/u;
23356
+ var UNIT_MS = [
23357
+ [/^d/u, 86400000],
23358
+ [/^h/u, 3600000],
23359
+ [/^m/u, 60000],
23360
+ [/^s/u, 1000]
23361
+ ];
23362
+ var durationMs = (text) => {
23363
+ let total = 0;
23364
+ for (const [, amount, unit] of text.matchAll(/(\d+(?:\.\d+)?)\s*([a-z]+)/giu))
23365
+ total += Number(amount) * (UNIT_MS.find(([re]) => re.test(unit.toLowerCase()))?.[1] ?? 0);
23366
+ return total;
22616
23367
  };
22617
23368
  var zoneOffset = (zone, at) => {
22618
23369
  const parts = new Intl.DateTimeFormat("en-US", {
@@ -22782,17 +23533,17 @@ var firstPrompt = (file) => {
22782
23533
  var claudeProjectSlug = (cwd) => cwd.replace(/[^A-Za-z0-9]/gu, "-");
22783
23534
  var listDir = (dir) => {
22784
23535
  try {
22785
- return readdirSync5(dir).map((name) => path37.join(dir, name));
23536
+ return readdirSync5(dir).map((name) => path38.join(dir, name));
22786
23537
  } catch {
22787
23538
  return [];
22788
23539
  }
22789
23540
  };
22790
23541
  var SCAN_MS = 30 * 60000;
22791
23542
  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));
23543
+ const projects = path38.join(env.CLAUDE_CONFIG_DIR || path38.join(env.HOME || os11.homedir(), ".claude"), "projects");
23544
+ const project = path38.join(projects, claudeProjectSlug(cwd));
22794
23545
  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 })));
23546
+ 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
23547
  for (const { file, worker } of files)
22797
23548
  try {
22798
23549
  const stat = statSync5(file);
@@ -22807,7 +23558,7 @@ var scanClaudeTranscripts = (cwd, env, now = new Date) => {
22807
23558
  if (!seen)
22808
23559
  continue;
22809
23560
  notes.push(worker ? redispatchNote(seen, {
22810
- label: `worker ${path37.basename(file, ".jsonl")}`,
23561
+ label: `worker ${path38.basename(file, ".jsonl")}`,
22811
23562
  prompt: firstPrompt(file)
22812
23563
  }, 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
23564
  } catch {}
@@ -22906,13 +23657,13 @@ var agentModelDecision = (cwd, tool, options = {}) => {
22906
23657
  var MADE_WORKTREE = /^WORKTREE:[ \t]*(?!not made yet)\S(?![^\n]*not made yet)/mu;
22907
23658
  var namesMade = (word) => {
22908
23659
  try {
22909
- const stat = fs24.statSync(word);
23660
+ const stat = fs25.statSync(word);
22910
23661
  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));
23662
+ return stat.size < 1e6 && MADE_WORKTREE.test(fs25.readFileSync(word, "utf8"));
23663
+ const dotGit = path39.join(word, ".git");
23664
+ const link = fs25.statSync(dotGit);
23665
+ const admin = link.isFile() && link.size <= 4096 && /^gitdir: *(.+)/u.exec(fs25.readFileSync(dotGit, "utf8"));
23666
+ return !!admin && fs25.existsSync(path39.resolve(word, admin[1].trim(), FANOUT_TOKEN_FILE));
22916
23667
  } catch {
22917
23668
  return false;
22918
23669
  }
@@ -22958,8 +23709,8 @@ var spawnDecision = (descriptor, cwd, tool, permissionMode = null) => {
22958
23709
 
22959
23710
  // packages/workit-core/src/hooks/teardown.ts
22960
23711
  import { spawn } from "node:child_process";
22961
- import fs25 from "node:fs";
22962
- import path39 from "node:path";
23712
+ import fs26 from "node:fs";
23713
+ import path40 from "node:path";
22963
23714
  var REAP_INTERVAL_MS = 10 * 60000;
22964
23715
  var LOG_MAX_BYTES = 1 << 20;
22965
23716
  var ENDS = {
@@ -22970,9 +23721,9 @@ var ENDS = {
22970
23721
  };
22971
23722
  var SAFE_SESSION = /^[\w.@+][\w.:@/+-]{0,127}$/u;
22972
23723
  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");
23724
+ var teardownDir = (env) => path40.join(stateDir3(env), "procs");
23725
+ var teardownLog = (env) => path40.join(teardownDir(env), "teardown.log");
23726
+ var reapStamp = (env) => path40.join(teardownDir(env), "reap-at-start.stamp");
22976
23727
  function spawnDetached(request) {
22977
23728
  try {
22978
23729
  const shell = process.platform === "win32" && !/\.exe$/iu.test(request.command);
@@ -22999,13 +23750,13 @@ var teardownDeps = {
22999
23750
  var openLog = (env, args) => {
23000
23751
  try {
23001
23752
  const file = teardownLog(env);
23002
- fs25.mkdirSync(path39.dirname(file), { recursive: true });
23753
+ fs26.mkdirSync(path40.dirname(file), { recursive: true });
23003
23754
  let size = 0;
23004
23755
  try {
23005
- size = fs25.statSync(file).size;
23756
+ size = fs26.statSync(file).size;
23006
23757
  } 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(" ")}
23758
+ const fd = fs26.openSync(file, size > LOG_MAX_BYTES ? "w" : "a", 384);
23759
+ fs26.writeSync(fd, `${new Date(teardownDeps.now()).toISOString()} workit ${args.join(" ")}
23009
23760
  `);
23010
23761
  return fd;
23011
23762
  } catch {
@@ -23017,7 +23768,7 @@ function runCli(args, env) {
23017
23768
  try {
23018
23769
  const cli = locateWorkitCli2({ env });
23019
23770
  const cwd = teardownDir(env);
23020
- fs25.mkdirSync(cwd, { recursive: true });
23771
+ fs26.mkdirSync(cwd, { recursive: true });
23021
23772
  log = openLog(env, args);
23022
23773
  const started = teardownDeps.spawn({
23023
23774
  command: cli.command,
@@ -23027,7 +23778,7 @@ function runCli(args, env) {
23027
23778
  log
23028
23779
  });
23029
23780
  if (!started && log !== null)
23030
- fs25.writeSync(log, ` not started
23781
+ fs26.writeSync(log, ` not started
23031
23782
  `);
23032
23783
  return started;
23033
23784
  } catch {
@@ -23035,7 +23786,7 @@ function runCli(args, env) {
23035
23786
  } finally {
23036
23787
  if (log !== null)
23037
23788
  try {
23038
- fs25.closeSync(log);
23789
+ fs26.closeSync(log);
23039
23790
  } catch {}
23040
23791
  }
23041
23792
  }
@@ -23054,24 +23805,24 @@ function endSession(end, env = process.env) {
23054
23805
  var claim2 = (file, now) => {
23055
23806
  for (let attempt = 0;attempt < 2; attempt += 1)
23056
23807
  try {
23057
- fs25.writeFileSync(file, String(now), { flag: "wx", mode: 384 });
23808
+ fs26.writeFileSync(file, String(now), { flag: "wx", mode: 384 });
23058
23809
  return true;
23059
23810
  } catch (error) {
23060
23811
  if (error.code !== "EEXIST")
23061
23812
  return false;
23062
23813
  let held = Number.NaN;
23063
23814
  try {
23064
- held = Number(fs25.readFileSync(file, "utf8"));
23815
+ held = Number(fs26.readFileSync(file, "utf8"));
23065
23816
  } catch {}
23066
23817
  if (now - held < REAP_INTERVAL_MS)
23067
23818
  return false;
23068
- fs25.rmSync(file, { force: true });
23819
+ fs26.rmSync(file, { force: true });
23069
23820
  }
23070
23821
  return false;
23071
23822
  };
23072
23823
  var fresh = (stamp, now) => {
23073
23824
  try {
23074
- const last = Number(fs25.readFileSync(stamp, "utf8"));
23825
+ const last = Number(fs26.readFileSync(stamp, "utf8"));
23075
23826
  return now - last < REAP_INTERVAL_MS && last <= now;
23076
23827
  } catch {
23077
23828
  return false;
@@ -23084,7 +23835,7 @@ function reapAtStart(_cwd, env = process.env) {
23084
23835
  try {
23085
23836
  if (fresh(stamp, now))
23086
23837
  return false;
23087
- fs25.mkdirSync(path39.dirname(stamp), { recursive: true });
23838
+ fs26.mkdirSync(path40.dirname(stamp), { recursive: true });
23088
23839
  if (!claim2(lock, now))
23089
23840
  return false;
23090
23841
  } catch {
@@ -23097,12 +23848,12 @@ function reapAtStart(_cwd, env = process.env) {
23097
23848
  started = runCli(["stop", "--orphans", "--reason", "session-start"], env);
23098
23849
  if (started) {
23099
23850
  const temp = `${stamp}.${process.pid}`;
23100
- fs25.writeFileSync(temp, String(now), { mode: 384 });
23101
- fs25.renameSync(temp, stamp);
23851
+ fs26.writeFileSync(temp, String(now), { mode: 384 });
23852
+ fs26.renameSync(temp, stamp);
23102
23853
  }
23103
23854
  } catch {} finally {
23104
23855
  try {
23105
- fs25.rmSync(lock, { force: true });
23856
+ fs26.rmSync(lock, { force: true });
23106
23857
  } catch {}
23107
23858
  }
23108
23859
  return started;
@@ -23681,102 +24432,10 @@ Retry as: ${retry}` : ""}`,
23681
24432
  };
23682
24433
  };
23683
24434
 
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
- }
23775
-
23776
24435
  // packages/workit-core/src/agent-stamp.ts
23777
24436
  import { randomBytes as randomBytes4 } from "node:crypto";
23778
- import fs26 from "node:fs";
23779
- import path40 from "node:path";
24437
+ import fs27 from "node:fs";
24438
+ import path41 from "node:path";
23780
24439
  var STAMP_TTL_MS = 120000;
23781
24440
  var AGENT_ID = /^[\w-]{1,64}$/u;
23782
24441
  var workitCalls2 = (command, dialect = "posix") => {
@@ -23800,12 +24459,12 @@ var noteAgentStamps = (env, session, agentId, command, options = {}) => {
23800
24459
  const call = options.toolUseId ? callTag2(options.toolUseId) : randomBytes4(4).toString("hex");
23801
24460
  try {
23802
24461
  const dir = stampDir2(env, session);
23803
- fs26.mkdirSync(dir, { recursive: true, mode: 448 });
24462
+ fs27.mkdirSync(dir, { recursive: true, mode: 448 });
23804
24463
  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}`), ""));
24464
+ for (const name of fs27.readdirSync(dir))
24465
+ if (now - fs27.statSync(path41.join(dir, name)).mtimeMs > STAMP_TTL_MS)
24466
+ fs27.rmSync(path41.join(dir, name), { force: true });
24467
+ calls.forEach((argv, index) => fs27.writeFileSync(path41.join(dir, `${stampHash2(argv.join("\x00"))}.${agentId ?? ""}.${call}-${index}`), ""));
23809
24468
  } catch {}
23810
24469
  };
23811
24470
  var dropAgentStamps = (env, session, toolUseId, command) => {
@@ -23815,7 +24474,7 @@ var dropAgentStamps = (env, session, toolUseId, command) => {
23815
24474
 
23816
24475
  // packages/workit-core/src/hooks/hook-entry.ts
23817
24476
  import { existsSync as existsSync14, readFileSync as readFileSync11, realpathSync as realpathSync10 } from "node:fs";
23818
- import path41 from "node:path";
24477
+ import path42 from "node:path";
23819
24478
  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
24479
  var PACKAGE_ENTRIES = {
23821
24480
  "claude-code": /^(?:bin\/workit-hook\.mjs|src\/(?:run|hook)\.ts|dist\/workit-hook\.js)$/u,
@@ -23856,7 +24515,7 @@ var MORE_WRAPPERS = new Set(["strace", "ltrace", "watch", "unshare", "firejail",
23856
24515
  var baseName3 = (word) => (word.split(/[\\/]/u).at(-1) ?? "").replace(/\.exe$/iu, "").toLowerCase();
23857
24516
  var packageAt = (dir) => {
23858
24517
  try {
23859
- const name = JSON.parse(readFileSync11(path41.join(dir, "package.json"), "utf8")).name;
24518
+ const name = JSON.parse(readFileSync11(path42.join(dir, "package.json"), "utf8")).name;
23860
24519
  const short = /^@workit-dev\/(claude-code|codex|cursor|core)$/u.exec(String(name))?.[1];
23861
24520
  if (short)
23862
24521
  return short;
@@ -23867,7 +24526,7 @@ var packageAt = (dir) => {
23867
24526
  [".cursor-plugin", "cursor"]
23868
24527
  ]) {
23869
24528
  try {
23870
- const name = JSON.parse(readFileSync11(path41.join(dir, manifest, "plugin.json"), "utf8")).name;
24529
+ const name = JSON.parse(readFileSync11(path42.join(dir, manifest, "plugin.json"), "utf8")).name;
23871
24530
  if (name === "workit")
23872
24531
  return short;
23873
24532
  } catch {}
@@ -23875,12 +24534,12 @@ var packageAt = (dir) => {
23875
24534
  return null;
23876
24535
  };
23877
24536
  var entryByPath = (file) => {
23878
- let dir = path41.dirname(file);
23879
- for (let depth = 0;depth < 4; depth += 1, dir = path41.dirname(dir)) {
24537
+ let dir = path42.dirname(file);
24538
+ for (let depth = 0;depth < 4; depth += 1, dir = path42.dirname(dir)) {
23880
24539
  const short = packageAt(dir);
23881
24540
  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")))
24541
+ return PACKAGE_ENTRIES[short]?.test(path42.relative(dir, file).split(path42.sep).join("/")) ?? false;
24542
+ if (existsSync14(path42.join(dir, "package.json")))
23884
24543
  return false;
23885
24544
  }
23886
24545
  return false;
@@ -23908,676 +24567,348 @@ var entryNamed = (word, scan) => {
23908
24567
  const fd = /^\/(?:dev|proc\/self)\/fd\/(\d+)$/u.exec(text)?.[1];
23909
24568
  if (fd !== undefined && scan.fds.has(fd))
23910
24569
  return text;
23911
- if (scan.dir === null && !path41.isAbsolute(text))
24570
+ if (scan.dir === null && !path42.isAbsolute(text))
23912
24571
  return null;
23913
- for (const file of expandGlob(path41.resolve(scan.dir ?? "/", text))) {
24572
+ for (const file of expandGlob(path42.resolve(scan.dir ?? "/", text))) {
23914
24573
  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;
24089
- }
24090
- return null;
24091
- };
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
- }
24102
- }
24103
- return null;
24104
- };
24105
- var scanCommand = (command, dialect, scan) => {
24106
- let segments;
24107
- try {
24108
- segments = segmentsOf(command, dialect);
24109
- } 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;
24203
- }
24204
- return null;
24205
- };
24206
- var cmdScript2 = (words) => {
24207
- const name = baseName3(words[0] ?? "");
24208
- if (!/^(?:cmd|pwsh|powershell)$/u.test(name))
24209
- 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] ?? "")))
24215
- 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) {
24574
+ return text;
24575
+ let real;
24310
24576
  try {
24311
- const real = fs27.realpathSync(place);
24312
- return isWorkit(real);
24313
- } catch {}
24577
+ real = realpathSync10(file);
24578
+ } catch {
24579
+ continue;
24580
+ }
24581
+ if (ENTRY_NAMES.test(baseName3(real)) || entryByPath(real))
24582
+ return text;
24314
24583
  }
24315
- return false;
24584
+ return null;
24316
24585
  };
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))))
24586
+ var noteLink = (words, scan) => {
24587
+ if (!/^(?:ln|cp|install)$/u.test(baseName3(words[0] ?? "")) || scan.dir === null)
24327
24588
  return;
24328
- if (seg)
24329
- seg.scoped ??= nameOf(word);
24330
- else
24331
- scan.shell ??= nameOf(word);
24589
+ const names = words.slice(1).filter((word) => !word.startsWith("-"));
24590
+ const dest = names.at(-1);
24591
+ if (dest === undefined || names.length < 2)
24592
+ return;
24593
+ for (const source of names.slice(0, -1).filter((name) => entryNamed(name, scan))) {
24594
+ const to = path42.resolve(scan.dir, expand(dest, scan.vars));
24595
+ scan.links.add(to);
24596
+ scan.links.add(path42.join(to, path42.basename(source)));
24597
+ }
24332
24598
  };
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;
24599
+ var runsEntry = (words, inputs, scan) => {
24600
+ const named = (word) => entryNamed(word, scan);
24601
+ let at = 0;
24602
+ while (at < words.length) {
24603
+ while (/^[A-Za-z_]\w*=/u.test(words[at] ?? ""))
24604
+ at += 1;
24605
+ const word = words[at];
24606
+ if (word === undefined)
24607
+ return null;
24608
+ const entry = named(word);
24609
+ if (entry)
24610
+ return entry;
24611
+ const name = baseName3(word);
24612
+ const split = name === "env" ? words.findIndex((w) => /^(?:-\w*S|--split-string)/u.test(w)) : -1;
24613
+ if (split > at) {
24614
+ const line = /^(?:-\w*S|--split-string=?)(.*)$/su.exec(words[split] ?? "")?.[1] || words[split + 1];
24615
+ const rest = words.slice(split + (line === words[split + 1] ? 2 : 1));
24616
+ return runsEntry([...(line ?? "").split(/\s+/u).filter(Boolean), ...rest], inputs, scan);
24364
24617
  }
24365
- if (options && word === "--") {
24366
- options = false;
24618
+ if (MORE_WRAPPERS.has(name)) {
24619
+ at = pastOptions(words, at + 1, "");
24367
24620
  continue;
24368
24621
  }
24369
- if (options && word === "-") {
24370
- risky("env -i");
24622
+ const takes = WRAPPERS3[name];
24623
+ if (takes !== undefined && !PACKAGE_RUNNERS2.has(name)) {
24624
+ at = pastOptions(words, at + 1, takes, name === "env" || name === "sudo");
24371
24625
  continue;
24372
24626
  }
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);
24627
+ if (name === "busybox" || name === "toybox") {
24628
+ at += 1;
24385
24629
  continue;
24386
24630
  }
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
- }
24631
+ 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] ?? "");
24632
+ if (runner) {
24633
+ at += PACKAGE_RUNNERS2.has(name) ? 1 : 2;
24634
+ while (words[at]?.startsWith("-"))
24635
+ at += /^(?:-p|--package|-c|--call)$/u.test(words[at] ?? "") ? 2 : 1;
24636
+ if (/^@workit-dev\/(?:claude-code|codex|cursor)(?:@|$)/u.test(words[at] ?? ""))
24637
+ return words[at] ?? null;
24409
24638
  continue;
24410
24639
  }
24411
- if (ASSIGN.test(word)) {
24412
- unset(word);
24413
- continue;
24640
+ if (!RUNNERS.has(name))
24641
+ return null;
24642
+ if ((name === "bun" || name === "deno") && NO_RUN.has(words[at + 1] ?? ""))
24643
+ return null;
24644
+ for (const arg of [...words.slice(at + 1), ...inputs]) {
24645
+ const hit = named(arg);
24646
+ if (hit)
24647
+ return hit;
24414
24648
  }
24415
- return commandAt(words.slice(index), scan, seg, new Set([...expands].filter((at2) => at2 >= index).map((at2) => at2 - index)));
24649
+ return null;
24416
24650
  }
24651
+ return null;
24417
24652
  };
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)
24653
+ var KEYWORDS3 = new Set([
24654
+ "{",
24655
+ "}",
24656
+ "if",
24657
+ "then",
24658
+ "elif",
24659
+ "else",
24660
+ "fi",
24661
+ "while",
24662
+ "until",
24663
+ "do",
24664
+ "done",
24665
+ "esac",
24666
+ "!"
24667
+ ]);
24668
+ var pastKeywords = (words) => {
24669
+ let at = 0;
24670
+ for (;; ) {
24671
+ if (words[at] === "function")
24672
+ at += 2;
24673
+ else if (KEYWORDS3.has(words[at] ?? ""))
24674
+ at += 1;
24675
+ else
24436
24676
  break;
24437
- index = pastOptions(words, index + 1, takes);
24438
24677
  }
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;
24678
+ return /^(?:for|case|select)$/u.test(words[at] ?? "") ? [] : words.slice(at);
24679
+ };
24680
+ 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(" "));
24681
+ var TOKENS2 = /[\s'"`(),[\]{};|&<>=!]+/u;
24682
+ var ENTRY_SAMPLES = [
24683
+ "workit-hook.mjs",
24684
+ "workit-hook.js",
24685
+ "workit-hook.ts",
24686
+ "cursor-session-start.js"
24687
+ ];
24688
+ var tokenEntry = (token, scan) => {
24689
+ if (!/[\\/]/u.test(token) && !existsSync14(path42.resolve(scan.dir ?? "/", token)))
24690
+ return null;
24691
+ return entryNamed(token, scan);
24692
+ };
24693
+ var opaqueEntry = (words, inputs, scan) => {
24694
+ let at = 0;
24695
+ while (/^[A-Za-z_]\w*=/u.test(words[at] ?? ""))
24696
+ at += 1;
24697
+ const head = baseName3(words[at] ?? "");
24698
+ if (READERS2.has(head))
24699
+ return null;
24700
+ if ((head === "bun" || head === "deno") && NO_RUN.has(words[at + 1] ?? ""))
24701
+ return null;
24702
+ if (head === "git" && !words.some((word) => word.includes("alias.")))
24703
+ return null;
24704
+ if (head === "workit" || head === "workit-cli")
24705
+ return null;
24706
+ const tokens = words.flatMap((word) => word.split(TOKENS2)).filter(Boolean);
24707
+ const runner = (token) => RUNNERS.has(baseName3(token)) && !/^(?:\.|source)$/u.test(token) || PACKAGE_RUNNERS2.has(baseName3(token));
24708
+ if (!tokens.some(runner))
24709
+ return null;
24710
+ if (scan.fed)
24711
+ return scan.fed;
24712
+ for (const token of tokens) {
24713
+ const hit = tokenEntry(token, scan);
24714
+ if (hit)
24715
+ return hit;
24716
+ }
24717
+ if (head === "find")
24718
+ for (const [index, word] of words.entries()) {
24719
+ const named = /^-i?name$/u.test(words[index - 1] ?? "") && /^[^*?[]/u.test(word);
24720
+ const pattern = named ? globPattern(word) : null;
24721
+ if (pattern && ENTRY_SAMPLES.some((sample) => pattern.test(sample)))
24722
+ return word;
24723
+ }
24724
+ if (/^(?:xargs|parallel)$/u.test(head) || tokens.includes("xargs"))
24725
+ for (const input of inputs) {
24726
+ try {
24727
+ const file = path42.resolve(scan.dir ?? "/", expand(input, scan.vars));
24728
+ const text = readFileSync11(file, "utf8").slice(0, 65536);
24729
+ for (const token of text.split(/\s+/u).filter(Boolean)) {
24730
+ const hit = tokenEntry(token, scan);
24731
+ if (hit)
24732
+ return hit;
24733
+ }
24734
+ } catch {}
24457
24735
  }
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
24736
+ return null;
24475
24737
  };
24476
- var loginScript = (words) => {
24477
- const at = words.findIndex((word) => /^(?:su|runuser|script)$/u.test(base2(word)));
24478
- if (at < 0)
24738
+ var expandedCommand = (words, scan) => {
24739
+ let at = 0;
24740
+ while (/^[A-Za-z_]\w*=/u.test(words[at] ?? ""))
24741
+ at += 1;
24742
+ if (!/[$`]/u.test(words[at] ?? ""))
24479
24743
  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))
24744
+ for (const word of words.slice(at + 1)) {
24745
+ const hit = entryNamed(word, scan);
24746
+ if (hit)
24747
+ return hit;
24748
+ }
24749
+ return null;
24750
+ };
24751
+ var optionsEntry = (words, scan) => {
24752
+ for (const word of words) {
24753
+ const value = /^(?:NODE_OPTIONS|BUN_OPTIONS)=(.*)$/su.exec(word)?.[1];
24754
+ if (value === undefined)
24488
24755
  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);
24756
+ for (const token of value.split(TOKENS2).filter(Boolean)) {
24757
+ const hit = tokenEntry(token, scan);
24758
+ if (hit)
24759
+ return hit;
24760
+ }
24492
24761
  }
24493
24762
  return null;
24494
24763
  };
24495
- var scanCommand2 = (command, dialect, depth, scan) => {
24764
+ var scanCommand2 = (command, dialect, scan) => {
24496
24765
  let segments;
24497
24766
  try {
24498
24767
  segments = segmentsOf(command, dialect);
24499
24768
  } catch {
24500
- return;
24769
+ return null;
24501
24770
  }
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
- }
24771
+ for (const [index, segment] of segments.entries()) {
24772
+ if (segment.unanalyzable)
24519
24773
  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;
24774
+ bindLoop(segment.words, segments.slice(index + 1), scan);
24775
+ const words = pastKeywords(segment.words);
24776
+ const fed = scan.fed;
24777
+ scan.fed = null;
24778
+ const hit = segmentEntry(segment, words, dialect, scan, fed);
24779
+ if (hit)
24780
+ return hit;
24537
24781
  }
24782
+ return null;
24538
24783
  };
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))
24784
+ var bindLoop = (raw, after, scan) => {
24785
+ const at = raw.findIndex((word) => !KEYWORDS3.has(word));
24786
+ const verb = raw[at];
24787
+ if ((verb === "for" || verb === "select") && raw[at + 2] === "in") {
24788
+ const name = raw[at + 1] ?? "";
24789
+ const items = raw.slice(at + 3);
24790
+ const item = items.find((word) => entryNamed(word, scan)) ?? items[0];
24791
+ if (/^[A-Za-z_]\w*$/u.test(name) && item !== undefined)
24792
+ scan.vars.set(name, expand(item, scan.vars));
24793
+ return;
24794
+ }
24795
+ const read = raw.indexOf("read");
24796
+ if (read < 0 || !raw.slice(0, read).some((word) => word === "while" || word === "until"))
24797
+ return;
24798
+ const fed = after.find((segment) => segment.words[0] === "done")?.stdin?.[0];
24799
+ const line = fed?.split(`
24800
+ `)[0]?.trim();
24801
+ const name = raw.slice(read + 1).find((word) => /^[A-Za-z_]\w*$/u.test(word));
24802
+ if (name && line)
24803
+ scan.vars.set(name, line);
24804
+ };
24805
+ var segmentEntry = (segment, words, dialect, scan, fed) => {
24806
+ const verb = baseName3(words[0] ?? "");
24807
+ if (["cd", "pushd", "chdir", "set-location", "sl"].includes(verb)) {
24808
+ const target = words.slice(1).find((word) => !word.startsWith("-") || word === "-");
24809
+ const moved = target === undefined ? userHome2(process.env) : expand(target, scan.vars);
24810
+ scan.dir = moved === "-" || /[$`]/u.test(moved) ? null : path42.isAbsolute(moved) ? moved : scan.dir && path42.resolve(scan.dir, moved);
24811
+ if (scan.dir === null)
24812
+ scan.vars.delete("PWD");
24813
+ else
24814
+ scan.vars.set("PWD", scan.dir);
24545
24815
  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;
24816
+ }
24817
+ if (verb === "popd") {
24818
+ scan.dir = null;
24819
+ return null;
24820
+ }
24821
+ const declares = ["export", "declare", "typeset", "local", "readonly"].includes(verb);
24822
+ const assigns = declares ? words.slice(1) : words.every((word) => /^[A-Za-z_]\w*=/u.test(word)) ? words : [];
24823
+ for (const word of assigns) {
24824
+ const [name = "", value] = word.split(/=(.*)/su);
24825
+ if (value !== undefined && /^[A-Za-z_]\w*$/u.test(name))
24826
+ scan.vars.set(name, expand(value.replace(/^(['"])(.*)\1$/su, "$2"), scan.vars));
24827
+ }
24828
+ const options = optionsEntry(declares ? words.slice(1) : words, scan);
24829
+ if (options)
24830
+ return options;
24831
+ if (verb === "exec" && words.slice(1).every((word) => /^\d+$/u.test(word))) {
24832
+ for (const input of segment.inputs ?? [])
24833
+ if (entryNamed(input, scan))
24834
+ for (const fd of words.slice(1))
24835
+ scan.fds.add(fd);
24836
+ }
24837
+ const inputs = segment.inputs ?? [];
24838
+ const entry = runsEntry(words, inputs, scan) ?? expandedCommand(words, scan) ?? opaqueEntry(words, inputs, { ...scan, fed });
24839
+ if (entry)
24840
+ return entry;
24841
+ if (segment.pipe)
24842
+ scan.fed = words.slice(1).flatMap((word) => word.split(TOKENS2)).map((token) => token ? tokenEntry(token, scan) : null).find(Boolean) ?? null;
24843
+ noteLink(words, scan);
24844
+ if (scan.depth >= 4)
24845
+ return null;
24846
+ const nested = (script) => scanCommand2(script, dialect, {
24847
+ ...scan,
24848
+ vars: new Map(scan.vars),
24849
+ fed: null,
24850
+ depth: scan.depth + 1
24851
+ });
24852
+ const scripts = [...segment.subs ?? []];
24853
+ const script = shellScript2(words) ?? cmdScript2(words) ?? workitScript(words);
24854
+ if (script)
24855
+ scripts.push(script);
24856
+ if (!script && /^(?:ba|z|da|k)?sh$/u.test(verb) && words.slice(1).every((word) => word.startsWith("-")) || verb === "at" || verb === "batch")
24857
+ scripts.push(...segment.stdin ?? []);
24858
+ for (const text of scripts) {
24859
+ const hit = nested(text);
24860
+ if (hit)
24861
+ return hit;
24862
+ }
24863
+ return null;
24550
24864
  };
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))
24865
+ var cmdScript2 = (words) => {
24866
+ const name = baseName3(words[0] ?? "");
24867
+ if (!/^(?:cmd|pwsh|powershell)$/u.test(name))
24556
24868
  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;
24869
+ const flag = words.findIndex((word, at) => at > 0 && /^[/-](?:c|k|command)$/iu.test(word));
24870
+ return flag < 0 ? null : words.slice(flag + 1).join(" ").replaceAll("\\", "/") || null;
24575
24871
  };
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}.`;
24872
+ var workitScript = (words) => {
24873
+ if (!/^workit(?:-cli)?$/u.test(baseName3(words[0] ?? "")))
24874
+ return null;
24875
+ const dash = words.indexOf("--");
24876
+ return dash < 0 ? null : words.slice(dash + 1).join(" ") || null;
24877
+ };
24878
+ var substitutions2 = (command) => {
24879
+ const found = [];
24880
+ for (let at = command.indexOf("$(");at >= 0 && found.length < 32; at = command.indexOf("$(", at + 1)) {
24881
+ if (command[at + 2] === "(")
24882
+ continue;
24883
+ let depth = 1;
24884
+ let end = at + 2;
24885
+ for (;end < command.length && depth > 0; end += 1)
24886
+ if (command[end] === "(")
24887
+ depth += 1;
24888
+ else if (command[end] === ")")
24889
+ depth -= 1;
24890
+ found.push(command.slice(at + 2, end - 1));
24891
+ }
24892
+ return found;
24893
+ };
24894
+ var hookEntryRun = (cwd, command, dialect = "posix") => {
24895
+ const scan = (text) => scanCommand2(text, dialect, {
24896
+ dir: cwd,
24897
+ vars: new Map([["PWD", cwd]]),
24898
+ links: new Set,
24899
+ fds: new Set,
24900
+ fed: null,
24901
+ depth: 0
24902
+ });
24903
+ const texts = dialect === "posix" && /[A-Za-z]:\\/u.test(command) ? [command, command.replaceAll("\\", "/")] : [command];
24904
+ for (const text of texts) {
24905
+ const hit = scan(text) ?? substitutions2(text).map(scan).find(Boolean);
24906
+ if (hit)
24907
+ return hit;
24908
+ }
24909
+ return null;
24580
24910
  };
24911
+ 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
24912
 
24582
24913
  // packages/workit-core/src/hooks/handle.ts
24583
24914
  var usable2 = (value) => value === "native" || value === "partial";