@workit-dev/codex 1.7.0 → 1.7.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.
@@ -55,7 +55,7 @@ var capabilitiesFor = (descriptor, observed = {}) => descriptor.capabilities.map
55
55
  };
56
56
  });
57
57
  // packages/workit-core/src/hooks/context.ts
58
- import { createHash as createHash13 } from "node:crypto";
58
+ import { createHash as createHash11 } from "node:crypto";
59
59
  import fs14 from "node:fs";
60
60
  import path19 from "node:path";
61
61
 
@@ -10278,15 +10278,15 @@ function candidateDigest(input) {
10278
10278
  }
10279
10279
 
10280
10280
  // packages/workit-core/src/core/task-evaluation.ts
10281
- import { createHash as createHash12 } from "node:crypto";
10281
+ import { createHash as createHash10 } from "node:crypto";
10282
10282
  import * as fs13 from "node:fs";
10283
10283
  import { spawnSync as spawnSync11 } from "node:child_process";
10284
10284
  import path18 from "node:path";
10285
10285
 
10286
- // packages/workit-core/src/core/task-store.ts
10287
- import { createHash as createHash10, randomUUID as randomUUID3 } from "node:crypto";
10288
- import * as fs11 from "node:fs";
10289
- import path14 from "node:path";
10286
+ // packages/workit-core/src/core/task-read.ts
10287
+ import { randomUUID as randomUUID3 } from "node:crypto";
10288
+ import * as fs10 from "node:fs";
10289
+ import path13 from "node:path";
10290
10290
 
10291
10291
  // node_modules/@openclaw/fs-safe/dist/errors.js
10292
10292
  var OPERATIONAL_CODES = new Set([
@@ -10889,180 +10889,15 @@ function acquireFileLockSync(targetPath, options) {
10889
10889
  }
10890
10890
  }
10891
10891
  }
