@brainervirus/workit-codex 2.1.1 → 2.1.3

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.
@@ -8783,6 +8783,45 @@ var metadataLockSchema = object({
8783
8783
  nonce: string2().min(1),
8784
8784
  externalAction: literal(true).optional()
8785
8785
  }).strict();
8786
+ var INDEX_VERSION = 1;
8787
+ var hostSession = (value) => isObject2(value) && value.kind === "host" && typeof value.host === "string" && typeof value.handle === "string" ? { host: value.host, handle: value.handle } : null;
8788
+ var indexEntry = (task, file) => {
8789
+ const sessions = [];
8790
+ const intent = hostSession(task.intent.provenance.session);
8791
+ if (intent)
8792
+ sessions.push({ ...intent, workerId: null });
8793
+ for (const worker of task.workers) {
8794
+ const session = hostSession(worker.data.session);
8795
+ if (session)
8796
+ sessions.push({ ...session, workerId: worker.id });
8797
+ }
8798
+ return {
8799
+ id: task.id,
8800
+ revision: task.revision,
8801
+ status: task.status,
8802
+ createdAt: task.createdAt,
8803
+ updatedAt: task.updatedAt,
8804
+ objective: task.intent.data.objective,
8805
+ source: { host: task.intent.provenance.host, kind: task.intent.provenance.kind },
8806
+ progress: { summary: task.progress.summary, nextAction: task.progress.nextAction },
8807
+ sessions,
8808
+ file
8809
+ };
8810
+ };
8811
+ var fileSignature = (file) => {
8812
+ try {
8813
+ const stat = fs4.statSync(file, { bigint: true });
8814
+ return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
8815
+ } catch {
8816
+ return null;
8817
+ }
8818
+ };
8819
+ var RACY_WINDOW_NS = 2000000000n;
8820
+ var racySignature = (signature) => {
8821
+ const [mtime = 0n, ctime = 0n] = signature.split(":").slice(3, 5).map(BigInt);
8822
+ const changed = mtime > ctime ? mtime : ctime;
8823
+ return BigInt(Date.now()) * 1000000n - changed < RACY_WINDOW_NS;
8824
+ };
8786
8825
  var now = () => new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
8787
8826
  var cachedRuntimeVersion = null;
8788
8827
  var runtimeVersion = () => {
@@ -8911,6 +8950,57 @@ class TaskStore {
8911
8950
  }
8912
8951
  return success(null, null, tasks);
8913
8952
  }