10892
- // packages/workit-core/src/host-session.ts
10893
- import { createHash as createHash8, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
10894
- import fs8 from "node:fs";
10895
- import path11 from "node:path";
10896
- var HOST_SESSION_VARS = [
10897
- ["OPENCODE_SESSION_ID", () => "opencode"],
10898
- ["PI_SESSION_ID", () => "pi"],
10899
- [
10900
- "CODEX_THREAD_ID",
10901
- (env) => env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE === "Codex Desktop" || env.CODEX_ELECTRON_RESOURCES_PATH ? "codex_desktop" : "codex_cli"
10902
- ]
10903
- ];
10904
- var family = (host) => host?.replace(/_(?:cli|desktop)$/, "") ?? null;
10905
- function hostSessionFromEnv(env) {
10906
- const value = (key) => env[key]?.trim() || null;
10907
- let inner = null;
10908
- for (const [key, host] of HOST_SESSION_VARS) {
10909
- const session = value(key);
10910
- if (session) {
10911
- inner = { host: host(env), session };
10912
- break;
10913
- }
10914
- }
10915
- const declared = value("WORKIT_HOST");
10916
- if (env.WORKIT_SESSION_ID !== undefined) {
10917
- const inherited = inner !== null && declared !== null && family(declared) !== family(inner.host);
10918
- if (!inherited)
10919
- return { host: declared, session: value("WORKIT_SESSION_ID") };
10920
- }
10921
- return inner ? { host: inner.host, session: inner.session } : { host: declared, session: null };
10922
- }
10923
- var ISSUED_PER_LEAD = 64;
10924
- var ISSUED_SESSIONS_MARKER = "workit-issued-sessions/3";
10925
- var hash = (value) => createHash8("sha256").update(value).digest("hex").slice(0, 32);
10926
- var userIssuedRoot = () => path11.join(resolveStateDir(), "issued");
10927
- var userTokenRoot = () => path11.join(resolveStateDir(), "issued-tokens");
10928
- function migrateRepoIssued(cwd) {
10929
- if (cwd === undefined)
10930
- return;
10931
- let old;
10932
- try {
10933
- const location = resolveStore(cwd);
10934
- if (location instanceof Error)
10935
- return;
10936
- old = path11.join(location.dir, "hooks", "issued");
10937
- if (!fs8.existsSync(old))
10938
- return;
10939
- } catch {
10940
- return;
10941
- }
10942
- for (const lead of safeList(old)) {
10943
- try {
10944
- const from = path11.join(old, lead);
10945
- if (!fs8.statSync(from).isDirectory())
10946
- continue;
10947
- const to = path11.join(userIssuedRoot(), lead);
10948
- fs8.mkdirSync(to, { recursive: true, mode: 448 });
10949
- for (const id of fs8.readdirSync(from)) {
10950
- try {
10951
- fs8.copyFileSync(path11.join(from, id), path11.join(to, id), fs8.constants.COPYFILE_EXCL);
10952
- } catch (error) {
10953
- if (error.code !== "EEXIST")
10954
- throw error;
10955
- }
10956
- fs8.rmSync(path11.join(from, id), { force: true });
10957
- }
10958
- removeIfEmpty(from);
10959
- } catch {}
10960
- }
10961
- removeIfEmpty(old);
10962
- }
10963
- var safeList = (dir) => {
10964
- try {
10965
- return fs8.readdirSync(dir);
10966
- } catch {
10967
- return [];
10968
- }
10969
- };
10970
- var removeIfEmpty = (dir) => {
10971
- try {
10972
- fs8.rmdirSync(dir);
10973
- } catch {}
10974
- };
10975
- var tokenHash = (token) => createHash8("sha256").update(token).digest("hex");
10976
- function recordIssuedSession(cwd, lead, issued) {
10977
- const token = randomBytes2(18).toString("hex");
10978
- try {
10979
- migrateRepoIssued(cwd);
10980
- const own = hash(issued);
10981
- const tokens = path11.join(userTokenRoot(), hash(lead));
10982
- fs8.mkdirSync(tokens, { recursive: true, mode: 448 });
10983
- fs8.writeFileSync(path11.join(tokens, own), `${tokenHash(token)}
10984
- `, { mode: 384, flag: "wx" });
10985
- const dir = path11.join(userIssuedRoot(), hash(lead));
10986
- fs8.mkdirSync(dir, { recursive: true, mode: 448 });
10987
- fs8.writeFileSync(path11.join(dir, own), `${ISSUED_SESSIONS_MARKER}
10988
- `, { mode: 384 });
10989
- pruneIssued(dir, own, tokens);
10990
- return token;
10991
- } catch {
10992
- return null;
10993
- }
10994
- }
10995
- function judgeBranch(cwd) {
10996
- const branch = currentBranch(cwd);
10997
- return branch && !isProtectedTarget(cwd, branch) ? branch : null;
10998
- }
10999
- function verdictCommand(options) {
11000
- const kind = options.judge === "verifier" ? "<live|unit>" : options.judge === "reviewer" ? "review" : "<live|unit|review>";
11001
- return [
11002
- "workit ledger verdict <verified|failed|blocked>",
11003
- `--kind ${kind}`,
11004
- `--branch ${options.branch ?? "<branch>"}`,
11005
- options.session ? `--session ${options.session}` : null,
11006
- options.token ? `--token=${options.token}` : null,
11007
- '--how "<what you ran and saw>"'
11008
- ].filter(Boolean).join(" ");
11009
- }
11010
- function pruneIssued(dir, own, tokens) {
11011
- try {
11012
- const entries = fs8.readdirSync(dir);
11013
- if (entries.length <= ISSUED_PER_LEAD)
11014
- return;
11015
- const byAge = entries.filter((name) => name !== own).map((name) => ({ name, at: fs8.statSync(path11.join(dir, name)).mtimeMs })).toSorted((a, b) => a.at - b.at);
11016
- for (const { name } of byAge.slice(0, entries.length - ISSUED_PER_LEAD)) {
11017
- fs8.rmSync(path11.join(dir, name), { force: true });
11018
- fs8.rmSync(path11.join(tokens, name), { force: true });
11019
- }
11020
- } catch {}
11021
- }
11022
- var issuedRecord = (cwd, claimed) => {
11023
- const cut = claimed.lastIndexOf(":");
11024
- if (cut <= 0)
11025
- return null;
11026
- migrateRepoIssued(cwd);
11027
- try {
11028
- return fs8.readFileSync(path11.join(userIssuedRoot(), hash(claimed.slice(0, cut)), hash(claimed)), "utf8");
11029
- } catch {
11030
- return null;
11031
- }
11032
- };
11033
- var TOKEN_HASH = /^([0-9a-f]{64})$/mu;
11034
- var issuedToken = (claimed) => {
11035
- const cut = claimed.lastIndexOf(":");
11036
- if (cut <= 0)
11037
- return { stored: null, leadBound: false };
11038
- const dir = path11.join(userTokenRoot(), hash(claimed.slice(0, cut)));
11039
- try {
11040
- const text = fs8.readFileSync(path11.join(dir, hash(claimed)), "utf8");
11041
- return { stored: TOKEN_HASH.exec(text)?.[1] ?? null, leadBound: true };
11042
- } catch {
11043
- return { stored: null, leadBound: safeList(dir).length > 0 };
11044
- }
11045
- };
11046
- function issuedBinding(cwd, claimed) {
11047
- const record = issuedRecord(cwd, claimed);
11048
- const { stored, leadBound } = issuedToken(claimed);
11049
- if (stored)
11050
- return "token";
11051
- if (record === null)
11052
- return null;
11053
- return leadBound ? "token" : "legacy";
11054
- }
11055
- var OWN_CHILD_SHELL = new Set(["opencode", "pi"]);
11056
-
11057
10892
  // packages/workit-core/src/core/package-root.ts
11058
10893
  import { existsSync as existsSync3 } from "node:fs";
11059
- import path12 from "node:path";
10894
+ import path11 from "node:path";
11060
10895
  import { fileURLToPath } from "node:url";
11061
10896
  var packageRoot = () => {
11062
- let dir = path12.dirname(fileURLToPath(import.meta.url));
10897
+ let dir = path11.dirname(fileURLToPath(import.meta.url));
11063
10898
  while (true) {
11064
- const parent = path12.dirname(dir);
11065
- if (existsSync3(path12.join(dir, "package.json")) || parent === dir)
10899
+ const parent = path11.dirname(dir);
10900
+ if (existsSync3(path11.join(dir, "package.json")) || parent === dir)
11066
10901
  return dir;
11067
10902
  dir = parent;
11068
10903
  }
@@ -11070,7 +10905,7 @@ var packageRoot = () => {
11070
10905
 
11071
10906
  // packages/workit-core/src/core/store-lock.ts
11072
10907
  import { spawnSync as spawnSync7 } from "node:child_process";
11073
- import fs9 from "node:fs";
10908
+ import fs8 from "node:fs";
11074
10909
  import { hostname } from "node:os";
11075
10910
  var metadataLockSchema = object({
11076
10911
  pid: number2().int().nonnegative().safe(),
@@ -11113,7 +10948,7 @@ var parseProcStatStart = (stat) => {
11113
10948
  };
11114
10949
  var readProcStat = (pid) => {
11115
10950
  try {
11116
- return fs9.readFileSync(`/proc/${pid}/stat`, "utf8");
10951
+ return fs8.readFileSync(`/proc/${pid}/stat`, "utf8");
11117
10952
  } catch {
11118
10953
  return null;
11119
10954
  }
@@ -11142,7 +10977,7 @@ var processStartOf = (pid, deps = {}) => {
11142
10977
  };
11143
10978
  var readTrimmed = (file) => {
11144
10979
  try {
11145
- return fs9.readFileSync(file, "utf8").trim() || null;
10980
+ return fs8.readFileSync(file, "utf8").trim() || null;
11146
10981
  } catch {
11147
10982
  return null;
11148
10983
  }
@@ -11153,7 +10988,7 @@ var localLockHost = () => {
11153
10988
  return cachedLockHost;
11154
10989
  let pidns = null;
11155
10990
  try {
11156
- pidns = /\[(\d+)\]/.exec(fs9.readlinkSync("/proc/self/ns/pid"))?.[1] ?? null;
10991
+ pidns = /\[(\d+)\]/.exec(fs8.readlinkSync("/proc/self/ns/pid"))?.[1] ?? null;
11157
10992
  } catch {}
11158
10993
  const boot = readTrimmed("/proc/sys/kernel/random/boot_id");
11159
10994
  cachedLockHost = pidns || boot ? `${hostname()}#${pidns ?? "?"}:${boot ?? "?"}` : hostname();
@@ -11199,7 +11034,7 @@ var classifyLockOwner = (payload, ageMs, localHost = localLockHost(), options =
11199
11034
  };
11200
11035
  var ageOf = (file, nowMs) => {
11201
11036
  try {
11202
- return nowMs - fs9.lstatSync(file).mtimeMs;
11037
+ return nowMs - fs8.lstatSync(file).mtimeMs;
11203
11038
  } catch {
11204
11039
  return null;
11205
11040
  }
@@ -11210,7 +11045,7 @@ var clearAbandonedReclaimGuard = (lockPath, nowMs = Date.now()) => {
11210
11045
  if (age === null || age <= RECLAIM_GUARD_TTL_MS)
11211
11046
  return false;
11212
11047
  try {
11213
- fs9.rmdirSync(guard);
11048
+ fs8.rmdirSync(guard);
11214
11049
  return true;
11215
11050
  } catch {
11216
11051
  return false;
@@ -11219,8 +11054,8 @@ var clearAbandonedReclaimGuard = (lockPath, nowMs = Date.now()) => {
11219
11054
 
11220
11055
  // packages/workit-core/src/store/event-log.ts
11221
11056
  import { randomUUID as randomUUID2 } from "node:crypto";
11222
- import fs10 from "node:fs";
11223
- import path13 from "node:path";
11057
+ import fs9 from "node:fs";
11058
+ import path12 from "node:path";
11224
11059
  var EVENT_VERSION = 1;
11225
11060
 
11226
11061
  class LogDamage extends Error {
@@ -11249,7 +11084,7 @@ var parseEvent = (line, file, offset) => {
11249
11084
  function readLog(file, from = 0, expectSeq = null) {
11250
11085
  let fd;
11251
11086
  try {
11252
- fd = fs10.openSync(file, "r");
11087
+ fd = fs9.openSync(file, "r");
11253
11088
  } catch (error) {
11254
11089
  if (error.code === "ENOENT")
11255
11090
  return null;
@@ -11258,13 +11093,13 @@ function readLog(file, from = 0, expectSeq = null) {
11258
11093
  let bytes;
11259
11094
  let size;
11260
11095
  try {
11261
- size = fs10.fstatSync(fd).size;
11096
+ size = fs9.fstatSync(fd).size;
11262
11097
  if (from > size)
11263
11098
  throw new LogDamage(`${file}: shorter than its snapshot`);
11264
11099
  bytes = Buffer.alloc(size - from);
11265
11100
  let read = 0;
11266
11101
  while (read < bytes.length) {
11267
- const got = fs10.readSync(fd, bytes, read, bytes.length - read, from + read);
11102
+ const got = fs9.readSync(fd, bytes, read, bytes.length - read, from + read);
11268
11103
  if (got === 0)
11269
11104
  break;
11270
11105
  read += got;
@@ -11272,7 +11107,7 @@ function readLog(file, from = 0, expectSeq = null) {
11272
11107
  bytes = bytes.subarray(0, read);
11273
11108
  size = from + read;
11274
11109
  } finally {
11275
- fs10.closeSync(fd);
11110
+ fs9.closeSync(fd);
11276
11111
  }
11277
11112
  const events = [];
11278
11113
  let start = 0;
@@ -11297,60 +11132,34 @@ function readLog(file, from = 0, expectSeq = null) {
11297
11132
  }
11298
11133
  var fsyncDirectory = (dir) => {
11299
11134
  try {
11300
- const fd = fs10.openSync(dir, "r");
11135
+ const fd = fs9.openSync(dir, "r");
11301
11136
  try {
11302
- fs10.fsyncSync(fd);
11137
+ fs9.fsyncSync(fd);
11303
11138
  } finally {
11304
- fs10.closeSync(fd);
11139
+ fs9.closeSync(fd);
11305
11140
  }
11306
11141
  } catch (error) {
11307
11142
  if (process.platform !== "win32")
11308
11143
  throw error;
11309
11144
  }
11310
11145
  };
11311
- function appendEvent(file, event, validEnd) {
11312
- const line = Buffer.from(`${JSON.stringify(event)}
11313
- `, "utf8");
11314
- const created = !fs10.existsSync(file);
11315
- if (!created && fs10.statSync(file).size !== validEnd) {
11316
- const cut = fs10.openSync(file, "r+");
11317
- try {
11318
- fs10.ftruncateSync(cut, validEnd);
11319
- fs10.fsyncSync(cut);
11320
- } finally {
11321
- fs10.closeSync(cut);
11322
- }
11323
- }
11324
- const fd = fs10.openSync(file, "a", 384);
11325
- try {
11326
- let written = 0;
11327
- while (written < line.length)
11328
- written += fs10.writeSync(fd, line, written, line.length - written);
11329
- fs10.fsyncSync(fd);
11330
- } finally {
11331
- fs10.closeSync(fd);
11332
- }
11333
- if (created)
11334
- fsyncDirectory(path13.dirname(file));
11335
- return validEnd;
11336
- }
11337
11146
  function replaceFile(file, bytes, durable) {
11338
11147
  const temporary = `${file}.${process.pid}.${randomUUID2()}.tmp`;
11339
11148
  try {
11340
- const fd = fs10.openSync(temporary, "wx", 384);
11149
+ const fd = fs9.openSync(temporary, "wx", 384);
11341
11150
  try {
11342
- fs10.writeSync(fd, bytes);
11151
+ fs9.writeSync(fd, bytes);
11343
11152
  if (durable)
11344
- fs10.fsyncSync(fd);
11153
+ fs9.fsyncSync(fd);
11345
11154
  } finally {
11346
- fs10.closeSync(fd);
11155
+ fs9.closeSync(fd);
11347
11156
  }
11348
11157
  renameWithRetry(temporary, file);
11349
11158
  if (durable)
11350
- fsyncDirectory(path13.dirname(file));
11159
+ fsyncDirectory(path12.dirname(file));
11351
11160
  } catch (error) {
11352
11161
  try {
11353
- fs10.unlinkSync(temporary);
11162
+ fs9.unlinkSync(temporary);
11354
11163
  } catch {}
11355
11164
  throw error;
11356
11165
  }
@@ -11375,62 +11184,10 @@ var retryTransient = (run) => {
11375
11184
  }
11376
11185
  }
11377
11186
  };
11378
- var renameWithRetry = (from, to) => retryTransient(() => fs10.renameSync(from, to));
11187
+ var renameWithRetry = (from, to) => retryTransient(() => fs9.renameSync(from, to));
11379
11188
 
11380
11189
  // packages/workit-core/src/store/patch.ts
11381
11190
  var isPlainObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11382
- var equal = (left, right) => {
11383
- if (left === right)
11384
- return true;
11385
- if (typeof left !== "object" || typeof right !== "object" || left === null || right === null)
11386
- return false;
11387
- if (Array.isArray(left) !== Array.isArray(right))
11388
- return false;
11389
- if (Array.isArray(left)) {
11390
- const other = right;
11391
- return left.length === other.length && left.every((item, index) => equal(item, other[index]));
11392
- }
11393
- const leftKeys = Object.keys(left).filter((key) => left[key] !== undefined);
11394
- const rightKeys = Object.keys(right).filter((key) => right[key] !== undefined);
11395
- return leftKeys.length === rightKeys.length && leftKeys.every((key) => equal(left[key], right[key]));
11396
- };
11397
- function diff(before, after, path = []) {
11398
- if (equal(before, after))
11399
- return [];
11400
- if (isPlainObject2(before) && isPlainObject2(after)) {
11401
- const ops = [];
11402
- for (const key of Object.keys(before))
11403
- if (before[key] !== undefined && after[key] === undefined)
11404
- ops.push({ op: "del", path: [...path, key] });
11405
- for (const key of Object.keys(after)) {
11406
- if (after[key] === undefined)
11407
- continue;
11408
- if (before[key] === undefined)
11409
- ops.push({ op: "set", path: [...path, key], value: after[key] });
11410
- else
11411
- ops.push(...diff(before[key], after[key], [...path, key]));
11412
- }
11413
- return ops;
11414
- }
11415
- if (Array.isArray(before) && Array.isArray(after)) {
11416
- const ops = [];
11417
- if (after.length < before.length)
11418
- ops.push({ op: "cut", path, length: after.length });
11419
- const shared = Math.min(before.length, after.length);
11420
- let changed = 0;
11421
- for (let index = 0;index < shared; index += 1)
11422
- if (!equal(before[index], after[index]))
11423
- changed += 1;
11424
- if (shared > 0 && changed > shared / 2 && changed > 4)
11425
- return [{ op: "set", path, value: after }];
11426
- for (let index = 0;index < shared; index += 1)
11427
- ops.push(...diff(before[index], after[index], [...path, index]));
11428
- if (after.length > before.length)
11429
- ops.push({ op: "push", path, values: after.slice(before.length) });
11430
- return ops;
11431
- }
11432
- return [{ op: "set", path, value: after }];
11433
- }
11434
11191
  var clone2 = (value) => structuredClone(value);
11435
11192
  function apply(target, ops) {
11436
11193
  let root = target;
@@ -11488,7 +11245,6 @@ var isPatch = (value) => Array.isArray(value) && value.every((op) => {
11488
11245
  });
11489
11246
 
11490
11247
  // packages/workit-core/src/store/reduce.ts
11491
- import { createHash as createHash9 } from "node:crypto";
11492
11248
  var OPENING_TYPES = new Set([
11493
11249
  "task.opened",
11494
11250
  "task.imported",
@@ -11517,26 +11273,6 @@ var isObject4 = (value) => typeof value === "object" && value !== null && !Array
11517
11273
  var isKey = (value) => isObject4(value) && typeof value.key === "string" && (value.kind === "branch" || value.kind === "detached" || value.kind === "dir") && (value.branch === null || typeof value.branch === "string");
11518
11274
  var BLOB_REF = "$blob";
11519
11275
  var blobRef = (value) => isObject4(value) && Object.keys(value).length === 1 && typeof value[BLOB_REF] === "string" && /^[0-9a-f]{64}$/.test(value[BLOB_REF]) ? value[BLOB_REF] : null;
11520
- var blobDigest = (value) => createHash9("sha256").update(JSON.stringify(value)).digest("hex");
11521
- var toBlob = (value, blobs) => {
11522
- if (!isObject4(value))
11523
- return value;
11524
- const digest = blobDigest(value);
11525
- blobs.write(digest, value);
11526
- return { [BLOB_REF]: digest };
11527
- };
11528
- var encodeRecord = (record, blobs) => Array.isArray(record.candidates) ? { ...record, candidates: record.candidates.map((item) => toBlob(item, blobs)) } : record;
11529
- var encodeOps = (ops, blobs) => ops.map((op) => {
11530
- if (op.path[0] !== "candidates")
11531
- return op;
11532
- if (op.op === "push" && op.path.length === 1)
11533
- return { ...op, values: op.values.map((item) => toBlob(item, blobs)) };
11534
- if (op.op === "set" && op.path.length === 1 && Array.isArray(op.value))
11535
- return { ...op, value: op.value.map((item) => toBlob(item, blobs)) };
11536
- if (op.op === "set" && op.path.length === 2)
11537
- return { ...op, value: toBlob(op.value, blobs) };
11538
- return op;
11539
- });
11540
11276
  var decode2 = (value, blobs) => {
11541
11277
  const digest = blobRef(value);
11542
11278
  if (digest)
@@ -11591,32 +11327,6 @@ function reduce(state, event, blobs) {
11591
11327
  };
11592
11328
  return next;
11593
11329
  }
11594
- function eventType(before, after) {
11595
- const count = (value) => Array.isArray(value) ? value.length : 0;
11596
- if (before.status !== after.status)
11597
- return after.status === "closed" ? "task.closed" : after.status === "paused" ? "task.paused" : "task.resumed";
11598
- if (count(after.evidence) > count(before.evidence)) {
11599
- const last = after.evidence.at(-1);
11600
- return last?.data?.observation ? "check.ran" : "evidence.recorded";
11601
- }
11602
- if (count(after.findings) > count(before.findings))
11603
- return "finding.recorded";
11604
- if (count(after.decisions) > count(before.decisions))
11605
- return "decision.recorded";
11606
- if (JSON.stringify(before.findings) !== JSON.stringify(after.findings))
11607
- return "finding.updated";
11608
- if (JSON.stringify(before.decisions) !== JSON.stringify(after.decisions))
11609
- return "decision.updated";
11610
- if (JSON.stringify(before.workers) !== JSON.stringify(after.workers))
11611
- return "worker.updated";
11612
- if (JSON.stringify(before.intent) !== JSON.stringify(after.intent))
11613
- return "task.revised";
11614
- if (JSON.stringify(before.assessments) !== JSON.stringify(after.assessments) || JSON.stringify(before.policy) !== JSON.stringify(after.policy))
11615
- return "task.judged";
11616
- if (JSON.stringify(before.progress) !== JSON.stringify(after.progress))
11617
- return "task.noted";
11618
- return "task.updated";
11619
- }
11620
11330
 
11621
11331
  // packages/workit-core/src/store/notes.ts
11622
11332
  var SLOT = Symbol.for("workit.migrationReporter");
@@ -11627,90 +11337,14 @@ var reportMigration = (report) => {
11627
11337
  reporter(report);
11628
11338
  } catch {}
11629
11339
  };
11630
- var migrationReporterInstalled = () => typeof globalThis[SLOT] === "function";
11631
11340
 
11632
- // packages/workit-core/src/core/task-store.ts
11341
+ // packages/workit-core/src/core/task-read.ts
11633
11342
  var MIGRATION_PENDING = "workit migration pending";
11634
11343
  var STORE_FORMAT = 3;
11635
11344
  var STORE_MIN_RUNTIME = "3.0.0";
11636
- var SNAPSHOT_EVERY = 32;
11637
- var COMPACT_ABOVE = 200;
11638
- var COMPACT_KEEP = 50;
11639
- var AUTO_COMPACT_BYTES = 2 * 1024 * 1024;
11640
11345
  var TOMBSTONE = Symbol("tombstone");
11641
- var STALE_TEMPORARY_MS = 60 * 60000;
11642
11346
  var INDEX_VERSION = 3;
11643
11347
  var isObject5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11644
- var CHECKOUT_LEFTOVERS = [
11645
- "workspace.json",
11646
- "index.json",
11647
- "tasks",
11648
- "recovery",
11649
- "metadata.lock",
11650
- "store.moved.json",
11651
- "task-index.json",
11652
- "checkouts",
11653
- "blobs",
11654
- "legacy",
11655
- "ledger",
11656
- "keys"
11657
- ];
11658
- var GENERATED_GITIGNORES = new Set([`*
11659
- `, `*
11660
- !risk-paths
11661
- `]);
11662
- var MARKER_FIELDS = {
11663
- workspace: ["schemaVersion", "id", "revision", "root", "runtime", "writer", "store", "critical"],
11664
- stub: ["schemaVersion", "id", "runtime", "store", "critical"],
11665
- moved: ["format", "version", "createdWith"]
11666
- };
11667
- var isKnownMarker = (file, kind) => {
11668
- try {
11669
- const value = JSON.parse(fs11.readFileSync(file, "utf8"));
11670
- if (!isObject5(value))
11671
- return false;
11672
- const fields = MARKER_FIELDS[kind];
11673
- if (!Object.keys(value).every((key) => fields.includes(key)))
11674
- return false;
11675
- if (kind === "moved")
11676
- return value.format === "workit-store";
11677
- return isObject5(value.store) && value.store.format === "workit-store" && JSON.stringify(value.critical) === '["store"]';
11678
- } catch {
11679
- return false;
11680
- }
11681
- };
11682
- var moveInto = (from, to) => {
11683
- if (fs11.lstatSync(from).isDirectory()) {
11684
- let target = to;
11685
- if (fs11.existsSync(target) && !fs11.lstatSync(target).isDirectory())
11686
- target = `${to}.dir`;
11687
- fs11.mkdirSync(target, { recursive: true });
11688
- for (const name of fs11.readdirSync(from))
11689
- moveInto(path14.join(from, name), path14.join(target, name));
11690
- fs11.rmdirSync(from);
11691
- return;
11692
- }
11693
- let target = to;
11694
- if (fs11.existsSync(target)) {
11695
- const bytes = fs11.readFileSync(from);
11696
- if (fs11.lstatSync(target).isFile() && bytes.equals(fs11.readFileSync(target))) {
11697
- fs11.rmSync(from);
11698
- return;
11699
- }
11700
- target = `${to}.${createHash10("sha256").update(bytes).digest("hex").slice(0, 12)}`;
11701
- if (fs11.existsSync(target)) {
11702
- fs11.rmSync(from);
11703
- return;
11704
- }
11705
- }
11706
- fs11.mkdirSync(path14.dirname(target), { recursive: true });
11707
- try {
11708
- fs11.renameSync(from, target);
11709
- } catch {
11710
- fs11.copyFileSync(from, target);
11711
- fs11.rmSync(from);
11712
- }
11713
- };
11714
11348
  var hostSession = (value) => isObject5(value) && value.kind === "host" && typeof value.host === "string" && typeof value.handle === "string" ? { host: value.host, handle: value.handle } : null;
11715
11349
  var indexEntry = (task, key, legacy, file) => {
11716
11350
  const sessions = [];
@@ -11742,7 +11376,7 @@ var indexEntry = (task, key, legacy, file) => {
11742
11376
  };
11743
11377
  var fileSignature = (file) => {
11744
11378
  try {
11745
- const stat = fs11.statSync(file, { bigint: true });
11379
+ const stat = fs10.statSync(file, { bigint: true });
11746
11380
  return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
11747
11381
  } catch {
11748
11382
  return null;
@@ -11754,13 +11388,12 @@ var racySignature = (signature) => {
11754
11388
  const changed = mtime > ctime ? mtime : ctime;
11755
11389
  return BigInt(Date.now()) * 1000000n - changed < RACY_WINDOW_NS;
11756
11390
  };
11757
- var now = () => new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
11758
11391
  var oldestFirst = (left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
11759
11392
  var cachedRuntimeVersion = null;
11760
11393
  var runtimeVersion = () => {
11761
11394
  if (cachedRuntimeVersion === null) {
11762
11395
  try {
11763
- const pkg = JSON.parse(fs11.readFileSync(path14.join(packageRoot(), "package.json"), "utf8"));
11396
+ const pkg = JSON.parse(fs10.readFileSync(path13.join(packageRoot(), "package.json"), "utf8"));
11764
11397
  cachedRuntimeVersion = typeof pkg.version === "string" && pkg.version ? pkg.version : "0.0.0";
11765
11398
  } catch {
11766
11399
  cachedRuntimeVersion = "0.0.0";
@@ -11768,10 +11401,6 @@ var runtimeVersion = () => {
11768
11401
  }
11769
11402
  return cachedRuntimeVersion;
11770
11403
  };
11771
- var stampNew = (record) => ({
11772
- createdWith: record.runtime?.createdWith ?? null,
11773
- updatedWith: runtimeVersion()
11774
- });
11775
11404
  var isNewerVersion = (candidate, current) => {
11776
11405
  const parts = (value) => value.split("-")[0].split(".").map((item) => Number.parseInt(item, 10) || 0);
11777
11406
  const [candidateParts, currentParts] = [parts(candidate), parts(current)];
@@ -11786,14 +11415,14 @@ var isNewerVersion = (candidate, current) => {
11786
11415
  var validId = (value) => /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value);
11787
11416
  var readText2 = (file) => {
11788
11417
  try {
11789
- return fs11.readFileSync(file, "utf8");
11418
+ return fs10.readFileSync(file, "utf8");
11790
11419
  } catch {
11791
11420
  return "";
11792
11421
  }
11793
11422
  };
11794
11423
  var REFLOG_LINE = /^[0-9a-f]+ ([0-9a-f]+) .* (\d+) [+-]\d{4}\t(.*)$/u;
11795
11424
  var branchStart = (location, branch, aliases) => {
11796
- const first = readText2(path14.join(path14.dirname(location.dir), "logs", "refs", "heads", branch)).split(`
11425
+ const first = readText2(path13.join(path13.dirname(location.dir), "logs", "refs", "heads", branch)).split(`
11797
11426
  `, 1)[0];
11798
11427
  const created = REFLOG_LINE.exec(first);
11799
11428
  const start = created && /^branch: Created from (\S+)$/u.exec(created[3])?.[1];
@@ -11803,7 +11432,7 @@ var branchStart = (location, branch, aliases) => {
11803
11432
  return start;
11804
11433
  if (!location.git)
11805
11434
  return null;
11806
- for (const line of readText2(path14.join(location.git.gitDir, "logs", "HEAD")).split(`
11435
+ for (const line of readText2(path13.join(location.git.gitDir, "logs", "HEAD")).split(`
11807
11436
  `)) {
11808
11437
  const entry = REFLOG_LINE.exec(line);
11809
11438
  const moved = entry && /^checkout: moving from (\S+) to (\S+)$/u.exec(entry[3]);
@@ -11813,23 +11442,23 @@ var branchStart = (location, branch, aliases) => {
11813
11442
  }
11814
11443
  return null;
11815
11444
  };
11816
- var refExists2 = (common, ref) => fs11.existsSync(path14.join(common, ref)) || readText2(path14.join(common, "packed-refs")).includes(` ${ref}
11445
+ var refExists2 = (common, ref) => fs10.existsSync(path13.join(common, ref)) || readText2(path13.join(common, "packed-refs")).includes(` ${ref}
11817
11446
  `);
11818
11447
  var origins = new Map;
11819
11448
  var sameDirectoryIdentity = (left, right) => {
11820
- if (!path14.isAbsolute(left) || !path14.isAbsolute(right))
11449
+ if (!path13.isAbsolute(left) || !path13.isAbsolute(right))
11821
11450
  return false;
11822
- const normalizedLeft = path14.resolve(left);
11823
- const normalizedRight = path14.resolve(right);
11451
+ const normalizedLeft = path13.resolve(left);
11452
+ const normalizedRight = path13.resolve(right);
11824
11453
  try {
11825
- const a = fs11.statSync(normalizedLeft, { bigint: true });
11826
- const b = fs11.statSync(normalizedRight, { bigint: true });
11454
+ const a = fs10.statSync(normalizedLeft, { bigint: true });
11455
+ const b = fs10.statSync(normalizedRight, { bigint: true });
11827
11456
  if (!a.isDirectory() || !b.isDirectory())
11828
11457
  return false;
11829
11458
  if (process.platform === "win32" ? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase() : normalizedLeft === normalizedRight)
11830
11459
  return true;
11831
- const canonicalLeft = fs11.realpathSync(normalizedLeft);
11832
- const canonicalRight = fs11.realpathSync(normalizedRight);
11460
+ const canonicalLeft = fs10.realpathSync(normalizedLeft);
11461
+ const canonicalRight = fs10.realpathSync(normalizedRight);
11833
11462
  if (process.platform === "win32" ? canonicalLeft.toLowerCase() === canonicalRight.toLowerCase() : canonicalLeft === canonicalRight)
11834
11463
  return true;
11835
11464
  return a.dev === b.dev && a.ino !== 0n && a.ino === b.ino;
@@ -11846,36 +11475,22 @@ var drop = (lock) => {
11846
11475
  else
11847
11476
  heldInProcess.delete(lock);
11848
11477
  };
11849
- var envActor = () => {
11850
- const value = (key) => process.env[key]?.trim() || null;
11851
- const acting = hostSessionFromEnv(process.env);
11852
- return {
11853
- host: acting.host ?? "runtime",
11854
- session: acting.session,
11855
- agentId: value("WORKIT_AGENT_ID")
11856
- };
11857
- };
11858
11478
 
11859
- class TaskStore {
11479
+ class TaskReader {
11860
11480
  root;
11861
11481
  origin;
11862
11482
  lockTimeoutMs;
11863
- actor;
11864
- migrateOnRead;
11865
11483
  located;
11866
11484
  migrationChecked = false;
11867
- compactDue = new Set;
11868
11485
  constructor(root, options = {}) {
11869
- const resolved = path14.resolve(root);
11870
- this.origin = fs11.existsSync(resolved) ? fs11.realpathSync(resolved) : resolved;
11486
+ const resolved = path13.resolve(root);
11487
+ this.origin = fs10.existsSync(resolved) ? fs10.realpathSync(resolved) : resolved;
11871
11488
  this.located = resolveStore(this.origin);
11872
11489
  this.root = checkoutRootOf(this.origin, this.located);
11873
11490
  this.lockTimeoutMs = options.lockTimeoutMs ?? defaultLockTimeout();
11874
- this.actor = options.actor ?? envActor();
11875
- this.migrateOnRead = options.migrateOnRead;
11876
11491
  }
11877
11492
  location() {
11878
- if (this.located !== undefined && !(this.located instanceof Error) && !this.located.shared && fs11.existsSync(path14.join(this.root, ".git"))) {
11493
+ if (this.located !== undefined && !(this.located instanceof Error) && !this.located.shared && fs10.existsSync(path13.join(this.root, ".git"))) {
11879
11494
  this.located = undefined;
11880
11495
  this.migrationChecked = false;
11881
11496
  }
@@ -11939,7 +11554,7 @@ class TaskStore {
11939
11554
  const tasksDir = this.paths().tasks;
11940
11555
  let names;
11941
11556
  try {
11942
- names = fs11.existsSync(tasksDir) ? fs11.readdirSync(tasksDir).filter((name) => validId(name)) : [];
11557
+ names = fs10.existsSync(tasksDir) ? fs10.readdirSync(tasksDir).filter((name) => validId(name)) : [];
11943
11558
  } catch (error) {
11944
11559
  return failure2("storage_error", `unable to list tasks: ${String(error)}`, {
11945
11560
  path: tasksDir
@@ -11980,7 +11595,7 @@ class TaskStore {
11980
11595
  const file = this.paths().workspace;
11981
11596
  let bytes;
11982
11597
  try {
11983
- bytes = retryTransient(() => fs11.readFileSync(file, "utf8"));
11598
+ bytes = retryTransient(() => fs10.readFileSync(file, "utf8"));
11984
11599
  } catch (error) {
11985
11600
  if (error.code === "ENOENT")
11986
11601
  return success(null, null, null);
@@ -11995,70 +11610,6 @@ class TaskStore {
11995
11610
  return failure2("recovery_required", "workspace root binding is invalid", { path: file });
11996
11611
  return parsed;
11997
11612
  }
11998
- implicitTask(input) {
11999
- const ready = this.ready(input.create !== false);
12000
- if (!ready.ok)
12001
- return ready;
12002
- const key = this.currentKey();
12003
- if (!key.ok)
12004
- return key;
12005
- const found = this.openTaskForKey(key.data.key);
12006
- if (!found.ok)
12007
- return found;
12008
- const workspace = this.readWorkspace();
12009
- if (!workspace.ok)
12010
- return workspace;
12011
- if (found.data && workspace.data && found.data.workspaceId === workspace.data.id && (found.data.key === key.data.key || input.create === false)) {
12012
- const task = this.readTask(found.data.id);
12013
- return task.ok ? success(task.revision, null, { task: task.data, created: false, key: key.data }) : task;
12014
- }
12015
- if (input.create === false) {
12016
- if (!found.data)
12017
- return success(null, null, null);
12018
- const loaded = this.load(found.data.id);
12019
- if (!loaded.ok)
12020
- return loaded;
12021
- return loaded.data ? success(null, null, { task: loaded.data.record, created: false, key: key.data }) : success(null, null, null);
12022
- }
12023
- return this.withLock(this.paths().checkoutLock, () => this.withKeyLock(key.data.key, () => this.implicitLocked(input, key.data)));
12024
- }
12025
- implicitLocked(input, key) {
12026
- {
12027
- const again = this.openTaskForKey(key.key);
12028
- if (!again.ok)
12029
- return again;
12030
- if (again.data) {
12031
- const moved = this.bindLocked(again.data.id, key, input.now);
12032
- return moved.ok ? success(moved.data.revision, null, { task: moved.data, created: false, key }) : moved;
12033
- }
12034
- const label = key.kind === "branch" ? `branch ${key.branch}` : key.kind === "detached" ? "a detached HEAD" : path14.basename(this.root) || this.root;
12035
- const intent = {
12036
- objective: input.objective?.trim() || `Work on ${label}`,
12037
- scope: { description: `the checkout (${label})`, paths: ["."], exclusions: [] },
12038
- authorityRefs: []
12039
- };
12040
- const created = this.createLocked({ intent, provenance: input.provenance, expectedWorkspaceRevision: null, now: input.now }, false, key, false);
12041
- return created.ok ? success(created.data.revision, null, { task: created.data, created: true, key }) : created;
12042
- }
12043
- }
12044
- adoptTask(taskId) {
12045
- if (!validId(taskId))
12046
- return failure2("invalid_input", "task ID is invalid", { taskId });
12047
- const ready = this.ready(true);
12048
- if (!ready.ok)
12049
- return ready;
12050
- const key = this.currentKey();
12051
- if (!key.ok)
12052
- return key;
12053
- return this.withLock(this.paths().checkoutLock, () => this.withKeyLock(key.data.key, () => {
12054
- const holder = this.openTaskForKey(key.data.key);
12055
- if (!holder.ok)
12056
- return holder;
12057
- if (holder.data && holder.data.id !== taskId)
12058
- return failure2("invalid_transition", `${key.data.key} already has open task ${holder.data.id}; close it (\`workit task close\`) before adopting another`, { taskId: holder.data.id });
12059
- return this.bindLocked(taskId, key.data);
12060
- }));
12061
- }
12062
11613
  keyReport() {
12063
11614
  const key = this.currentKey();
12064
11615
  if (!key.ok)
@@ -12097,14 +11648,14 @@ class TaskStore {
12097
11648
  const branch = key.ok ? key.data.branch : null;
12098
11649
  if (!branch || !location.ok)
12099
11650
  return success(null, null, null);
12100
- const common = path14.dirname(location.data.dir);
12101
- const heads = path14.join(common, "logs", "refs", "heads");
12102
- const headLog = location.data.git ? path14.join(location.data.git.gitDir, "logs", "HEAD") : "";
11651
+ const common = path13.dirname(location.data.dir);
11652
+ const heads = path13.join(common, "logs", "refs", "heads");
11653
+ const headLog = location.data.git ? path13.join(location.data.git.gitDir, "logs", "HEAD") : "";
12103
11654
  const signatures = [
12104
- path14.join(heads, branch),
11655
+ path13.join(heads, branch),
12105
11656
  headLog,
12106
11657
  heads,
12107
- path14.join(common, "packed-refs")
11658
+ path13.join(common, "packed-refs")
12108
11659
  ].map((file) => fileSignature(file) ?? "-");
12109
11660
  const slot = `${location.data.dir}\x00${headLog}\x00${branch}`;
12110
11661
  let resolved = origins.get(slot);
@@ -12116,7 +11667,7 @@ class TaskStore {
12116
11667
  aliases.push(rename.from);
12117
11668
  const start = branchStart(location.data, branch, aliases);
12118
11669
  const slash = start?.indexOf("/") ?? -1;
12119
- 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)}"]`));
11670
+ const remote = slash > 0 && !refExists2(common, `refs/heads/${start}`) && (refExists2(common, `refs/remotes/${start}`) || readText2(path13.join(common, "config")).includes(`[remote "${start.slice(0, slash)}"]`));
12120
11671
  const name = start && (remote ? start.slice(slash + 1) : start);
12121
11672
  resolved = {
12122
11673
  signature: signatures.join("|"),
@@ -12134,423 +11685,72 @@ class TaskStore {
12134
11685
  const loaded = this.load(taskId);
12135
11686
  return loaded.ok ? success(null, null, loaded.data?.record ?? null) : loaded;
12136
11687
  }
12137
- create(input, provenance, expectedWorkspaceRevision) {
12138
- const value = "intent" in input ? input : {
12139
- intent: input,
12140
- provenance,
12141
- expectedWorkspaceRevision: expectedWorkspaceRevision ?? null
11688
+ paths() {
11689
+ const location = this.location();
11690
+ const dir = location.ok ? location.data.dir : path13.join(this.root, ".workit");
11691
+ const checkout = path13.join(dir, "checkouts", checkoutSlug(this.root));
11692
+ return {
11693
+ dir,
11694
+ shared: location.ok ? location.data.shared : false,
11695
+ marker: path13.join(dir, "store.json"),
11696
+ checkout,
11697
+ workspace: path13.join(checkout, "workspace.json"),
11698
+ checkoutLock: path13.join(checkout, "metadata.lock"),
11699
+ tasks: path13.join(dir, "tasks"),
11700
+ index: path13.join(dir, "task-index.json"),
11701
+ blobs: path13.join(dir, "blobs", "candidates"),
11702
+ legacy: path13.join(dir, "legacy", checkoutSlug(this.root), "v2"),
11703
+ v2: path13.join(this.root, ".workit")
12142
11704
  };
12143
- const ready = this.ready(true);
12144
- if (!ready.ok)
12145
- return ready;
12146
- return this.withLock(this.paths().checkoutLock, () => this.createLocked(value, true, null));
12147
11705
  }
12148
- importTask(input) {
12149
- const ready = this.ready(true);
12150
- if (!ready.ok)
12151
- return ready;
12152
- return this.withLock(this.paths().checkoutLock, () => {
12153
- const current = this.readWorkspace();
12154
- if (!current.ok)
12155
- return current;
12156
- const origin = input.task.origin;
12157
- if (current.data && origin) {
12158
- if (origin.workspaceId === current.data.id) {
12159
- const source = this.readTask(origin.taskId);
12160
- if (source.ok)
12161
- return success(source.data.revision, current.data.revision, source.data);
12162
- if (source.code !== "not_found")
12163
- return source;
12164
- return failure2("not_found", "source task is not present in this shared workspace");
12165
- }
12166
- const tasks = this.listTasks();
12167
- if (!tasks.ok)
12168
- return tasks;
12169
- const prior = tasks.data.filter((task) => task.origin?.workspaceId === origin.workspaceId && task.origin?.taskId === origin.taskId);
12170
- if (prior.length > 1)
12171
- return failure2("recovery_required", `source task has multiple imported mappings: ${prior.map((task) => task.id).join(", ")}`);
12172
- if (prior.length === 1) {
12173
- const existing = prior[0];
12174
- if (existing.origin.exportDigest !== origin.exportDigest)
12175
- return failure2("revision_conflict", "source task export changed; reconcile the mapped destination task before importing", { taskId: existing.id });
12176
- return success(existing.revision, current.data.revision, existing);
11706
+ eventsPath(taskId) {
11707
+ return path13.join(this.paths().tasks, taskId, "events.jsonl");
11708
+ }
11709
+ snapshotPath(taskId) {
11710
+ return path13.join(this.paths().tasks, taskId, "snapshot.json");
11711
+ }
11712
+ ready(write = false) {
11713
+ const location = this.location();
11714
+ if (!location.ok)
11715
+ return location;
11716
+ if (this.migrationChecked)
11717
+ return success(null, null, null);
11718
+ const dirs = this.paths();
11719
+ try {
11720
+ const marker = JSON.parse(fs10.readFileSync(dirs.marker, "utf8"));
11721
+ if (typeof marker.version === "number" && marker.version > STORE_FORMAT)
11722
+ return failure2("recovery_required", `the workit store at ${dirs.dir} has format ${marker.version}; upgrade Workit to use it`, { path: dirs.marker });
11723
+ } catch {}
11724
+ this.migrationChecked = true;
11725
+ const settled = this.settleMigrations(write);
11726
+ if (!settled.ok)
11727
+ this.migrationChecked = false;
11728
+ return settled;
11729
+ }
11730
+ settleMigrations(_write) {
11731
+ const moved = this.adoptLocalStore();
11732
+ if (!moved.ok)
11733
+ return moved;
11734
+ const pending = this.pendingMigrations();
11735
+ return pending.length > 0 ? this.migrationPending(pending[0]) : success(null, null, null);
11736
+ }
11737
+ migrationPending(dir) {
11738
+ return failure2("needs_input", `${MIGRATION_PENDING}: the task store at ${dir} has not been migrated yet; run \`workit task status\` to migrate it`, { path: dir, guidance: "workit task status" });
11739
+ }
11740
+ blobStore() {
11741
+ const dir = this.paths().blobs;
11742
+ return {
11743
+ read: (digest) => {
11744
+ try {
11745
+ return JSON.parse(fs10.readFileSync(path13.join(dir, `${digest}.json`), "utf8"));
11746
+ } catch (error) {
11747
+ throw new LogDamage(`stored candidate ${digest} is missing or unreadable: ${String(error)}`);
12177
11748
  }
11749
+ },
11750
+ write: () => {
11751
+ throw new Error("a TaskReader writes no candidates");
12178
11752
  }
12179
- if (current.data ? input.expectedWorkspaceRevision !== current.data.revision : input.expectedWorkspaceRevision !== null)
12180
- return failure2("revision_conflict", "workspace revision does not match; omit expectedWorkspaceRevision to use the current record", {
12181
- expectedWorkspaceRevision: input.expectedWorkspaceRevision,
12182
- actualWorkspaceRevision: current.data?.revision ?? null
12183
- });
12184
- const timestamp = input.now ?? now();
12185
- const workspace = this.nextWorkspace(current.data, input.workspaceId);
12186
- const task = {
12187
- ...input.task,
12188
- workspaceId: workspace.id,
12189
- revision: newRevision(),
12190
- createdAt: timestamp,
12191
- updatedAt: timestamp,
12192
- runtime: {
12193
- createdWith: input.task.runtime?.createdWith ?? null,
12194
- updatedWith: runtimeVersion()
12195
- }
12196
- };
12197
- const validTask = taskRecordSchema.safeParse(task);
12198
- if (!validTask.success)
12199
- return failure2("invalid_input", "imported task does not satisfy its schema");
12200
- return this.writeNewTask(current.data, workspace, validTask.data, "task.imported", null, {
12201
- operation: "import"
12202
- });
12203
- });
12204
- }
12205
- mutateTask(taskId, expected, update, timestamp) {
12206
- if (!validId(taskId))
12207
- return failure2("invalid_input", "task ID is invalid", { taskId });
12208
- const ready = this.ready(true);
12209
- if (!ready.ok)
12210
- return ready;
12211
- const result = this.withLock(this.taskLockPath(taskId), () => {
12212
- const loaded = this.loadBound(taskId);
12213
- if (!loaded.ok)
12214
- return loaded;
12215
- if (loaded.data.record.revision !== expected)
12216
- return this.conflict(expected, loaded.data.record.revision);
12217
- const context = { now: timestamp ?? now(), revision: newRevision() };
12218
- let changed;
12219
- try {
12220
- changed = update(structuredClone(loaded.data.record), Object.freeze({ ...context }));
12221
- } catch (error) {
12222
- return failure2("storage_error", `task mutation failed: ${String(error)}`);
12223
- }
12224
- if (!changed.ok)
12225
- return changed;
12226
- const valid = this.nextTask(loaded.data.record, changed.data, context);
12227
- if (!valid)
12228
- return failure2("invalid_input", "task mutation produced an invalid record");
12229
- const written = this.appendPatch(loaded.data, valid);
12230
- return written.ok ? success(valid.revision, null, valid) : written;
12231
- });
12232
- this.compactPending();
12233
- return result;
12234
- }
12235
- mutateWorkspace(expected, update) {
12236
- const ready = this.ready(true);
12237
- if (!ready.ok)
12238
- return ready;
12239
- return this.withLock(this.paths().checkoutLock, () => {
12240
- const current = this.readWorkspace();
12241
- if (!current.ok)
12242
- return current;
12243
- if (!current.data)
12244
- return failure2("not_found", "workspace not found");
12245
- if (current.data.revision !== expected)
12246
- return this.workspaceConflict(expected, current.data.revision);
12247
- const context = { now: now(), revision: newRevision() };
12248
- let changed;
12249
- try {
12250
- changed = update(current.data, Object.freeze({ ...context }));
12251
- } catch (error) {
12252
- return failure2("storage_error", `workspace mutation failed: ${String(error)}`);
12253
- }
12254
- if (!changed.ok)
12255
- return changed;
12256
- const valid = workspaceRecordSchema.safeParse({
12257
- ...changed.data,
12258
- id: current.data.id,
12259
- root: this.root,
12260
- revision: context.revision,
12261
- runtime: stampNew(current.data)
12262
- });
12263
- if (!valid.success)
12264
- return failure2("invalid_input", "workspace mutation produced an invalid record");
12265
- const written = this.writeWorkspace(valid.data);
12266
- return written.ok ? success(valid.data.revision, valid.data.revision, valid.data) : written;
12267
- });
12268
- }
12269
- mutateTaskAndWorkspace(input) {
12270
- if (!validId(input.taskId))
12271
- return failure2("invalid_input", "task ID is invalid", { taskId: input.taskId });
12272
- const ready = this.ready(true);
12273
- if (!ready.ok)
12274
- return ready;
12275
- const result = this.withLock(this.paths().checkoutLock, () => this.withLock(this.taskLockPath(input.taskId), () => {
12276
- const task = this.loadBound(input.taskId);
12277
- if (!task.ok)
12278
- return task;
12279
- const workspace = this.readWorkspace();
12280
- if (!workspace.ok)
12281
- return workspace;
12282
- if (!workspace.data)
12283
- return failure2("not_found", "workspace not found");
12284
- const expected = input.expectedRevision;
12285
- if (!expected)
12286
- return failure2("invalid_input", "task revision is required");
12287
- if (task.data.record.revision !== expected)
12288
- return this.conflict(expected, task.data.record.revision);
12289
- if (workspace.data.revision !== input.expectedWorkspaceRevision)
12290
- return this.workspaceConflict(input.expectedWorkspaceRevision, workspace.data.revision);
12291
- const workspaceContext = { now: input.now ?? now(), revision: newRevision() };
12292
- let changedWorkspace;
12293
- try {
12294
- changedWorkspace = input.workspace(workspace.data, Object.freeze({ ...workspaceContext }));
12295
- } catch (error) {
12296
- return failure2("storage_error", `workspace mutation failed: ${String(error)}`);
12297
- }
12298
- if (!changedWorkspace.ok)
12299
- return changedWorkspace;
12300
- const nextWorkspace = workspaceRecordSchema.safeParse({
12301
- ...changedWorkspace.data,
12302
- id: workspace.data.id,
12303
- root: this.root,
12304
- revision: workspaceContext.revision,
12305
- runtime: stampNew(workspace.data)
12306
- });
12307
- if (!nextWorkspace.success)
12308
- return failure2("invalid_input", "workspace mutation produced an invalid record");
12309
- const reserved = this.writeWorkspace(nextWorkspace.data);
12310
- if (!reserved.ok)
12311
- return reserved;
12312
- const uncertain = (message) => {
12313
- return failure2("external_outcome_unknown", message, {
12314
- operation: "coupled_mutation",
12315
- outcome: "unknown"
12316
- });
12317
- };
12318
- const taskContext = { now: input.now ?? now(), revision: newRevision() };
12319
- let changedTask;
12320
- try {
12321
- changedTask = input.task(structuredClone(task.data.record), Object.freeze({ ...taskContext }));
12322
- } catch (error) {
12323
- return uncertain(`workspace reserved but task mutation threw: ${String(error)}`);
12324
- }
12325
- if (!changedTask.ok)
12326
- return uncertain("workspace reserved but task update is uncertain");
12327
- const nextTask = this.nextTask(task.data.record, changedTask.data, taskContext);
12328
- if (!nextTask)
12329
- return uncertain("workspace reserved but task update is uncertain");
12330
- const written = this.appendPatch(task.data, nextTask);
12331
- if (!written.ok)
12332
- return uncertain("workspace reserved but task append is uncertain");
12333
- return success(nextTask.revision, nextWorkspace.data.revision, {
12334
- task: nextTask,
12335
- workspace: nextWorkspace.data
12336
- });
12337
- }));
12338
- this.compactPending();
12339
- return result;
12340
- }
12341
- collectGarbage(options = {}) {
12342
- const dryRun = options.dryRun === true;
12343
- const compactAbove = options.compactAbove ?? COMPACT_ABOVE;
12344
- const report = {
12345
- dryRun,
12346
- compacted: { tasks: [], eventsFolded: 0, bytesBefore: 0, bytesAfter: 0 },
12347
- blobs: { removed: 0, removedBytes: 0, kept: 0 },
12348
- temporary: { removed: 0 },
12349
- legacyRecovery: null,
12350
- retried: [],
12351
- failed: []
12352
- };
12353
- const ready = this.ready(!dryRun);
12354
- if (!ready.ok)
12355
- return ready;
12356
- const dirs = this.paths();
12357
- const recovery = [path14.join(this.root, ".workit", "recovery"), path14.join(dirs.legacy, "recovery")].find((dir) => fs11.existsSync(dir)) ?? null;
12358
- if (recovery) {
12359
- let files = 0;
12360
- let bytes = 0;
12361
- try {
12362
- for (const name of fs11.readdirSync(recovery)) {
12363
- const stat = fs11.lstatSync(path14.join(recovery, name));
12364
- if (!stat.isFile())
12365
- continue;
12366
- files += 1;
12367
- bytes += stat.size;
12368
- }
12369
- } catch {}
12370
- const remove = options.pruneRecovery === true && !dryRun;
12371
- if (remove)
12372
- fs11.rmSync(recovery, { recursive: true, force: true });
12373
- report.legacyRecovery = { path: recovery, files, bytes, removed: remove };
12374
- }
12375
- if (!fs11.existsSync(dirs.tasks))
12376
- return success(null, null, report);
12377
- const names = fs11.readdirSync(dirs.tasks).filter((name) => validId(name));
12378
- for (const name of names) {
12379
- const file = this.eventsPath(name);
12380
- let size = 0;
12381
- try {
12382
- size = fs11.statSync(file).size;
12383
- } catch {
12384
- continue;
12385
- }
12386
- const lines = this.countEvents(file);
12387
- if (lines > compactAbove) {
12388
- if (dryRun) {
12389
- report.compacted.tasks.push(name);
12390
- report.compacted.eventsFolded += lines - COMPACT_KEEP;
12391
- report.compacted.bytesBefore += size;
12392
- } else {
12393
- const compacted = this.compact(name);
12394
- if (!compacted.ok)
12395
- (compacted.code === "busy" ? report.retried : report.failed).push(name);
12396
- else {
12397
- report.compacted.tasks.push(name);
12398
- report.compacted.eventsFolded += compacted.data.folded;
12399
- report.compacted.bytesBefore += size;
12400
- report.compacted.bytesAfter += compacted.data.bytes;
12401
- }
12402
- }
12403
- }
12404
- }
12405
- const nowMs = Date.now();
12406
- const sweep = () => {
12407
- const references = new Set;
12408
- for (const name of names)
12409
- try {
12410
- for (const match of fs11.readFileSync(this.eventsPath(name), "utf8").matchAll(/"\$blob":"([0-9a-f]{64})"/g))
12411
- references.add(match[1]);
12412
- } catch {}
12413
- if (fs11.existsSync(dirs.blobs))
12414
- for (const name of fs11.readdirSync(dirs.blobs)) {
12415
- const digest = name.replace(/\.json$/, "");
12416
- const file = path14.join(dirs.blobs, name);
12417
- let stat;
12418
- try {
12419
- stat = fs11.lstatSync(file);
12420
- } catch {
12421
- continue;
12422
- }
12423
- if (references.has(digest) || nowMs - stat.mtimeMs <= STALE_TEMPORARY_MS) {
12424
- report.blobs.kept += 1;
12425
- continue;
12426
- }
12427
- report.blobs.removed += 1;
12428
- report.blobs.removedBytes += stat.size;
12429
- if (!dryRun)
12430
- fs11.rmSync(file, { force: true });
12431
- }
12432
- return success(null, null, null);
12433
- };
12434
- const swept = dryRun ? sweep() : this.withLock(path14.join(dirs.dir, "gc.lock"), sweep);
12435
- if (!swept.ok)
12436
- return swept;
12437
- const temporaryDirs = [
12438
- dirs.dir,
12439
- dirs.tasks,
12440
- dirs.blobs,
12441
- dirs.checkout,
12442
- ...names.map((name) => path14.join(dirs.tasks, name))
12443
- ];
12444
- for (const directory of temporaryDirs) {
12445
- if (!fs11.existsSync(directory))
12446
- continue;
12447
- for (const name of fs11.readdirSync(directory)) {
12448
- if (!name.endsWith(".tmp") && !name.endsWith(".probe"))
12449
- continue;
12450
- const file = path14.join(directory, name);
12451
- try {
12452
- const stat = fs11.lstatSync(file);
12453
- if (!stat.isFile() || nowMs - stat.mtimeMs <= STALE_TEMPORARY_MS)
12454
- continue;
12455
- } catch {
12456
- continue;
12457
- }
12458
- report.temporary.removed += 1;
12459
- if (!dryRun)
12460
- fs11.rmSync(file, { force: true });
12461
- }
12462
- }
12463
- return success(null, null, report);
12464
- }
12465
- paths() {
12466
- const location = this.location();
12467
- const dir = location.ok ? location.data.dir : path14.join(this.root, ".workit");
12468
- const checkout = path14.join(dir, "checkouts", checkoutSlug(this.root));
12469
- return {
12470
- dir,
12471
- shared: location.ok ? location.data.shared : false,
12472
- marker: path14.join(dir, "store.json"),
12473
- checkout,
12474
- workspace: path14.join(checkout, "workspace.json"),
12475
- checkoutLock: path14.join(checkout, "metadata.lock"),
12476
- tasks: path14.join(dir, "tasks"),
12477
- index: path14.join(dir, "task-index.json"),
12478
- blobs: path14.join(dir, "blobs", "candidates"),
12479
- legacy: path14.join(dir, "legacy", checkoutSlug(this.root), "v2"),
12480
- v2: path14.join(this.root, ".workit")
12481
- };
12482
- }
12483
- eventsPath(taskId) {
12484
- return path14.join(this.paths().tasks, taskId, "events.jsonl");
12485
- }
12486
- snapshotPath(taskId) {
12487
- return path14.join(this.paths().tasks, taskId, "snapshot.json");
12488
- }
12489
- taskLockPath(taskId) {
12490
- return path14.join(this.paths().tasks, taskId, "lock");
12491
- }
12492
- ready(write = false) {
12493
- const location = this.location();
12494
- if (!location.ok)
12495
- return location;
12496
- if (this.migrationChecked)
12497
- return success(null, null, null);
12498
- const dirs = this.paths();
12499
- try {
12500
- const marker = JSON.parse(fs11.readFileSync(dirs.marker, "utf8"));
12501
- if (typeof marker.version === "number" && marker.version > STORE_FORMAT)
12502
- return failure2("recovery_required", `the workit store at ${dirs.dir} has format ${marker.version}; upgrade Workit to use it`, { path: dirs.marker });
12503
- } catch {}
12504
- this.migrationChecked = true;
12505
- const settled = this.settleMigrations(write);
12506
- if (!settled.ok)
12507
- this.migrationChecked = false;
12508
- return settled;
12509
- }
12510
- settleMigrations(write) {
12511
- const moved = this.adoptLocalStore();
12512
- if (!moved.ok)
12513
- return moved;
12514
- const pending = this.pendingMigrations();
12515
- if (pending.length > 0 && !write && !(this.migrateOnRead ?? migrationReporterInstalled()))
12516
- return failure2("needs_input", `${MIGRATION_PENDING}: the task store at ${pending[0]} has not been migrated yet; run \`workit task status\` to migrate it`, { path: pending[0], guidance: "workit task status" });
12517
- for (const v2 of this.v2Dirs()) {
12518
- const migrated = this.migrateV2(v2);
12519
- if (!migrated.ok)
12520
- return migrated;
12521
- }
12522
- if (!write && !(this.migrateOnRead ?? migrationReporterInstalled()))
12523
- return success(null, null, null);
12524
- for (const v2 of this.v2Dirs()) {
12525
- const cleared = this.clearCheckoutLeftovers(v2);
12526
- if (!cleared.ok)
12527
- return cleared;
12528
- }
12529
- return success(null, null, null);
12530
- }
12531
- blobStore() {
12532
- const dir = this.paths().blobs;
12533
- return {
12534
- read: (digest) => {
12535
- try {
12536
- return JSON.parse(fs11.readFileSync(path14.join(dir, `${digest}.json`), "utf8"));
12537
- } catch (error) {
12538
- throw new LogDamage(`stored candidate ${digest} is missing or unreadable: ${String(error)}`);
12539
- }
12540
- },
12541
- write: (digest, value) => {
12542
- const file = path14.join(dir, `${digest}.json`);
12543
- if (fs11.existsSync(file)) {
12544
- const stamp = new Date;
12545
- try {
12546
- fs11.utimesSync(file, stamp, stamp);
12547
- return;
12548
- } catch {}
12549
- }
12550
- fs11.mkdirSync(dir, { recursive: true });
12551
- replaceFile(file, JSON.stringify(value), true);
12552
- }
12553
- };
11753
+ };
12554
11754
  }
12555
11755
  load(taskId) {
12556
11756
  try {
@@ -12629,7 +11829,7 @@ class TaskStore {
12629
11829
  }
12630
11830
  readSnapshot(taskId) {
12631
11831
  try {
12632
- const value = JSON.parse(fs11.readFileSync(this.snapshotPath(taskId), "utf8"));
11832
+ const value = JSON.parse(fs10.readFileSync(this.snapshotPath(taskId), "utf8"));
12633
11833
  if (!isObject5(value) || value.v !== 1 || value.task !== taskId || typeof value.seq !== "number" || typeof value.lastId !== "string" || typeof value.lastStart !== "number" || typeof value.end !== "number" || !isObject5(value.record))
12634
11834
  return null;
12635
11835
  return value;
@@ -12637,179 +11837,11 @@ class TaskStore {
12637
11837
  return null;
12638
11838
  }
12639
11839
  }
12640
- writeSnapshot(taskId, loaded) {
12641
- const snapshot = {
12642
- v: 1,
12643
- task: taskId,
12644
- seq: loaded.seq,
12645
- lastId: loaded.lastId,
12646
- lastStart: loaded.lastStart,
12647
- end: loaded.end,
12648
- key: loaded.key,
12649
- legacy: loaded.legacy,
12650
- record: loaded.record
12651
- };
12652
- try {
12653
- replaceFile(this.snapshotPath(taskId), JSON.stringify(snapshot), false);
12654
- } catch {}
12655
- }
12656
- loadBound(taskId) {
12657
- const loaded = this.load(taskId);
12658
- if (!loaded.ok)
12659
- return loaded;
12660
- if (!loaded.data)
12661
- return failure2("not_found", "task not found", { taskId });
12662
- const workspace = this.readWorkspace();
12663
- if (!workspace.ok)
12664
- return workspace;
12665
- const bound = this.bindingError(loaded.data.record, workspace.data);
12666
- return bound ?? success(null, null, loaded.data);
12667
- }
12668
11840
  bindingError(task, workspace) {
12669
11841
  if (workspace && task.workspaceId === workspace.id)
12670
11842
  return null;
12671
11843
  return failure2("not_found", `task ${task.id} belongs to another checkout of this repository; run there, or move it here with \`workit task adopt ${task.id}\``, { taskId: task.id });
12672
11844
  }
12673
- nextTask(current, changed, context) {
12674
- const valid = taskRecordSchema.safeParse({
12675
- ...changed,
12676
- id: current.id,
12677
- workspaceId: current.workspaceId,
12678
- createdAt: current.createdAt,
12679
- revision: context.revision,
12680
- updatedAt: context.now,
12681
- runtime: stampNew(current)
12682
- });
12683
- return valid.success ? valid.data : null;
12684
- }
12685
- event(taskId, seq, type, data) {
12686
- return {
12687
- v: EVENT_VERSION,
12688
- seq,
12689
- at: new Date().toISOString(),
12690
- id: newId(),
12691
- task: taskId,
12692
- actor: this.actor,
12693
- type,
12694
- data
12695
- };
12696
- }
12697
- appendPatch(loaded, next, extra = {}) {
12698
- const taskId = next.id;
12699
- try {
12700
- const blobs = this.blobStore();
12701
- const before = loaded.record;
12702
- const after = next;
12703
- const ops = encodeOps(diff(before, after), blobs);
12704
- const { type, ...data } = extra;
12705
- if (data.key)
12706
- data.key = { ...data.key, boundAt: data.key.boundAt ?? new Date().toISOString() };
12707
- const event = this.event(taskId, loaded.seq + 1, type ?? ("key" in extra ? "task.bound" : eventType(before, after)), { ops, ...data });
12708
- const start = appendEvent(this.eventsPath(taskId), event, loaded.end);
12709
- const end = start + Buffer.byteLength(`${JSON.stringify(event)}
12710
- `);
12711
- const key = "key" in data ? data.key ?? null : loaded.key;
12712
- const state = {
12713
- record: next,
12714
- key,
12715
- legacy: extra.legacy ?? loaded.legacy,
12716
- seq: event.seq,
12717
- lastId: event.id,
12718
- lastStart: start,
12719
- end
12720
- };
12721
- if (event.seq - loaded.snapshotSeq >= SNAPSHOT_EVERY || next.status !== loaded.record.status || loaded.snapshotSeq === 0)
12722
- this.writeSnapshot(taskId, state);
12723
- if (end > AUTO_COMPACT_BYTES)
12724
- this.compactDue.add(taskId);
12725
- this.indexTask(next, key, (extra.legacy ?? loaded.legacy) !== null);
12726
- return success(null, null, null);
12727
- } catch (error) {
12728
- return failure2("storage_error", `task append failed: ${String(error)}`, {
12729
- path: this.eventsPath(taskId)
12730
- });
12731
- }
12732
- }
12733
- openTask(record, type, key, legacy = null) {
12734
- const dir = path14.join(this.paths().tasks, record.id);
12735
- fs11.mkdirSync(dir, { recursive: true });
12736
- const blobs = this.blobStore();
12737
- const bound = key ? { ...key, boundAt: key.boundAt ?? new Date().toISOString() } : null;
12738
- const event = this.event(record.id, 1, type, {
12739
- record: encodeRecord(record, blobs),
12740
- key: bound,
12741
- ...legacy ? { legacy } : {}
12742
- });
12743
- const file = this.eventsPath(record.id);
12744
- const existing = readLog(file, 0, null);
12745
- if (existing && existing.events.length > 0)
12746
- throw new Error(`task ${record.id} already has a log`);
12747
- appendEvent(file, event, 0);
12748
- this.indexTask(record, bound, legacy !== null);
12749
- }
12750
- compactPending() {
12751
- for (const taskId of this.compactDue) {
12752
- this.compactDue.delete(taskId);
12753
- this.compact(taskId);
12754
- }
12755
- }
12756
- compact(taskId) {
12757
- try {
12758
- const file = this.eventsPath(taskId);
12759
- const log = readLog(file, 0, null);
12760
- if (!log || log.events.length <= COMPACT_KEEP + 1)
12761
- return success(null, null, { folded: 0, bytes: log?.size ?? 0 });
12762
- const blobs = this.blobStore();
12763
- const cut = log.events.length - COMPACT_KEEP;
12764
- let state = null;
12765
- for (const event of log.events.slice(0, cut))
12766
- state = reduce(state, event, blobs);
12767
- const folded = log.events[cut - 1];
12768
- const checkpoint = {
12769
- ...this.event(taskId, folded.seq, "task.checkpoint", {
12770
- record: encodeRecord(state.record, blobs),
12771
- key: state.key,
12772
- ...state.legacy ? { legacy: state.legacy } : {},
12773
- folded: { from: log.events[0].seq, to: folded.seq }
12774
- })
12775
- };
12776
- const prefix = `${[checkpoint, ...log.events.slice(cut)].map((event) => JSON.stringify(event)).join(`
12777
- `)}
12778
- `;
12779
- const last = log.events.at(-1);
12780
- return this.withLock(this.taskLockPath(taskId), () => {
12781
- let latest = null;
12782
- try {
12783
- latest = readLog(file, log.lastStart, last.seq);
12784
- } catch {}
12785
- if (!latest || latest.events[0]?.id !== last.id)
12786
- return failure2("busy", "the task log changed during compaction; retry", { taskId });
12787
- const appended = fs11.readFileSync(file).subarray(log.end, latest.end);
12788
- const bytes = Buffer.concat([Buffer.from(prefix, "utf8"), appended]);
12789
- replaceFile(file, bytes.toString("utf8"), true);
12790
- try {
12791
- fs11.rmSync(this.snapshotPath(taskId), { force: true });
12792
- } catch {}
12793
- const reloaded = this.load(taskId);
12794
- if (reloaded.ok && reloaded.data)
12795
- this.writeSnapshot(taskId, reloaded.data);
12796
- return success(null, null, { folded: cut, bytes: bytes.length });
12797
- });
12798
- } catch (error) {
12799
- return failure2("storage_error", `compaction failed: ${String(error)}`, { taskId });
12800
- }
12801
- }
12802
- countEvents(file) {
12803
- try {
12804
- const bytes = fs11.readFileSync(file);
12805
- let count = 0;
12806
- for (let index = bytes.indexOf(10);index >= 0; index = bytes.indexOf(10, index + 1))
12807
- count += 1;
12808
- return count;
12809
- } catch {
12810
- return 0;
12811
- }
12812
- }
12813
11845
  openTasksForKey(key, known) {
12814
11846
  const all = this.listStoreIndex();
12815
11847
  if (!all.ok)
@@ -12822,160 +11854,9 @@ class TaskStore {
12822
11854
  const bound = this.openTasksForKey(key);
12823
11855
  return bound.ok ? success(null, null, bound.data[0] ?? null) : bound;
12824
11856
  }
12825
- withKeyLock(key, operation) {
12826
- const digest = createHash10("sha256").update(key).digest("hex").slice(0, 32);
12827
- return this.withLock(path14.join(this.paths().dir, "keys", `${digest}.lock`), operation);
12828
- }
12829
- bindLocked(taskId, key, timestamp) {
12830
- const current = this.readWorkspace();
12831
- if (!current.ok)
12832
- return current;
12833
- let workspace = current.data;
12834
- if (!workspace) {
12835
- workspace = this.nextWorkspace(null);
12836
- const written = this.writeWorkspace(workspace);
12837
- if (!written.ok)
12838
- return written;
12839
- }
12840
- const target = workspace;
12841
- return this.withLock(this.taskLockPath(taskId), () => {
12842
- const loaded = this.load(taskId);
12843
- if (!loaded.ok)
12844
- return loaded;
12845
- if (!loaded.data)
12846
- return failure2("not_found", "task not found", { taskId });
12847
- if (loaded.data.record.status === "closed")
12848
- return failure2("invalid_transition", "a closed task cannot be adopted", { taskId });
12849
- if (loaded.data.record.workspaceId === target.id && loaded.data.key?.key === key.key)
12850
- return success(loaded.data.record.revision, null, loaded.data.record);
12851
- const next = taskRecordSchema.safeParse({
12852
- ...loaded.data.record,
12853
- workspaceId: target.id,
12854
- revision: newRevision(),
12855
- updatedAt: timestamp ?? now(),
12856
- runtime: stampNew(loaded.data.record)
12857
- });
12858
- if (!next.success)
12859
- return failure2("invalid_input", "rebound task is invalid");
12860
- const written = this.appendPatch(loaded.data, next.data, { key });
12861
- return written.ok ? success(next.data.revision, null, next.data) : written;
12862
- });
12863
- }
12864
- unbindLocked(taskId) {
12865
- return this.withLock(this.taskLockPath(taskId), () => {
12866
- const loaded = this.load(taskId);
12867
- if (!loaded.ok)
12868
- return loaded;
12869
- if (!loaded.data || loaded.data.key === null)
12870
- return success(null, null, null);
12871
- return this.appendPatch(loaded.data, loaded.data.record, { key: null });
12872
- });
12873
- }
12874
- createLocked(value, bindCurrent, key, checkRevision = true) {
12875
- const current = this.readWorkspace();
12876
- if (!current.ok)
12877
- return current;
12878
- if (checkRevision && (current.data ? value.expectedWorkspaceRevision !== current.data.revision : value.expectedWorkspaceRevision !== null))
12879
- return failure2("revision_conflict", "workspace revision does not match; omit expectedWorkspaceRevision to use the current record", {
12880
- expectedWorkspaceRevision: value.expectedWorkspaceRevision,
12881
- actualWorkspaceRevision: current.data?.revision ?? null
12882
- });
12883
- if (!value.provenance)
12884
- return failure2("invalid_input", "provenance is required");
12885
- if (!intentSchema.safeParse(value.intent).success || !provenanceSchema.safeParse(value.provenance).success)
12886
- return failure2("invalid_input", "task intent or provenance is invalid");
12887
- if (bindCurrent) {
12888
- const currentKey = this.currentKey();
12889
- if (currentKey.ok)
12890
- return this.withKeyLock(currentKey.data.key, () => {
12891
- const holder = this.openTaskForKey(currentKey.data.key);
12892
- if (!holder.ok)
12893
- return holder;
12894
- if (holder.data) {
12895
- const released = this.unbindLocked(holder.data.id);
12896
- if (!released.ok)
12897
- return released;
12898
- }
12899
- return this.newTask(value, current.data, currentKey.data);
12900
- });
12901
- }
12902
- return this.newTask(value, current.data, key);
12903
- }
12904
- newTask(value, previous, binding) {
12905
- const current = { data: previous };
12906
- const workspace = this.nextWorkspace(current.data);
12907
- const timestamp = value.now ?? now();
12908
- const task = {
12909
- schemaVersion: SCHEMA_VERSION,
12910
- id: newId(),
12911
- workspaceId: workspace.id,
12912
- revision: newRevision(),
12913
- createdAt: timestamp,
12914
- updatedAt: timestamp,
12915
- origin: null,
12916
- intent: {
12917
- id: newId(),
12918
- recordedAt: timestamp,
12919
- provenance: value.provenance,
12920
- data: value.intent
12921
- },
12922
- constraints: [],
12923
- status: "active",
12924
- closure: null,
12925
- progress: { summary: "", nextAction: null, blockers: [] },
12926
- runtime: { createdWith: runtimeVersion(), updatedWith: runtimeVersion() },
12927
- assessments: [],
12928
- policy: null,
12929
- policyChanges: [],
12930
- candidates: [],
12931
- evidence: [],
12932
- decisions: [],
12933
- findings: [],
12934
- workers: []
12935
- };
12936
- return this.writeNewTask(current.data, workspace, task, "task.opened", binding, {
12937
- operation: "create"
12938
- });
12939
- }
12940
- nextWorkspace(current, id) {
12941
- return current ? { ...current, revision: newRevision(), root: this.root, runtime: stampNew(current) } : {
12942
- schemaVersion: SCHEMA_VERSION,
12943
- id: id ?? newId(),
12944
- revision: newRevision(),
12945
- root: this.root,
12946
- runtime: { createdWith: runtimeVersion(), updatedWith: runtimeVersion() }
12947
- };
12948
- }
12949
- writeNewTask(previous, workspace, task, type, key, details) {
12950
- const written = this.writeWorkspace(workspace);
12951
- if (!written.ok)
12952
- return written;
12953
- try {
12954
- this.openTask(task, type, key);
12955
- } catch (error) {
12956
- if (previous) {
12957
- const restored = this.writeWorkspace(previous);
12958
- if (!restored.ok)
12959
- return failure2("external_outcome_unknown", `task ${details.operation} failed and workspace restoration is uncertain`, { ...details, outcome: "unknown" });
12960
- }
12961
- return failure2("external_outcome_unknown", `workspace written but the task log is uncertain: ${String(error)}`, { ...details, outcome: "unknown" });
12962
- }
12963
- return success(task.revision, workspace.revision, task);
12964
- }
12965
- writeWorkspace(record) {
12966
- const file = this.paths().workspace;
12967
- try {
12968
- fs11.mkdirSync(path14.dirname(file), { recursive: true });
12969
- replaceFile(file, `${canonicalJson(record)}
12970
- `, true);
12971
- return success(null, null, null);
12972
- } catch (error) {
12973
- return failure2("storage_error", `workspace write failed: ${String(error)}`, { path: file });
12974
- }
12975
- }
12976
11857
  readIndex() {
12977
11858
  try {
12978
- const value = JSON.parse(fs11.readFileSync(this.paths().index, "utf8"));
11859
+ const value = JSON.parse(fs10.readFileSync(this.paths().index, "utf8"));
12979
11860
  if (!isObject5(value) || value.version !== INDEX_VERSION || !isObject5(value.tasks))
12980
11861
  return {};
12981
11862
  const tasks = {};
@@ -12989,23 +11870,13 @@ class TaskStore {
12989
11870
  }
12990
11871
  writeIndex(entries) {
12991
11872
  try {
12992
- fs11.mkdirSync(this.paths().tasks, { recursive: true });
11873
+ fs10.mkdirSync(this.paths().tasks, { recursive: true });
12993
11874
  replaceFile(this.paths().index, JSON.stringify({
12994
11875
  version: INDEX_VERSION,
12995
11876
  tasks: Object.fromEntries(entries.map((entry) => [entry.id, entry]))
12996
11877
  }), false);
12997
11878
  } catch {}
12998
11879
  }
12999
- indexTask(task, key, legacy) {
13000
- try {
13001
- const signature = fileSignature(this.eventsPath(task.id));
13002
- if (signature === null)
13003
- return;
13004
- const tasks = this.readIndex();
13005
- tasks[task.id] = indexEntry(task, key, legacy, signature);
13006
- this.writeIndex(Object.values(tasks));
13007
- } catch {}
13008
- }
13009
11880
  parseTask(record, taskId) {
13010
11881
  const parsed = this.parseValue(record, taskRecordSchema, "task");
13011
11882
  if (!parsed.ok)
@@ -13036,237 +11907,56 @@ class TaskStore {
13036
11907
  return failure2("recovery_required", `${label} record was written by workit ${writerVersion}; upgrade Workit before mutating this checkout`);
13037
11908
  return failure2("recovery_required", `${label} record does not satisfy its schema`);
13038
11909
  }
13039
- conflict(expected, actual) {
13040
- return failure2("revision_conflict", "snapshot revision does not match; omit expectedRevision to use the current record", { expectedRevision: expected, actualRevision: actual });
13041
- }
13042
- workspaceConflict(expected, actual) {
13043
- return failure2("revision_conflict", "workspace revision does not match; omit expectedWorkspaceRevision to use the current record", { expectedWorkspaceRevision: expected, actualWorkspaceRevision: actual });
13044
- }
13045
11910
  v2Dirs() {
13046
- return [...new Set([this.root, this.origin])].map((dir) => path14.join(dir, ".workit"));
11911
+ return [...new Set([this.root, this.origin])].map((dir) => path13.join(dir, ".workit"));
13047
11912
  }
13048
11913
  pendingMigrations() {
13049
11914
  return this.v2Dirs().filter((dir) => {
13050
- const raw = this.readV2Workspace(path14.join(dir, "workspace.json"));
11915
+ const raw = this.readV2Workspace(path13.join(dir, "workspace.json"));
13051
11916
  return raw !== null && raw !== TOMBSTONE;
13052
11917
  });
13053
11918
  }
13054
- migrateV2(v2) {
13055
- const dirs = this.paths();
13056
- const v2Workspace = path14.join(v2, "workspace.json");
13057
- const v2Tasks = path14.join(v2, "tasks");
13058
- const legacy = path14.join(dirs.dir, "legacy", checkoutSlug(path14.dirname(v2)), "v2");
13059
- const raw = this.readV2Workspace(v2Workspace);
13060
- if (raw === null || raw === TOMBSTONE)
13061
- return success(null, null, null);
13062
- return this.withLock(dirs.checkoutLock, () => this.withLock(path14.join(v2, "metadata.lock"), () => {
13063
- const workspace = this.readV2Workspace(v2Workspace);
13064
- if (workspace === null || workspace === TOMBSTONE)
13065
- return success(null, null, null);
13066
- const parsedWorkspace = this.parseRecord(workspace.bytes, workspaceRecordSchema, "2.x workspace");
13067
- if (!parsedWorkspace.ok)
13068
- return failure2("recovery_required", `cannot migrate the 2.x store at ${v2}: ${parsedWorkspace.error}; move it aside to start fresh`, { path: v2Workspace });
13069
- let files = [];
13070
- try {
13071
- files = fs11.readdirSync(v2Tasks).filter((name) => name.endsWith(".json") && validId(name.slice(0, -5))).filter((name) => !this.isStub(path14.join(v2Tasks, name)));
13072
- } catch {}
13073
- const current = this.readWorkspace();
13074
- if (!current.ok)
13075
- return current;
13076
- let workspaceMoved = false;
13077
- let target = current.data;
13078
- if (!target) {
13079
- target = { ...parsedWorkspace.data, root: this.root };
13080
- const written = this.writeWorkspace(target);
13081
- if (!written.ok)
13082
- return written;
13083
- workspaceMoved = true;
13084
- }
13085
- let migrated = 0;
13086
- let skipped = 0;
13087
- const done = new Map;
13088
- try {
13089
- fs11.mkdirSync(path14.join(legacy, "tasks"), { recursive: true });
13090
- for (const name of ["workspace.json", "index.json"])
13091
- if (fs11.existsSync(path14.join(v2, name)))
13092
- fs11.copyFileSync(path14.join(v2, name), path14.join(legacy, name));
13093
- for (const name of files) {
13094
- const id = name.slice(0, -5);
13095
- const file = path14.join(v2Tasks, name);
13096
- const bytes = fs11.readFileSync(file, "utf8");
13097
- const digest = sha256(bytes);
13098
- fs11.writeFileSync(path14.join(legacy, "tasks", name), bytes);
13099
- const parsed = this.parseRecord(bytes, taskRecordSchema, "2.x task");
13100
- if (!parsed.ok || parsed.data.id !== id)
13101
- return failure2("recovery_required", `cannot migrate 2.x task ${id}: ${parsed.ok ? "file name and record ID differ" : parsed.error}; move ${file} aside to continue`, { path: file });
13102
- const record = { ...parsed.data, workspaceId: target.id };
13103
- const origin = { path: path14.join(legacy, "tasks", name), digest };
13104
- if (!fs11.existsSync(this.eventsPath(id))) {
13105
- this.openTask(record, "migrated.from_v2", null, origin);
13106
- migrated += 1;
13107
- } else {
13108
- const resynced = this.withLock(this.taskLockPath(id), () => {
13109
- const loaded = this.load(id);
13110
- if (!loaded.ok)
13111
- return loaded;
13112
- if (!loaded.data)
13113
- return failure2("not_found", "task not found", { taskId: id });
13114
- if (loaded.data.legacy?.digest === digest)
13115
- return success(null, null, false);
13116
- const appended = this.appendPatch(loaded.data, record, {
13117
- type: "migrated.from_v2",
13118
- legacy: origin
13119
- });
13120
- return appended.ok ? success(null, null, true) : appended;
13121
- });
13122
- if (!resynced.ok)
13123
- return resynced;
13124
- if (resynced.data)
13125
- migrated += 1;
13126
- else
13127
- skipped += 1;
13128
- }
13129
- done.set(name, digest);
13130
- }
13131
- } catch (error) {
13132
- return failure2("storage_error", `cannot migrate the 2.x store at ${v2}: ${String(error)}`, {
13133
- path: v2
13134
- });
13135
- }
13136
- try {
13137
- let complete = true;
13138
- for (const [name, digest] of done) {
13139
- const file = path14.join(v2Tasks, name);
13140
- if (sha256(fs11.readFileSync(file, "utf8")) !== digest) {
13141
- complete = false;
13142
- continue;
13143
- }
13144
- if (dirs.shared)
13145
- fs11.rmSync(file);
13146
- else
13147
- replaceFile(file, this.stubFor(name.slice(0, -5)), false);
13148
- }
13149
- if (!complete)
13150
- return failure2("busy", `the 2.x store at ${v2} changed during migration; retry`, {
13151
- path: v2
13152
- });
13153
- fs11.rmSync(path14.join(v2, "index.json"), { force: true });
13154
- if (dirs.shared)
13155
- fs11.rmSync(v2Workspace, { force: true });
13156
- else
13157
- this.writeTombstone(v2, target.id);
13158
- } catch (error) {
13159
- return failure2("storage_error", `cannot finish the 2.x migration: ${String(error)}`, {
13160
- path: v2
13161
- });
13162
- }
13163
- reportMigration({
13164
- from: v2,
13165
- to: dirs.dir,
13166
- backup: legacy,
13167
- tasks: migrated,
13168
- skipped,
13169
- workspace: workspaceMoved
13170
- });
13171
- return success(null, null, null);
13172
- }));
13173
- }
13174
- clearCheckoutLeftovers(v2) {
13175
- const dirs = this.paths();
13176
- if (!dirs.shared)
13177
- return success(null, null, null);
13178
- const present = () => CHECKOUT_LEFTOVERS.filter((name) => fs11.existsSync(path14.join(v2, name)));
13179
- const ignore = path14.join(v2, ".gitignore");
13180
- const onlyGeneratedIgnore = () => {
13181
- try {
13182
- return fs11.readdirSync(v2).length === 1 && GENERATED_GITIGNORES.has(fs11.readFileSync(ignore, "utf8"));
13183
- } catch {
13184
- return false;
13185
- }
13186
- };
13187
- if (present().length === 0 && !onlyGeneratedIgnore())
13188
- return success(null, null, null);
13189
- const backup = path14.join(dirs.dir, "legacy", checkoutSlug(path14.dirname(v2)), "v2");
13190
- return this.withLock(dirs.checkoutLock, () => {
13191
- let moved = 0;
13192
- try {
13193
- for (const name of present()) {
13194
- const entry = path14.join(v2, name);
13195
- const marker = name === "workspace.json" ? isKnownMarker(entry, "workspace") : name === "store.moved.json" && isKnownMarker(entry, "moved");
13196
- const empty = fs11.lstatSync(entry).isDirectory() && fs11.readdirSync(entry).length === 0;
13197
- if (marker || empty) {
13198
- fs11.rmSync(entry, { recursive: true });
13199
- continue;
13200
- }
13201
- if (name === "tasks" && fs11.lstatSync(entry).isDirectory()) {
13202
- for (const task of fs11.readdirSync(entry)) {
13203
- const file = path14.join(entry, task);
13204
- if (fs11.lstatSync(file).isFile() && isKnownMarker(file, "stub"))
13205
- fs11.rmSync(file);
13206
- else {
13207
- moveInto(file, path14.join(backup, "tasks", task));
13208
- moved += 1;
13209
- }
13210
- }
13211
- fs11.rmdirSync(entry);
13212
- continue;
13213
- }
13214
- moveInto(entry, path14.join(backup, name));
13215
- moved += 1;
13216
- }
13217
- if (onlyGeneratedIgnore())
13218
- fs11.rmSync(ignore);
13219
- if (fs11.readdirSync(v2).length === 0)
13220
- fs11.rmdirSync(v2);
13221
- } catch (error) {
13222
- return failure2("storage_error", `cannot clear ${v2}: ${String(error)}`, { path: v2 });
13223
- }
13224
- if (moved > 0)
13225
- reportMigration({ from: v2, to: dirs.dir, backup, tasks: 0, skipped: 0, workspace: false });
13226
- return success(null, null, null);
13227
- });
13228
- }
13229
11919
  adoptLocalStore() {
13230
11920
  const dirs = this.paths();
13231
- const marker = path14.join(dirs.v2, "store.json");
13232
- if (!dirs.shared || !fs11.existsSync(marker))
11921
+ const marker = path13.join(dirs.v2, "store.json");
11922
+ if (!dirs.shared || !fs10.existsSync(marker))
13233
11923
  return success(null, null, null);
13234
11924
  return this.withLock(dirs.checkoutLock, () => {
13235
- if (!fs11.existsSync(marker))
11925
+ if (!fs10.existsSync(marker))
13236
11926
  return success(null, null, null);
13237
11927
  let tasks = 0;
13238
11928
  try {
13239
11929
  const merge = (from, to) => {
13240
- if (!fs11.existsSync(to)) {
13241
- fs11.mkdirSync(path14.dirname(to), { recursive: true });
11930
+ if (!fs10.existsSync(to)) {
11931
+ fs10.mkdirSync(path13.dirname(to), { recursive: true });
13242
11932
  try {
13243
- fs11.renameSync(from, to);
11933
+ fs10.renameSync(from, to);
13244
11934
  } catch {
13245
- fs11.cpSync(from, to, { recursive: true, errorOnExist: true, force: false });
13246
- fs11.rmSync(from, { recursive: true, force: true });
11935
+ fs10.cpSync(from, to, { recursive: true, errorOnExist: true, force: false });
11936
+ fs10.rmSync(from, { recursive: true, force: true });
13247
11937
  }
13248
11938
  return;
13249
11939
  }
13250
- if (fs11.lstatSync(from).isDirectory() && fs11.lstatSync(to).isDirectory())
13251
- for (const name of fs11.readdirSync(from))
13252
- merge(path14.join(from, name), path14.join(to, name));
11940
+ if (fs10.lstatSync(from).isDirectory() && fs10.lstatSync(to).isDirectory())
11941
+ for (const name of fs10.readdirSync(from))
11942
+ merge(path13.join(from, name), path13.join(to, name));
13253
11943
  };
13254
11944
  for (const sub of ["tasks", "checkouts", "blobs", "legacy"]) {
13255
- const from = path14.join(dirs.v2, sub);
13256
- if (!fs11.existsSync(from))
11945
+ const from = path13.join(dirs.v2, sub);
11946
+ if (!fs10.existsSync(from))
13257
11947
  continue;
13258
11948
  if (sub === "tasks") {
13259
- for (const name of fs11.readdirSync(from))
13260
- if (validId(name) && !fs11.existsSync(path14.join(dirs.dir, sub, name)))
11949
+ for (const name of fs10.readdirSync(from))
11950
+ if (validId(name) && !fs10.existsSync(path13.join(dirs.dir, sub, name)))
13261
11951
  tasks += 1;
13262
11952
  }
13263
- merge(from, path14.join(dirs.dir, sub));
11953
+ merge(from, path13.join(dirs.dir, sub));
13264
11954
  }
13265
- const ledger = path14.join(dirs.v2, "ledger");
13266
- if (fs11.existsSync(ledger) && !fs11.existsSync(path14.join(dirs.dir, "ledger")))
13267
- merge(ledger, path14.join(dirs.dir, "ledger"));
13268
- fs11.rmSync(path14.join(dirs.v2, "task-index.json"), { force: true });
13269
- fs11.renameSync(marker, path14.join(dirs.v2, "store.moved.json"));
11955
+ const ledger = path13.join(dirs.v2, "ledger");
11956
+ if (fs10.existsSync(ledger) && !fs10.existsSync(path13.join(dirs.dir, "ledger")))
11957
+ merge(ledger, path13.join(dirs.dir, "ledger"));
11958
+ fs10.rmSync(path13.join(dirs.v2, "task-index.json"), { force: true });
11959
+ fs10.renameSync(marker, path13.join(dirs.v2, "store.moved.json"));
13270
11960
  } catch (error) {
13271
11961
  return failure2("storage_error", `cannot move ${dirs.v2} into ${dirs.dir}: ${String(error)}`, {
13272
11962
  path: dirs.v2
@@ -13286,7 +11976,7 @@ class TaskStore {
13286
11976
  readV2Workspace(file) {
13287
11977
  let bytes;
13288
11978
  try {
13289
- bytes = fs11.readFileSync(file, "utf8");
11979
+ bytes = fs10.readFileSync(file, "utf8");
13290
11980
  } catch {
13291
11981
  return null;
13292
11982
  }
@@ -13304,7 +11994,7 @@ class TaskStore {
13304
11994
  schemaVersion: SCHEMA_VERSION,
13305
11995
  id: workspaceId ?? newId(),
13306
11996
  revision: newRevision(),
13307
- root: path14.dirname(v2),
11997
+ root: path13.dirname(v2),
13308
11998
  runtime: { createdWith: version, updatedWith: version },
13309
11999
  writer: null,
13310
12000
  store: {
@@ -13315,63 +12005,44 @@ class TaskStore {
13315
12005
  },
13316
12006
  critical: ["store"]
13317
12007
  };
13318
- fs11.mkdirSync(v2, { recursive: true });
13319
- const ignore = path14.join(v2, ".gitignore");
13320
- if (!fs11.existsSync(ignore))
13321
- fs11.writeFileSync(ignore, `*
12008
+ fs10.mkdirSync(v2, { recursive: true });
12009
+ const ignore = path13.join(v2, ".gitignore");
12010
+ if (!fs10.existsSync(ignore))
12011
+ fs10.writeFileSync(ignore, `*
13322
12012
  `);
13323
- replaceFile(path14.join(v2, "workspace.json"), `${JSON.stringify(marker, null, 2)}
12013
+ replaceFile(path13.join(v2, "workspace.json"), `${JSON.stringify(marker, null, 2)}
13324
12014
  `, true);
13325
12015
  }
13326
- stubFor(taskId) {
13327
- const version = isNewerVersion(runtimeVersion(), STORE_MIN_RUNTIME) ? runtimeVersion() : STORE_MIN_RUNTIME;
13328
- return `${JSON.stringify({
13329
- schemaVersion: SCHEMA_VERSION,
13330
- id: taskId,
13331
- runtime: { createdWith: version, updatedWith: version },
13332
- store: { format: "workit-store", version: STORE_FORMAT, path: this.paths().dir },
13333
- critical: ["store"]
13334
- })}
13335
- `;
13336
- }
13337
- isStub(file) {
13338
- try {
13339
- const value = JSON.parse(fs11.readFileSync(file, "utf8"));
13340
- return isObject5(value) && isObject5(value.store) && value.store.format === "workit-store";
13341
- } catch {
13342
- return false;
13343
- }
13344
- }
13345
12016
  writeTombstoneIfMissing() {
13346
12017
  try {
13347
12018
  if (this.paths().shared)
13348
12019
  return;
13349
- const v2 = path14.join(this.root, ".workit");
13350
- if (fs11.existsSync(path14.join(v2, "workspace.json")))
12020
+ const v2 = path13.join(this.root, ".workit");
12021
+ if (fs10.existsSync(path13.join(v2, "workspace.json")))
13351
12022
  return;
13352
12023
  let id = null;
13353
12024
  try {
13354
- id = JSON.parse(fs11.readFileSync(this.paths().workspace, "utf8")).id ?? null;
12025
+ id = JSON.parse(fs10.readFileSync(this.paths().workspace, "utf8")).id ?? null;
13355
12026
  } catch {}
13356
12027
  this.writeTombstone(v2, id);
13357
12028
  } catch {}
13358
12029
  }
13359
12030
  initializeStorage() {
13360
12031
  const dirs = this.paths();
13361
- retryTransient(() => fs11.mkdirSync(dirs.checkout, { recursive: true }));
13362
- retryTransient(() => fs11.mkdirSync(dirs.tasks, { recursive: true }));
13363
- if (!fs11.existsSync(dirs.marker))
12032
+ retryTransient(() => fs10.mkdirSync(dirs.checkout, { recursive: true }));
12033
+ retryTransient(() => fs10.mkdirSync(dirs.tasks, { recursive: true }));
12034
+ if (!fs10.existsSync(dirs.marker))
13364
12035
  replaceFile(dirs.marker, `${JSON.stringify({ format: "workit-store", version: STORE_FORMAT, createdWith: runtimeVersion() })}
13365
12036
  `, false);
13366
12037
  if (!dirs.shared) {
13367
- const ignore = path14.join(dirs.dir, ".gitignore");
12038
+ const ignore = path13.join(dirs.dir, ".gitignore");
13368
12039
  let current = null;
13369
12040
  try {
13370
- current = fs11.readFileSync(ignore, "utf8");
12041
+ current = fs10.readFileSync(ignore, "utf8");
13371
12042
  } catch {}
13372
12043
  if (current !== `*
13373
12044
  `)
13374
- retryTransient(() => fs11.writeFileSync(ignore, `*
12045
+ retryTransient(() => fs10.writeFileSync(ignore, `*
13375
12046
  `));
13376
12047
  }
13377
12048
  this.writeTombstoneIfMissing();
@@ -13387,7 +12058,7 @@ class TaskStore {
13387
12058
  shouldReclaim: ({ payload, nowMs }) => {
13388
12059
  let ageMs = null;
13389
12060
  try {
13390
- ageMs = nowMs - fs11.lstatSync(lockPath).mtimeMs;
12061
+ ageMs = nowMs - fs10.lstatSync(lockPath).mtimeMs;
13391
12062
  } catch {}
13392
12063
  return classifyLockOwner(payload, ageMs, localLockHost(), TASK_STORE_LOCK).state === "stale";
13393
12064
  },
@@ -13424,7 +12095,7 @@ class TaskStore {
13424
12095
  withLock(lockPath, operation) {
13425
12096
  try {
13426
12097
  this.initializeStorage();
13427
- fs11.mkdirSync(path14.dirname(lockPath), { recursive: true });
12098
+ fs10.mkdirSync(path13.dirname(lockPath), { recursive: true });
13428
12099
  } catch (error) {
13429
12100
  return failure2("storage_error", `unable to initialize store: ${String(error)}`, {
13430
12101
  path: this.paths().dir
@@ -13464,18 +12135,18 @@ class TaskStore {
13464
12135
  lockDirWritable(lockPath) {
13465
12136
  const probe = `${lockPath}.${process.pid}.${randomUUID3()}.probe`;
13466
12137
  try {
13467
- fs11.closeSync(fs11.openSync(probe, "wx", 384));
12138
+ fs10.closeSync(fs10.openSync(probe, "wx", 384));
13468
12139
  } catch {
13469
12140
  return false;
13470
12141
  }
13471
12142
  try {
13472
- fs11.rmSync(probe, { force: true });
12143
+ fs10.rmSync(probe, { force: true });
13473
12144
  } catch {}
13474
12145
  return true;
13475
12146
  }
13476
12147
  lockHolderPresent(lockPath) {
13477
12148
  try {
13478
- fs11.lstatSync(lockPath);
12149
+ fs10.lstatSync(lockPath);
13479
12150
  return true;
13480
12151
  } catch (error) {
13481
12152
  return error?.code !== "ENOENT";
@@ -13487,12 +12158,12 @@ class TaskStore {
13487
12158
  if (isTransientWindowsError(error) && !this.lockHolderPresent(lockPath) && !this.lockDirWritable(lockPath))
13488
12159
  return failure2("storage_error", `cannot create the workit lock (${code}); no other Workit call holds it`, {
13489
12160
  path: lockPath,
13490
- guidance: `Check permissions and the read-only attribute on ${path14.dirname(lockPath)}.`
12161
+ guidance: `Check permissions and the read-only attribute on ${path13.dirname(lockPath)}.`
13491
12162
  });
13492
12163
  if (code === "EEXIST" || code === "file_lock_timeout" || code === "file_lock_stale" || isTransientWindowsError(error)) {
13493
12164
  let lock = null;
13494
12165
  try {
13495
- lock = parseMetadataLockOrNull(fs11.readFileSync(lockPath, "utf8"));
12166
+ lock = parseMetadataLockOrNull(fs10.readFileSync(lockPath, "utf8"));
13496
12167
  } catch {}
13497
12168
  return failure2("busy", `workit lock is held by another Workit call${lock ? ` (pid ${lock.pid} on ${lock.host})` : ""}; retry shortly`, {
13498
12169
  outcome: "not_started",
@@ -13511,7 +12182,7 @@ import path17 from "node:path";
13511
12182
 
13512
12183
  // packages/workit-core/src/ledger.ts
13513
12184
  import { spawnSync as spawnSync10 } from "node:child_process";
13514
- import { createHash as createHash11, randomBytes as randomBytes3 } from "node:crypto";
12185
+ import { createHash as createHash9, randomBytes as randomBytes3 } from "node:crypto";
13515
12186
  import fs12 from "node:fs";
13516
12187
  import path16 from "node:path";
13517
12188
 
@@ -13594,7 +12265,7 @@ function bookkeepingPaths(cwd, input) {
13594
12265
 
13595
12266
  // packages/workit-core/src/core/policy/lane.ts
13596
12267
  import { existsSync as existsSync5, readFileSync as readFileSync6 } from "node:fs";
13597
- import path15 from "node:path";
12268
+ import path14 from "node:path";
13598
12269
 
13599
12270
  // packages/workit-core/src/git/default-base.ts
13600
12271
  import { spawnSync as spawnSync9 } from "node:child_process";
@@ -14248,7 +12919,7 @@ function computeLane(input) {
14248
12919
  }
14249
12920
  function untrackedStat(cwd, file) {
14250
12921
  try {
14251
- const bytes = readFileSync6(path15.join(cwd, file));
12922
+ const bytes = readFileSync6(path14.join(cwd, file));
14252
12923
  if (bytes.includes(0))
14253
12924
  return { path: file, added: 0, deleted: 0, binary: true };
14254
12925
  const text = bytes.toString("utf8");
@@ -14279,7 +12950,7 @@ function cosmeticFiles(cwd, fork, head) {
14279
12950
  let after = blobs.get(entry.newBlob);
14280
12951
  if (!after && head === null && ABSENT.test(entry.newBlob))
14281
12952
  try {
14282
- after = readFileSync6(path15.join(cwd, entry.path));
12953
+ after = readFileSync6(path14.join(cwd, entry.path));
14283
12954
  } catch {
14284
12955
  after = undefined;
14285
12956
  }
@@ -14424,6 +13095,144 @@ function verdictDrift(cwd, input) {
14424
13095
  return stale(lane.reasons[0] ?? `lane ${lane.lane}`, paths, lane.lane === "self");
14425
13096
  }
14426
13097
 
13098
+ // packages/workit-core/src/host-session.ts
13099
+ import { createHash as createHash8, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
13100
+ import fs11 from "node:fs";
13101
+ import path15 from "node:path";
13102
+ var ISSUED_PER_LEAD = 64;
13103
+ var ISSUED_SESSIONS_MARKER = "workit-issued-sessions/3";
13104
+ var hash = (value) => createHash8("sha256").update(value).digest("hex").slice(0, 32);
13105
+ var userIssuedRoot = () => path15.join(resolveStateDir(), "issued");
13106
+ var userTokenRoot = () => path15.join(resolveStateDir(), "issued-tokens");
13107
+ function migrateRepoIssued(cwd) {
13108
+ if (cwd === undefined)
13109
+ return;
13110
+ let old;
13111
+ try {
13112
+ const location = resolveStore(cwd);
13113
+ if (location instanceof Error)
13114
+ return;
13115
+ old = path15.join(location.dir, "hooks", "issued");
13116
+ if (!fs11.existsSync(old))
13117
+ return;
13118
+ } catch {
13119
+ return;
13120
+ }
13121
+ for (const lead of safeList(old)) {
13122
+ try {
13123
+ const from = path15.join(old, lead);
13124
+ if (!fs11.statSync(from).isDirectory())
13125
+ continue;
13126
+ const to = path15.join(userIssuedRoot(), lead);
13127
+ fs11.mkdirSync(to, { recursive: true, mode: 448 });
13128
+ for (const id of fs11.readdirSync(from)) {
13129
+ try {
13130
+ fs11.copyFileSync(path15.join(from, id), path15.join(to, id), fs11.constants.COPYFILE_EXCL);
13131
+ } catch (error) {
13132
+ if (error.code !== "EEXIST")
13133
+ throw error;
13134
+ }
13135
+ fs11.rmSync(path15.join(from, id), { force: true });
13136
+ }
13137
+ removeIfEmpty(from);
13138
+ } catch {}
13139
+ }
13140
+ removeIfEmpty(old);
13141
+ }
13142
+ var safeList = (dir) => {
13143
+ try {
13144
+ return fs11.readdirSync(dir);
13145
+ } catch {
13146
+ return [];
13147
+ }
13148
+ };
13149
+ var removeIfEmpty = (dir) => {
13150
+ try {
13151
+ fs11.rmdirSync(dir);
13152
+ } catch {}
13153
+ };
13154
+ var tokenHash = (token) => createHash8("sha256").update(token).digest("hex");
13155
+ function recordIssuedSession(cwd, lead, issued) {
13156
+ const token = randomBytes2(18).toString("hex");
13157
+ try {
13158
+ migrateRepoIssued(cwd);
13159
+ const own = hash(issued);
13160
+ const tokens = path15.join(userTokenRoot(), hash(lead));
13161
+ fs11.mkdirSync(tokens, { recursive: true, mode: 448 });
13162
+ fs11.writeFileSync(path15.join(tokens, own), `${tokenHash(token)}
13163
+ `, { mode: 384, flag: "wx" });
13164
+ const dir = path15.join(userIssuedRoot(), hash(lead));
13165
+ fs11.mkdirSync(dir, { recursive: true, mode: 448 });
13166
+ fs11.writeFileSync(path15.join(dir, own), `${ISSUED_SESSIONS_MARKER}
13167
+ `, { mode: 384 });
13168
+ pruneIssued(dir, own, tokens);
13169
+ return token;
13170
+ } catch {
13171
+ return null;
13172
+ }
13173
+ }
13174
+ function judgeBranch(cwd) {
13175
+ const branch = currentBranch(cwd);
13176
+ return branch && !isProtectedTarget(cwd, branch) ? branch : null;
13177
+ }
13178
+ function verdictCommand(options) {
13179
+ const kind = options.judge === "verifier" ? "<live|unit>" : options.judge === "reviewer" ? "review" : "<live|unit|review>";
13180
+ return [
13181
+ "workit ledger verdict <verified|failed|blocked>",
13182
+ `--kind ${kind}`,
13183
+ `--branch ${options.branch ?? "<branch>"}`,
13184
+ options.session ? `--session ${options.session}` : null,
13185
+ options.token ? `--token=${options.token}` : null,
13186
+ '--how "<what you ran and saw>"'
13187
+ ].filter(Boolean).join(" ");
13188
+ }
13189
+ function pruneIssued(dir, own, tokens) {
13190
+ try {
13191
+ const entries = fs11.readdirSync(dir);
13192
+ if (entries.length <= ISSUED_PER_LEAD)
13193
+ return;
13194
+ const byAge = entries.filter((name) => name !== own).map((name) => ({ name, at: fs11.statSync(path15.join(dir, name)).mtimeMs })).toSorted((a, b) => a.at - b.at);
13195
+ for (const { name } of byAge.slice(0, entries.length - ISSUED_PER_LEAD)) {
13196
+ fs11.rmSync(path15.join(dir, name), { force: true });
13197
+ fs11.rmSync(path15.join(tokens, name), { force: true });
13198
+ }
13199
+ } catch {}
13200
+ }
13201
+ var issuedRecord = (cwd, claimed) => {
13202
+ const cut = claimed.lastIndexOf(":");
13203
+ if (cut <= 0)
13204
+ return null;
13205
+ migrateRepoIssued(cwd);
13206
+ try {
13207
+ return fs11.readFileSync(path15.join(userIssuedRoot(), hash(claimed.slice(0, cut)), hash(claimed)), "utf8");
13208
+ } catch {
13209
+ return null;
13210
+ }
13211
+ };
13212
+ var TOKEN_HASH = /^([0-9a-f]{64})$/mu;
13213
+ var issuedToken = (claimed) => {
13214
+ const cut = claimed.lastIndexOf(":");
13215
+ if (cut <= 0)
13216
+ return { stored: null, leadBound: false };
13217
+ const dir = path15.join(userTokenRoot(), hash(claimed.slice(0, cut)));
13218
+ try {
13219
+ const text = fs11.readFileSync(path15.join(dir, hash(claimed)), "utf8");
13220
+ return { stored: TOKEN_HASH.exec(text)?.[1] ?? null, leadBound: true };
13221
+ } catch {
13222
+ return { stored: null, leadBound: safeList(dir).length > 0 };
13223
+ }
13224
+ };
13225
+ function issuedBinding(cwd, claimed) {
13226
+ const record = issuedRecord(cwd, claimed);
13227
+ const { stored, leadBound } = issuedToken(claimed);
13228
+ if (stored)
13229
+ return "token";
13230
+ if (record === null)
13231
+ return null;
13232
+ return leadBound ? "token" : "legacy";
13233
+ }
13234
+ var OWN_CHILD_SHELL = new Set(["opencode", "pi"]);
13235
+
14427
13236
  // packages/workit-core/src/ledger.ts
14428
13237
  var LEDGER_VERSION = 1;
14429
13238
  var MAX_LINE_BYTES = 4096;
@@ -14501,7 +13310,7 @@ var binaryRangeDiff = (cwd, base, head) => {
14501
13310
  return diff.ok && diff.stdout ? diff.stdout : null;
14502
13311
  };
14503
13312
  var hashOfDiff = (diff) => {
14504
- const hash = createHash11("sha256");
13313
+ const hash = createHash9("sha256");
14505
13314
  for (const line of diff.split(`
14506
13315
  `)) {
14507
13316
  if (line.startsWith("index "))
@@ -14657,7 +13466,7 @@ function withLedgerLock(file, fn, waitMs = hostAwareLockTimeout(LOCK_WAIT_MS)) {
14657
13466
  ledgerLock.release(lock, token);
14658
13467
  }
14659
13468
  }
14660
- var sha2562 = (text) => createHash11("sha256").update(text).digest("hex");
13469
+ var sha2562 = (text) => createHash9("sha256").update(text).digest("hex");
14661
13470
  var chainHash = (prevHash, body) => sha2562(`${prevHash ?? ""}
14662
13471
  ${body}`);
14663
13472
  var TAIL_BYTES = 64 * 1024;
@@ -15416,7 +14225,7 @@ function verdictMirrorPath(cwd) {
15416
14225
  }
15417
14226
  if (!identity)
15418
14227
  return null;
15419
- const key = createHash11("sha256").update(identity).digest("hex").slice(0, 32);
14228
+ const key = createHash9("sha256").update(identity).digest("hex").slice(0, 32);
15420
14229
  return path16.join(resolveStateDir(), "verdicts", key, "ledger.jsonl");
15421
14230
  }
15422
14231
  var importedStamp = new Map;
@@ -15632,7 +14441,7 @@ function writeBlockers(task, root) {
15632
14441
  }
15633
14442
 
15634
14443
  // packages/workit-core/src/core/task-evaluation.ts
15635
- var digestBytes = (value) => createHash12("sha256").update(value).digest("hex");
14444
+ var digestBytes = (value) => createHash10("sha256").update(value).digest("hex");
15636
14445
  var inside = (root, candidate) => candidate === root || candidate.startsWith(`${root}${path18.sep}`);
15637
14446
  var relative = (root, candidate) => path18.relative(root, candidate).split(path18.sep).join("/") || ".";
15638
14447
  var canonicalPath = (value) => {
@@ -16499,7 +15308,7 @@ var sessionContextText = (input, descriptor, options) => {
16499
15308
  let compact = "";
16500
15309
  let offer = null;
16501
15310
  try {
16502
- const store = new TaskStore(input.cwd);
15311
+ const store = new TaskReader(input.cwd);
16503
15312
  const listed = store.listTaskIndex();
16504
15313
  if (migrationPending(listed))
16505
15314
  return `<workit-contract>
@@ -16556,7 +15365,7 @@ var whereLine = (cwd) => {
16556
15365
  };
16557
15366
  var turnContextText = (input, descriptor) => {
16558
15367
  try {
16559
- const text = sessionCompactContext(new TaskStore(input.cwd), { host: input.host, handle: input.session.id }, hookOperationContext(input, descriptor), descriptor.context.task);
15368
+ const text = sessionCompactContext(new TaskReader(input.cwd), { host: input.host, handle: input.session.id }, hookOperationContext(input, descriptor), descriptor.context.task);
16560
15369
  if (text === MIGRATION_PENDING_NOTE)
16561
15370
  return text;
16562
15371
  return text ? `<workit-task-context>${[whereLine(input.cwd), text].filter(Boolean).join(`
@@ -16566,7 +15375,7 @@ var turnContextText = (input, descriptor) => {
16566
15375
  }
16567
15376
  };
16568
15377
  var TURN_TTL_MS = 7 * 24 * 60 * 60 * 1000;
16569
- var digestOf = (text) => createHash13("sha256").update(text).digest("hex");
15378
+ var digestOf = (text) => createHash11("sha256").update(text).digest("hex");
16570
15379
  var turnMarker = (input) => {
16571
15380
  if (!input.session.id)
16572
15381
  return null;
@@ -16640,7 +15449,7 @@ import path24 from "node:path";
16640
15449
 
16641
15450
  // packages/workit-core/src/hooks/raw-git.ts
16642
15451
  import { spawnSync as spawnSync12 } from "node:child_process";
16643
- import { createHash as createHash15 } from "node:crypto";
15452
+ import { createHash as createHash13 } from "node:crypto";
16644
15453
  import fs16 from "node:fs";
16645
15454
  import os6 from "node:os";
16646
15455
  import path23 from "node:path";
@@ -16959,7 +15768,7 @@ var raises = (kind, current, next) => {
16959
15768
  };
16960
15769
 
16961
15770
  // packages/workit-core/src/hooks/session-marker.ts
16962
- import { createHash as createHash14 } from "node:crypto";
15771
+ import { createHash as createHash12 } from "node:crypto";
16963
15772
  import fs15 from "node:fs";
16964
15773
  import path22 from "node:path";
16965
15774
  var sessionMarkerFile = (input, session, store) => {
@@ -16970,7 +15779,7 @@ var sessionMarkerFile = (input, session, store) => {
16970
15779
  return null;
16971
15780
  dir = location.dir;
16972
15781
  }
16973
- const name = createHash14("sha256").update(`${input.host}\x00${session}`).digest("hex").slice(0, 32);
15782
+ const name = createHash12("sha256").update(`${input.host}\x00${session}`).digest("hex").slice(0, 32);
16974
15783
  return path22.join(dir, "hooks", `skills-${name}.json`);
16975
15784
  };
16976
15785
  var list = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
@@ -18970,9 +17779,15 @@ var messageOf = (segment, index) => {
18970
17779
  return null;
18971
17780
  return match[3].replace(/\n+$/u, "");
18972
17781
  };
17782
+ var sameGitDir = (a, b, platform = process.platform) => {
17783
+ if (platform !== "win32")
17784
+ return path23.posix.resolve(a) === path23.posix.resolve(b);
17785
+ const fold = (value) => path23.win32.resolve(value).toLowerCase();
17786
+ return fold(a) === fold(b);
17787
+ };
18973
17788
  var cdCommitCall = (input, command, target, repo) => {
18974
17789
  const { top, git, dir: store } = repo.location;
18975
- if (!top || !git || git.gitDir === path23.dirname(store) || repoAt(input.cwd)?.location.top === top)
17790
+ if (!top || !git || sameGitDir(git.gitDir, path23.dirname(store)) || repoAt(input.cwd)?.location.top === top)
18976
17791
  return null;
18977
17792
  const bare = command.replaceAll(/'[^']*'|"(?:[^"\\]|\\.)*"/gu, "").replaceAll("&&", "");
18978
17793
  if (/[;|&<>`$()\n\\]/u.test(bare))
@@ -19168,8 +17983,8 @@ var analysisDenial = (error) => ({
19168
17983
  });
19169
17984
  var NEXT_COMMAND = "next";
19170
17985
  var MARKER_TTL_SECONDS = 3600;
19171
- var markerFile = (repo, session, key) => path23.join(repo.location.dir, "hooks", `commit-${createHash15("sha256").update(`${session}\x00${key}`).digest("hex").slice(0, 32)}.json`);
19172
- var callKey = (toolUseId, command) => toolUseId ?? `cmd:${createHash15("sha256").update(command).digest("hex")}`;
17986
+ var markerFile = (repo, session, key) => path23.join(repo.location.dir, "hooks", `commit-${createHash13("sha256").update(`${session}\x00${key}`).digest("hex").slice(0, 32)}.json`);
17987
+ var callKey = (toolUseId, command) => toolUseId ?? `cmd:${createHash13("sha256").update(command).digest("hex")}`;
19173
17988
  function noteRawCommit(input, command, key) {
19174
17989
  try {
19175
17990
  if (!input.session.id || !/\bcommit\b/.test(command))
@@ -20288,7 +19103,7 @@ import path28 from "node:path";
20288
19103
 
20289
19104
  // packages/workit-core/src/core/live-session.ts
20290
19105
  import { spawnSync as spawnSync14 } from "node:child_process";
20291
- import { createHash as createHash16 } from "node:crypto";
19106
+ import { createHash as createHash14 } from "node:crypto";
20292
19107
  import fs19 from "node:fs";
20293
19108
  import os8 from "node:os";
20294
19109
  import path27 from "node:path";
@@ -20383,7 +19198,7 @@ var checkoutOf = (target) => {
20383
19198
  } catch {}
20384
19199
  return top;
20385
19200
  };
20386
- var markerFile2 = (top) => path27.join(resolveStateDir(), "live-sessions", `${createHash16("sha256").update(checkoutKey(top)).digest("hex").slice(0, 32)}.json`);
19201
+ var markerFile2 = (top) => path27.join(resolveStateDir(), "live-sessions", `${createHash14("sha256").update(checkoutKey(top)).digest("hex").slice(0, 32)}.json`);
20387
19202
  var checkoutKey = (top, platform = process.platform) => {
20388
19203
  let key = path27.resolve(top);
20389
19204
  try {
@@ -20892,7 +19707,7 @@ var shellWrites = (command, depth = 0) => {
20892
19707
  var cache2 = new Map;
20893
19708
  var planKeyOf = (root, plans) => [...plans].map((file) => fileSignature(path28.resolve(root, file)) ?? "-").join("\x00");
20894
19709
  var gateFor = (cwd) => {
20895
- const store = new TaskStore(cwd);
19710
+ const store = new TaskReader(cwd);
20896
19711
  const listed = store.listTaskIndex();
20897
19712
  if (!listed.ok)
20898
19713
  return null;
@@ -21647,7 +20462,7 @@ var sameSha = (left, right) => left.length >= right.length ? left.startsWith(rig
21647
20462
  // packages/workit-core/src/core/policy/current-judgment.ts
21648
20463
  function currentJudgment(cwd) {
21649
20464
  try {
21650
- const store = new TaskStore(cwd);
20465
+ const store = new TaskReader(cwd);
21651
20466
  const listed = store.listTaskIndex();
21652
20467
  const key = store.currentKey();
21653
20468
  if (!listed.ok || !key.ok)
@@ -22807,7 +21622,7 @@ function neededChecks(lane, configured) {
22807
21622
  }
22808
21623
 
22809
21624
  // packages/workit-core/src/hooks/worktree-confine.ts
22810
- import { createHash as createHash17 } from "node:crypto";
21625
+ import { createHash as createHash15 } from "node:crypto";
22811
21626
  import fs21 from "node:fs";
22812
21627
  import path31 from "node:path";
22813
21628
  var FANOUT_TOKEN_FILE = "workit-fanout-token";
@@ -22855,7 +21670,7 @@ var workitWorktreeOf = (file) => {
22855
21670
  }
22856
21671
  };
22857
21672
  var bindingDir = () => path31.join(resolveStateDir(), "worktree-bind");
22858
- var bindingFile = (session, agentId) => path31.join(bindingDir(), `${createHash17("sha256").update(`${session}\x00${agentId}`).digest("hex").slice(0, 32)}.json`);
21673
+ var bindingFile = (session, agentId) => path31.join(bindingDir(), `${createHash15("sha256").update(`${session}\x00${agentId}`).digest("hex").slice(0, 32)}.json`);
22859
21674
  var readBinding = (file) => {
22860
21675
  try {
22861
21676
  const value = JSON.parse(fs21.readFileSync(file, "utf8"));
@@ -23251,10 +22066,12 @@ var substitutingHeredoc = (command) => {
23251
22066
  }
23252
22067
  return false;
23253
22068
  };
23254
- var judgeDeny = (input, what) => {
22069
+ var judgeDeny = (input, what, target) => {
23255
22070
  const role = input.session.agentType?.endsWith("reviewer") ? "reviewer" : "verifier";
23256
22071
  const root = checkoutOf2(input.cwd)?.root;
23257
- const scratch = root ? path31.join(root, SCRATCH) : `${SCRATCH}/ at the root of the checkout you judge`;
22072
+ const candidate = target ? checkoutOf2(target)?.root : undefined;
22073
+ const also = root && candidate && candidate !== root && commonDir(candidate) === commonDir(root) ? ` or ${path31.join(candidate, SCRATCH)}` : "";
22074
+ const scratch = root ? `${path31.join(root, SCRATCH)}${also}` : `${SCRATCH}/ at the root of the checkout you judge`;
23258
22075
  const unblock = `Write only under ${scratch} (mkdir -p it): put a generated case in a file there with a quoted heredoc (<<'EOF') and never run it in the shell. Reads, \`workit check\` and \`workit ledger verdict|finding\` stay allowed; a change the candidate needs is a finding, not an edit.`;
23259
22076
  return {
23260
22077
  kind: "deny",
@@ -23275,7 +22092,7 @@ function confineJudge(input, targets) {
23275
22092
  if (inScratch(canonical4(target), repo))
23276
22093
  continue;
23277
22094
  const runner = runnerAt(target);
23278
- return judgeDeny(input, runner === null ? `${shown(target)} is outside it` : `\`${runner}\` runs in ${shown(target)}, outside it`);
22095
+ return judgeDeny(input, runner === null ? `${shown(target)} is outside it` : `\`${runner}\` runs in ${shown(target)}, outside it`, target);
23279
22096
  }
23280
22097
  return NONE5;
23281
22098
  } catch {