8953
+ listTaskIndex() {
8954
+ if (!fs4.existsSync(this.tasksDir))
8955
+ return success(null, null, []);
8956
+ let names;
8957
+ try {
8958
+ names = fs4.readdirSync(this.tasksDir).filter((name) => name.endsWith(".json"));
8959
+ } catch (error) {
8960
+ return failure("storage_error", `unable to list tasks: ${String(error)}`, {
8961
+ path: this.tasksDir
8962
+ });
8963
+ }
8964
+ const workspace = this.readWorkspace();
8965
+ if (!workspace.ok)
8966
+ return workspace;
8967
+ if (!workspace.data)
8968
+ return failure("recovery_required", "task workspace binding is invalid", {
8969
+ path: this.workspacePath
8970
+ });
8971
+ const stored = this.readIndex(workspace.data.id);
8972
+ const entries = [];
8973
+ let changed = Object.keys(stored).length !== names.length;
8974
+ for (const name of names.sort()) {
8975
+ const file = path4.join(this.tasksDir, name);
8976
+ const signature = fileSignature(file);
8977
+ if (signature === null) {
8978
+ changed = true;
8979
+ continue;
8980
+ }
8981
+ const cached = stored[name.slice(0, -5)];
8982
+ if (cached && cached.file === signature && !racySignature(signature)) {
8983
+ entries.push(cached);
8984
+ continue;
8985
+ }
8986
+ const item = this.readRecord(file, taskRecordSchema);
8987
+ if (!item.exists)
8988
+ continue;
8989
+ if (!item.result.ok)
8990
+ return item.result;
8991
+ if (!validId(name.slice(0, -5)) || item.result.data.id !== name.slice(0, -5))
8992
+ return failure("recovery_required", "task filename and record ID differ", { path: name });
8993
+ if (item.result.data.workspaceId !== workspace.data.id)
8994
+ return failure("recovery_required", "task workspace binding is invalid", { path: name });
8995
+ const entry = indexEntry(item.result.data, signature);
8996
+ if (!cached || canonicalJson(cached) !== canonicalJson(entry))
8997
+ changed = true;
8998
+ entries.push(entry);
8999
+ }
9000
+ if (changed)
9001
+ this.writeIndex(workspace.data.id, entries);
9002
+ return success(null, null, entries);
9003
+ }
8914
9004
  readWorkspace() {
8915
9005
  const item = this.readRecord(this.workspacePath, workspaceRecordSchema);
8916
9006
  if (!item.exists)
@@ -9590,6 +9680,8 @@ class TaskStore {
9590
9680
  fs4.renameSync(temporary, file);
9591
9681
  temporary = undefined;
9592
9682
  this.fsyncDirectory(path4.dirname(file));
9683
+ if (path4.dirname(file) === this.tasksDir)
9684
+ this.indexTaskWrite(file, value);
9593
9685
  return success(null, null, value);
9594
9686
  } catch (error) {
9595
9687
  return failure("storage_error", `snapshot replacement failed: ${String(error)}`, {
@@ -9602,6 +9694,45 @@ class TaskStore {
9602
9694
  } catch {}
9603
9695
  }
9604
9696
  }
9697
+ readIndex(workspaceId) {
9698
+ try {
9699
+ const value = JSON.parse(fs4.readFileSync(this.indexPath, "utf8"));
9700
+ if (!isObject2(value) || value.version !== INDEX_VERSION || value.workspaceId !== workspaceId || !isObject2(value.tasks))
9701
+ return {};
9702
+ const tasks = {};
9703
+ for (const [id, entry] of Object.entries(value.tasks))
9704
+ if (isObject2(entry) && entry.id === id && typeof entry.file === "string" && typeof entry.status === "string" && typeof entry.updatedAt === "string" && Array.isArray(entry.sessions) && isObject2(entry.progress) && isObject2(entry.source))
9705
+ tasks[id] = entry;
9706
+ return tasks;
9707
+ } catch {
9708
+ return {};
9709
+ }
9710
+ }
9711
+ writeIndex(workspaceId, entries) {
9712
+ const temporary = `${this.indexPath}.${process.pid}.${randomUUID2()}.tmp`;
9713
+ try {
9714
+ fs4.writeFileSync(temporary, JSON.stringify({
9715
+ version: INDEX_VERSION,
9716
+ workspaceId,
9717
+ tasks: Object.fromEntries(entries.map((entry) => [entry.id, entry]))
9718
+ }), { mode: 384, flag: "wx" });
9719
+ fs4.renameSync(temporary, this.indexPath);
9720
+ } catch {
9721
+ try {
9722
+ fs4.unlinkSync(temporary);
9723
+ } catch {}
9724
+ }
9725
+ }
9726
+ indexTaskWrite(file, task) {
9727
+ try {
9728
+ const signature = fileSignature(file);
9729
+ if (signature === null)
9730
+ return;
9731
+ const tasks = this.readIndex(task.workspaceId);
9732
+ tasks[task.id] = indexEntry(task, signature);
9733
+ this.writeIndex(task.workspaceId, Object.values(tasks));
9734
+ } catch {}
9735
+ }
9605
9736
  saveRecovery(file, bytes) {
9606
9737
  const target = path4.basename(file) === "workspace.json" ? "workspace" : "task";
9607
9738
  const id = target === "task" ? path4.basename(file, ".json") : "workspace";
@@ -9760,6 +9891,9 @@ class TaskStore {
9760
9891
  get workspacePath() {
9761
9892
  return path4.join(this.workitDir, "workspace.json");
9762
9893
  }
9894
+ get indexPath() {
9895
+ return path4.join(this.workitDir, "index.json");
9896
+ }
9763
9897
  get lockPath() {
9764
9898
  return path4.join(this.workitDir, "metadata.lock");
9765
9899
  }
@@ -9767,71 +9901,8 @@ class TaskStore {
9767
9901
  return path4.join(this.workitDir, ".gitignore");
9768
9902
  }
9769
9903
  }
9770
- // packages/workit-core/src/core/workers.ts
9771
- var same = (left, right) => {
9772
- try {
9773
- return canonicalJson(left) === canonicalJson(right);
9774
- } catch {
9775
- return false;
9776
- }
9777
- };
9778
- var UNCERTAIN_WORKER_STATES = ["dispatching", "running", "cancelling", "unknown"];
9779
- var isUncertainWorker = (state) => UNCERTAIN_WORKER_STATES.includes(state);
9780
- var workerBlocksTransition = (transition, state) => transition === "pause" ? false : isUncertainWorker(state);
9781
- var callerSession = (caller) => caller.session ?? { kind: "host", host: caller.host, handle: caller.actor };
9782
- var validPath = (value) => typeof value === "string" && value.length > 0 && ![...value].some((char) => {
9783
- const code = char.charCodeAt(0);
9784
- return code < 32 || code === 127;
9785
- }) && !value.split(/[\\/]/).includes("..");
9786
- var callerValue = (value) => ({ host: value.host, actor: value.actor });
9787
- var workerIdOf = (value) => value.workerId ?? null;
9788
- var currentWriterOwnsTask = (task, workspace, caller) => {
9789
- const owner = workspace.writer?.owner;
9790
- return task.status === "active" && task.workspaceId === workspace.id && owner?.taskId === task.id && owner.session.host === caller.host && owner.session.handle === caller.actor;
9791
- };
9792
- function assertProductWriteAllowed(input) {
9793
- if (!Array.isArray(input.paths) || input.paths.some((path) => !validPath(path)))
9794
- return failure("invalid_input", "invalid product write path");
9795
- if (!input.store)
9796
- return failure("permission_denied", "write authorization requires core state");
9797
- const task = input.store.readTask(input.task.id);
9798
- if (!task.ok)
9799
- return task;
9800
- const workspace = input.store.readWorkspace();
9801
- if (!workspace.ok)
9802
- return workspace;
9803
- if (!workspace.data)
9804
- return failure("not_found", "workspace not found");
9805
- const workspaceRecord = workspace.data;
9806
- if (task.data.status !== "active")
9807
- return failure("invalid_transition", "paused or closed tasks cannot own product writes");
9808
- if (workspaceRecord.id !== task.data.workspaceId || workspaceRecord.root.length === 0)
9809
- return failure("recovery_required", "task and workspace bindings are invalid");
9810
- const writer = workspaceRecord.writer;
9811
- if (!writer)
9812
- return failure("permission_denied", "checkout has no writer owner");
9813
- if (writer.state === "uncertain")
9814
- return failure("recovery_required", "checkout writer requires recovery", {
9815
- owner: writer.owner
9816
- });
9817
- const caller = callerValue(input.caller);
9818
- const workerId = workerIdOf(input.caller);
9819
- const owner = writer.owner;
9820
- if (owner.taskId !== task.data.id || owner.workerId !== workerId || owner.session.host !== caller.host || owner.session.handle !== caller.actor)
9821
- return failure("writer_conflict", "checkout is owned by another validated actor", { owner });
9822
- const worker = workerId === null ? null : task.data.workers.find((entry) => entry.id === workerId);
9823
- if (workerId !== null && (!worker || worker.data.assignment.role !== "implementer"))
9824
- return failure("permission_denied", "only implementers can own product writes");
9825
- if (workerId !== null && (!worker?.data.session || worker.data.state === "cancelling" || worker.data.state === "unknown" || worker.data.state === "stopped" || !same(worker.data.session, callerSession(input.caller))))
9826
- return failure("recovery_required", "worker session is not an active writer");
9827
- return success(null, workspaceRecord.revision, owner);
9828
- }
9829
-
9830
- // packages/workit-core/src/core/task-evaluation.ts
9831
- import { createHash as createHash7 } from "node:crypto";
9832
- import * as fs7 from "node:fs";
9833
- import { spawnSync as spawnSync2 } from "node:child_process";
9834
- import path10 from "node:path";
9904
+ // packages/workit-core/src/core/task-engine.ts
9905
+ import { realpathSync as realpathSync6 } from "node:fs";
9835
9906
 
9836
9907
  // packages/workit-core/src/core/authority.ts
9837
9908
  import { createHash as createHash6 } from "node:crypto";
@@ -9950,7 +10021,6 @@ var LOCALE_RE = /^[a-z]{2,3}(-(?:[A-Z]{2}|[0-9]{3}))?$/;
9950
10021
  var DEFAULTS = {
9951
10022
  locale: "en",
9952
10023
  localeOptions: ["en", "es-CL", "es-MX", "es-AR", "pt-BR"],
9953
- timezone: "America/Santiago",
9954
10024
  branchPolicy: {
9955
10025
  preset: "gitflow",
9956
10026
  allowed: [...PRESETS.gitflow.allowed],
@@ -9988,7 +10058,6 @@ var parseConfigResult = (raw, file) => {
9988
10058
  config: {
9989
10059
  locale,
9990
10060
  localeOptions: Array.isArray(input.localeOptions) ? input.localeOptions : DEFAULTS.localeOptions,
9991
- timezone: input.timezone ?? DEFAULTS.timezone,
9992
10061
  branchPolicy: mergePreset(preset, {
9993
10062
  allowed: Array.isArray(input.branchPolicy?.allowed) ? input.branchPolicy.allowed : undefined,
9994
10063
  protectedNames: Array.isArray(input.branchPolicy?.protected) ? input.branchPolicy.protected : undefined
@@ -10656,6 +10725,66 @@ var verifyPushIdentity = (root, provider, account) => {
10656
10725
  return { ok: true };
10657
10726
  };
10658
10727
 
10728
+ // packages/workit-core/src/core/workers.ts
10729
+ var same = (left, right) => {
10730
+ try {
10731
+ return canonicalJson(left) === canonicalJson(right);
10732
+ } catch {
10733
+ return false;
10734
+ }
10735
+ };
10736
+ var UNCERTAIN_WORKER_STATES = ["dispatching", "running", "cancelling", "unknown"];
10737
+ var isUncertainWorker = (state) => UNCERTAIN_WORKER_STATES.includes(state);
10738
+ var workerBlocksTransition = (transition, state) => transition === "pause" ? false : isUncertainWorker(state);
10739
+ var callerSession = (caller) => caller.session ?? { kind: "host", host: caller.host, handle: caller.actor };
10740
+ var validPath = (value) => typeof value === "string" && value.length > 0 && ![...value].some((char) => {
10741
+ const code = char.charCodeAt(0);
10742
+ return code < 32 || code === 127;
10743
+ }) && !value.split(/[\\/]/).includes("..");
10744
+ var callerValue = (value) => ({ host: value.host, actor: value.actor });
10745
+ var workerIdOf = (value) => value.workerId ?? null;
10746
+ var currentWriterOwnsTask = (task, workspace, caller) => {
10747
+ const owner = workspace.writer?.owner;
10748
+ return task.status === "active" && task.workspaceId === workspace.id && owner?.taskId === task.id && owner.session.host === caller.host && owner.session.handle === caller.actor;
10749
+ };
10750
+ function assertProductWriteAllowed(input) {
10751
+ if (!Array.isArray(input.paths) || input.paths.some((path) => !validPath(path)))
10752
+ return failure("invalid_input", "invalid product write path");
10753
+ if (!input.store)
10754
+ return failure("permission_denied", "write authorization requires core state");
10755
+ const task = input.store.readTask(input.task.id);
10756
+ if (!task.ok)
10757
+ return task;
10758
+ const workspace = input.store.readWorkspace();
10759
+ if (!workspace.ok)
10760
+ return workspace;
10761
+ if (!workspace.data)
10762
+ return failure("not_found", "workspace not found");
10763
+ const workspaceRecord = workspace.data;
10764
+ if (task.data.status !== "active")
10765
+ return failure("invalid_transition", "paused or closed tasks cannot own product writes");
10766
+ if (workspaceRecord.id !== task.data.workspaceId || workspaceRecord.root.length === 0)
10767
+ return failure("recovery_required", "task and workspace bindings are invalid");
10768
+ const writer = workspaceRecord.writer;
10769
+ if (!writer)
10770
+ return failure("permission_denied", "checkout has no writer owner");
10771
+ if (writer.state === "uncertain")
10772
+ return failure("recovery_required", "checkout writer requires recovery", {
10773
+ owner: writer.owner
10774
+ });
10775
+ const caller = callerValue(input.caller);
10776
+ const workerId = workerIdOf(input.caller);
10777
+ const owner = writer.owner;
10778
+ if (owner.taskId !== task.data.id || owner.workerId !== workerId || owner.session.host !== caller.host || owner.session.handle !== caller.actor)
10779
+ return failure("writer_conflict", "checkout is owned by another validated actor", { owner });
10780
+ const worker = workerId === null ? null : task.data.workers.find((entry) => entry.id === workerId);
10781
+ if (workerId !== null && (!worker || worker.data.assignment.role !== "implementer"))
10782
+ return failure("permission_denied", "only implementers can own product writes");
10783
+ if (workerId !== null && (!worker?.data.session || worker.data.state === "cancelling" || worker.data.state === "unknown" || worker.data.state === "stopped" || !same(worker.data.session, callerSession(input.caller))))
10784
+ return failure("recovery_required", "worker session is not an active writer");
10785
+ return success(null, workspaceRecord.revision, owner);
10786
+ }
10787
+
10659
10788
  // packages/workit-core/src/core/auto-approval.ts
10660
10789
  var AUTO_CLASSES = ["branch", "commit", "push", "pr", "merge"];
10661
10790
  var OPERATION_CLASS = {
@@ -11346,41 +11475,18 @@ function reconcileAction(input) {
11346
11475
  var bindingCovers = scopeCovers;
11347
11476
  var verifyDecisionContent = verifyContentRefs;
11348
11477
 
11349
- // packages/workit-core/src/core/task-evaluation.ts
11350
- var digestBytes3 = (value) => createHash7("sha256").update(value).digest("hex");
11351
- var inside = (root, candidate) => candidate === root || candidate.startsWith(`${root}${path10.sep}`);
11352
- var relative = (root, candidate) => path10.relative(root, candidate).split(path10.sep).join("/") || ".";
11353
- var canonicalPath = (value) => {
11354
- if (typeof value !== "string" || !value)
11355
- return null;
11356
- if (value.includes("\\") || value.split("/").includes(".."))
11357
- return null;
11358
- const normalized = path10.posix.normalize(value);
11359
- if (normalized === ".." || normalized.startsWith("../") || normalized.startsWith("/"))
11360
- return null;
11361
- return normalized === "." ? "." : normalized.replace(/\/$/, "");
11362
- };
11363
- var canonicalScope = (scope) => {
11364
- const paths = scope.paths.length ? scope.paths : ["."];
11365
- const normalizedPaths = paths.map(canonicalPath);
11366
- const normalizedExclusions = scope.exclusions.map(canonicalPath);
11367
- if (normalizedPaths.some((value) => value === null) || normalizedExclusions.some((value) => value === null))
11368
- return null;
11369
- return {
11370
- description: scope.description,
11371
- paths: [...new Set(normalizedPaths)],
11372
- exclusions: [...new Set(normalizedExclusions)]
11373
- };
11374
- };
11375
- var excluded = (value, exclusions) => exclusions.some((item) => item === value || item !== "." && value.startsWith(`${item}/`));
11376
- var scopeMatches = (value, scope) => {
11377
- const normalized = canonicalScope(scope);
11378
- if (!normalized)
11379
- return false;
11380
- const paths = normalized.paths;
11381
- return paths.some((item) => item === "." || value === item || value.startsWith(`${item}/`)) && !excluded(value, normalized.exclusions);
11382
- };
11383
- var pathRelevant = (value, scope) => scopeMatches(value, scope);
11478
+ // packages/workit-core/src/core/policy-resolver.ts
11479
+ var resolverInputSchema = object({
11480
+ intent: intentSchema,
11481
+ assessment: assessmentSchema,
11482
+ constraints: array(constraintSchema),
11483
+ prior: object({
11484
+ decisions: array(decisionSchema),
11485
+ findings: array(findingSchema),
11486
+ requirements: array(requirementSchema)
11487
+ }).strict(),
11488
+ preferences: object({ fast: boolean2().optional(), thorough: boolean2().optional() }).strict().optional()
11489
+ }).strict();
11384
11490
  var compareCodeUnits2 = (left, right) => {
11385
11491
  const length = Math.min(left.length, right.length);
11386
11492
  for (let index = 0;index < length; index += 1) {
@@ -11390,1152 +11496,1049 @@ var compareCodeUnits2 = (left, right) => {
11390
11496
  }
11391
11497
  return left.length - right.length;
11392
11498
  };
11393
- var gitPaths = (root) => {
11394
- const result = spawnSync2("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
11395
- cwd: root,
11396
- encoding: "buffer"
11397
- });
11398
- if (result.status !== 0) {
11399
- const stderr = result.stderr?.toString("utf8") ?? "";
11400
- return {
11401
- paths: [],
11402
- uncertain: !/not a git repository/i.test(stderr),
11403
- git: /not a git repository/i.test(stderr) ? false : true
11404
- };
11405
- }
11406
- const paths = result.stdout ? result.stdout.toString("utf8").split("\x00").filter(Boolean).map((item) => item.split(path10.sep).join("/")) : [];
11407
- const stagedDeleted = spawnSync2("git", ["diff", "--cached", "--name-only", "--diff-filter=D", "-z"], { cwd: root, encoding: "buffer" });
11408
- if (stagedDeleted.status !== 0) {
11409
- const stderr = stagedDeleted.stderr?.toString("utf8") ?? "";
11410
- if (!/not a git repository/i.test(stderr))
11411
- return { paths, uncertain: true, git: true };
11412
- } else if (stagedDeleted.stdout) {
11413
- paths.push(...stagedDeleted.stdout.toString("utf8").split("\x00").filter(Boolean).map((item) => item.split(path10.sep).join("/")));
11414
- }
11415
- return { paths: [...new Set(paths)], uncertain: false, git: true };
11416
- };
11417
- var walk = (root, directory, output) => {
11418
- let names;
11419
- try {
11420
- names = fs7.readdirSync(directory);
11421
- } catch {
11422
- return true;
11423
- }
11424
- let uncertain = false;
11425
- for (const name of names) {
11426
- if (name === ".git" || name === ".workit")
11427
- continue;
11428
- const target = path10.join(directory, name);
11429
- let stat;
11430
- try {
11431
- stat = fs7.lstatSync(target);
11432
- } catch {
11433
- uncertain = true;
11434
- continue;
11435
- }
11436
- const item = relative(root, target);
11437
- output.add(item);
11438
- if (stat.isDirectory() && !stat.isSymbolicLink())
11439
- uncertain = walk(root, target, output) || uncertain;
11440
- }
11441
- return uncertain;
11442
- };
11443
- var scopeRoots = (root, scope) => {
11444
- const roots = [];
11445
- for (const item of scope.paths.length ? scope.paths : ["."]) {
11446
- const target = path10.resolve(root, item);
11447
- if (!inside(root, target))
11448
- return failure("invalid_input", `candidate scope escapes checkout: ${item} — keep one task per repository and coordinate a separate linked task in the other checkout`, { fields: [{ path: "scope.paths", reason: `${item} is outside the checkout` }] });
11449
- let ancestor = target;
11450
- while (!fs7.existsSync(ancestor) && ancestor !== root)
11451
- ancestor = path10.dirname(ancestor);
11452
- try {
11453
- if (!inside(root, fs7.realpathSync(ancestor)))
11454
- return failure("invalid_input", `candidate scope escapes checkout through a symlink: ${item} — keep one task per repository and coordinate a separate linked task in the other checkout`, { fields: [{ path: "scope.paths", reason: `${item} resolves outside the checkout` }] });
11455
- } catch {
11456
- return failure("invalid_input", `candidate scope cannot be inspected: ${item}`);
11457
- }
11458
- roots.push(target);
11459
- }
11460
- return success(null, null, roots);
11461
- };
11462
- function captureCandidate(root, scope, environment = []) {
11463
- let checkout;
11464
- try {
11465
- checkout = fs7.realpathSync(root);
11466
- } catch {
11467
- return failure("invalid_input", "candidate root does not exist");
11468
- }
11469
- const normalizedScope = canonicalScope(scope);
11470
- if (!normalizedScope)
11471
- return failure("invalid_input", "candidate scope is invalid: paths must be checkout-relative — to work in another repository, keep this task here and coordinate a separate linked task in that checkout", { fields: [{ path: "scope.paths", reason: "must be checkout-relative" }] });
11472
- const roots = scopeRoots(checkout, normalizedScope);
11473
- if (!roots.ok)
11474
- return roots;
11475
- const git = gitPaths(checkout);
11476
- const names = new Set;
11477
- let uncertain = git.uncertain;
11478
- for (const target of roots.data) {
11479
- const item = relative(checkout, target);
11480
- if (item === ".git" || item === ".workit")
11481
- continue;
11482
- names.add(item);
11483
- if (!fs7.existsSync(target))
11484
- continue;
11485
- let stat;
11486
- try {
11487
- stat = fs7.lstatSync(target);
11488
- } catch {
11489
- uncertain = true;
11490
- continue;
11491
- }
11492
- if (!git.git && stat.isDirectory() && !stat.isSymbolicLink())
11493
- uncertain = walk(checkout, target, names) || uncertain;
11494
- }
11495
- for (const item of git.paths)
11496
- if (scopeMatches(item, normalizedScope))
11497
- names.add(item);
11498
- const files = [];
11499
- let completeness = uncertain ? "uncertain" : "known";
11500
- for (const item of [...names].sort()) {
11501
- if (!scopeMatches(item, normalizedScope))
11502
- continue;
11503
- const target = path10.join(checkout, item);
11504
- try {
11505
- const stat = fs7.lstatSync(target);
11506
- if (stat.isSymbolicLink()) {
11507
- const link = fs7.readlinkSync(target);
11508
- files.push({ path: item, kind: "symlink", digest: digestBytes3(link), executable: null });
11509
- } else if (stat.isFile()) {
11510
- files.push({
11511
- path: item,
11512
- kind: "file",
11513
- digest: digestBytes3(fs7.readFileSync(target)),
11514
- executable: (stat.mode & 73) !== 0
11515
- });
11516
- } else if (!stat.isDirectory()) {
11517
- completeness = "uncertain";
11518
- } else if (git.git && git.paths.includes(item)) {
11519
- completeness = "uncertain";
11520
- }
11521
- } catch (error) {
11522
- if (error?.code === "ENOENT") {
11523
- files.push({ path: item, kind: "absent", digest: null, executable: null });
11524
- } else
11525
- completeness = "uncertain";
11526
- }
11527
- }
11528
- const supplied = Array.isArray(environment) ? environment.map((value) => typeof value === "string" ? { name: value, value: process.env[value] ?? null } : { name: value.name, value: value.value ?? null }) : Object.keys(environment).map((name) => ({
11499
+ var stableUnique = (values) => [...new Set(values)].sort(compareCodeUnits2);
11500
+ var stableList = (values) => [...values].sort((left, right) => compareCodeUnits2(canonicalJson(left), canonicalJson(right)));
11501
+ var normalizedScope = (scope) => ({
11502
+ description: scope.description,
11503
+ paths: stableUnique(scope.paths),
11504
+ exclusions: stableUnique(scope.exclusions)
11505
+ });
11506
+ var normalizedRefList = (values) => stableList(values);
11507
+ var normalizeAssessment = (assessment) => ({
11508
+ facts: stableList(assessment.facts.map((fact) => ({ ...fact, refs: normalizedRefList(fact.refs) }))),
11509
+ signals: Object.fromEntries(Object.entries(assessment.signals).map(([name, signal]) => [
11529
11510
  name,
11530
- value: environment[name] ?? null
11531
- }));
11532
- const namesByEnvironment = supplied.map(({ name }) => name);
11533
- if (new Set(namesByEnvironment).size !== namesByEnvironment.length || namesByEnvironment.some((name) => typeof name !== "string" || !name))
11534
- return failure("invalid_input", "candidate environment names must be unique and non-empty");
11535
- const values = supplied.sort((left, right) => compareCodeUnits2(left.name, right.name)).map(({ name, value }) => ({ name, value, refs: [] }));
11536
- if (values.some(({ value }) => value === null))
11537
- completeness = "uncertain";
11538
- const headResult = spawnSync2("git", ["rev-parse", "HEAD"], { cwd: checkout, encoding: "utf8" });
11539
- if (headResult.status !== 0 && !/not a git repository/i.test(headResult.stderr ?? ""))
11540
- completeness = "uncertain";
11541
- const head = headResult.status === 0 ? headResult.stdout.trim() : null;
11542
- const partial = {
11543
- id: "0".repeat(64),
11544
- scope: normalizedScope,
11545
- completeness,
11546
- files,
11547
- environment: values,
11548
- head
11511
+ { ...signal, refs: normalizedRefList(signal.refs) }
11512
+ ])),
11513
+ consequences: stableList(assessment.consequences.map((consequence) => ({
11514
+ ...consequence,
11515
+ fact: { ...consequence.fact, refs: normalizedRefList(consequence.fact.refs) }
11516
+ }))),
11517
+ verification: stableList(assessment.verification.map((verification) => ({
11518
+ ...verification,
11519
+ scope: normalizedScope(verification.scope),
11520
+ availableChecks: normalizedRefList(verification.availableChecks),
11521
+ gaps: stableUnique(verification.gaps)
11522
+ })))
11523
+ });
11524
+ var normalizeConstraint = (constraint) => ({
11525
+ ...constraint,
11526
+ source: constraint.source,
11527
+ requires: stableList(constraint.requires.map((requirement) => ({
11528
+ ...requirement,
11529
+ scope: normalizedScope(requirement.scope),
11530
+ refs: normalizedRefList(requirement.refs)
11531
+ })))
11532
+ });
11533
+ var normalizeDecision = (decision) => ({
11534
+ ...decision,
11535
+ binding: {
11536
+ ...decision.binding,
11537
+ scope: normalizedScope(decision.binding.scope),
11538
+ contentRefs: normalizedRefList(decision.binding.contentRefs)
11539
+ },
11540
+ requirementIds: stableUnique(decision.requirementIds)
11541
+ });
11542
+ var normalizeIntent = (intent) => ({
11543
+ ...intent,
11544
+ scope: normalizedScope(intent.scope),
11545
+ authorityRefs: normalizedRefList(intent.authorityRefs)
11546
+ });
11547
+ var normalizePrior = (prior) => ({
11548
+ decisions: stableList(prior.decisions.map(normalizeDecision)),
11549
+ findings: stableList(prior.findings.map((finding) => ({
11550
+ ...finding,
11551
+ scope: normalizedScope(finding.scope),
11552
+ refs: normalizedRefList(finding.refs),
11553
+ resolution: finding.resolution ? {
11554
+ ...finding.resolution,
11555
+ evidenceIds: stableUnique(finding.resolution.evidenceIds),
11556
+ decisionIds: stableUnique(finding.resolution.decisionIds)
11557
+ } : null
11558
+ }))),
11559
+ requirements: stableList(prior.requirements.map((requirement) => ({
11560
+ ...requirement,
11561
+ scope: normalizedScope(requirement.scope)
11562
+ })))
11563
+ });
11564
+ var invalidFields = (error) => ({
11565
+ fields: error.issues.map((issue) => ({
11566
+ path: issue.code === "unrecognized_keys" ? issue.keys.join(".") : issue.path.join("."),
11567
+ reason: issue.message
11568
+ }))
11569
+ });
11570
+ function normalizeResolverInput(input) {
11571
+ const parsed = resolverInputSchema.safeParse(input);
11572
+ if (!parsed.success)
11573
+ return failure("invalid_input", "resolver input is invalid", invalidFields(parsed.error));
11574
+ const value = parsed.data;
11575
+ const signals = value.assessment.signals;
11576
+ if (signals.behaviorChange.value === true && signals.mechanicalLowRisk.value === true)
11577
+ return failure("invalid_input", "behavioral change cannot be wholly mechanical", {
11578
+ fields: [
11579
+ {
11580
+ path: "assessment.signals",
11581
+ reason: "contradictory behaviorChange and mechanicalLowRisk"
11582
+ }
11583
+ ]
11584
+ });
11585
+ const ids = value.constraints.map((constraint) => constraint.id);
11586
+ if (new Set(ids).size !== ids.length)
11587
+ return failure("invalid_input", "constraint IDs must be unique", {
11588
+ fields: [{ path: "constraints", reason: "duplicate constraint id" }]
11589
+ });
11590
+ if (value.preferences?.fast && value.preferences.thorough)
11591
+ return failure("invalid_input", "fast and thorough preferences contradict", {
11592
+ fields: [{ path: "preferences", reason: "fast and thorough cannot both be enabled" }]
11593
+ });
11594
+ const normalized = {
11595
+ intent: normalizeIntent(value.intent),
11596
+ assessment: normalizeAssessment(value.assessment),
11597
+ constraints: stableList(value.constraints.map(normalizeConstraint)),
11598
+ prior: normalizePrior(value.prior),
11599
+ ...value.preferences ? { preferences: { ...value.preferences } } : {},
11600
+ policyVersion: POLICY_VERSION
11549
11601
  };
11550
- const candidate = { ...partial, id: candidateDigest(partial) };
11551
- const parsed = candidateSchema.safeParse(candidate);
11552
- return parsed.success ? success(null, null, parsed.data) : failure("invalid_input", "captured candidate is invalid");
11602
+ return success(null, null, normalized);
11553
11603
  }
11554
- var fileMap = (candidate) => new Map(candidate.files.map((file) => [file.path, file]));
11555
- var changedPaths = (before, after) => {
11556
- const paths = new Set([...before.files, ...after.files].map((file) => file.path));
11557
- const left = fileMap(before);
11558
- const right = fileMap(after);
11559
- const changed = [...paths].filter((item) => JSON.stringify(left.get(item) ?? null) !== JSON.stringify(right.get(item) ?? null));
11560
- if (before.head !== after.head)
11561
- changed.push(".");
11562
- if (JSON.stringify(before.environment) !== JSON.stringify(after.environment))
11563
- changed.push(".");
11564
- return changed;
11565
- };
11566
- var sessionFromRef = (value) => {
11567
- if (typeof value !== "object" || value === null || value.kind !== "host")
11568
- return null;
11569
- return typeof value.host === "string" && typeof value.handle === "string" ? { host: value.host, handle: value.handle } : null;
11570
- };
11571
- var sameSession = (left, right) => {
11572
- const other = sessionFromRef(right);
11573
- return left !== null && other !== null && left.host === other.host && left.handle === other.handle;
11574
- };
11575
- var evidenceScopes = (task, ids) => (task.policy?.requirements ?? []).filter((requirement) => ids.includes(requirement.id)).map((requirement) => requirement.scope);
11576
- function evaluateEvidence(task, candidate) {
11577
- const current = candidate ?? task.candidates.at(-1) ?? null;
11578
- return task.evidence.map((entry) => {
11579
- const evidence = entry.data;
11580
- if (evidence.result === "failed")
11581
- return {
11582
- evidenceId: entry.id,
11583
- status: "failed",
11584
- reason: "failed evidence remains historical"
11585
- };
11586
- if (evidence.kind === "check" || evidence.kind === "review") {
11587
- if (!evidence.beforeCandidateId || !evidence.candidateId)
11588
- return {
11589
- evidenceId: entry.id,
11590
- status: "stale",
11591
- reason: "check or review evidence lacks start and end candidates"
11592
- };
11593
- if (evidence.beforeCandidateId !== evidence.candidateId)
11594
- return {
11595
- evidenceId: entry.id,
11596
- status: "stale",
11597
- reason: "candidate changed during the check or review"
11598
- };
11604
+ var requirement = (spec) => ({
11605
+ ...spec,
11606
+ id: requirementId({
11607
+ ruleId: spec.ruleId,
11608
+ scope: spec.scope,
11609
+ satisfaction: spec.satisfaction,
11610
+ before: spec.before,
11611
+ dependentAction: spec.dependentAction
11612
+ })
11613
+ });
11614
+ var signalReason = (input, name) => input.assessment.signals[name].reason;
11615
+ function resolveRequirements(input) {
11616
+ const { signals } = input.assessment;
11617
+ const scope = input.intent.scope;
11618
+ const requirements = [];
11619
+ const hasUnknownSignal = Object.values(signals).some((signal) => signal.value === "unknown");
11620
+ const hasUnknownFact = [
11621
+ ...input.assessment.facts,
11622
+ ...input.assessment.consequences.map(({ fact }) => fact)
11623
+ ].some((fact) => fact.basis === "unknown");
11624
+ if (hasUnknownSignal || hasUnknownFact)
11625
+ requirements.push(requirement({
11626
+ ruleId: "consequential-unknown",
11627
+ dimension: "investigation",
11628
+ scope,
11629
+ reason: `Resolve consequential uncertainty before the dependent action: ${[
11630
+ ...Object.entries(signals).filter(([, signal]) => signal.value === "unknown").map(([name]) => name),
11631
+ ...hasUnknownFact ? ["unknown fact"] : []
11632
+ ].join(", ")}`,
11633
+ satisfaction: "An observed or inferred fact resolves the uncertainty and records its supporting references.",
11634
+ before: "dependent_action",
11635
+ dependentAction: null,
11636
+ acceptanceAllowed: false
11637
+ }));
11638
+ if (signals.productChoiceOpen.value === true)
11639
+ requirements.push(requirement({
11640
+ ruleId: "product-decision",
11641
+ dimension: "decisions",
11642
+ scope,
11643
+ reason: `A consequential product choice remains open: ${signalReason(input, "productChoiceOpen")}`,
11644
+ satisfaction: "Present the material alternatives and record the user's decision before the dependent action.",
11645
+ before: "dependent_action",
11646
+ dependentAction: null,
11647
+ acceptanceAllowed: false
11648
+ }));
11649
+ const independentBehaviorReview = input.preferences?.thorough === true || input.assessment.consequences.some((consequence) => ["security", "data", "public_contract", "operations"].includes(consequence.area));
11650
+ if (signals.behaviorChange.value === true)
11651
+ requirements.push(requirement({
11652
+ ruleId: "behavioral-verification",
11653
+ dimension: "testing",
11654
+ scope,
11655
+ reason: `Behavior, side effects, permissions, or data handling may change: ${signalReason(input, "behaviorChange")}`,
11656
+ satisfaction: "A useful behavioral check passes against the affected behavior and current candidate.",
11657
+ before: "close",
11658
+ dependentAction: null,
11659
+ acceptanceAllowed: false
11660
+ }), requirement({
11661
+ ruleId: independentBehaviorReview ? "fresh-context-review" : "self-review",
11662
+ dimension: "review",
11663
+ scope,
11664
+ reason: independentBehaviorReview ? "Consequential behavior or the thorough preference requires fresh-context review." : "Bounded behavior changes use self-review unless consequential risks or trusted rules require more.",
11665
+ satisfaction: independentBehaviorReview ? "A separate review context examines the current candidate and records its result." : "The lead reviews the resulting diff and records the relevant scope and checks.",
11666
+ before: "close",
11667
+ dependentAction: null,
11668
+ acceptanceAllowed: !independentBehaviorReview
11669
+ }));
11670
+ else if (signals.mechanicalLowRisk.value === true)
11671
+ requirements.push(requirement({
11672
+ ruleId: "mechanical-existing-checks",
11673
+ dimension: "verification",
11674
+ scope,
11675
+ reason: `The change is demonstrably mechanical and low-risk: ${signalReason(input, "mechanicalLowRisk")}`,
11676
+ satisfaction: "Run the relevant existing checks for affected consumers; do not add tautological tests.",
11677
+ before: "close",
11678
+ dependentAction: null,
11679
+ acceptanceAllowed: true
11680
+ }), requirement({
11681
+ ruleId: input.preferences?.thorough ? "fresh-context-review" : "self-review",
11682
+ dimension: "review",
11683
+ scope,
11684
+ reason: input.preferences?.thorough ? "The thorough preference upgrades mechanical self-review to fresh-context review." : "Mechanical low-risk work uses self-review rather than mandatory fresh-context review.",
11685
+ satisfaction: input.preferences?.thorough ? "A separate review context examines the current candidate and records its result." : "The lead reviews the resulting diff and records the relevant scope and checks.",
11686
+ before: "close",
11687
+ dependentAction: null,
11688
+ acceptanceAllowed: !input.preferences?.thorough
11689
+ }));
11690
+ if (signals.behaviorChange.value === true || signals.mechanicalLowRisk.value === true)
11691
+ requirements.push(requirement({
11692
+ ruleId: "pre-pr-cleanup",
11693
+ dimension: "verification",
11694
+ scope,
11695
+ reason: "Implementation output must be deslopped before it is delivered.",
11696
+ satisfaction: "Run the workit-deslop pass and record passing check evidence, or record an approved limitation decision waiving cleanup.",
11697
+ before: "dependent_action",
11698
+ dependentAction: "hosting.pull_request",
11699
+ acceptanceAllowed: true
11700
+ }));
11701
+ if (signals.durableAgreementNeeded.value === true)
11702
+ requirements.push(requirement({
11703
+ ruleId: "durable-spec",
11704
+ dimension: "artifacts",
11705
+ scope,
11706
+ reason: `The work needs a durable agreement about intended behavior: ${signalReason(input, "durableAgreementNeeded")}`,
11707
+ satisfaction: "Record the agreed behavior in a durable specification before implementation writes.",
11708
+ before: "write",
11709
+ dependentAction: null,
11710
+ acceptanceAllowed: true
11711
+ }));
11712
+ if (signals.coordinationPlanNeeded.value === true)
11713
+ requirements.push(requirement({
11714
+ ruleId: "coordination-plan",
11715
+ dimension: "continuity",
11716
+ scope,
11717
+ reason: `Dependencies, sequencing, or resumption need durable coordination: ${signalReason(input, "coordinationPlanNeeded")}`,
11718
+ satisfaction: "Record useful sequencing, dependencies, and the next action in a compact plan.",
11719
+ before: "dependent_action",
11720
+ dependentAction: null,
11721
+ acceptanceAllowed: true
11722
+ }));
11723
+ if (signals.helperUseful.value === true && !input.preferences?.fast)
11724
+ requirements.push(requirement({
11725
+ ruleId: "helper-usefulness",
11726
+ dimension: "delegation",
11727
+ scope,
11728
+ reason: `Independent judgment or investigation justifies a scoped helper: ${signalReason(input, "helperUseful")}`,
11729
+ satisfaction: "Use a bounded helper only for the independent objective and reconcile its result.",
11730
+ before: "dependent_action",
11731
+ dependentAction: null,
11732
+ acceptanceAllowed: true
11733
+ }));
11734
+ for (const constraint of input.constraints)
11735
+ for (const obligation of constraint.requires) {
11736
+ const dimension = obligation.method ?? (obligation.kind === "check" ? "verification" : obligation.kind === "decision" ? "decisions" : "challenge");
11737
+ requirements.push(requirement({
11738
+ ruleId: `project-constraint:${constraint.id}:${obligation.kind}:${sha256({
11739
+ kind: obligation.kind,
11740
+ scope: normalizedScope(obligation.scope),
11741
+ refs: normalizedRefList(obligation.refs),
11742
+ method: obligation.method,
11743
+ before: obligation.before,
11744
+ dependentAction: obligation.dependentAction
11745
+ })}`,
11746
+ dimension,
11747
+ scope: obligation.scope,
11748
+ reason: `${constraint.kind} constraint requires ${obligation.kind}: ${constraint.statement}`,
11749
+ satisfaction: `Satisfy the constraint obligation using its referenced ${obligation.kind}.`,
11750
+ before: obligation.before,
11751
+ dependentAction: obligation.dependentAction,
11752
+ acceptanceAllowed: constraint.acceptanceAllowed && obligation.kind !== "decision"
11753
+ }));
11599
11754
  }
11600
- if (!evidence.candidateId || !current)
11601
- return {
11602
- evidenceId: entry.id,
11603
- status: evidence.result,
11604
- reason: "evidence has no candidate binding"
11605
- };
11606
- const observed = task.candidates.find((item) => item.id === evidence.candidateId) ?? (current.id === evidence.candidateId ? current : undefined);
11607
- if (!observed || observed.completeness === "uncertain" || current.completeness === "uncertain")
11608
- return { evidenceId: entry.id, status: "stale", reason: "candidate is missing or uncertain" };
11609
- if (observed.id === current.id)
11610
- return { evidenceId: entry.id, status: evidence.result, reason: "candidate is unchanged" };
11611
- const scopes = evidenceScopes(task, evidence.requirementIds);
11612
- const changed = changedPaths(observed, current);
11613
- const environmentChanged = JSON.stringify(observed.environment) !== JSON.stringify(current.environment);
11614
- if (!scopes.length || environmentChanged || changed.some((item) => scopes.some((scope) => pathRelevant(item, scope))))
11615
- return { evidenceId: entry.id, status: "stale", reason: "relevant candidate state changed" };
11616
- return {
11617
- evidenceId: entry.id,
11618
- status: evidence.result,
11619
- reason: "candidate changed outside evidence scope"
11620
- };
11755
+ const seen = new Set;
11756
+ return requirements.filter((item) => {
11757
+ if (seen.has(item.id))
11758
+ return false;
11759
+ seen.add(item.id);
11760
+ return true;
11621
11761
  });
11622
11762
  }
11623
- var scopeCovers2 = scopeCovers;
11624
- var checkPin = (assignment, beforeCandidateId, candidateId) => {
11625
- const pin = assignment.candidateId ?? null;
11626
- if (pin === null)
11627
- return true;
11628
- return (beforeCandidateId ?? null) === pin || (candidateId ?? null) === pin;
11629
- };
11630
- var resolveBinding = (evidence, pin, currentCandidateId) => {
11631
- const bound = evidence.kind === "check" || evidence.kind === "review";
11632
- const fallback = bound ? pin ?? currentCandidateId : null;
11633
- return {
11634
- beforeCandidateId: evidence.beforeCandidateId ?? fallback,
11635
- candidateId: evidence.candidateId ?? fallback
11763
+ function resolvePolicy(input) {
11764
+ const normalized = normalizeResolverInput(input);
11765
+ if (!normalized.ok)
11766
+ return normalized;
11767
+ const requirements = resolveRequirements(normalized.data);
11768
+ const policy = {
11769
+ policyVersion: POLICY_VERSION,
11770
+ inputDigest: sha256(canonicalJson(normalized.data)),
11771
+ requirements
11636
11772
  };
11637
- };
11638
- var findingVerificationPasses = (findingCandidateId, evidence) => evidence.status === "passed" && (evidence.kind === "check" || evidence.kind === "review") && ((findingCandidateId ?? null) === null || evidence.candidateId != null);
11639
- var applicableDecision2 = (task, workspace, requirement, checkoutRoot) => task.decisions.filter((entry) => entry.provenance.kind !== "imported").map((entry) => entry.data).filter((decision) => decision.purpose === "limitation" && decision.response === "approved" && decision.revoked === null && decision.binding.taskId === task.id && decision.binding.workspaceId === workspace.id && decision.requirementIds.includes(requirement.id) && decision.binding.scope && scopeCovers2(decision.binding.scope, requirement.scope) && decision.digest === decisionDigest(decision) && (checkoutRoot ? verifyDecisionContentAtRoot(checkoutRoot, decision.binding).ok : decision.binding.contentRefs.every((reference) => reference.kind !== "file")));
11640
- var applicableRequirementDecision = (task, workspace, requirement, checkoutRoot) => task.decisions.filter(({ data, provenance }) => provenance.kind !== "imported" && data.purpose !== "limitation" && (data.response === "approved" || data.response === "stated") && data.revoked === null && data.binding.taskId === task.id && data.binding.workspaceId === workspace.id && data.requirementIds.includes(requirement.id) && scopeCovers2(data.binding.scope, requirement.scope) && data.digest === decisionDigest(data) && (checkoutRoot ? verifyDecisionContentAtRoot(checkoutRoot, data.binding).ok : data.binding.contentRefs.every((reference) => reference.kind !== "file"))).map(({ id }) => ({ id }));
11641
- var evidenceMatchesRequirement = (kind, evidenceKind, dimension, ruleId) => {
11642
- if (kind !== "passed")
11643
- return false;
11644
- if (dimension === "testing" || dimension === "verification")
11645
- return evidenceKind === "check" || ruleId === "pre-pr-cleanup" && evidenceKind === "artifact";
11646
- if (dimension === "review")
11647
- return evidenceKind === "review";
11648
- if (dimension === "investigation" || dimension === "challenge")
11649
- return evidenceKind === "investigation";
11650
- if (dimension === "artifacts" || dimension === "continuity")
11651
- return evidenceKind === "artifact";
11652
- return false;
11653
- };
11654
- var expectedKinds = (dimension, ruleId) => {
11655
- if (dimension === "testing")
11656
- return "check";
11657
- if (dimension === "verification")
11658
- return ruleId === "pre-pr-cleanup" ? "check or artifact" : "check";
11659
- if (dimension === "review")
11660
- return "review";
11661
- if (dimension === "investigation" || dimension === "challenge")
11662
- return "investigation";
11663
- if (dimension === "artifacts" || dimension === "continuity")
11664
- return "artifact";
11665
- if (dimension === "decisions")
11666
- return "decision";
11667
- return "worker report";
11668
- };
11669
- function evaluateRequirements(task, workspace, capabilities, candidate, checkoutRoot, _caller) {
11670
- const evidence = evaluateEvidence(task, candidate);
11671
- if (task.policy && task.policy.policyVersion !== POLICY_VERSION)
11672
- return task.policy.requirements.map((requirement) => ({
11673
- requirementId: requirement.id,
11674
- status: "unsatisfied",
11675
- evidenceIds: [],
11676
- decisionIds: [],
11677
- reason: "stored policy version is unsupported; reassessment is required"
11678
- }));
11679
- return (task.policy?.requirements ?? []).map((requirement) => {
11680
- const related = task.evidence.map((entry, index) => ({ entry, evaluation: evidence[index] })).filter(({ entry }) => entry.data.requirementIds.includes(requirement.id));
11681
- const passed = related.filter(({ entry, evaluation }) => {
11682
- if (!evidenceMatchesRequirement(evaluation.status, entry.data.kind, requirement.dimension, requirement.ruleId))
11683
- return false;
11684
- if ((entry.data.kind === "check" || entry.data.kind === "review") && (!entry.data.beforeCandidateId || !entry.data.candidateId || entry.data.beforeCandidateId !== entry.data.candidateId))
11685
- return false;
11686
- if (requirement.dimension !== "review")
11687
- return true;
11688
- const reviewSession = sessionFromRef(entry.data.reviewContext);
11689
- const sameImplementation = sameSession(reviewSession, task.intent.provenance.session);
11690
- const sameEvidenceSession = related.some(({ entry: other }) => other.id !== entry.id && other.data.kind === "review" && other.data.candidateId !== null && other.data.candidateId === entry.data.candidateId && sameSession(reviewSession, other.provenance.session));
11691
- return entry.data.kind === "review" && reviewSession !== null && sameSession(reviewSession, entry.provenance.session) && (requirement.ruleId === "self-review" || !sameImplementation && !sameEvidenceSession);
11692
- });
11693
- if (passed.length) {
11694
- const currentId = candidate?.id ?? null;
11695
- const withRed = requirement.dimension === "testing" ? passed.filter(({ entry }) => related.some((other) => other.entry.data.kind === "check" && other.evaluation.status === "failed" && other.entry.data.requirementIds.includes(requirement.id) && other.entry.recordedAt <= entry.recordedAt) || related.some((baseline) => baseline.entry.id !== entry.id && baseline.entry.data.kind === "check" && baseline.entry.data.result === "passed" && baseline.entry.data.candidateId !== null && currentId !== null && baseline.entry.data.candidateId !== currentId)) : passed;
11696
- if (withRed.length)
11697
- return {
11698
- requirementId: requirement.id,
11699
- status: "satisfied",
11700
- evidenceIds: withRed.map(({ entry }) => entry.id),
11701
- decisionIds: [],
11702
- reason: "fresh applicable evidence passed"
11703
- };
11704
- if (requirement.dimension === "testing")
11705
- return {
11706
- requirementId: requirement.id,
11707
- status: "unsatisfied",
11708
- evidenceIds: [],
11709
- decisionIds: [],
11710
- reason: "testing requirement has GREEN evidence but no preceding RED"
11711
- };
11712
- }
11713
- if (requirement.dimension === "delegation") {
11714
- const dot = (scope) => scope.paths.length > 0 ? scope : { ...scope, paths: ["."] };
11715
- const reconciled = task.workers.some((worker) => worker.data.report?.outcome === "completed" && (worker.data.assignment.requirementIds.includes(requirement.id) || scopeCovers2(dot(requirement.scope), dot(worker.data.assignment.scope))));
11716
- if (reconciled)
11717
- return {
11718
- requirementId: requirement.id,
11719
- status: "satisfied",
11720
- evidenceIds: [],
11721
- decisionIds: [],
11722
- reason: "bounded helper completed and its result is recorded"
11723
- };
11724
- }
11725
- const decisions = requirement.dimension === "decisions" ? applicableRequirementDecision(task, workspace, requirement, checkoutRoot) : [];
11726
- if (decisions.length)
11727
- return {
11728
- requirementId: requirement.id,
11729
- status: "satisfied",
11730
- evidenceIds: [],
11731
- decisionIds: decisions.map((decision) => decision.id),
11732
- reason: "an applicable approved or stated decision satisfies the requirement"
11733
- };
11734
- const limitations = requirement.acceptanceAllowed ? applicableDecision2(task, workspace, requirement, checkoutRoot) : [];
11735
- if (limitations.length)
11736
- return {
11737
- requirementId: requirement.id,
11738
- status: "accepted_limitation",
11739
- evidenceIds: [],
11740
- decisionIds: limitations.map((decision) => task.decisions.find((entry) => entry.data === decision).id),
11741
- reason: "an applicable approved limitation permits the missing evidence"
11742
- };
11743
- const unavailable = capabilities.some((capability) => capability.assurance === "unavailable" && (capability.name === requirement.dimension || capability.surface === requirement.dimension));
11744
- if (!unavailable && related.length > 0 && !passed.length)
11745
- return {
11746
- requirementId: requirement.id,
11747
- status: "unsatisfied",
11748
- evidenceIds: related.map(({ entry }) => entry.id),
11749
- decisionIds: [],
11750
- reason: `no passing evidence (needs kind:${expectedKinds(requirement.dimension, requirement.ruleId)})`
11751
- };
11752
- return {
11753
- requirementId: requirement.id,
11754
- status: unavailable ? "unavailable" : "unsatisfied",
11755
- evidenceIds: related.map(({ entry }) => entry.id),
11756
- decisionIds: [],
11757
- reason: unavailable ? "required capability is unavailable" : "no fresh passing evidence"
11758
- };
11759
- });
11773
+ const parsed = policySchema.safeParse(policy);
11774
+ if (!parsed.success)
11775
+ return failure("invalid_input", "resolved policy is invalid", invalidFields(parsed.error));
11776
+ return success(null, null, parsed.data);
11760
11777
  }
11761
- function evaluateClosure(requestedOutcome, view) {
11762
- if (requestedOutcome !== "stopped" && !view.task.policy)
11763
- return failure("requirements_unsatisfied", "task has not been assessed");
11764
- if (view.task.policy && view.task.policy.policyVersion !== POLICY_VERSION)
11765
- return failure("requirements_unsatisfied", "stored policy version is unsupported; reassessment is required");
11766
- const evaluations = view.requirements;
11767
- const openFindings = view.task.findings.filter((entry) => entry.data.disposition === "open");
11768
- if (requestedOutcome !== "stopped" && openFindings.length)
11769
- return failure("requirements_unsatisfied", "open findings must be resolved before closure");
11770
- if (requestedOutcome !== "stopped") {
11771
- const evidenceById = new Map(view.evidence.map((entry) => [entry.evidenceId, entry.status]));
11772
- for (const entry of view.task.findings) {
11773
- if (entry.data.disposition === "fixed") {
11774
- const verified = entry.data.resolution?.evidenceIds.some((id) => {
11775
- const evidence = view.task.evidence.find((item) => item.id === id);
11776
- if (!evidence)
11777
- return false;
11778
- return findingVerificationPasses(entry.data.candidateId, {
11779
- kind: evidence.data.kind,
11780
- candidateId: evidence.data.candidateId,
11781
- status: evidenceById.get(id) ?? "missing"
11782
- });
11783
- });
11784
- if (!verified)
11785
- return failure("requirements_unsatisfied", "fixed findings require current verification");
11786
- }
11787
- if (entry.data.disposition === "deferred") {
11788
- const valid = entry.data.resolution?.decisionIds.some((id) => {
11789
- const decisionEntry = view.task.decisions.find((item) => item.id === id);
11790
- const decision = decisionEntry?.data;
11791
- return Boolean(decision && decisionEntry?.provenance.kind !== "imported" && decision.purpose === "limitation" && decision.response === "approved" && decision.revoked === null && decision.digest === decisionDigest(decision) && verifyDecisionContentAtRoot(view.workspace.root, decision.binding).ok && decision.binding.taskId === view.task.id && decision.binding.workspaceId === view.workspace.id && scopeCovers2(decision.binding.scope, entry.data.scope) && decision.requirementIds.some((requirementId) => view.task.policy?.requirements.some((requirement) => requirement.id === requirementId && requirement.acceptanceAllowed)));
11792
- });
11793
- if (!valid)
11794
- return failure("requirements_unsatisfied", "deferred findings require an approved limitation decision that references an acceptanceAllowed requirement and covers the finding scope");
11795
- }
11796
- }
11797
- }
11798
- const blocking = evaluations.filter((item) => {
11799
- if (item.status !== "unsatisfied" && item.status !== "unavailable")
11800
- return false;
11801
- const requirement = view.task.policy?.requirements.find((candidate) => candidate.id === item.requirementId);
11802
- return !requirement || requirement.before === "close";
11803
- });
11804
- if (requestedOutcome !== "stopped" && blocking.length)
11805
- return failure("requirements_unsatisfied", "applicable requirements are unsatisfied", {
11806
- requirementIds: blocking.map((item) => item.requirementId),
11807
- requirements: blocking.map((item) => {
11808
- const requirement = view.task.policy?.requirements.find((candidate) => candidate.id === item.requirementId);
11809
- return {
11810
- requirementId: item.requirementId,
11811
- ruleId: requirement?.ruleId ?? "unknown",
11812
- reason: item.reason,
11813
- satisfaction: requirement?.satisfaction ?? "",
11814
- dependentAction: requirement?.dependentAction ?? null
11815
- };
11816
- })
11817
- });
11818
- const accepted = evaluations.filter((item) => item.status === "accepted_limitation");
11819
- if (requestedOutcome === "verified" && accepted.length)
11820
- return failure("requirements_unsatisfied", "accepted limitations cannot be reported as verified", {
11821
- requirementIds: accepted.map((item) => item.requirementId)
11822
- });
11823
- const evidenceIds = [
11824
- ...new Set([
11825
- ...evaluations.flatMap((item) => item.evidenceIds),
11826
- ...view.task.findings.flatMap((item) => item.data.resolution?.evidenceIds ?? [])
11827
- ])
11828
- ];
11829
- const decisionIds = [
11830
- ...new Set([
11831
- ...evaluations.flatMap((item) => item.decisionIds),
11832
- ...view.task.findings.flatMap((item) => item.data.resolution?.decisionIds ?? [])
11833
- ])
11834
- ];
11835
- return success(null, null, {
11836
- outcome: requestedOutcome === "stopped" ? "stopped" : accepted.length ? "accepted_limitations" : "verified",
11837
- evidenceIds,
11838
- decisionIds,
11839
- requirementIds: evaluations.map((item) => item.requirementId)
11840
- });
11778
+ function diffPolicy(previous, next, reason, now) {
11779
+ if (!policySchema.safeParse(previous).success && previous !== null)
11780
+ throw new TypeError("previous policy is invalid");
11781
+ if (!policySchema.safeParse(next).success)
11782
+ throw new TypeError("next policy is invalid");
11783
+ const oldIds = new Set(previous?.requirements.map((requirement) => requirement.id) ?? []);
11784
+ const newIds = new Set(next.requirements.map((requirement) => requirement.id));
11785
+ const added = [...newIds].filter((id) => !oldIds.has(id)).sort(compareCodeUnits2);
11786
+ const retired = [...oldIds].filter((id) => !newIds.has(id)).sort(compareCodeUnits2);
11787
+ if (added.length === 0 && retired.length === 0)
11788
+ return null;
11789
+ const normalizedReason = reason.trim();
11790
+ const changeReason = retired.length ? `${normalizedReason || "policy reassessed"} (retired: ${retired.join(",")})` : normalizedReason || "policy reassessed";
11791
+ const change = {
11792
+ recordedAt: now,
11793
+ fromInputDigest: previous?.inputDigest ?? null,
11794
+ toInputDigest: next.inputDigest,
11795
+ added,
11796
+ retired,
11797
+ reason: changeReason
11798
+ };
11799
+ const parsed = policyChangeSchema.safeParse(change);
11800
+ if (!parsed.success)
11801
+ throw new TypeError("policy change is invalid");
11802
+ return parsed.data;
11841
11803
  }
11842
11804
 
11843
- // packages/workit-core/src/core/methods.ts
11844
- var METHODS = {
11845
- "workit-challenge": { dimensions: ["challenge", "decisions"] },
11846
- "workit-behavioral-tdd": { dimensions: ["testing"], ruleIds: ["mechanical-existing-checks"] },
11847
- "workit-review": { dimensions: ["review"], ruleIds: ["fresh-context-review", "self-review"] },
11848
- "workit-plan": { dimensions: ["artifacts", "continuity"] },
11849
- "workit-implement": { dimensions: ["delegation"] },
11850
- "workit-debug": {},
11851
- "workit-handoff": {},
11852
- "workit-deslop": { ruleIds: ["pre-pr-cleanup"] }
11805
+ // packages/workit-core/src/core/task-evaluation.ts
11806
+ import { createHash as createHash7 } from "node:crypto";
11807
+ import * as fs7 from "node:fs";
11808
+ import { spawnSync as spawnSync2 } from "node:child_process";
11809
+ import path10 from "node:path";
11810
+ var digestBytes3 = (value) => createHash7("sha256").update(value).digest("hex");
11811
+ var inside = (root, candidate) => candidate === root || candidate.startsWith(`${root}${path10.sep}`);
11812
+ var relative = (root, candidate) => path10.relative(root, candidate).split(path10.sep).join("/") || ".";
11813
+ var canonicalPath = (value) => {
11814
+ if (typeof value !== "string" || !value)
11815
+ return null;
11816
+ if (value.includes("\\") || value.split("/").includes(".."))
11817
+ return null;
11818
+ const normalized = path10.posix.normalize(value);
11819
+ if (normalized === ".." || normalized.startsWith("../") || normalized.startsWith("/"))
11820
+ return null;
11821
+ return normalized === "." ? "." : normalized.replace(/\/$/, "");
11853
11822
  };
11854
- var methodMatches = (definition, requirement) => definition.dimensions?.includes(requirement.dimension) === true || definition.ruleIds?.includes(requirement.ruleId) === true;
11855
- var assuranceFor = (id, definition, capabilities) => {
11856
- const keys = new Set([
11857
- id,
11858
- ...definition.dimensions ?? [],
11859
- ...definition.ruleIds ?? []
11860
- ]);
11861
- const matches = capabilities.filter((capability) => keys.has(capability.name) || keys.has(capability.surface));
11862
- if (id === "workit-review" && matches.length === 0)
11863
- return { assurance: "unavailable", reasons: ["independent review capability is unavailable"] };
11864
- if (matches.some((capability) => capability.assurance === "unavailable"))
11865
- return {
11866
- assurance: "unavailable",
11867
- reasons: matches.filter((capability) => capability.assurance === "unavailable").map((capability) => capability.reason)
11868
- };
11869
- if (matches.some((capability) => capability.assurance === "enforced"))
11870
- return { assurance: "enforced", reasons: matches.map((capability) => capability.reason) };
11871
- return { assurance: "agent_guided", reasons: matches.map((capability) => capability.reason) };
11823
+ var canonicalScope = (scope) => {
11824
+ const paths = scope.paths.length ? scope.paths : ["."];
11825
+ const normalizedPaths = paths.map(canonicalPath);
11826
+ const normalizedExclusions = scope.exclusions.map(canonicalPath);
11827
+ if (normalizedPaths.some((value) => value === null) || normalizedExclusions.some((value) => value === null))
11828
+ return null;
11829
+ return {
11830
+ description: scope.description,
11831
+ paths: [...new Set(normalizedPaths)],
11832
+ exclusions: [...new Set(normalizedExclusions)]
11833
+ };
11872
11834
  };
11873
- function selectMethods(policy, capabilities) {
11874
- return Object.entries(METHODS).flatMap(([id, definition]) => {
11875
- const requirements = policy.requirements.filter((requirement) => methodMatches(definition, requirement));
11876
- if (requirements.length === 0)
11877
- return [];
11878
- const capability = assuranceFor(id, definition, capabilities);
11879
- const reasons = [
11880
- ...new Set(requirements.map((requirement) => requirement.reason)),
11881
- ...capability.reasons
11882
- ];
11883
- if (capability.assurance === "unavailable")
11884
- reasons.unshift("required capability is unavailable");
11885
- return [{ id, reason: reasons.join("; "), assurance: capability.assurance }];
11886
- });
11887
- }
11888
- var invariantBootstrap = () => `
11889
- Workit is optional coordination and repository-policy tooling around the host,
11890
- not a permission system or a mandatory workflow. Native host allow/ask/deny,
11891
- sandbox, plan/read-only mode, and organization rules remain authoritative.
11892
- Ordinary investigation, questions, non-Git work, and routine reversible edits
11893
- need zero Workit task, assessment, or writer calls. Use one compact tracked
11894
- record only when handoff, dependent steps, concurrent actors, or meaningful
11895
- decisions make continuity useful; similar titles alone never merge tasks.
11896
-
11897
- For a routine user-authorized branch or commit, prefer native host Git/shell
11898
- tools from the outset when managed coordination or outcome reconciliation is
11899
- not needed. Inspect the actual target checkout and its configured conventions;
11900
- use Workit's read-only context/policy tools when needed. Do not start a task,
11901
- acquire a writer, or mint a decision receipt solely for a native Git action.
11902
- Native permissions still apply. Never switch execution paths to evade a denial
11903
- or repeat an uncertain managed effect. A local-commit endpoint does not imply
11904
- PR readiness, a fresh review, or post-commit assessment/closure paperwork.
11905
-
11906
- For tracked work, inspect its current state and use the shared operations for
11907
- task, policy, evidence, finding, decision, worker, writer, and state changes.
11908
- Start a record once for an explicit tracked objective; assess or reassess only
11909
- when policy selection or changed evidence/constraints requires it. Omitted
11910
- expectedRevision and expectedWorkspaceRevision use current values; explicit
11911
- values are still concurrency-checked, so never copy revisions between calls.
11912
- A solo edit does not need writer acquisition; use it when concurrent checkout
11913
- writers need coordination. Record only observed facts and checks. Evidence can
11914
- become stale when its bound candidate changes; reconcile findings against the
11915
- current candidate before recording completion.
11916
-
11917
- Workit validates domain policy against the actual action target, configured
11918
- account, branch and commit conventions, protected refs, and current repository
11919
- state. The task directory is coordination state, not a boundary on which
11920
- repository may be changed. Use an action-time cwd target where a managed
11921
- Git/hosting action supports it; a non-Git directory remains valid for OS work.
11922
- GitHub/GitLab use the active gh/glab CLI identity; YouTrack uses its own token.
11923
- Preserve uncertain external outcomes and reconcile repository/provider state
11924
- before retrying. Internal reservations prevent duplicate or ambiguous effects;
11925
- they are not permission tickets for every edit.
11926
-
11927
- On OpenCode V1 and V2, use native host tools for external mutations. Workit
11928
- provides read-only workit_context; it has no managed external-action executor.
11929
- Do not create proposals or request Workit approvals merely to invoke native
11930
- tools. Old uncertain managed effects still require evidence before any retry.
11931
-
11932
- Use host-native authorization through the host's supported path. A native
11933
- question receipt records an actual question interaction; it is not automatic
11934
- host permission. Record a meaningful user choice once with provenance when
11935
- future retrieval helps. Never fabricate a receipt, re-ask only to mint one, or
11936
- let imported decisions grant authority. Never turn a host deny into allow or
11937
- claim enforcement/evidence a host cannot provide. A precise request with settled
11938
- constraints does not need an interview. Present genuine unresolved options with
11939
- evidence and a recommendation, then continue toward the requested delivery
11940
- endpoint: investigation, implementation, branch/commit/push, PR/MR-ready,
11941
- merge, or release. Run
11942
- applicable checks and safe repairs without repeated continuation questions;
11943
- stop for missing host authority, a new consequential choice, a conflicting edit,
11944
- or an unresolved blocker. A tracked record may close when actual evidence
11945
- supports its outcome; no final human closure ceremony is required.
11946
-
11947
- A completed native subagent run stops its bound worker by itself; if a worker
11948
- strands in cancelling with its run verifiably over, repeat worker.cancel to
11949
- confirm the stop. Preserve unresolved requirements, gaps, and uncertain workers.
11950
- When context changes, distinguish a quick question, same-task adjustment, and
11951
- separate request. Answer a quick question without pausing/resuming task state;
11952
- park a concise checkpoint only when substantial work needs to continue later.
11953
- For work spanning repositories, bind each unfinished item to its actual checkout,
11954
- branch, requested deliverables, and delivery endpoint. Preserve held items with
11955
- an explicit resume condition. Resolve competing plausible targets before a
11956
- mutation; ask only when available context cannot settle that consequential choice.
11957
- Before reporting delivery, reconcile every requested item and observe the actual
11958
- target result; a local commit alone is not evidence of a requested remote push.
11959
-
11960
- Skill routing: slash aliases /wk-* load on demand. Use workit-steer for a
11961
- substantial interruption or change of direction, workit-deslop when relevant
11962
- to a PR-ready endpoint, workit-green-run for failing CI, workit-blast-radius
11963
- when impact is uncertain, and workit-challenge for genuinely open consequential
11964
- choices. Load workit-plan when dependencies or handoff need durable next actions.
11965
- Load the skill; never act from memory of it.
11966
- `.trim();
11967
-
11968
- // packages/workit-core/src/core/task-context.ts
11969
- function reconcileResume(view, observations = []) {
11970
- if (observations.length > 0)
11971
- return failure("permission_denied", "worker observations require native host verification");
11972
- const candidate = captureCandidate(view.workspace.root, view.task.intent.data.scope, []);
11973
- if (!candidate.ok)
11974
- return candidate;
11975
- const staleEvidenceIds = evaluateEvidence(view.task, candidate.data).filter((entry) => entry.status === "stale").map((entry) => entry.evidenceId);
11976
- const blockers = [...view.task.progress.blockers];
11977
- if (view.task.workers.some((entry) => isUncertainWorker(entry.data.state)))
11978
- blockers.push({
11979
- reason: "worker state requires reconciliation",
11980
- dependentAction: "resume",
11981
- refs: []
11982
- });
11983
- return success(null, null, {
11984
- candidate: candidate.data,
11985
- staleEvidenceIds,
11986
- workerUpdates: [],
11987
- blockers,
11988
- reassessmentRequired: view.task.policy?.policyVersion !== POLICY_VERSION
11989
- });
11990
- }
11991
- var COMPACT_MAX_BYTES = 4096;
11992
- var COMPACT_MAX_ITEMS = 8;
11993
- var COMPACT_TEXT_BYTES = 128;
11994
- var sensitiveUrl = /\bhttps?:\/\/[^/\s:@]+:[^@\s]+@/gi;
11995
- var sensitiveValue = /(?:token|secret|password|passwd|api[-_ ]?key|private[-_ ]?key|authorization)\s*[:=]\s*(?:bearer\s+)?\S+|\bbearer\s+\S+/gi;
11996
- var privateKey = /-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/gi;
11997
- var compactText = (value, limit) => value === null ? null : value.replace(privateKey, "<redacted-private-key>").replace(sensitiveUrl, "<redacted-url>").replace(sensitiveValue, (match) => {
11998
- const separator = match.search(/[:=]/u);
11999
- if (separator >= 0)
12000
- return `${match.slice(0, separator)}=<redacted>`;
12001
- const space = match.search(/\s/u);
12002
- return `${match.slice(0, space)} <redacted>`;
12003
- }).slice(0, limit);
12004
- var compactBytes = (value) => new TextEncoder().encode(value).byteLength;
12005
- var compactTimestamp = (value) => `${value.slice(0, 19)}.${value.slice(20, -1).padEnd(9, "0")}`;
12006
- var compactDecisionChoice = (entry) => {
12007
- const stated = entry.data.binding.statedChoice?.text;
12008
- const approved = entry.data.response === "approved" ? entry.data.binding.approvedContent : "";
12009
- const source = stated?.trim() || approved.trim() || null;
12010
- return compactText(source, COMPACT_TEXT_BYTES);
11835
+ var excluded = (value, exclusions) => exclusions.some((item) => item === value || item !== "." && value.startsWith(`${item}/`));
11836
+ var scopeMatches = (value, scope) => {
11837
+ const normalized = canonicalScope(scope);
11838
+ if (!normalized)
11839
+ return false;
11840
+ const paths = normalized.paths;
11841
+ return paths.some((item) => item === "." || value === item || value.startsWith(`${item}/`)) && !excluded(value, normalized.exclusions);
12011
11842
  };
12012
- var compactReference = (ref) => {
12013
- if (ref.kind === "file")
12014
- return {
12015
- kind: "file",
12016
- path: compactText(ref.path, COMPACT_TEXT_BYTES) ?? ""
12017
- };
12018
- if (ref.kind === "record")
11843
+ var pathRelevant = (value, scope) => scopeMatches(value, scope);
11844
+ var compareCodeUnits3 = (left, right) => {
11845
+ const length = Math.min(left.length, right.length);
11846
+ for (let index = 0;index < length; index += 1) {
11847
+ const difference = left.charCodeAt(index) - right.charCodeAt(index);
11848
+ if (difference !== 0)
11849
+ return difference;
11850
+ }
11851
+ return left.length - right.length;
11852
+ };
11853
+ var gitPaths = (root) => {
11854
+ const result = spawnSync2("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
11855
+ cwd: root,
11856
+ encoding: "buffer"
11857
+ });
11858
+ if (result.status !== 0) {
11859
+ const stderr = result.stderr?.toString("utf8") ?? "";
12019
11860
  return {
12020
- kind: "record",
12021
- collection: ref.collection,
12022
- id: ref.id
11861
+ paths: [],
11862
+ uncertain: !/not a git repository/i.test(stderr),
11863
+ git: /not a git repository/i.test(stderr) ? false : true
12023
11864
  };
12024
- return { kind: ref.kind };
12025
- };
12026
- function compactTaskContext(view) {
12027
- const decisions = view.task.decisions.slice().sort((left, right) => {
12028
- const leftAt = compactTimestamp(left.recordedAt);
12029
- const rightAt = compactTimestamp(right.recordedAt);
12030
- if (leftAt !== rightAt)
12031
- return leftAt > rightAt ? -1 : 1;
12032
- return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;
12033
- }).slice(0, COMPACT_MAX_ITEMS).map((entry) => ({
12034
- id: entry.id,
12035
- purpose: entry.data.purpose,
12036
- status: entry.data.response,
12037
- digest: entry.data.digest,
12038
- choice: compactDecisionChoice(entry) || `task.inspect taskId=${view.task.id} view=full; decision=${entry.id}`,
12039
- references: entry.data.binding.contentRefs.slice(0, 1).map(compactReference)
12040
- }));
12041
- const methods = view.task.policy ? selectMethods(view.task.policy, view.capabilities).map((method) => ({
12042
- id: method.id,
12043
- assurance: method.assurance,
12044
- reason: compactText(method.reason, COMPACT_TEXT_BYTES) ?? ""
12045
- })) : [];
12046
- const gaps = Array.from(new Set([
12047
- ...view.evidence.filter((entry) => entry.status === "stale").map((entry) => `stale evidence: ${entry.evidenceId}`),
12048
- ...view.requirements.filter((entry) => entry.status !== "satisfied").map((entry) => entry.reason),
12049
- ...view.task.progress.blockers.map((entry) => entry.reason)
12050
- ])).sort().slice(0, COMPACT_MAX_ITEMS).map((gap) => compactText(gap, COMPACT_TEXT_BYTES));
12051
- const context = {
12052
- objective: compactText(view.task.intent.data.objective, COMPACT_TEXT_BYTES) ?? "",
12053
- status: view.task.status,
12054
- decisions,
12055
- methods,
12056
- gaps,
12057
- nextAction: compactText(view.task.progress.nextAction, COMPACT_TEXT_BYTES)
12058
- };
12059
- let encoded = JSON.stringify(context);
12060
- while (compactBytes(encoded) > COMPACT_MAX_BYTES && (context.decisions.length || context.methods.length || context.gaps.length)) {
12061
- if (context.gaps.length)
12062
- context.gaps.pop();
12063
- else if (context.decisions.length)
12064
- context.decisions.pop();
12065
- else
12066
- context.methods.pop();
12067
- encoded = JSON.stringify(context);
12068
11865
  }
12069
- if (compactBytes(encoded) > COMPACT_MAX_BYTES) {
12070
- context.objective = compactText(context.objective, 64) ?? "";
12071
- context.nextAction = compactText(context.nextAction, 64);
12072
- encoded = JSON.stringify(context);
11866
+ const paths = result.stdout ? result.stdout.toString("utf8").split("\x00").filter(Boolean).map((item) => item.split(path10.sep).join("/")) : [];
11867
+ const stagedDeleted = spawnSync2("git", ["diff", "--cached", "--name-only", "--diff-filter=D", "-z"], { cwd: root, encoding: "buffer" });
11868
+ if (stagedDeleted.status !== 0) {
11869
+ const stderr = stagedDeleted.stderr?.toString("utf8") ?? "";
11870
+ if (!/not a git repository/i.test(stderr))
11871
+ return { paths, uncertain: true, git: true };
11872
+ } else if (stagedDeleted.stdout) {
11873
+ paths.push(...stagedDeleted.stdout.toString("utf8").split("\x00").filter(Boolean).map((item) => item.split(path10.sep).join("/")));
12073
11874
  }
12074
- return encoded;
12075
- }
12076
- var exportDigest = (bundle) => sha256({
12077
- schemaVersion: bundle.schemaVersion,
12078
- exportedAt: bundle.exportedAt,
12079
- sourceWorkspaceId: bundle.sourceWorkspaceId,
12080
- task: bundle.task
12081
- });
12082
- // packages/workit-core/src/core/route-intent.ts
12083
- var shellBranchTarget = (command) => {
12084
- if (!command.trim() || /[\r\n;&|<>`'"$()\\*?{}~!#]/u.test(command) || command.includes("[") || command.includes("]"))
12085
- return null;
12086
- const args = command.trim().split(/\s+/u);
12087
- if (args[0] !== "git")
12088
- return null;
12089
- const option = args[2];
12090
- const target = args[1] === "switch" && ["-c", "--create", "-C", "--force-create"].includes(option ?? "") && (args.length === 4 || args.length === 5) ? args[3] : args[1] === "checkout" && ["-b", "-B"].includes(option ?? "") && (args.length === 4 || args.length === 5) ? args[3] : args[1] === "branch" && (args.length === 3 || args.length === 4) ? args[2] : null;
12091
- return target && !target.startsWith("-") ? target : null;
12092
- };
12093
- var shellBranchPolicyViolation = (root, command) => {
12094
- const target = shellBranchTarget(command);
12095
- return target === null ? null : validateBranchNameFor(root, target);
11875
+ return { paths: [...new Set(paths)], uncertain: false, git: true };
12096
11876
  };
12097
- // packages/workit-core/src/core/external-action.ts
12098
- var chainStepSchema = union([
12099
- string2().min(1),
12100
- object({ branch: string2().min(1) }).strict(),
12101
- object({ pr: literal(true) }).strict()
12102
- ]);
12103
- var externalActionSchema = discriminatedUnion("operation", [
12104
- object({
12105
- operation: literal("git.branch_setup"),
12106
- payload: object({
12107
- action: _enum(["setup", "reapply_stash"]).optional(),
12108
- sdd_dir: string2().optional(),
12109
- target_branch: string2().optional(),
12110
- stash: _enum(["yes", "no"]).optional(),
12111
- cwd: string2().min(1).optional()
12112
- }).strict()
12113
- }).strict(),
12114
- object({
12115
- operation: literal("git.commit"),
12116
- payload: object({
12117
- message: string2().min(1).optional(),
12118
- plan_steps: array(chainStepSchema).min(1).max(32).optional(),
12119
- plan_branch: string2().min(1).optional(),
12120
- cwd: string2().min(1).optional()
12121
- }).strict()
12122
- }).strict(),
12123
- object({
12124
- operation: literal("git.push"),
12125
- payload: object({ branch: string2().min(1).optional(), cwd: string2().min(1).optional() }).strict()
12126
- }).strict(),
12127
- object({
12128
- operation: literal("hosting.pull_request"),
12129
- payload: object({
12130
- title: string2().min(1),
12131
- body: string2().optional(),
12132
- draft: boolean2().optional(),
12133
- target_branch: string2().optional(),
12134
- babysit: boolean2().optional(),
12135
- cwd: string2().min(1).optional()
12136
- }).strict()
12137
- }).strict(),
12138
- object({
12139
- operation: literal("hosting.merge"),
12140
- payload: object({
12141
- target_branch: string2().min(1).optional(),
12142
- source_branch: string2().min(1).optional(),
12143
- cwd: string2().min(1).optional()
12144
- }).strict()
12145
- }).strict(),
12146
- object({
12147
- operation: literal("hosting.delete_branch"),
12148
- payload: object({ branch: string2().min(1), cwd: string2().min(1).optional() }).strict()
12149
- }).strict(),
12150
- object({
12151
- operation: literal("youtrack.update"),
12152
- payload: object({
12153
- issueId: string2().min(1),
12154
- markdown: string2().min(1),
12155
- minutes: number2().positive().optional()
12156
- }).strict()
12157
- }).strict(),
12158
- object({
12159
- operation: literal("youtrack.time"),
12160
- payload: object({
12161
- issueId: string2().min(1),
12162
- minutes: number2().positive(),
12163
- text: string2().optional(),
12164
- dateMs: number2().finite().optional()
12165
- }).strict()
12166
- }).strict(),
12167
- object({
12168
- operation: literal("youtrack.meeting"),
12169
- payload: object({
12170
- issueId: string2().min(1),
12171
- minutes: number2().positive(),
12172
- text: string2().min(1)
12173
- }).strict()
12174
- }).strict(),
12175
- object({
12176
- operation: literal("changelog.apply"),
12177
- payload: object({
12178
- entries: union([
12179
- record(string2(), array(string2())),
12180
- array(object({ category: string2().min(1), text: string2().min(1) }).strict())
12181
- ]).optional(),
12182
- path: string2().optional(),
12183
- normalize_only: boolean2().optional()
12184
- }).strict()
12185
- }).strict(),
12186
- object({
12187
- operation: literal("context.read"),
12188
- payload: object({
12189
- kind: _enum([
12190
- "git",
12191
- "pr",
12192
- "youtrack",
12193
- "github_issue",
12194
- "gitlab_issue",
12195
- "changelog",
12196
- "release",
12197
- "affected"
12198
- ]),
12199
- range: string2().optional(),
12200
- issueId: string2().optional(),
12201
- issueUrl: string2().optional(),
12202
- issueRef: string2().optional(),
12203
- mode: string2().optional(),
12204
- specPath: string2().optional(),
12205
- planPath: string2().optional(),
12206
- cwd: string2().min(1).optional()
12207
- }).strict()
12208
- }).strict()
12209
- ]);
12210
- // packages/workit-core/src/core/task-engine.ts
12211
- import { realpathSync as realpathSync6 } from "node:fs";
12212
-
12213
- // packages/workit-core/src/core/policy-resolver.ts
12214
- var resolverInputSchema = object({
12215
- intent: intentSchema,
12216
- assessment: assessmentSchema,
12217
- constraints: array(constraintSchema),
12218
- prior: object({
12219
- decisions: array(decisionSchema),
12220
- findings: array(findingSchema),
12221
- requirements: array(requirementSchema)
12222
- }).strict(),
12223
- preferences: object({ fast: boolean2().optional(), thorough: boolean2().optional() }).strict().optional()
12224
- }).strict();
12225
- var compareCodeUnits3 = (left, right) => {
12226
- const length = Math.min(left.length, right.length);
12227
- for (let index = 0;index < length; index += 1) {
12228
- const difference = left.charCodeAt(index) - right.charCodeAt(index);
12229
- if (difference !== 0)
12230
- return difference;
11877
+ var walk = (root, directory, output) => {
11878
+ let names;
11879
+ try {
11880
+ names = fs7.readdirSync(directory);
11881
+ } catch {
11882
+ return true;
12231
11883
  }
12232
- return left.length - right.length;
11884
+ let uncertain = false;
11885
+ for (const name of names) {
11886
+ if (name === ".git" || name === ".workit")
11887
+ continue;
11888
+ const target = path10.join(directory, name);
11889
+ let stat;
11890
+ try {
11891
+ stat = fs7.lstatSync(target);
11892
+ } catch {
11893
+ uncertain = true;
11894
+ continue;
11895
+ }
11896
+ const item = relative(root, target);
11897
+ output.add(item);
11898
+ if (stat.isDirectory() && !stat.isSymbolicLink())
11899
+ uncertain = walk(root, target, output) || uncertain;
11900
+ }
11901
+ return uncertain;
12233
11902
  };
12234
- var stableUnique = (values) => [...new Set(values)].sort(compareCodeUnits3);
12235
- var stableList = (values) => [...values].sort((left, right) => compareCodeUnits3(canonicalJson(left), canonicalJson(right)));
12236
- var normalizedScope = (scope) => ({
12237
- description: scope.description,
12238
- paths: stableUnique(scope.paths),
12239
- exclusions: stableUnique(scope.exclusions)
12240
- });
12241
- var normalizedRefList = (values) => stableList(values);
12242
- var normalizeAssessment = (assessment) => ({
12243
- facts: stableList(assessment.facts.map((fact) => ({ ...fact, refs: normalizedRefList(fact.refs) }))),
12244
- signals: Object.fromEntries(Object.entries(assessment.signals).map(([name, signal]) => [
11903
+ var scopeRoots = (root, scope) => {
11904
+ const roots = [];
11905
+ for (const item of scope.paths.length ? scope.paths : ["."]) {
11906
+ const target = path10.resolve(root, item);
11907
+ if (!inside(root, target))
11908
+ return failure("invalid_input", `candidate scope escapes checkout: ${item} — keep one task per repository and coordinate a separate linked task in the other checkout`, { fields: [{ path: "scope.paths", reason: `${item} is outside the checkout` }] });
11909
+ let ancestor = target;
11910
+ while (!fs7.existsSync(ancestor) && ancestor !== root)
11911
+ ancestor = path10.dirname(ancestor);
11912
+ try {
11913
+ if (!inside(root, fs7.realpathSync(ancestor)))
11914
+ return failure("invalid_input", `candidate scope escapes checkout through a symlink: ${item} — keep one task per repository and coordinate a separate linked task in the other checkout`, { fields: [{ path: "scope.paths", reason: `${item} resolves outside the checkout` }] });
11915
+ } catch {
11916
+ return failure("invalid_input", `candidate scope cannot be inspected: ${item}`);
11917
+ }
11918
+ roots.push(target);
11919
+ }
11920
+ return success(null, null, roots);
11921
+ };
11922
+ function captureCandidate(root, scope, environment = []) {
11923
+ let checkout;
11924
+ try {
11925
+ checkout = fs7.realpathSync(root);
11926
+ } catch {
11927
+ return failure("invalid_input", "candidate root does not exist");
11928
+ }
11929
+ const normalizedScope = canonicalScope(scope);
11930
+ if (!normalizedScope)
11931
+ return failure("invalid_input", "candidate scope is invalid: paths must be checkout-relative — to work in another repository, keep this task here and coordinate a separate linked task in that checkout", { fields: [{ path: "scope.paths", reason: "must be checkout-relative" }] });
11932
+ const roots = scopeRoots(checkout, normalizedScope);
11933
+ if (!roots.ok)
11934
+ return roots;
11935
+ const git = gitPaths(checkout);
11936
+ const names = new Set;
11937
+ let uncertain = git.uncertain;
11938
+ for (const target of roots.data) {
11939
+ const item = relative(checkout, target);
11940
+ if (item === ".git" || item === ".workit")
11941
+ continue;
11942
+ names.add(item);
11943
+ if (!fs7.existsSync(target))
11944
+ continue;
11945
+ let stat;
11946
+ try {
11947
+ stat = fs7.lstatSync(target);
11948
+ } catch {
11949
+ uncertain = true;
11950
+ continue;
11951
+ }
11952
+ if (!git.git && stat.isDirectory() && !stat.isSymbolicLink())
11953
+ uncertain = walk(checkout, target, names) || uncertain;
11954
+ }
11955
+ for (const item of git.paths)
11956
+ if (scopeMatches(item, normalizedScope))
11957
+ names.add(item);
11958
+ const files = [];
11959
+ let completeness = uncertain ? "uncertain" : "known";
11960
+ for (const item of [...names].sort()) {
11961
+ if (!scopeMatches(item, normalizedScope))
11962
+ continue;
11963
+ const target = path10.join(checkout, item);
11964
+ try {
11965
+ const stat = fs7.lstatSync(target);
11966
+ if (stat.isSymbolicLink()) {
11967
+ const link = fs7.readlinkSync(target);
11968
+ files.push({ path: item, kind: "symlink", digest: digestBytes3(link), executable: null });
11969
+ } else if (stat.isFile()) {
11970
+ files.push({
11971
+ path: item,
11972
+ kind: "file",
11973
+ digest: digestBytes3(fs7.readFileSync(target)),
11974
+ executable: (stat.mode & 73) !== 0
11975
+ });
11976
+ } else if (!stat.isDirectory()) {
11977
+ completeness = "uncertain";
11978
+ } else if (git.git && git.paths.includes(item)) {
11979
+ completeness = "uncertain";
11980
+ }
11981
+ } catch (error) {
11982
+ if (error?.code === "ENOENT") {
11983
+ files.push({ path: item, kind: "absent", digest: null, executable: null });
11984
+ } else
11985
+ completeness = "uncertain";
11986
+ }
11987
+ }
11988
+ const supplied = Array.isArray(environment) ? environment.map((value) => typeof value === "string" ? { name: value, value: process.env[value] ?? null } : { name: value.name, value: value.value ?? null }) : Object.keys(environment).map((name) => ({
12245
11989
  name,
12246
- { ...signal, refs: normalizedRefList(signal.refs) }
12247
- ])),
12248
- consequences: stableList(assessment.consequences.map((consequence) => ({
12249
- ...consequence,
12250
- fact: { ...consequence.fact, refs: normalizedRefList(consequence.fact.refs) }
12251
- }))),
12252
- verification: stableList(assessment.verification.map((verification) => ({
12253
- ...verification,
12254
- scope: normalizedScope(verification.scope),
12255
- availableChecks: normalizedRefList(verification.availableChecks),
12256
- gaps: stableUnique(verification.gaps)
12257
- })))
12258
- });
12259
- var normalizeConstraint = (constraint) => ({
12260
- ...constraint,
12261
- source: constraint.source,
12262
- requires: stableList(constraint.requires.map((requirement) => ({
12263
- ...requirement,
12264
- scope: normalizedScope(requirement.scope),
12265
- refs: normalizedRefList(requirement.refs)
12266
- })))
12267
- });
12268
- var normalizeDecision = (decision) => ({
12269
- ...decision,
12270
- binding: {
12271
- ...decision.binding,
12272
- scope: normalizedScope(decision.binding.scope),
12273
- contentRefs: normalizedRefList(decision.binding.contentRefs)
12274
- },
12275
- requirementIds: stableUnique(decision.requirementIds)
12276
- });
12277
- var normalizeIntent = (intent) => ({
12278
- ...intent,
12279
- scope: normalizedScope(intent.scope),
12280
- authorityRefs: normalizedRefList(intent.authorityRefs)
12281
- });
12282
- var normalizePrior = (prior) => ({
12283
- decisions: stableList(prior.decisions.map(normalizeDecision)),
12284
- findings: stableList(prior.findings.map((finding) => ({
12285
- ...finding,
12286
- scope: normalizedScope(finding.scope),
12287
- refs: normalizedRefList(finding.refs),
12288
- resolution: finding.resolution ? {
12289
- ...finding.resolution,
12290
- evidenceIds: stableUnique(finding.resolution.evidenceIds),
12291
- decisionIds: stableUnique(finding.resolution.decisionIds)
12292
- } : null
12293
- }))),
12294
- requirements: stableList(prior.requirements.map((requirement) => ({
12295
- ...requirement,
12296
- scope: normalizedScope(requirement.scope)
12297
- })))
12298
- });
12299
- var invalidFields = (error) => ({
12300
- fields: error.issues.map((issue) => ({
12301
- path: issue.code === "unrecognized_keys" ? issue.keys.join(".") : issue.path.join("."),
12302
- reason: issue.message
12303
- }))
12304
- });
12305
- function normalizeResolverInput(input) {
12306
- const parsed = resolverInputSchema.safeParse(input);
12307
- if (!parsed.success)
12308
- return failure("invalid_input", "resolver input is invalid", invalidFields(parsed.error));
12309
- const value = parsed.data;
12310
- const signals = value.assessment.signals;
12311
- if (signals.behaviorChange.value === true && signals.mechanicalLowRisk.value === true)
12312
- return failure("invalid_input", "behavioral change cannot be wholly mechanical", {
12313
- fields: [
12314
- {
12315
- path: "assessment.signals",
12316
- reason: "contradictory behaviorChange and mechanicalLowRisk"
12317
- }
12318
- ]
12319
- });
12320
- const ids = value.constraints.map((constraint) => constraint.id);
12321
- if (new Set(ids).size !== ids.length)
12322
- return failure("invalid_input", "constraint IDs must be unique", {
12323
- fields: [{ path: "constraints", reason: "duplicate constraint id" }]
12324
- });
12325
- if (value.preferences?.fast && value.preferences.thorough)
12326
- return failure("invalid_input", "fast and thorough preferences contradict", {
12327
- fields: [{ path: "preferences", reason: "fast and thorough cannot both be enabled" }]
12328
- });
12329
- const normalized = {
12330
- intent: normalizeIntent(value.intent),
12331
- assessment: normalizeAssessment(value.assessment),
12332
- constraints: stableList(value.constraints.map(normalizeConstraint)),
12333
- prior: normalizePrior(value.prior),
12334
- ...value.preferences ? { preferences: { ...value.preferences } } : {},
12335
- policyVersion: POLICY_VERSION
11990
+ value: environment[name] ?? null
11991
+ }));
11992
+ const namesByEnvironment = supplied.map(({ name }) => name);
11993
+ if (new Set(namesByEnvironment).size !== namesByEnvironment.length || namesByEnvironment.some((name) => typeof name !== "string" || !name))
11994
+ return failure("invalid_input", "candidate environment names must be unique and non-empty");
11995
+ const values = supplied.sort((left, right) => compareCodeUnits3(left.name, right.name)).map(({ name, value }) => ({ name, value, refs: [] }));
11996
+ if (values.some(({ value }) => value === null))
11997
+ completeness = "uncertain";
11998
+ const headResult = spawnSync2("git", ["rev-parse", "HEAD"], { cwd: checkout, encoding: "utf8" });
11999
+ if (headResult.status !== 0 && !/not a git repository/i.test(headResult.stderr ?? ""))
12000
+ completeness = "uncertain";
12001
+ const head = headResult.status === 0 ? headResult.stdout.trim() : null;
12002
+ const partial = {
12003
+ id: "0".repeat(64),
12004
+ scope: normalizedScope,
12005
+ completeness,
12006
+ files,
12007
+ environment: values,
12008
+ head
12336
12009
  };
12337
- return success(null, null, normalized);
12010
+ const candidate = { ...partial, id: candidateDigest(partial) };
12011
+ const parsed = candidateSchema.safeParse(candidate);
12012
+ return parsed.success ? success(null, null, parsed.data) : failure("invalid_input", "captured candidate is invalid");
12338
12013
  }
12339
- var requirement = (spec) => ({
12340
- ...spec,
12341
- id: requirementId({
12342
- ruleId: spec.ruleId,
12343
- scope: spec.scope,
12344
- satisfaction: spec.satisfaction,
12345
- before: spec.before,
12346
- dependentAction: spec.dependentAction
12347
- })
12348
- });
12349
- var signalReason = (input, name) => input.assessment.signals[name].reason;
12350
- function resolveRequirements(input) {
12351
- const { signals } = input.assessment;
12352
- const scope = input.intent.scope;
12353
- const requirements = [];
12354
- const hasUnknownSignal = Object.values(signals).some((signal) => signal.value === "unknown");
12355
- const hasUnknownFact = [
12356
- ...input.assessment.facts,
12357
- ...input.assessment.consequences.map(({ fact }) => fact)
12358
- ].some((fact) => fact.basis === "unknown");
12359
- if (hasUnknownSignal || hasUnknownFact)
12360
- requirements.push(requirement({
12361
- ruleId: "consequential-unknown",
12362
- dimension: "investigation",
12363
- scope,
12364
- reason: `Resolve consequential uncertainty before the dependent action: ${[
12365
- ...Object.entries(signals).filter(([, signal]) => signal.value === "unknown").map(([name]) => name),
12366
- ...hasUnknownFact ? ["unknown fact"] : []
12367
- ].join(", ")}`,
12368
- satisfaction: "An observed or inferred fact resolves the uncertainty and records its supporting references.",
12369
- before: "dependent_action",
12370
- dependentAction: null,
12371
- acceptanceAllowed: false
12372
- }));
12373
- if (signals.productChoiceOpen.value === true)
12374
- requirements.push(requirement({
12375
- ruleId: "product-decision",
12376
- dimension: "decisions",
12377
- scope,
12378
- reason: `A consequential product choice remains open: ${signalReason(input, "productChoiceOpen")}`,
12379
- satisfaction: "Present the material alternatives and record the user's decision before the dependent action.",
12380
- before: "dependent_action",
12381
- dependentAction: null,
12382
- acceptanceAllowed: false
12383
- }));
12384
- const independentBehaviorReview = input.preferences?.thorough === true || input.assessment.consequences.some((consequence) => ["security", "data", "public_contract", "operations"].includes(consequence.area));
12385
- if (signals.behaviorChange.value === true)
12386
- requirements.push(requirement({
12387
- ruleId: "behavioral-verification",
12388
- dimension: "testing",
12389
- scope,
12390
- reason: `Behavior, side effects, permissions, or data handling may change: ${signalReason(input, "behaviorChange")}`,
12391
- satisfaction: "A useful behavioral check passes against the affected behavior and current candidate.",
12392
- before: "close",
12393
- dependentAction: null,
12394
- acceptanceAllowed: false
12395
- }), requirement({
12396
- ruleId: independentBehaviorReview ? "fresh-context-review" : "self-review",
12397
- dimension: "review",
12398
- scope,
12399
- reason: independentBehaviorReview ? "Consequential behavior or the thorough preference requires fresh-context review." : "Bounded behavior changes use self-review unless consequential risks or trusted rules require more.",
12400
- satisfaction: independentBehaviorReview ? "A separate review context examines the current candidate and records its result." : "The lead reviews the resulting diff and records the relevant scope and checks.",
12401
- before: "close",
12402
- dependentAction: null,
12403
- acceptanceAllowed: !independentBehaviorReview
12404
- }));
12405
- else if (signals.mechanicalLowRisk.value === true)
12406
- requirements.push(requirement({
12407
- ruleId: "mechanical-existing-checks",
12408
- dimension: "verification",
12409
- scope,
12410
- reason: `The change is demonstrably mechanical and low-risk: ${signalReason(input, "mechanicalLowRisk")}`,
12411
- satisfaction: "Run the relevant existing checks for affected consumers; do not add tautological tests.",
12412
- before: "close",
12413
- dependentAction: null,
12414
- acceptanceAllowed: true
12415
- }), requirement({
12416
- ruleId: input.preferences?.thorough ? "fresh-context-review" : "self-review",
12417
- dimension: "review",
12418
- scope,
12419
- reason: input.preferences?.thorough ? "The thorough preference upgrades mechanical self-review to fresh-context review." : "Mechanical low-risk work uses self-review rather than mandatory fresh-context review.",
12420
- satisfaction: input.preferences?.thorough ? "A separate review context examines the current candidate and records its result." : "The lead reviews the resulting diff and records the relevant scope and checks.",
12421
- before: "close",
12422
- dependentAction: null,
12423
- acceptanceAllowed: !input.preferences?.thorough
12424
- }));
12425
- if (signals.behaviorChange.value === true || signals.mechanicalLowRisk.value === true)
12426
- requirements.push(requirement({
12427
- ruleId: "pre-pr-cleanup",
12428
- dimension: "verification",
12429
- scope,
12430
- reason: "Implementation output must be deslopped before it is delivered.",
12431
- satisfaction: "Run the workit-deslop pass and record passing check evidence, or record an approved limitation decision waiving cleanup.",
12432
- before: "dependent_action",
12433
- dependentAction: "hosting.pull_request",
12434
- acceptanceAllowed: true
12435
- }));
12436
- if (signals.durableAgreementNeeded.value === true)
12437
- requirements.push(requirement({
12438
- ruleId: "durable-spec",
12439
- dimension: "artifacts",
12440
- scope,
12441
- reason: `The work needs a durable agreement about intended behavior: ${signalReason(input, "durableAgreementNeeded")}`,
12442
- satisfaction: "Record the agreed behavior in a durable specification before implementation writes.",
12443
- before: "write",
12444
- dependentAction: null,
12445
- acceptanceAllowed: true
12446
- }));
12447
- if (signals.coordinationPlanNeeded.value === true)
12448
- requirements.push(requirement({
12449
- ruleId: "coordination-plan",
12450
- dimension: "continuity",
12451
- scope,
12452
- reason: `Dependencies, sequencing, or resumption need durable coordination: ${signalReason(input, "coordinationPlanNeeded")}`,
12453
- satisfaction: "Record useful sequencing, dependencies, and the next action in a compact plan.",
12454
- before: "dependent_action",
12455
- dependentAction: null,
12456
- acceptanceAllowed: true
12457
- }));
12458
- if (signals.helperUseful.value === true && !input.preferences?.fast)
12459
- requirements.push(requirement({
12460
- ruleId: "helper-usefulness",
12461
- dimension: "delegation",
12462
- scope,
12463
- reason: `Independent judgment or investigation justifies a scoped helper: ${signalReason(input, "helperUseful")}`,
12464
- satisfaction: "Use a bounded helper only for the independent objective and reconcile its result.",
12465
- before: "dependent_action",
12466
- dependentAction: null,
12467
- acceptanceAllowed: true
12014
+ var fileMap = (candidate) => new Map(candidate.files.map((file) => [file.path, file]));
12015
+ var changedPaths = (before, after) => {
12016
+ const paths = new Set([...before.files, ...after.files].map((file) => file.path));
12017
+ const left = fileMap(before);
12018
+ const right = fileMap(after);
12019
+ const changed = [...paths].filter((item) => JSON.stringify(left.get(item) ?? null) !== JSON.stringify(right.get(item) ?? null));
12020
+ if (before.head !== after.head)
12021
+ changed.push(".");
12022
+ if (JSON.stringify(before.environment) !== JSON.stringify(after.environment))
12023
+ changed.push(".");
12024
+ return changed;
12025
+ };
12026
+ var sessionFromRef = (value) => {
12027
+ if (typeof value !== "object" || value === null || value.kind !== "host")
12028
+ return null;
12029
+ return typeof value.host === "string" && typeof value.handle === "string" ? { host: value.host, handle: value.handle } : null;
12030
+ };
12031
+ var sameSession = (left, right) => {
12032
+ const other = sessionFromRef(right);
12033
+ return left !== null && other !== null && left.host === other.host && left.handle === other.handle;
12034
+ };
12035
+ var evidenceScopes = (task, ids) => (task.policy?.requirements ?? []).filter((requirement) => ids.includes(requirement.id)).map((requirement) => requirement.scope);
12036
+ function evaluateEvidence(task, candidate) {
12037
+ const current = candidate ?? task.candidates.at(-1) ?? null;
12038
+ return task.evidence.map((entry) => {
12039
+ const evidence = entry.data;
12040
+ if (evidence.result === "failed")
12041
+ return {
12042
+ evidenceId: entry.id,
12043
+ status: "failed",
12044
+ reason: "failed evidence remains historical"
12045
+ };
12046
+ if (evidence.kind === "check" || evidence.kind === "review") {
12047
+ if (!evidence.beforeCandidateId || !evidence.candidateId)
12048
+ return {
12049
+ evidenceId: entry.id,
12050
+ status: "stale",
12051
+ reason: "check or review evidence lacks start and end candidates"
12052
+ };
12053
+ if (evidence.beforeCandidateId !== evidence.candidateId)
12054
+ return {
12055
+ evidenceId: entry.id,
12056
+ status: "stale",
12057
+ reason: "candidate changed during the check or review"
12058
+ };
12059
+ }
12060
+ if (!evidence.candidateId || !current)
12061
+ return {
12062
+ evidenceId: entry.id,
12063
+ status: evidence.result,
12064
+ reason: "evidence has no candidate binding"
12065
+ };
12066
+ const observed = task.candidates.find((item) => item.id === evidence.candidateId) ?? (current.id === evidence.candidateId ? current : undefined);
12067
+ if (!observed || observed.completeness === "uncertain" || current.completeness === "uncertain")
12068
+ return { evidenceId: entry.id, status: "stale", reason: "candidate is missing or uncertain" };
12069
+ if (observed.id === current.id)
12070
+ return { evidenceId: entry.id, status: evidence.result, reason: "candidate is unchanged" };
12071
+ const scopes = evidenceScopes(task, evidence.requirementIds);
12072
+ const changed = changedPaths(observed, current);
12073
+ const environmentChanged = JSON.stringify(observed.environment) !== JSON.stringify(current.environment);
12074
+ if (!scopes.length || environmentChanged || changed.some((item) => scopes.some((scope) => pathRelevant(item, scope))))
12075
+ return { evidenceId: entry.id, status: "stale", reason: "relevant candidate state changed" };
12076
+ return {
12077
+ evidenceId: entry.id,
12078
+ status: evidence.result,
12079
+ reason: "candidate changed outside evidence scope"
12080
+ };
12081
+ });
12082
+ }
12083
+ var scopeCovers2 = scopeCovers;
12084
+ var checkPin = (assignment, beforeCandidateId, candidateId) => {
12085
+ const pin = assignment.candidateId ?? null;
12086
+ if (pin === null)
12087
+ return true;
12088
+ return (beforeCandidateId ?? null) === pin || (candidateId ?? null) === pin;
12089
+ };
12090
+ var resolveBinding = (evidence, pin, currentCandidateId) => {
12091
+ const bound = evidence.kind === "check" || evidence.kind === "review";
12092
+ const fallback = bound ? pin ?? currentCandidateId : null;
12093
+ return {
12094
+ beforeCandidateId: evidence.beforeCandidateId ?? fallback,
12095
+ candidateId: evidence.candidateId ?? fallback
12096
+ };
12097
+ };
12098
+ var findingVerificationPasses = (findingCandidateId, evidence) => evidence.status === "passed" && (evidence.kind === "check" || evidence.kind === "review") && ((findingCandidateId ?? null) === null || evidence.candidateId != null);
12099
+ var applicableDecision2 = (task, workspace, requirement, checkoutRoot) => task.decisions.filter((entry) => entry.provenance.kind !== "imported").map((entry) => entry.data).filter((decision) => decision.purpose === "limitation" && decision.response === "approved" && decision.revoked === null && decision.binding.taskId === task.id && decision.binding.workspaceId === workspace.id && decision.requirementIds.includes(requirement.id) && decision.binding.scope && scopeCovers2(decision.binding.scope, requirement.scope) && decision.digest === decisionDigest(decision) && (checkoutRoot ? verifyDecisionContentAtRoot(checkoutRoot, decision.binding).ok : decision.binding.contentRefs.every((reference) => reference.kind !== "file")));
12100
+ var applicableRequirementDecision = (task, workspace, requirement, checkoutRoot) => task.decisions.filter(({ data, provenance }) => provenance.kind !== "imported" && data.purpose !== "limitation" && (data.response === "approved" || data.response === "stated") && data.revoked === null && data.binding.taskId === task.id && data.binding.workspaceId === workspace.id && data.requirementIds.includes(requirement.id) && scopeCovers2(data.binding.scope, requirement.scope) && data.digest === decisionDigest(data) && (checkoutRoot ? verifyDecisionContentAtRoot(checkoutRoot, data.binding).ok : data.binding.contentRefs.every((reference) => reference.kind !== "file"))).map(({ id }) => ({ id }));
12101
+ var evidenceMatchesRequirement = (kind, evidenceKind, dimension, ruleId) => {
12102
+ if (kind !== "passed")
12103
+ return false;
12104
+ if (dimension === "testing" || dimension === "verification")
12105
+ return evidenceKind === "check" || ruleId === "pre-pr-cleanup" && evidenceKind === "artifact";
12106
+ if (dimension === "review")
12107
+ return evidenceKind === "review";
12108
+ if (dimension === "investigation" || dimension === "challenge")
12109
+ return evidenceKind === "investigation";
12110
+ if (dimension === "artifacts" || dimension === "continuity")
12111
+ return evidenceKind === "artifact";
12112
+ return false;
12113
+ };
12114
+ var expectedKinds = (dimension, ruleId) => {
12115
+ if (dimension === "testing")
12116
+ return "check";
12117
+ if (dimension === "verification")
12118
+ return ruleId === "pre-pr-cleanup" ? "check or artifact" : "check";
12119
+ if (dimension === "review")
12120
+ return "review";
12121
+ if (dimension === "investigation" || dimension === "challenge")
12122
+ return "investigation";
12123
+ if (dimension === "artifacts" || dimension === "continuity")
12124
+ return "artifact";
12125
+ if (dimension === "decisions")
12126
+ return "decision";
12127
+ return "worker report";
12128
+ };
12129
+ function evaluateRequirements(task, workspace, capabilities, candidate, checkoutRoot, _caller) {
12130
+ const evidence = evaluateEvidence(task, candidate);
12131
+ if (task.policy && task.policy.policyVersion !== POLICY_VERSION)
12132
+ return task.policy.requirements.map((requirement) => ({
12133
+ requirementId: requirement.id,
12134
+ status: "unsatisfied",
12135
+ evidenceIds: [],
12136
+ decisionIds: [],
12137
+ reason: "stored policy version is unsupported; reassessment is required"
12468
12138
  }));
12469
- for (const constraint of input.constraints)
12470
- for (const obligation of constraint.requires) {
12471
- const dimension = obligation.method ?? (obligation.kind === "check" ? "verification" : obligation.kind === "decision" ? "decisions" : "challenge");
12472
- requirements.push(requirement({
12473
- ruleId: `project-constraint:${constraint.id}:${obligation.kind}:${sha256({
12474
- kind: obligation.kind,
12475
- scope: normalizedScope(obligation.scope),
12476
- refs: normalizedRefList(obligation.refs),
12477
- method: obligation.method,
12478
- before: obligation.before,
12479
- dependentAction: obligation.dependentAction
12480
- })}`,
12481
- dimension,
12482
- scope: obligation.scope,
12483
- reason: `${constraint.kind} constraint requires ${obligation.kind}: ${constraint.statement}`,
12484
- satisfaction: `Satisfy the constraint obligation using its referenced ${obligation.kind}.`,
12485
- before: obligation.before,
12486
- dependentAction: obligation.dependentAction,
12487
- acceptanceAllowed: constraint.acceptanceAllowed && obligation.kind !== "decision"
12488
- }));
12139
+ return (task.policy?.requirements ?? []).map((requirement) => {
12140
+ const related = task.evidence.map((entry, index) => ({ entry, evaluation: evidence[index] })).filter(({ entry }) => entry.data.requirementIds.includes(requirement.id));
12141
+ const passed = related.filter(({ entry, evaluation }) => {
12142
+ if (!evidenceMatchesRequirement(evaluation.status, entry.data.kind, requirement.dimension, requirement.ruleId))
12143
+ return false;
12144
+ if ((entry.data.kind === "check" || entry.data.kind === "review") && (!entry.data.beforeCandidateId || !entry.data.candidateId || entry.data.beforeCandidateId !== entry.data.candidateId))
12145
+ return false;
12146
+ if (requirement.dimension !== "review")
12147
+ return true;
12148
+ const reviewSession = sessionFromRef(entry.data.reviewContext);
12149
+ const sameImplementation = sameSession(reviewSession, task.intent.provenance.session);
12150
+ const sameEvidenceSession = related.some(({ entry: other }) => other.id !== entry.id && other.data.kind === "review" && other.data.candidateId !== null && other.data.candidateId === entry.data.candidateId && sameSession(reviewSession, other.provenance.session));
12151
+ return entry.data.kind === "review" && reviewSession !== null && sameSession(reviewSession, entry.provenance.session) && (requirement.ruleId === "self-review" || !sameImplementation && !sameEvidenceSession);
12152
+ });
12153
+ if (passed.length) {
12154
+ const currentId = candidate?.id ?? null;
12155
+ const withRed = requirement.dimension === "testing" ? passed.filter(({ entry }) => related.some((other) => other.entry.data.kind === "check" && other.evaluation.status === "failed" && other.entry.data.requirementIds.includes(requirement.id) && other.entry.recordedAt <= entry.recordedAt) || related.some((baseline) => baseline.entry.id !== entry.id && baseline.entry.data.kind === "check" && baseline.entry.data.result === "passed" && baseline.entry.data.candidateId !== null && currentId !== null && baseline.entry.data.candidateId !== currentId)) : passed;
12156
+ if (withRed.length)
12157
+ return {
12158
+ requirementId: requirement.id,
12159
+ status: "satisfied",
12160
+ evidenceIds: withRed.map(({ entry }) => entry.id),
12161
+ decisionIds: [],
12162
+ reason: "fresh applicable evidence passed"
12163
+ };
12164
+ if (requirement.dimension === "testing")
12165
+ return {
12166
+ requirementId: requirement.id,
12167
+ status: "unsatisfied",
12168
+ evidenceIds: [],
12169
+ decisionIds: [],
12170
+ reason: "testing requirement has GREEN evidence but no preceding RED"
12171
+ };
12172
+ }
12173
+ if (requirement.dimension === "delegation") {
12174
+ const dot = (scope) => scope.paths.length > 0 ? scope : { ...scope, paths: ["."] };
12175
+ const reconciled = task.workers.some((worker) => worker.data.report?.outcome === "completed" && (worker.data.assignment.requirementIds.includes(requirement.id) || scopeCovers2(dot(requirement.scope), dot(worker.data.assignment.scope))));
12176
+ if (reconciled)
12177
+ return {
12178
+ requirementId: requirement.id,
12179
+ status: "satisfied",
12180
+ evidenceIds: [],
12181
+ decisionIds: [],
12182
+ reason: "bounded helper completed and its result is recorded"
12183
+ };
12184
+ }
12185
+ const decisions = requirement.dimension === "decisions" ? applicableRequirementDecision(task, workspace, requirement, checkoutRoot) : [];
12186
+ if (decisions.length)
12187
+ return {
12188
+ requirementId: requirement.id,
12189
+ status: "satisfied",
12190
+ evidenceIds: [],
12191
+ decisionIds: decisions.map((decision) => decision.id),
12192
+ reason: "an applicable approved or stated decision satisfies the requirement"
12193
+ };
12194
+ const limitations = requirement.acceptanceAllowed ? applicableDecision2(task, workspace, requirement, checkoutRoot) : [];
12195
+ if (limitations.length)
12196
+ return {
12197
+ requirementId: requirement.id,
12198
+ status: "accepted_limitation",
12199
+ evidenceIds: [],
12200
+ decisionIds: limitations.map((decision) => task.decisions.find((entry) => entry.data === decision).id),
12201
+ reason: "an applicable approved limitation permits the missing evidence"
12202
+ };
12203
+ const unavailable = capabilities.some((capability) => capability.assurance === "unavailable" && (capability.name === requirement.dimension || capability.surface === requirement.dimension));
12204
+ if (!unavailable && related.length > 0 && !passed.length)
12205
+ return {
12206
+ requirementId: requirement.id,
12207
+ status: "unsatisfied",
12208
+ evidenceIds: related.map(({ entry }) => entry.id),
12209
+ decisionIds: [],
12210
+ reason: `no passing evidence (needs kind:${expectedKinds(requirement.dimension, requirement.ruleId)})`
12211
+ };
12212
+ return {
12213
+ requirementId: requirement.id,
12214
+ status: unavailable ? "unavailable" : "unsatisfied",
12215
+ evidenceIds: related.map(({ entry }) => entry.id),
12216
+ decisionIds: [],
12217
+ reason: unavailable ? "required capability is unavailable" : "no fresh passing evidence"
12218
+ };
12219
+ });
12220
+ }
12221
+ function evaluateClosure(requestedOutcome, view) {
12222
+ if (requestedOutcome !== "stopped" && !view.task.policy)
12223
+ return failure("requirements_unsatisfied", "task has not been assessed");
12224
+ if (view.task.policy && view.task.policy.policyVersion !== POLICY_VERSION)
12225
+ return failure("requirements_unsatisfied", "stored policy version is unsupported; reassessment is required");
12226
+ const evaluations = view.requirements;
12227
+ const openFindings = view.task.findings.filter((entry) => entry.data.disposition === "open");
12228
+ if (requestedOutcome !== "stopped" && openFindings.length)
12229
+ return failure("requirements_unsatisfied", "open findings must be resolved before closure");
12230
+ if (requestedOutcome !== "stopped") {
12231
+ const evidenceById = new Map(view.evidence.map((entry) => [entry.evidenceId, entry.status]));
12232
+ for (const entry of view.task.findings) {
12233
+ if (entry.data.disposition === "fixed") {
12234
+ const verified = entry.data.resolution?.evidenceIds.some((id) => {
12235
+ const evidence = view.task.evidence.find((item) => item.id === id);
12236
+ if (!evidence)
12237
+ return false;
12238
+ return findingVerificationPasses(entry.data.candidateId, {
12239
+ kind: evidence.data.kind,
12240
+ candidateId: evidence.data.candidateId,
12241
+ status: evidenceById.get(id) ?? "missing"
12242
+ });
12243
+ });
12244
+ if (!verified)
12245
+ return failure("requirements_unsatisfied", "fixed findings require current verification");
12246
+ }
12247
+ if (entry.data.disposition === "deferred") {
12248
+ const valid = entry.data.resolution?.decisionIds.some((id) => {
12249
+ const decisionEntry = view.task.decisions.find((item) => item.id === id);
12250
+ const decision = decisionEntry?.data;
12251
+ return Boolean(decision && decisionEntry?.provenance.kind !== "imported" && decision.purpose === "limitation" && decision.response === "approved" && decision.revoked === null && decision.digest === decisionDigest(decision) && verifyDecisionContentAtRoot(view.workspace.root, decision.binding).ok && decision.binding.taskId === view.task.id && decision.binding.workspaceId === view.workspace.id && scopeCovers2(decision.binding.scope, entry.data.scope) && decision.requirementIds.some((requirementId) => view.task.policy?.requirements.some((requirement) => requirement.id === requirementId && requirement.acceptanceAllowed)));
12252
+ });
12253
+ if (!valid)
12254
+ return failure("requirements_unsatisfied", "deferred findings require an approved limitation decision that references an acceptanceAllowed requirement and covers the finding scope");
12255
+ }
12489
12256
  }
12490
- const seen = new Set;
12491
- return requirements.filter((item) => {
12492
- if (seen.has(item.id))
12257
+ }
12258
+ const blocking = evaluations.filter((item) => {
12259
+ if (item.status !== "unsatisfied" && item.status !== "unavailable")
12493
12260
  return false;
12494
- seen.add(item.id);
12495
- return true;
12261
+ const requirement = view.task.policy?.requirements.find((candidate) => candidate.id === item.requirementId);
12262
+ return !requirement || requirement.before === "close";
12263
+ });
12264
+ if (requestedOutcome !== "stopped" && blocking.length)
12265
+ return failure("requirements_unsatisfied", "applicable requirements are unsatisfied", {
12266
+ requirementIds: blocking.map((item) => item.requirementId),
12267
+ requirements: blocking.map((item) => {
12268
+ const requirement = view.task.policy?.requirements.find((candidate) => candidate.id === item.requirementId);
12269
+ return {
12270
+ requirementId: item.requirementId,
12271
+ ruleId: requirement?.ruleId ?? "unknown",
12272
+ reason: item.reason,
12273
+ satisfaction: requirement?.satisfaction ?? "",
12274
+ dependentAction: requirement?.dependentAction ?? null
12275
+ };
12276
+ })
12277
+ });
12278
+ const accepted = evaluations.filter((item) => item.status === "accepted_limitation");
12279
+ if (requestedOutcome === "verified" && accepted.length)
12280
+ return failure("requirements_unsatisfied", "accepted limitations cannot be reported as verified", {
12281
+ requirementIds: accepted.map((item) => item.requirementId)
12282
+ });
12283
+ const evidenceIds = [
12284
+ ...new Set([
12285
+ ...evaluations.flatMap((item) => item.evidenceIds),
12286
+ ...view.task.findings.flatMap((item) => item.data.resolution?.evidenceIds ?? [])
12287
+ ])
12288
+ ];
12289
+ const decisionIds = [
12290
+ ...new Set([
12291
+ ...evaluations.flatMap((item) => item.decisionIds),
12292
+ ...view.task.findings.flatMap((item) => item.data.resolution?.decisionIds ?? [])
12293
+ ])
12294
+ ];
12295
+ return success(null, null, {
12296
+ outcome: requestedOutcome === "stopped" ? "stopped" : accepted.length ? "accepted_limitations" : "verified",
12297
+ evidenceIds,
12298
+ decisionIds,
12299
+ requirementIds: evaluations.map((item) => item.requirementId)
12496
12300
  });
12497
12301
  }
12498
- function resolvePolicy(input) {
12499
- const normalized = normalizeResolverInput(input);
12500
- if (!normalized.ok)
12501
- return normalized;
12502
- const requirements = resolveRequirements(normalized.data);
12503
- const policy = {
12504
- policyVersion: POLICY_VERSION,
12505
- inputDigest: sha256(canonicalJson(normalized.data)),
12506
- requirements
12507
- };
12508
- const parsed = policySchema.safeParse(policy);
12509
- if (!parsed.success)
12510
- return failure("invalid_input", "resolved policy is invalid", invalidFields(parsed.error));
12511
- return success(null, null, parsed.data);
12302
+
12303
+ // packages/workit-core/src/core/methods.ts
12304
+ var METHODS = {
12305
+ "workit-challenge": { dimensions: ["challenge", "decisions"] },
12306
+ "workit-behavioral-tdd": { dimensions: ["testing"], ruleIds: ["mechanical-existing-checks"] },
12307
+ "workit-review": { dimensions: ["review"], ruleIds: ["fresh-context-review", "self-review"] },
12308
+ "workit-plan": { dimensions: ["artifacts", "continuity"] },
12309
+ "workit-implement": { dimensions: ["delegation"] },
12310
+ "workit-debug": {},
12311
+ "workit-handoff": {},
12312
+ "workit-deslop": { ruleIds: ["pre-pr-cleanup"] }
12313
+ };
12314
+ var methodMatches = (definition, requirement) => definition.dimensions?.includes(requirement.dimension) === true || definition.ruleIds?.includes(requirement.ruleId) === true;
12315
+ var assuranceFor = (id, definition, capabilities) => {
12316
+ const keys = new Set([
12317
+ id,
12318
+ ...definition.dimensions ?? [],
12319
+ ...definition.ruleIds ?? []
12320
+ ]);
12321
+ const matches = capabilities.filter((capability) => keys.has(capability.name) || keys.has(capability.surface));
12322
+ if (id === "workit-review" && matches.length === 0)
12323
+ return { assurance: "unavailable", reasons: ["independent review capability is unavailable"] };
12324
+ if (matches.some((capability) => capability.assurance === "unavailable"))
12325
+ return {
12326
+ assurance: "unavailable",
12327
+ reasons: matches.filter((capability) => capability.assurance === "unavailable").map((capability) => capability.reason)
12328
+ };
12329
+ if (matches.some((capability) => capability.assurance === "enforced"))
12330
+ return { assurance: "enforced", reasons: matches.map((capability) => capability.reason) };
12331
+ return { assurance: "agent_guided", reasons: matches.map((capability) => capability.reason) };
12332
+ };
12333
+ function selectMethods(policy, capabilities) {
12334
+ return Object.entries(METHODS).flatMap(([id, definition]) => {
12335
+ const requirements = policy.requirements.filter((requirement) => methodMatches(definition, requirement));
12336
+ if (requirements.length === 0)
12337
+ return [];
12338
+ const capability = assuranceFor(id, definition, capabilities);
12339
+ const reasons = [
12340
+ ...new Set(requirements.map((requirement) => requirement.reason)),
12341
+ ...capability.reasons
12342
+ ];
12343
+ if (capability.assurance === "unavailable")
12344
+ reasons.unshift("required capability is unavailable");
12345
+ return [{ id, reason: reasons.join("; "), assurance: capability.assurance }];
12346
+ });
12347
+ }
12348
+ var invariantBootstrap = () => `
12349
+ Workit is optional coordination and repository-policy tooling around the host,
12350
+ not a permission system or a mandatory workflow. Native host allow/ask/deny,
12351
+ sandbox, plan/read-only mode, and organization rules remain authoritative.
12352
+ Ordinary investigation, questions, non-Git work, and routine reversible edits
12353
+ need zero Workit task, assessment, or writer calls. Use one compact tracked
12354
+ record only when handoff, dependent steps, concurrent actors, or meaningful
12355
+ decisions make continuity useful; similar titles alone never merge tasks.
12356
+
12357
+ For a routine user-authorized branch or commit, prefer native host Git/shell
12358
+ tools from the outset when managed coordination or outcome reconciliation is
12359
+ not needed. Inspect the actual target checkout and its configured conventions;
12360
+ use Workit's read-only context/policy tools when needed. Do not start a task,
12361
+ acquire a writer, or mint a decision receipt solely for a native Git action.
12362
+ Native permissions still apply. Never switch execution paths to evade a denial
12363
+ or repeat an uncertain managed effect. A local-commit endpoint does not imply
12364
+ PR readiness, a fresh review, or post-commit assessment/closure paperwork.
12365
+
12366
+ For tracked work, inspect its current state and use the shared operations for
12367
+ task, policy, evidence, finding, decision, worker, writer, and state changes.
12368
+ Start a record once for an explicit tracked objective; assess or reassess only
12369
+ when policy selection or changed evidence/constraints requires it. Omitted
12370
+ expectedRevision and expectedWorkspaceRevision use current values; explicit
12371
+ values are still concurrency-checked, so never copy revisions between calls.
12372
+ A solo edit does not need writer acquisition; use it when concurrent checkout
12373
+ writers need coordination. Record only observed facts and checks. Evidence can
12374
+ become stale when its bound candidate changes; reconcile findings against the
12375
+ current candidate before recording completion.
12376
+
12377
+ Workit validates domain policy against the actual action target, configured
12378
+ account, branch and commit conventions, protected refs, and current repository
12379
+ state. The task directory is coordination state, not a boundary on which
12380
+ repository may be changed. Use an action-time cwd target where a managed
12381
+ Git/hosting action supports it; a non-Git directory remains valid for OS work.
12382
+ GitHub/GitLab use the active gh/glab CLI identity; YouTrack uses its own token.
12383
+ Preserve uncertain external outcomes and reconcile repository/provider state
12384
+ before retrying. Internal reservations prevent duplicate or ambiguous effects;
12385
+ they are not permission tickets for every edit.
12386
+
12387
+ On OpenCode V1 and V2, use native host tools for external mutations. Workit
12388
+ provides read-only workit_context; it has no managed external-action executor.
12389
+ Do not create proposals or request Workit approvals merely to invoke native
12390
+ tools. Old uncertain managed effects still require evidence before any retry.
12391
+
12392
+ Use host-native authorization through the host's supported path. A native
12393
+ question receipt records an actual question interaction; it is not automatic
12394
+ host permission. Record a meaningful user choice once with provenance when
12395
+ future retrieval helps. Never fabricate a receipt, re-ask only to mint one, or
12396
+ let imported decisions grant authority. Never turn a host deny into allow or
12397
+ claim enforcement/evidence a host cannot provide. A precise request with settled
12398
+ constraints does not need an interview. Present genuine unresolved options with
12399
+ evidence and a recommendation, then continue toward the requested delivery
12400
+ endpoint: investigation, implementation, branch/commit/push, PR/MR-ready,
12401
+ merge, or release. Run
12402
+ applicable checks and safe repairs without repeated continuation questions;
12403
+ stop for missing host authority, a new consequential choice, a conflicting edit,
12404
+ or an unresolved blocker. A tracked record may close when actual evidence
12405
+ supports its outcome; no final human closure ceremony is required.
12406
+
12407
+ A completed native subagent run stops its bound worker by itself; if a worker
12408
+ strands in cancelling with its run verifiably over, repeat worker.cancel to
12409
+ confirm the stop. Preserve unresolved requirements, gaps, and uncertain workers.
12410
+ When context changes, distinguish a quick question, same-task adjustment, and
12411
+ separate request. Answer a quick question without pausing/resuming task state;
12412
+ park a concise checkpoint only when substantial work needs to continue later.
12413
+ For work spanning repositories, bind each unfinished item to its actual checkout,
12414
+ branch, requested deliverables, and delivery endpoint. Preserve held items with
12415
+ an explicit resume condition. Resolve competing plausible targets before a
12416
+ mutation; ask only when available context cannot settle that consequential choice.
12417
+ Before reporting delivery, reconcile every requested item and observe the actual
12418
+ target result; a local commit alone is not evidence of a requested remote push.
12419
+
12420
+ Skill routing: slash aliases /wk-* load on demand. Use workit-steer for a
12421
+ substantial interruption or change of direction, workit-deslop when relevant
12422
+ to a PR-ready endpoint, workit-green-run for failing CI, workit-blast-radius
12423
+ when impact is uncertain, and workit-challenge for genuinely open consequential
12424
+ choices. Load workit-plan when dependencies or handoff need durable next actions.
12425
+ Load the skill; never act from memory of it.
12426
+ `.trim();
12427
+
12428
+ // packages/workit-core/src/core/task-context.ts
12429
+ function reconcileResume(view, observations = []) {
12430
+ if (observations.length > 0)
12431
+ return failure("permission_denied", "worker observations require native host verification");
12432
+ const candidate = captureCandidate(view.workspace.root, view.task.intent.data.scope, []);
12433
+ if (!candidate.ok)
12434
+ return candidate;
12435
+ const staleEvidenceIds = evaluateEvidence(view.task, candidate.data).filter((entry) => entry.status === "stale").map((entry) => entry.evidenceId);
12436
+ const blockers = [...view.task.progress.blockers];
12437
+ if (view.task.workers.some((entry) => isUncertainWorker(entry.data.state)))
12438
+ blockers.push({
12439
+ reason: "worker state requires reconciliation",
12440
+ dependentAction: "resume",
12441
+ refs: []
12442
+ });
12443
+ return success(null, null, {
12444
+ candidate: candidate.data,
12445
+ staleEvidenceIds,
12446
+ workerUpdates: [],
12447
+ blockers,
12448
+ reassessmentRequired: view.task.policy?.policyVersion !== POLICY_VERSION
12449
+ });
12512
12450
  }
12513
- function diffPolicy(previous, next, reason, now) {
12514
- if (!policySchema.safeParse(previous).success && previous !== null)
12515
- throw new TypeError("previous policy is invalid");
12516
- if (!policySchema.safeParse(next).success)
12517
- throw new TypeError("next policy is invalid");
12518
- const oldIds = new Set(previous?.requirements.map((requirement) => requirement.id) ?? []);
12519
- const newIds = new Set(next.requirements.map((requirement) => requirement.id));
12520
- const added = [...newIds].filter((id) => !oldIds.has(id)).sort(compareCodeUnits3);
12521
- const retired = [...oldIds].filter((id) => !newIds.has(id)).sort(compareCodeUnits3);
12522
- if (added.length === 0 && retired.length === 0)
12523
- return null;
12524
- const normalizedReason = reason.trim();
12525
- const changeReason = retired.length ? `${normalizedReason || "policy reassessed"} (retired: ${retired.join(",")})` : normalizedReason || "policy reassessed";
12526
- const change = {
12527
- recordedAt: now,
12528
- fromInputDigest: previous?.inputDigest ?? null,
12529
- toInputDigest: next.inputDigest,
12530
- added,
12531
- retired,
12532
- reason: changeReason
12451
+ var COMPACT_MAX_BYTES = 4096;
12452
+ var COMPACT_MAX_ITEMS = 8;
12453
+ var COMPACT_TEXT_BYTES = 128;
12454
+ var sensitiveUrl = /\bhttps?:\/\/[^/\s:@]+:[^@\s]+@/gi;
12455
+ var sensitiveValue = /(?:token|secret|password|passwd|api[-_ ]?key|private[-_ ]?key|authorization)\s*[:=]\s*(?:bearer\s+)?\S+|\bbearer\s+\S+/gi;
12456
+ var privateKey = /-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/gi;
12457
+ var compactText = (value, limit) => value === null ? null : value.replace(privateKey, "<redacted-private-key>").replace(sensitiveUrl, "<redacted-url>").replace(sensitiveValue, (match) => {
12458
+ const separator = match.search(/[:=]/u);
12459
+ if (separator >= 0)
12460
+ return `${match.slice(0, separator)}=<redacted>`;
12461
+ const space = match.search(/\s/u);
12462
+ return `${match.slice(0, space)} <redacted>`;
12463
+ }).slice(0, limit);
12464
+ var compactBytes = (value) => new TextEncoder().encode(value).byteLength;
12465
+ var compactTimestamp = (value) => `${value.slice(0, 19)}.${value.slice(20, -1).padEnd(9, "0")}`;
12466
+ var compactDecisionChoice = (entry) => {
12467
+ const stated = entry.data.binding.statedChoice?.text;
12468
+ const approved = entry.data.response === "approved" ? entry.data.binding.approvedContent : "";
12469
+ const source = stated?.trim() || approved.trim() || null;
12470
+ return compactText(source, COMPACT_TEXT_BYTES);
12471
+ };
12472
+ var compactReference = (ref) => {
12473
+ if (ref.kind === "file")
12474
+ return {
12475
+ kind: "file",
12476
+ path: compactText(ref.path, COMPACT_TEXT_BYTES) ?? ""
12477
+ };
12478
+ if (ref.kind === "record")
12479
+ return {
12480
+ kind: "record",
12481
+ collection: ref.collection,
12482
+ id: ref.id
12483
+ };
12484
+ return { kind: ref.kind };
12485
+ };
12486
+ function compactTaskContext(view) {
12487
+ const decisions = view.task.decisions.slice().sort((left, right) => {
12488
+ const leftAt = compactTimestamp(left.recordedAt);
12489
+ const rightAt = compactTimestamp(right.recordedAt);
12490
+ if (leftAt !== rightAt)
12491
+ return leftAt > rightAt ? -1 : 1;
12492
+ return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;
12493
+ }).slice(0, COMPACT_MAX_ITEMS).map((entry) => ({
12494
+ id: entry.id,
12495
+ purpose: entry.data.purpose,
12496
+ status: entry.data.response,
12497
+ digest: entry.data.digest,
12498
+ choice: compactDecisionChoice(entry) || `task.inspect taskId=${view.task.id} view=full; decision=${entry.id}`,
12499
+ references: entry.data.binding.contentRefs.slice(0, 1).map(compactReference)
12500
+ }));
12501
+ const methods = view.task.policy ? selectMethods(view.task.policy, view.capabilities).map((method) => ({
12502
+ id: method.id,
12503
+ assurance: method.assurance,
12504
+ reason: compactText(method.reason, COMPACT_TEXT_BYTES) ?? ""
12505
+ })) : [];
12506
+ const gaps = Array.from(new Set([
12507
+ ...view.evidence.filter((entry) => entry.status === "stale").map((entry) => `stale evidence: ${entry.evidenceId}`),
12508
+ ...view.requirements.filter((entry) => entry.status !== "satisfied").map((entry) => entry.reason),
12509
+ ...view.task.progress.blockers.map((entry) => entry.reason)
12510
+ ])).sort().slice(0, COMPACT_MAX_ITEMS).map((gap) => compactText(gap, COMPACT_TEXT_BYTES));
12511
+ const context = {
12512
+ objective: compactText(view.task.intent.data.objective, COMPACT_TEXT_BYTES) ?? "",
12513
+ status: view.task.status,
12514
+ decisions,
12515
+ methods,
12516
+ gaps,
12517
+ nextAction: compactText(view.task.progress.nextAction, COMPACT_TEXT_BYTES)
12533
12518
  };
12534
- const parsed = policyChangeSchema.safeParse(change);
12535
- if (!parsed.success)
12536
- throw new TypeError("policy change is invalid");
12537
- return parsed.data;
12519
+ let encoded = JSON.stringify(context);
12520
+ while (compactBytes(encoded) > COMPACT_MAX_BYTES && (context.decisions.length || context.methods.length || context.gaps.length)) {
12521
+ if (context.gaps.length)
12522
+ context.gaps.pop();
12523
+ else if (context.decisions.length)
12524
+ context.decisions.pop();
12525
+ else
12526
+ context.methods.pop();
12527
+ encoded = JSON.stringify(context);
12528
+ }
12529
+ if (compactBytes(encoded) > COMPACT_MAX_BYTES) {
12530
+ context.objective = compactText(context.objective, 64) ?? "";
12531
+ context.nextAction = compactText(context.nextAction, 64);
12532
+ encoded = JSON.stringify(context);
12533
+ }
12534
+ return encoded;
12538
12535
  }
12536
+ var exportDigest = (bundle) => sha256({
12537
+ schemaVersion: bundle.schemaVersion,
12538
+ exportedAt: bundle.exportedAt,
12539
+ sourceWorkspaceId: bundle.sourceWorkspaceId,
12540
+ task: bundle.task
12541
+ });
12539
12542
 
12540
12543
  // packages/workit-core/src/core/task-engine.ts
12541
12544
  var provenance = (context, kind = context.provenanceKind ?? "host_observed") => ({
@@ -14223,14 +14226,29 @@ class WorkitCore {
14223
14226
  writer: evaluationWorkspace.writer
14224
14227
  });
14225
14228
  }
14226
- view(task) {
14229
+ compactContext(taskId) {
14230
+ const root = this.contextRootError();
14231
+ if (!root.ok)
14232
+ return root;
14233
+ const task = this.store.readTask(taskId);
14234
+ if (!task.ok)
14235
+ return task;
14236
+ const helper = this.helperTaskGuard(task.data, true);
14237
+ if (!helper.ok)
14238
+ return helper;
14239
+ const view = this.view(task.data, false);
14240
+ if (!view.ok)
14241
+ return view;
14242
+ return success(view.revision, view.workspaceRevision, compactTaskContext(view.data));
14243
+ }
14244
+ view(task, capture = true) {
14227
14245
  const workspace = this.store.readWorkspace();
14228
14246
  if (!workspace.ok)
14229
14247
  return workspace;
14230
14248
  if (!workspace.data)
14231
14249
  return failure("not_found", "workspace not found");
14232
14250
  const historical = task.status === "closed" ? task.candidates.at(-1) : undefined;
14233
- const current = historical ? success(null, null, historical) : captureCandidate(this.store.root, task.intent.data.scope, environment());
14251
+ const current = historical ? success(null, null, historical) : capture ? captureCandidate(this.store.root, task.intent.data.scope, environment()) : success(null, null, task.candidates.at(-1) ?? null);
14234
14252
  if (!current.ok)
14235
14253
  return current;
14236
14254
  const evaluationWorkspace = task.status === "closed" ? { ...workspace.data, writer: null } : workspace.data;
@@ -14502,6 +14520,137 @@ class WorkitCore {
14502
14520
  return this.summary(changed.data.task);
14503
14521
  }
14504
14522
  }
14523
+
14524
+ // packages/workit-core/src/core/session-context.ts
14525
+ var cache = new Map;
14526
+ // packages/workit-core/src/core/route-intent.ts
14527
+ var shellBranchTarget = (command) => {
14528
+ if (!command.trim() || /[\r\n;&|<>`'"$()\\*?{}~!#]/u.test(command) || command.includes("[") || command.includes("]"))
14529
+ return null;
14530
+ const args = command.trim().split(/\s+/u);
14531
+ if (args[0] !== "git")
14532
+ return null;
14533
+ const option = args[2];
14534
+ const target = args[1] === "switch" && ["-c", "--create", "-C", "--force-create"].includes(option ?? "") && (args.length === 4 || args.length === 5) ? args[3] : args[1] === "checkout" && ["-b", "-B"].includes(option ?? "") && (args.length === 4 || args.length === 5) ? args[3] : args[1] === "branch" && (args.length === 3 || args.length === 4) ? args[2] : null;
14535
+ return target && !target.startsWith("-") ? target : null;
14536
+ };
14537
+ var shellBranchPolicyViolation = (root, command) => {
14538
+ const target = shellBranchTarget(command);
14539
+ return target === null ? null : validateBranchNameFor(root, target);
14540
+ };
14541
+ // packages/workit-core/src/core/external-action.ts
14542
+ var chainStepSchema = union([
14543
+ string2().min(1),
14544
+ object({ branch: string2().min(1) }).strict(),
14545
+ object({ pr: literal(true) }).strict()
14546
+ ]);
14547
+ var externalActionSchema = discriminatedUnion("operation", [
14548
+ object({
14549
+ operation: literal("git.branch_setup"),
14550
+ payload: object({
14551
+ action: _enum(["setup", "reapply_stash"]).optional(),
14552
+ sdd_dir: string2().optional(),
14553
+ target_branch: string2().optional(),
14554
+ stash: _enum(["yes", "no"]).optional(),
14555
+ cwd: string2().min(1).optional()
14556
+ }).strict()
14557
+ }).strict(),
14558
+ object({
14559
+ operation: literal("git.commit"),
14560
+ payload: object({
14561
+ message: string2().min(1).optional(),
14562
+ plan_steps: array(chainStepSchema).min(1).max(32).optional(),
14563
+ plan_branch: string2().min(1).optional(),
14564
+ cwd: string2().min(1).optional()
14565
+ }).strict()
14566
+ }).strict(),
14567
+ object({
14568
+ operation: literal("git.push"),
14569
+ payload: object({ branch: string2().min(1).optional(), cwd: string2().min(1).optional() }).strict()
14570
+ }).strict(),
14571
+ object({
14572
+ operation: literal("hosting.pull_request"),
14573
+ payload: object({
14574
+ title: string2().min(1),
14575
+ body: string2().optional(),
14576
+ draft: boolean2().optional(),
14577
+ target_branch: string2().optional(),
14578
+ babysit: boolean2().optional(),
14579
+ cwd: string2().min(1).optional()
14580
+ }).strict()
14581
+ }).strict(),
14582
+ object({
14583
+ operation: literal("hosting.merge"),
14584
+ payload: object({
14585
+ target_branch: string2().min(1).optional(),
14586
+ source_branch: string2().min(1).optional(),
14587
+ cwd: string2().min(1).optional()
14588
+ }).strict()
14589
+ }).strict(),
14590
+ object({
14591
+ operation: literal("hosting.delete_branch"),
14592
+ payload: object({ branch: string2().min(1), cwd: string2().min(1).optional() }).strict()
14593
+ }).strict(),
14594
+ object({
14595
+ operation: literal("youtrack.update"),
14596
+ payload: object({
14597
+ issueId: string2().min(1),
14598
+ markdown: string2().min(1),
14599
+ minutes: number2().positive().optional()
14600
+ }).strict()
14601
+ }).strict(),
14602
+ object({
14603
+ operation: literal("youtrack.time"),
14604
+ payload: object({
14605
+ issueId: string2().min(1),
14606
+ minutes: number2().positive(),
14607
+ text: string2().optional(),
14608
+ dateMs: number2().finite().optional()
14609
+ }).strict()
14610
+ }).strict(),
14611
+ object({
14612
+ operation: literal("youtrack.meeting"),
14613
+ payload: object({
14614
+ issueId: string2().min(1),
14615
+ minutes: number2().positive(),
14616
+ text: string2().min(1)
14617
+ }).strict()
14618
+ }).strict(),
14619
+ object({
14620
+ operation: literal("changelog.apply"),
14621
+ payload: object({
14622
+ entries: union([
14623
+ record(string2(), array(string2())),
14624
+ array(object({ category: string2().min(1), text: string2().min(1) }).strict())
14625
+ ]).optional(),
14626
+ path: string2().optional(),
14627
+ normalize_only: boolean2().optional()
14628
+ }).strict()
14629
+ }).strict(),
14630
+ object({
14631
+ operation: literal("context.read"),
14632
+ payload: object({
14633
+ kind: _enum([
14634
+ "git",
14635
+ "pr",
14636
+ "youtrack",
14637
+ "github_issue",
14638
+ "gitlab_issue",
14639
+ "changelog",
14640
+ "release",
14641
+ "affected"
14642
+ ]),
14643
+ range: string2().optional(),
14644
+ issueId: string2().optional(),
14645
+ issueUrl: string2().optional(),
14646
+ issueRef: string2().optional(),
14647
+ mode: string2().optional(),
14648
+ specPath: string2().optional(),
14649
+ planPath: string2().optional(),
14650
+ cwd: string2().min(1).optional()
14651
+ }).strict()
14652
+ }).strict()
14653
+ ]);
14505
14654
  // packages/workit-codex/hooks/workit-hook.ts
14506
14655
  var ref = (host, handle) => ({ kind: "host", host, handle });
14507
14656
  function detectCodexSurface(env) {
@@ -14705,7 +14854,7 @@ var activeTask = (store) => {
14705
14854
  return { ok: true, task: active[0], workspace: workspace.data };
14706
14855
  };
14707
14856
  var historyOfferSessions = new Set;
14708
- var unfinishedTaskOffer = (input, excludedTaskId) => {
14857
+ var unfinishedTaskOffer2 = (input, excludedTaskId) => {
14709
14858
  if (input.source !== "startup" || historyOfferSessions.has(input.session_id))
14710
14859
  return null;
14711
14860
  historyOfferSessions.add(input.session_id);
@@ -14740,21 +14889,16 @@ var sessionContext = (input) => {
14740
14889
  capabilities: codexCapabilities(detectCodexSurface(process.env), { sessionStart: true }),
14741
14890
  constraints: [],
14742
14891
  now: new Date().toISOString().replace(/\.\d{3}Z$/, "Z")
14743
- }).task({
14744
- schemaVersion: 1,
14745
- action: "inspect",
14746
- taskId: state.task.id,
14747
- view: "full"
14748
- });
14892
+ }).compactContext(state.task.id);
14749
14893
  if (view.ok)
14750
14894
  compact = `
14751
- <workit-task-context>${compactTaskContext(view.data)}</workit-task-context>`;
14895
+ <workit-task-context>${view.data}</workit-task-context>`;
14752
14896
  }
14753
14897
  } catch {
14754
14898
  compact = `
14755
14899
  [workit diagnostic: task state unavailable]`;
14756
14900
  }
14757
- const offer = unfinishedTaskOffer(input, currentTaskId);
14901
+ const offer = unfinishedTaskOffer2(input, currentTaskId);
14758
14902
  return `<workit-contract>
14759
14903
  ${invariantBootstrap()}${compact}${offer ? `
14760
14904
  ${offer}` : ""}