@brainervirus/workit-cursor 2.1.1 → 2.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 createHash6 } 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 createHash5 } from "node:crypto";
@@ -10597,6 +10668,66 @@ var verifyPushIdentity = (root, provider, account) => {
10597
10668
  return { ok: true };
10598
10669
  };
10599
10670
 
10671
+ // packages/workit-core/src/core/workers.ts
10672
+ var same = (left, right) => {
10673
+ try {
10674
+ return canonicalJson(left) === canonicalJson(right);
10675
+ } catch {
10676
+ return false;
10677
+ }
10678
+ };
10679
+ var UNCERTAIN_WORKER_STATES = ["dispatching", "running", "cancelling", "unknown"];
10680
+ var isUncertainWorker = (state) => UNCERTAIN_WORKER_STATES.includes(state);
10681
+ var workerBlocksTransition = (transition, state) => transition === "pause" ? false : isUncertainWorker(state);
10682
+ var callerSession = (caller) => caller.session ?? { kind: "host", host: caller.host, handle: caller.actor };
10683
+ var validPath = (value) => typeof value === "string" && value.length > 0 && ![...value].some((char) => {
10684
+ const code = char.charCodeAt(0);
10685
+ return code < 32 || code === 127;
10686
+ }) && !value.split(/[\\/]/).includes("..");
10687
+ var callerValue = (value) => ({ host: value.host, actor: value.actor });
10688
+ var workerIdOf = (value) => value.workerId ?? null;
10689
+ var currentWriterOwnsTask = (task, workspace, caller) => {
10690
+ const owner = workspace.writer?.owner;
10691
+ return task.status === "active" && task.workspaceId === workspace.id && owner?.taskId === task.id && owner.session.host === caller.host && owner.session.handle === caller.actor;
10692
+ };
10693
+ function assertProductWriteAllowed(input) {
10694
+ if (!Array.isArray(input.paths) || input.paths.some((path) => !validPath(path)))
10695
+ return failure("invalid_input", "invalid product write path");
10696
+ if (!input.store)
10697
+ return failure("permission_denied", "write authorization requires core state");
10698
+ const task = input.store.readTask(input.task.id);
10699
+ if (!task.ok)
10700
+ return task;
10701
+ const workspace = input.store.readWorkspace();
10702
+ if (!workspace.ok)
10703
+ return workspace;
10704
+ if (!workspace.data)
10705
+ return failure("not_found", "workspace not found");
10706
+ const workspaceRecord = workspace.data;
10707
+ if (task.data.status !== "active")
10708
+ return failure("invalid_transition", "paused or closed tasks cannot own product writes");
10709
+ if (workspaceRecord.id !== task.data.workspaceId || workspaceRecord.root.length === 0)
10710
+ return failure("recovery_required", "task and workspace bindings are invalid");
10711
+ const writer = workspaceRecord.writer;
10712
+ if (!writer)
10713
+ return failure("permission_denied", "checkout has no writer owner");
10714
+ if (writer.state === "uncertain")
10715
+ return failure("recovery_required", "checkout writer requires recovery", {
10716
+ owner: writer.owner
10717
+ });
10718
+ const caller = callerValue(input.caller);
10719
+ const workerId = workerIdOf(input.caller);
10720
+ const owner = writer.owner;
10721
+ if (owner.taskId !== task.data.id || owner.workerId !== workerId || owner.session.host !== caller.host || owner.session.handle !== caller.actor)
10722
+ return failure("writer_conflict", "checkout is owned by another validated actor", { owner });
10723
+ const worker = workerId === null ? null : task.data.workers.find((entry) => entry.id === workerId);
10724
+ if (workerId !== null && (!worker || worker.data.assignment.role !== "implementer"))
10725
+ return failure("permission_denied", "only implementers can own product writes");
10726
+ 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))))
10727
+ return failure("recovery_required", "worker session is not an active writer");
10728
+ return success(null, workspaceRecord.revision, owner);
10729
+ }
10730
+
10600
10731
  // packages/workit-core/src/core/auto-approval.ts
10601
10732
  var AUTO_CLASSES = ["branch", "commit", "push", "pr", "merge"];
10602
10733
  var OPERATION_CLASS = {
@@ -11287,41 +11418,18 @@ function reconcileAction(input) {
11287
11418
  var bindingCovers = scopeCovers;
11288
11419
  var verifyDecisionContent = verifyContentRefs;
11289
11420
 
11290
- // packages/workit-core/src/core/task-evaluation.ts
11291
- var digestBytes3 = (value) => createHash6("sha256").update(value).digest("hex");
11292
- var inside = (root, candidate) => candidate === root || candidate.startsWith(`${root}${path10.sep}`);
11293
- var relative = (root, candidate) => path10.relative(root, candidate).split(path10.sep).join("/") || ".";
11294
- var canonicalPath = (value) => {
11295
- if (typeof value !== "string" || !value)
11296
- return null;
11297
- if (value.includes("\\") || value.split("/").includes(".."))
11298
- return null;
11299
- const normalized = path10.posix.normalize(value);
11300
- if (normalized === ".." || normalized.startsWith("../") || normalized.startsWith("/"))
11301
- return null;
11302
- return normalized === "." ? "." : normalized.replace(/\/$/, "");
11303
- };
11304
- var canonicalScope = (scope) => {
11305
- const paths = scope.paths.length ? scope.paths : ["."];
11306
- const normalizedPaths = paths.map(canonicalPath);
11307
- const normalizedExclusions = scope.exclusions.map(canonicalPath);
11308
- if (normalizedPaths.some((value) => value === null) || normalizedExclusions.some((value) => value === null))
11309
- return null;
11310
- return {
11311
- description: scope.description,
11312
- paths: [...new Set(normalizedPaths)],
11313
- exclusions: [...new Set(normalizedExclusions)]
11314
- };
11315
- };
11316
- var excluded = (value, exclusions) => exclusions.some((item) => item === value || item !== "." && value.startsWith(`${item}/`));
11317
- var scopeMatches = (value, scope) => {
11318
- const normalized = canonicalScope(scope);
11319
- if (!normalized)
11320
- return false;
11321
- const paths = normalized.paths;
11322
- return paths.some((item) => item === "." || value === item || value.startsWith(`${item}/`)) && !excluded(value, normalized.exclusions);
11323
- };
11324
- var pathRelevant = (value, scope) => scopeMatches(value, scope);
11421
+ // packages/workit-core/src/core/policy-resolver.ts
11422
+ var resolverInputSchema = object({
11423
+ intent: intentSchema,
11424
+ assessment: assessmentSchema,
11425
+ constraints: array(constraintSchema),
11426
+ prior: object({
11427
+ decisions: array(decisionSchema),
11428
+ findings: array(findingSchema),
11429
+ requirements: array(requirementSchema)
11430
+ }).strict(),
11431
+ preferences: object({ fast: boolean2().optional(), thorough: boolean2().optional() }).strict().optional()
11432
+ }).strict();
11325
11433
  var compareCodeUnits2 = (left, right) => {
11326
11434
  const length = Math.min(left.length, right.length);
11327
11435
  for (let index = 0;index < length; index += 1) {
@@ -11331,1137 +11439,1049 @@ var compareCodeUnits2 = (left, right) => {
11331
11439
  }
11332
11440
  return left.length - right.length;
11333
11441
  };
11334
- var gitPaths = (root) => {
11335
- const result = spawnSync2("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
11336
- cwd: root,
11337
- encoding: "buffer"
11338
- });
11339
- if (result.status !== 0) {
11340
- const stderr = result.stderr?.toString("utf8") ?? "";
11341
- return {
11342
- paths: [],
11343
- uncertain: !/not a git repository/i.test(stderr),
11344
- git: /not a git repository/i.test(stderr) ? false : true
11345
- };
11346
- }
11347
- const paths = result.stdout ? result.stdout.toString("utf8").split("\x00").filter(Boolean).map((item) => item.split(path10.sep).join("/")) : [];
11348
- const stagedDeleted = spawnSync2("git", ["diff", "--cached", "--name-only", "--diff-filter=D", "-z"], { cwd: root, encoding: "buffer" });
11349
- if (stagedDeleted.status !== 0) {
11350
- const stderr = stagedDeleted.stderr?.toString("utf8") ?? "";
11351
- if (!/not a git repository/i.test(stderr))
11352
- return { paths, uncertain: true, git: true };
11353
- } else if (stagedDeleted.stdout) {
11354
- paths.push(...stagedDeleted.stdout.toString("utf8").split("\x00").filter(Boolean).map((item) => item.split(path10.sep).join("/")));
11355
- }
11356
- return { paths: [...new Set(paths)], uncertain: false, git: true };
11357
- };
11358
- var walk = (root, directory, output) => {
11359
- let names;
11360
- try {
11361
- names = fs7.readdirSync(directory);
11362
- } catch {
11363
- return true;
11364
- }
11365
- let uncertain = false;
11366
- for (const name of names) {
11367
- if (name === ".git" || name === ".workit")
11368
- continue;
11369
- const target = path10.join(directory, name);
11370
- let stat;
11371
- try {
11372
- stat = fs7.lstatSync(target);
11373
- } catch {
11374
- uncertain = true;
11375
- continue;
11376
- }
11377
- const item = relative(root, target);
11378
- output.add(item);
11379
- if (stat.isDirectory() && !stat.isSymbolicLink())
11380
- uncertain = walk(root, target, output) || uncertain;
11381
- }
11382
- return uncertain;
11383
- };
11384
- var scopeRoots = (root, scope) => {
11385
- const roots = [];
11386
- for (const item of scope.paths.length ? scope.paths : ["."]) {
11387
- const target = path10.resolve(root, item);
11388
- if (!inside(root, target))
11389
- 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` }] });
11390
- let ancestor = target;
11391
- while (!fs7.existsSync(ancestor) && ancestor !== root)
11392
- ancestor = path10.dirname(ancestor);
11393
- try {
11394
- if (!inside(root, fs7.realpathSync(ancestor)))
11395
- 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` }] });
11396
- } catch {
11397
- return failure("invalid_input", `candidate scope cannot be inspected: ${item}`);
11398
- }
11399
- roots.push(target);
11400
- }
11401
- return success(null, null, roots);
11402
- };
11403
- function captureCandidate(root, scope, environment = []) {
11404
- let checkout;
11405
- try {
11406
- checkout = fs7.realpathSync(root);
11407
- } catch {
11408
- return failure("invalid_input", "candidate root does not exist");
11409
- }
11410
- const normalizedScope = canonicalScope(scope);
11411
- if (!normalizedScope)
11412
- 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" }] });
11413
- const roots = scopeRoots(checkout, normalizedScope);
11414
- if (!roots.ok)
11415
- return roots;
11416
- const git = gitPaths(checkout);
11417
- const names = new Set;
11418
- let uncertain = git.uncertain;
11419
- for (const target of roots.data) {
11420
- const item = relative(checkout, target);
11421
- if (item === ".git" || item === ".workit")
11422
- continue;
11423
- names.add(item);
11424
- if (!fs7.existsSync(target))
11425
- continue;
11426
- let stat;
11427
- try {
11428
- stat = fs7.lstatSync(target);
11429
- } catch {
11430
- uncertain = true;
11431
- continue;
11432
- }
11433
- if (!git.git && stat.isDirectory() && !stat.isSymbolicLink())
11434
- uncertain = walk(checkout, target, names) || uncertain;
11435
- }
11436
- for (const item of git.paths)
11437
- if (scopeMatches(item, normalizedScope))
11438
- names.add(item);
11439
- const files = [];
11440
- let completeness = uncertain ? "uncertain" : "known";
11441
- for (const item of [...names].sort()) {
11442
- if (!scopeMatches(item, normalizedScope))
11443
- continue;
11444
- const target = path10.join(checkout, item);
11445
- try {
11446
- const stat = fs7.lstatSync(target);
11447
- if (stat.isSymbolicLink()) {
11448
- const link = fs7.readlinkSync(target);
11449
- files.push({ path: item, kind: "symlink", digest: digestBytes3(link), executable: null });
11450
- } else if (stat.isFile()) {
11451
- files.push({
11452
- path: item,
11453
- kind: "file",
11454
- digest: digestBytes3(fs7.readFileSync(target)),
11455
- executable: (stat.mode & 73) !== 0
11456
- });
11457
- } else if (!stat.isDirectory()) {
11458
- completeness = "uncertain";
11459
- } else if (git.git && git.paths.includes(item)) {
11460
- completeness = "uncertain";
11461
- }
11462
- } catch (error) {
11463
- if (error?.code === "ENOENT") {
11464
- files.push({ path: item, kind: "absent", digest: null, executable: null });
11465
- } else
11466
- completeness = "uncertain";
11467
- }
11468
- }
11469
- 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) => ({
11442
+ var stableUnique = (values) => [...new Set(values)].sort(compareCodeUnits2);
11443
+ var stableList = (values) => [...values].sort((left, right) => compareCodeUnits2(canonicalJson(left), canonicalJson(right)));
11444
+ var normalizedScope = (scope) => ({
11445
+ description: scope.description,
11446
+ paths: stableUnique(scope.paths),
11447
+ exclusions: stableUnique(scope.exclusions)
11448
+ });
11449
+ var normalizedRefList = (values) => stableList(values);
11450
+ var normalizeAssessment = (assessment) => ({
11451
+ facts: stableList(assessment.facts.map((fact) => ({ ...fact, refs: normalizedRefList(fact.refs) }))),
11452
+ signals: Object.fromEntries(Object.entries(assessment.signals).map(([name, signal]) => [
11470
11453
  name,
11471
- value: environment[name] ?? null
11472
- }));
11473
- const namesByEnvironment = supplied.map(({ name }) => name);
11474
- if (new Set(namesByEnvironment).size !== namesByEnvironment.length || namesByEnvironment.some((name) => typeof name !== "string" || !name))
11475
- return failure("invalid_input", "candidate environment names must be unique and non-empty");
11476
- const values = supplied.sort((left, right) => compareCodeUnits2(left.name, right.name)).map(({ name, value }) => ({ name, value, refs: [] }));
11477
- if (values.some(({ value }) => value === null))
11478
- completeness = "uncertain";
11479
- const headResult = spawnSync2("git", ["rev-parse", "HEAD"], { cwd: checkout, encoding: "utf8" });
11480
- if (headResult.status !== 0 && !/not a git repository/i.test(headResult.stderr ?? ""))
11481
- completeness = "uncertain";
11482
- const head = headResult.status === 0 ? headResult.stdout.trim() : null;
11483
- const partial = {
11484
- id: "0".repeat(64),
11485
- scope: normalizedScope,
11486
- completeness,
11487
- files,
11488
- environment: values,
11489
- head
11454
+ { ...signal, refs: normalizedRefList(signal.refs) }
11455
+ ])),
11456
+ consequences: stableList(assessment.consequences.map((consequence) => ({
11457
+ ...consequence,
11458
+ fact: { ...consequence.fact, refs: normalizedRefList(consequence.fact.refs) }
11459
+ }))),
11460
+ verification: stableList(assessment.verification.map((verification) => ({
11461
+ ...verification,
11462
+ scope: normalizedScope(verification.scope),
11463
+ availableChecks: normalizedRefList(verification.availableChecks),
11464
+ gaps: stableUnique(verification.gaps)
11465
+ })))
11466
+ });
11467
+ var normalizeConstraint = (constraint) => ({
11468
+ ...constraint,
11469
+ source: constraint.source,
11470
+ requires: stableList(constraint.requires.map((requirement) => ({
11471
+ ...requirement,
11472
+ scope: normalizedScope(requirement.scope),
11473
+ refs: normalizedRefList(requirement.refs)
11474
+ })))
11475
+ });
11476
+ var normalizeDecision = (decision) => ({
11477
+ ...decision,
11478
+ binding: {
11479
+ ...decision.binding,
11480
+ scope: normalizedScope(decision.binding.scope),
11481
+ contentRefs: normalizedRefList(decision.binding.contentRefs)
11482
+ },
11483
+ requirementIds: stableUnique(decision.requirementIds)
11484
+ });
11485
+ var normalizeIntent = (intent) => ({
11486
+ ...intent,
11487
+ scope: normalizedScope(intent.scope),
11488
+ authorityRefs: normalizedRefList(intent.authorityRefs)
11489
+ });
11490
+ var normalizePrior = (prior) => ({
11491
+ decisions: stableList(prior.decisions.map(normalizeDecision)),
11492
+ findings: stableList(prior.findings.map((finding) => ({
11493
+ ...finding,
11494
+ scope: normalizedScope(finding.scope),
11495
+ refs: normalizedRefList(finding.refs),
11496
+ resolution: finding.resolution ? {
11497
+ ...finding.resolution,
11498
+ evidenceIds: stableUnique(finding.resolution.evidenceIds),
11499
+ decisionIds: stableUnique(finding.resolution.decisionIds)
11500
+ } : null
11501
+ }))),
11502
+ requirements: stableList(prior.requirements.map((requirement) => ({
11503
+ ...requirement,
11504
+ scope: normalizedScope(requirement.scope)
11505
+ })))
11506
+ });
11507
+ var invalidFields = (error) => ({
11508
+ fields: error.issues.map((issue) => ({
11509
+ path: issue.code === "unrecognized_keys" ? issue.keys.join(".") : issue.path.join("."),
11510
+ reason: issue.message
11511
+ }))
11512
+ });
11513
+ function normalizeResolverInput(input) {
11514
+ const parsed = resolverInputSchema.safeParse(input);
11515
+ if (!parsed.success)
11516
+ return failure("invalid_input", "resolver input is invalid", invalidFields(parsed.error));
11517
+ const value = parsed.data;
11518
+ const signals = value.assessment.signals;
11519
+ if (signals.behaviorChange.value === true && signals.mechanicalLowRisk.value === true)
11520
+ return failure("invalid_input", "behavioral change cannot be wholly mechanical", {
11521
+ fields: [
11522
+ {
11523
+ path: "assessment.signals",
11524
+ reason: "contradictory behaviorChange and mechanicalLowRisk"
11525
+ }
11526
+ ]
11527
+ });
11528
+ const ids = value.constraints.map((constraint) => constraint.id);
11529
+ if (new Set(ids).size !== ids.length)
11530
+ return failure("invalid_input", "constraint IDs must be unique", {
11531
+ fields: [{ path: "constraints", reason: "duplicate constraint id" }]
11532
+ });
11533
+ if (value.preferences?.fast && value.preferences.thorough)
11534
+ return failure("invalid_input", "fast and thorough preferences contradict", {
11535
+ fields: [{ path: "preferences", reason: "fast and thorough cannot both be enabled" }]
11536
+ });
11537
+ const normalized = {
11538
+ intent: normalizeIntent(value.intent),
11539
+ assessment: normalizeAssessment(value.assessment),
11540
+ constraints: stableList(value.constraints.map(normalizeConstraint)),
11541
+ prior: normalizePrior(value.prior),
11542
+ ...value.preferences ? { preferences: { ...value.preferences } } : {},
11543
+ policyVersion: POLICY_VERSION
11490
11544
  };
11491
- const candidate = { ...partial, id: candidateDigest(partial) };
11492
- const parsed = candidateSchema.safeParse(candidate);
11493
- return parsed.success ? success(null, null, parsed.data) : failure("invalid_input", "captured candidate is invalid");
11545
+ return success(null, null, normalized);
11494
11546
  }
11495
- var fileMap = (candidate) => new Map(candidate.files.map((file) => [file.path, file]));
11496
- var changedPaths = (before, after) => {
11497
- const paths = new Set([...before.files, ...after.files].map((file) => file.path));
11498
- const left = fileMap(before);
11499
- const right = fileMap(after);
11500
- const changed = [...paths].filter((item) => JSON.stringify(left.get(item) ?? null) !== JSON.stringify(right.get(item) ?? null));
11501
- if (before.head !== after.head)
11502
- changed.push(".");
11503
- if (JSON.stringify(before.environment) !== JSON.stringify(after.environment))
11504
- changed.push(".");
11505
- return changed;
11506
- };
11507
- var sessionFromRef = (value) => {
11508
- if (typeof value !== "object" || value === null || value.kind !== "host")
11509
- return null;
11510
- return typeof value.host === "string" && typeof value.handle === "string" ? { host: value.host, handle: value.handle } : null;
11511
- };
11512
- var sameSession = (left, right) => {
11513
- const other = sessionFromRef(right);
11514
- return left !== null && other !== null && left.host === other.host && left.handle === other.handle;
11515
- };
11516
- var evidenceScopes = (task, ids) => (task.policy?.requirements ?? []).filter((requirement) => ids.includes(requirement.id)).map((requirement) => requirement.scope);
11517
- function evaluateEvidence(task, candidate) {
11518
- const current = candidate ?? task.candidates.at(-1) ?? null;
11519
- return task.evidence.map((entry) => {
11520
- const evidence = entry.data;
11521
- if (evidence.result === "failed")
11522
- return {
11523
- evidenceId: entry.id,
11524
- status: "failed",
11525
- reason: "failed evidence remains historical"
11526
- };
11527
- if (evidence.kind === "check" || evidence.kind === "review") {
11528
- if (!evidence.beforeCandidateId || !evidence.candidateId)
11529
- return {
11530
- evidenceId: entry.id,
11531
- status: "stale",
11532
- reason: "check or review evidence lacks start and end candidates"
11533
- };
11534
- if (evidence.beforeCandidateId !== evidence.candidateId)
11535
- return {
11536
- evidenceId: entry.id,
11537
- status: "stale",
11538
- reason: "candidate changed during the check or review"
11539
- };
11547
+ var requirement = (spec) => ({
11548
+ ...spec,
11549
+ id: requirementId({
11550
+ ruleId: spec.ruleId,
11551
+ scope: spec.scope,
11552
+ satisfaction: spec.satisfaction,
11553
+ before: spec.before,
11554
+ dependentAction: spec.dependentAction
11555
+ })
11556
+ });
11557
+ var signalReason = (input, name) => input.assessment.signals[name].reason;
11558
+ function resolveRequirements(input) {
11559
+ const { signals } = input.assessment;
11560
+ const scope = input.intent.scope;
11561
+ const requirements = [];
11562
+ const hasUnknownSignal = Object.values(signals).some((signal) => signal.value === "unknown");
11563
+ const hasUnknownFact = [
11564
+ ...input.assessment.facts,
11565
+ ...input.assessment.consequences.map(({ fact }) => fact)
11566
+ ].some((fact) => fact.basis === "unknown");
11567
+ if (hasUnknownSignal || hasUnknownFact)
11568
+ requirements.push(requirement({
11569
+ ruleId: "consequential-unknown",
11570
+ dimension: "investigation",
11571
+ scope,
11572
+ reason: `Resolve consequential uncertainty before the dependent action: ${[
11573
+ ...Object.entries(signals).filter(([, signal]) => signal.value === "unknown").map(([name]) => name),
11574
+ ...hasUnknownFact ? ["unknown fact"] : []
11575
+ ].join(", ")}`,
11576
+ satisfaction: "An observed or inferred fact resolves the uncertainty and records its supporting references.",
11577
+ before: "dependent_action",
11578
+ dependentAction: null,
11579
+ acceptanceAllowed: false
11580
+ }));
11581
+ if (signals.productChoiceOpen.value === true)
11582
+ requirements.push(requirement({
11583
+ ruleId: "product-decision",
11584
+ dimension: "decisions",
11585
+ scope,
11586
+ reason: `A consequential product choice remains open: ${signalReason(input, "productChoiceOpen")}`,
11587
+ satisfaction: "Present the material alternatives and record the user's decision before the dependent action.",
11588
+ before: "dependent_action",
11589
+ dependentAction: null,
11590
+ acceptanceAllowed: false
11591
+ }));
11592
+ const independentBehaviorReview = input.preferences?.thorough === true || input.assessment.consequences.some((consequence) => ["security", "data", "public_contract", "operations"].includes(consequence.area));
11593
+ if (signals.behaviorChange.value === true)
11594
+ requirements.push(requirement({
11595
+ ruleId: "behavioral-verification",
11596
+ dimension: "testing",
11597
+ scope,
11598
+ reason: `Behavior, side effects, permissions, or data handling may change: ${signalReason(input, "behaviorChange")}`,
11599
+ satisfaction: "A useful behavioral check passes against the affected behavior and current candidate.",
11600
+ before: "close",
11601
+ dependentAction: null,
11602
+ acceptanceAllowed: false
11603
+ }), requirement({
11604
+ ruleId: independentBehaviorReview ? "fresh-context-review" : "self-review",
11605
+ dimension: "review",
11606
+ scope,
11607
+ 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.",
11608
+ 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.",
11609
+ before: "close",
11610
+ dependentAction: null,
11611
+ acceptanceAllowed: !independentBehaviorReview
11612
+ }));
11613
+ else if (signals.mechanicalLowRisk.value === true)
11614
+ requirements.push(requirement({
11615
+ ruleId: "mechanical-existing-checks",
11616
+ dimension: "verification",
11617
+ scope,
11618
+ reason: `The change is demonstrably mechanical and low-risk: ${signalReason(input, "mechanicalLowRisk")}`,
11619
+ satisfaction: "Run the relevant existing checks for affected consumers; do not add tautological tests.",
11620
+ before: "close",
11621
+ dependentAction: null,
11622
+ acceptanceAllowed: true
11623
+ }), requirement({
11624
+ ruleId: input.preferences?.thorough ? "fresh-context-review" : "self-review",
11625
+ dimension: "review",
11626
+ scope,
11627
+ 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.",
11628
+ 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.",
11629
+ before: "close",
11630
+ dependentAction: null,
11631
+ acceptanceAllowed: !input.preferences?.thorough
11632
+ }));
11633
+ if (signals.behaviorChange.value === true || signals.mechanicalLowRisk.value === true)
11634
+ requirements.push(requirement({
11635
+ ruleId: "pre-pr-cleanup",
11636
+ dimension: "verification",
11637
+ scope,
11638
+ reason: "Implementation output must be deslopped before it is delivered.",
11639
+ satisfaction: "Run the workit-deslop pass and record passing check evidence, or record an approved limitation decision waiving cleanup.",
11640
+ before: "dependent_action",
11641
+ dependentAction: "hosting.pull_request",
11642
+ acceptanceAllowed: true
11643
+ }));
11644
+ if (signals.durableAgreementNeeded.value === true)
11645
+ requirements.push(requirement({
11646
+ ruleId: "durable-spec",
11647
+ dimension: "artifacts",
11648
+ scope,
11649
+ reason: `The work needs a durable agreement about intended behavior: ${signalReason(input, "durableAgreementNeeded")}`,
11650
+ satisfaction: "Record the agreed behavior in a durable specification before implementation writes.",
11651
+ before: "write",
11652
+ dependentAction: null,
11653
+ acceptanceAllowed: true
11654
+ }));
11655
+ if (signals.coordinationPlanNeeded.value === true)
11656
+ requirements.push(requirement({
11657
+ ruleId: "coordination-plan",
11658
+ dimension: "continuity",
11659
+ scope,
11660
+ reason: `Dependencies, sequencing, or resumption need durable coordination: ${signalReason(input, "coordinationPlanNeeded")}`,
11661
+ satisfaction: "Record useful sequencing, dependencies, and the next action in a compact plan.",
11662
+ before: "dependent_action",
11663
+ dependentAction: null,
11664
+ acceptanceAllowed: true
11665
+ }));
11666
+ if (signals.helperUseful.value === true && !input.preferences?.fast)
11667
+ requirements.push(requirement({
11668
+ ruleId: "helper-usefulness",
11669
+ dimension: "delegation",
11670
+ scope,
11671
+ reason: `Independent judgment or investigation justifies a scoped helper: ${signalReason(input, "helperUseful")}`,
11672
+ satisfaction: "Use a bounded helper only for the independent objective and reconcile its result.",
11673
+ before: "dependent_action",
11674
+ dependentAction: null,
11675
+ acceptanceAllowed: true
11676
+ }));
11677
+ for (const constraint of input.constraints)
11678
+ for (const obligation of constraint.requires) {
11679
+ const dimension = obligation.method ?? (obligation.kind === "check" ? "verification" : obligation.kind === "decision" ? "decisions" : "challenge");
11680
+ requirements.push(requirement({
11681
+ ruleId: `project-constraint:${constraint.id}:${obligation.kind}:${sha256({
11682
+ kind: obligation.kind,
11683
+ scope: normalizedScope(obligation.scope),
11684
+ refs: normalizedRefList(obligation.refs),
11685
+ method: obligation.method,
11686
+ before: obligation.before,
11687
+ dependentAction: obligation.dependentAction
11688
+ })}`,
11689
+ dimension,
11690
+ scope: obligation.scope,
11691
+ reason: `${constraint.kind} constraint requires ${obligation.kind}: ${constraint.statement}`,
11692
+ satisfaction: `Satisfy the constraint obligation using its referenced ${obligation.kind}.`,
11693
+ before: obligation.before,
11694
+ dependentAction: obligation.dependentAction,
11695
+ acceptanceAllowed: constraint.acceptanceAllowed && obligation.kind !== "decision"
11696
+ }));
11540
11697
  }
11541
- if (!evidence.candidateId || !current)
11542
- return {
11543
- evidenceId: entry.id,
11544
- status: evidence.result,
11545
- reason: "evidence has no candidate binding"
11546
- };
11547
- const observed = task.candidates.find((item) => item.id === evidence.candidateId) ?? (current.id === evidence.candidateId ? current : undefined);
11548
- if (!observed || observed.completeness === "uncertain" || current.completeness === "uncertain")
11549
- return { evidenceId: entry.id, status: "stale", reason: "candidate is missing or uncertain" };
11550
- if (observed.id === current.id)
11551
- return { evidenceId: entry.id, status: evidence.result, reason: "candidate is unchanged" };
11552
- const scopes = evidenceScopes(task, evidence.requirementIds);
11553
- const changed = changedPaths(observed, current);
11554
- const environmentChanged = JSON.stringify(observed.environment) !== JSON.stringify(current.environment);
11555
- if (!scopes.length || environmentChanged || changed.some((item) => scopes.some((scope) => pathRelevant(item, scope))))
11556
- return { evidenceId: entry.id, status: "stale", reason: "relevant candidate state changed" };
11557
- return {
11558
- evidenceId: entry.id,
11559
- status: evidence.result,
11560
- reason: "candidate changed outside evidence scope"
11561
- };
11698
+ const seen = new Set;
11699
+ return requirements.filter((item) => {
11700
+ if (seen.has(item.id))
11701
+ return false;
11702
+ seen.add(item.id);
11703
+ return true;
11562
11704
  });
11563
11705
  }
11564
- var scopeCovers2 = scopeCovers;
11565
- var checkPin = (assignment, beforeCandidateId, candidateId) => {
11566
- const pin = assignment.candidateId ?? null;
11567
- if (pin === null)
11568
- return true;
11569
- return (beforeCandidateId ?? null) === pin || (candidateId ?? null) === pin;
11570
- };
11571
- var resolveBinding = (evidence, pin, currentCandidateId) => {
11572
- const bound = evidence.kind === "check" || evidence.kind === "review";
11573
- const fallback = bound ? pin ?? currentCandidateId : null;
11574
- return {
11575
- beforeCandidateId: evidence.beforeCandidateId ?? fallback,
11576
- candidateId: evidence.candidateId ?? fallback
11706
+ function resolvePolicy(input) {
11707
+ const normalized = normalizeResolverInput(input);
11708
+ if (!normalized.ok)
11709
+ return normalized;
11710
+ const requirements = resolveRequirements(normalized.data);
11711
+ const policy = {
11712
+ policyVersion: POLICY_VERSION,
11713
+ inputDigest: sha256(canonicalJson(normalized.data)),
11714
+ requirements
11577
11715
  };
11578
- };
11579
- var findingVerificationPasses = (findingCandidateId, evidence) => evidence.status === "passed" && (evidence.kind === "check" || evidence.kind === "review") && ((findingCandidateId ?? null) === null || evidence.candidateId != null);
11580
- 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")));
11581
- 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 }));
11582
- var evidenceMatchesRequirement = (kind, evidenceKind, dimension, ruleId) => {
11583
- if (kind !== "passed")
11584
- return false;
11585
- if (dimension === "testing" || dimension === "verification")
11586
- return evidenceKind === "check" || ruleId === "pre-pr-cleanup" && evidenceKind === "artifact";
11587
- if (dimension === "review")
11588
- return evidenceKind === "review";
11589
- if (dimension === "investigation" || dimension === "challenge")
11590
- return evidenceKind === "investigation";
11591
- if (dimension === "artifacts" || dimension === "continuity")
11592
- return evidenceKind === "artifact";
11593
- return false;
11594
- };
11595
- var expectedKinds = (dimension, ruleId) => {
11596
- if (dimension === "testing")
11597
- return "check";
11598
- if (dimension === "verification")
11599
- return ruleId === "pre-pr-cleanup" ? "check or artifact" : "check";
11600
- if (dimension === "review")
11601
- return "review";
11602
- if (dimension === "investigation" || dimension === "challenge")
11603
- return "investigation";
11604
- if (dimension === "artifacts" || dimension === "continuity")
11605
- return "artifact";
11606
- if (dimension === "decisions")
11607
- return "decision";
11608
- return "worker report";
11609
- };
11610
- function evaluateRequirements(task, workspace, capabilities, candidate, checkoutRoot, _caller) {
11611
- const evidence = evaluateEvidence(task, candidate);
11612
- if (task.policy && task.policy.policyVersion !== POLICY_VERSION)
11613
- return task.policy.requirements.map((requirement) => ({
11614
- requirementId: requirement.id,
11615
- status: "unsatisfied",
11616
- evidenceIds: [],
11617
- decisionIds: [],
11618
- reason: "stored policy version is unsupported; reassessment is required"
11619
- }));
11620
- return (task.policy?.requirements ?? []).map((requirement) => {
11621
- const related = task.evidence.map((entry, index) => ({ entry, evaluation: evidence[index] })).filter(({ entry }) => entry.data.requirementIds.includes(requirement.id));
11622
- const passed = related.filter(({ entry, evaluation }) => {
11623
- if (!evidenceMatchesRequirement(evaluation.status, entry.data.kind, requirement.dimension, requirement.ruleId))
11624
- return false;
11625
- if ((entry.data.kind === "check" || entry.data.kind === "review") && (!entry.data.beforeCandidateId || !entry.data.candidateId || entry.data.beforeCandidateId !== entry.data.candidateId))
11626
- return false;
11627
- if (requirement.dimension !== "review")
11628
- return true;
11629
- const reviewSession = sessionFromRef(entry.data.reviewContext);
11630
- const sameImplementation = sameSession(reviewSession, task.intent.provenance.session);
11631
- 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));
11632
- return entry.data.kind === "review" && reviewSession !== null && sameSession(reviewSession, entry.provenance.session) && (requirement.ruleId === "self-review" || !sameImplementation && !sameEvidenceSession);
11633
- });
11634
- if (passed.length) {
11635
- const currentId = candidate?.id ?? null;
11636
- 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;
11637
- if (withRed.length)
11638
- return {
11639
- requirementId: requirement.id,
11640
- status: "satisfied",
11641
- evidenceIds: withRed.map(({ entry }) => entry.id),
11642
- decisionIds: [],
11643
- reason: "fresh applicable evidence passed"
11644
- };
11645
- if (requirement.dimension === "testing")
11646
- return {
11647
- requirementId: requirement.id,
11648
- status: "unsatisfied",
11649
- evidenceIds: [],
11650
- decisionIds: [],
11651
- reason: "testing requirement has GREEN evidence but no preceding RED"
11652
- };
11653
- }
11654
- if (requirement.dimension === "delegation") {
11655
- const dot = (scope) => scope.paths.length > 0 ? scope : { ...scope, paths: ["."] };
11656
- 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))));
11657
- if (reconciled)
11658
- return {
11659
- requirementId: requirement.id,
11660
- status: "satisfied",
11661
- evidenceIds: [],
11662
- decisionIds: [],
11663
- reason: "bounded helper completed and its result is recorded"
11664
- };
11665
- }
11666
- const decisions = requirement.dimension === "decisions" ? applicableRequirementDecision(task, workspace, requirement, checkoutRoot) : [];
11667
- if (decisions.length)
11668
- return {
11669
- requirementId: requirement.id,
11670
- status: "satisfied",
11671
- evidenceIds: [],
11672
- decisionIds: decisions.map((decision) => decision.id),
11673
- reason: "an applicable approved or stated decision satisfies the requirement"
11674
- };
11675
- const limitations = requirement.acceptanceAllowed ? applicableDecision2(task, workspace, requirement, checkoutRoot) : [];
11676
- if (limitations.length)
11677
- return {
11678
- requirementId: requirement.id,
11679
- status: "accepted_limitation",
11680
- evidenceIds: [],
11681
- decisionIds: limitations.map((decision) => task.decisions.find((entry) => entry.data === decision).id),
11682
- reason: "an applicable approved limitation permits the missing evidence"
11683
- };
11684
- const unavailable = capabilities.some((capability) => capability.assurance === "unavailable" && (capability.name === requirement.dimension || capability.surface === requirement.dimension));
11685
- if (!unavailable && related.length > 0 && !passed.length)
11686
- return {
11687
- requirementId: requirement.id,
11688
- status: "unsatisfied",
11689
- evidenceIds: related.map(({ entry }) => entry.id),
11690
- decisionIds: [],
11691
- reason: `no passing evidence (needs kind:${expectedKinds(requirement.dimension, requirement.ruleId)})`
11692
- };
11693
- return {
11694
- requirementId: requirement.id,
11695
- status: unavailable ? "unavailable" : "unsatisfied",
11696
- evidenceIds: related.map(({ entry }) => entry.id),
11697
- decisionIds: [],
11698
- reason: unavailable ? "required capability is unavailable" : "no fresh passing evidence"
11699
- };
11700
- });
11716
+ const parsed = policySchema.safeParse(policy);
11717
+ if (!parsed.success)
11718
+ return failure("invalid_input", "resolved policy is invalid", invalidFields(parsed.error));
11719
+ return success(null, null, parsed.data);
11701
11720
  }
11702
- function evaluateClosure(requestedOutcome, view) {
11703
- if (requestedOutcome !== "stopped" && !view.task.policy)
11704
- return failure("requirements_unsatisfied", "task has not been assessed");
11705
- if (view.task.policy && view.task.policy.policyVersion !== POLICY_VERSION)
11706
- return failure("requirements_unsatisfied", "stored policy version is unsupported; reassessment is required");
11707
- const evaluations = view.requirements;
11708
- const openFindings = view.task.findings.filter((entry) => entry.data.disposition === "open");
11709
- if (requestedOutcome !== "stopped" && openFindings.length)
11710
- return failure("requirements_unsatisfied", "open findings must be resolved before closure");
11711
- if (requestedOutcome !== "stopped") {
11712
- const evidenceById = new Map(view.evidence.map((entry) => [entry.evidenceId, entry.status]));
11713
- for (const entry of view.task.findings) {
11714
- if (entry.data.disposition === "fixed") {
11715
- const verified = entry.data.resolution?.evidenceIds.some((id) => {
11716
- const evidence = view.task.evidence.find((item) => item.id === id);
11717
- if (!evidence)
11718
- return false;
11719
- return findingVerificationPasses(entry.data.candidateId, {
11720
- kind: evidence.data.kind,
11721
- candidateId: evidence.data.candidateId,
11722
- status: evidenceById.get(id) ?? "missing"
11723
- });
11724
- });
11725
- if (!verified)
11726
- return failure("requirements_unsatisfied", "fixed findings require current verification");
11727
- }
11728
- if (entry.data.disposition === "deferred") {
11729
- const valid = entry.data.resolution?.decisionIds.some((id) => {
11730
- const decisionEntry = view.task.decisions.find((item) => item.id === id);
11731
- const decision = decisionEntry?.data;
11732
- 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)));
11733
- });
11734
- if (!valid)
11735
- return failure("requirements_unsatisfied", "deferred findings require an approved limitation decision that references an acceptanceAllowed requirement and covers the finding scope");
11736
- }
11737
- }
11738
- }
11739
- const blocking = evaluations.filter((item) => {
11740
- if (item.status !== "unsatisfied" && item.status !== "unavailable")
11741
- return false;
11742
- const requirement = view.task.policy?.requirements.find((candidate) => candidate.id === item.requirementId);
11743
- return !requirement || requirement.before === "close";
11744
- });
11745
- if (requestedOutcome !== "stopped" && blocking.length)
11746
- return failure("requirements_unsatisfied", "applicable requirements are unsatisfied", {
11747
- requirementIds: blocking.map((item) => item.requirementId),
11748
- requirements: blocking.map((item) => {
11749
- const requirement = view.task.policy?.requirements.find((candidate) => candidate.id === item.requirementId);
11750
- return {
11751
- requirementId: item.requirementId,
11752
- ruleId: requirement?.ruleId ?? "unknown",
11753
- reason: item.reason,
11754
- satisfaction: requirement?.satisfaction ?? "",
11755
- dependentAction: requirement?.dependentAction ?? null
11756
- };
11757
- })
11758
- });
11759
- const accepted = evaluations.filter((item) => item.status === "accepted_limitation");
11760
- if (requestedOutcome === "verified" && accepted.length)
11761
- return failure("requirements_unsatisfied", "accepted limitations cannot be reported as verified", {
11762
- requirementIds: accepted.map((item) => item.requirementId)
11763
- });
11764
- const evidenceIds = [
11765
- ...new Set([
11766
- ...evaluations.flatMap((item) => item.evidenceIds),
11767
- ...view.task.findings.flatMap((item) => item.data.resolution?.evidenceIds ?? [])
11768
- ])
11769
- ];
11770
- const decisionIds = [
11771
- ...new Set([
11772
- ...evaluations.flatMap((item) => item.decisionIds),
11773
- ...view.task.findings.flatMap((item) => item.data.resolution?.decisionIds ?? [])
11774
- ])
11775
- ];
11776
- return success(null, null, {
11777
- outcome: requestedOutcome === "stopped" ? "stopped" : accepted.length ? "accepted_limitations" : "verified",
11778
- evidenceIds,
11779
- decisionIds,
11780
- requirementIds: evaluations.map((item) => item.requirementId)
11781
- });
11721
+ function diffPolicy(previous, next, reason, now) {
11722
+ if (!policySchema.safeParse(previous).success && previous !== null)
11723
+ throw new TypeError("previous policy is invalid");
11724
+ if (!policySchema.safeParse(next).success)
11725
+ throw new TypeError("next policy is invalid");
11726
+ const oldIds = new Set(previous?.requirements.map((requirement) => requirement.id) ?? []);
11727
+ const newIds = new Set(next.requirements.map((requirement) => requirement.id));
11728
+ const added = [...newIds].filter((id) => !oldIds.has(id)).sort(compareCodeUnits2);
11729
+ const retired = [...oldIds].filter((id) => !newIds.has(id)).sort(compareCodeUnits2);
11730
+ if (added.length === 0 && retired.length === 0)
11731
+ return null;
11732
+ const normalizedReason = reason.trim();
11733
+ const changeReason = retired.length ? `${normalizedReason || "policy reassessed"} (retired: ${retired.join(",")})` : normalizedReason || "policy reassessed";
11734
+ const change = {
11735
+ recordedAt: now,
11736
+ fromInputDigest: previous?.inputDigest ?? null,
11737
+ toInputDigest: next.inputDigest,
11738
+ added,
11739
+ retired,
11740
+ reason: changeReason
11741
+ };
11742
+ const parsed = policyChangeSchema.safeParse(change);
11743
+ if (!parsed.success)
11744
+ throw new TypeError("policy change is invalid");
11745
+ return parsed.data;
11782
11746
  }
11783
11747
 
11784
- // packages/workit-core/src/core/methods.ts
11785
- var METHODS = {
11786
- "workit-challenge": { dimensions: ["challenge", "decisions"] },
11787
- "workit-behavioral-tdd": { dimensions: ["testing"], ruleIds: ["mechanical-existing-checks"] },
11788
- "workit-review": { dimensions: ["review"], ruleIds: ["fresh-context-review", "self-review"] },
11789
- "workit-plan": { dimensions: ["artifacts", "continuity"] },
11790
- "workit-implement": { dimensions: ["delegation"] },
11791
- "workit-debug": {},
11792
- "workit-handoff": {},
11793
- "workit-deslop": { ruleIds: ["pre-pr-cleanup"] }
11748
+ // packages/workit-core/src/core/task-evaluation.ts
11749
+ import { createHash as createHash6 } from "node:crypto";
11750
+ import * as fs7 from "node:fs";
11751
+ import { spawnSync as spawnSync2 } from "node:child_process";
11752
+ import path10 from "node:path";
11753
+ var digestBytes3 = (value) => createHash6("sha256").update(value).digest("hex");
11754
+ var inside = (root, candidate) => candidate === root || candidate.startsWith(`${root}${path10.sep}`);
11755
+ var relative = (root, candidate) => path10.relative(root, candidate).split(path10.sep).join("/") || ".";
11756
+ var canonicalPath = (value) => {
11757
+ if (typeof value !== "string" || !value)
11758
+ return null;
11759
+ if (value.includes("\\") || value.split("/").includes(".."))
11760
+ return null;
11761
+ const normalized = path10.posix.normalize(value);
11762
+ if (normalized === ".." || normalized.startsWith("../") || normalized.startsWith("/"))
11763
+ return null;
11764
+ return normalized === "." ? "." : normalized.replace(/\/$/, "");
11794
11765
  };
11795
- var methodMatches = (definition, requirement) => definition.dimensions?.includes(requirement.dimension) === true || definition.ruleIds?.includes(requirement.ruleId) === true;
11796
- var assuranceFor = (id, definition, capabilities) => {
11797
- const keys = new Set([
11798
- id,
11799
- ...definition.dimensions ?? [],
11800
- ...definition.ruleIds ?? []
11801
- ]);
11802
- const matches = capabilities.filter((capability) => keys.has(capability.name) || keys.has(capability.surface));
11803
- if (id === "workit-review" && matches.length === 0)
11804
- return { assurance: "unavailable", reasons: ["independent review capability is unavailable"] };
11805
- if (matches.some((capability) => capability.assurance === "unavailable"))
11806
- return {
11807
- assurance: "unavailable",
11808
- reasons: matches.filter((capability) => capability.assurance === "unavailable").map((capability) => capability.reason)
11809
- };
11810
- if (matches.some((capability) => capability.assurance === "enforced"))
11811
- return { assurance: "enforced", reasons: matches.map((capability) => capability.reason) };
11812
- return { assurance: "agent_guided", reasons: matches.map((capability) => capability.reason) };
11766
+ var canonicalScope = (scope) => {
11767
+ const paths = scope.paths.length ? scope.paths : ["."];
11768
+ const normalizedPaths = paths.map(canonicalPath);
11769
+ const normalizedExclusions = scope.exclusions.map(canonicalPath);
11770
+ if (normalizedPaths.some((value) => value === null) || normalizedExclusions.some((value) => value === null))
11771
+ return null;
11772
+ return {
11773
+ description: scope.description,
11774
+ paths: [...new Set(normalizedPaths)],
11775
+ exclusions: [...new Set(normalizedExclusions)]
11776
+ };
11813
11777
  };
11814
- function selectMethods(policy, capabilities) {
11815
- return Object.entries(METHODS).flatMap(([id, definition]) => {
11816
- const requirements = policy.requirements.filter((requirement) => methodMatches(definition, requirement));
11817
- if (requirements.length === 0)
11818
- return [];
11819
- const capability = assuranceFor(id, definition, capabilities);
11820
- const reasons = [
11821
- ...new Set(requirements.map((requirement) => requirement.reason)),
11822
- ...capability.reasons
11823
- ];
11824
- if (capability.assurance === "unavailable")
11825
- reasons.unshift("required capability is unavailable");
11826
- return [{ id, reason: reasons.join("; "), assurance: capability.assurance }];
11827
- });
11828
- }
11829
- var invariantBootstrap = () => `
11830
- Workit is optional coordination and repository-policy tooling around the host,
11831
- not a permission system or a mandatory workflow. Native host allow/ask/deny,
11832
- sandbox, plan/read-only mode, and organization rules remain authoritative.
11833
- Ordinary investigation, questions, non-Git work, and routine reversible edits
11834
- need zero Workit task, assessment, or writer calls. Use one compact tracked
11835
- record only when handoff, dependent steps, concurrent actors, or meaningful
11836
- decisions make continuity useful; similar titles alone never merge tasks.
11837
-
11838
- For a routine user-authorized branch or commit, prefer native host Git/shell
11839
- tools from the outset when managed coordination or outcome reconciliation is
11840
- not needed. Inspect the actual target checkout and its configured conventions;
11841
- use Workit's read-only context/policy tools when needed. Do not start a task,
11842
- acquire a writer, or mint a decision receipt solely for a native Git action.
11843
- Native permissions still apply. Never switch execution paths to evade a denial
11844
- or repeat an uncertain managed effect. A local-commit endpoint does not imply
11845
- PR readiness, a fresh review, or post-commit assessment/closure paperwork.
11846
-
11847
- For tracked work, inspect its current state and use the shared operations for
11848
- task, policy, evidence, finding, decision, worker, writer, and state changes.
11849
- Start a record once for an explicit tracked objective; assess or reassess only
11850
- when policy selection or changed evidence/constraints requires it. Omitted
11851
- expectedRevision and expectedWorkspaceRevision use current values; explicit
11852
- values are still concurrency-checked, so never copy revisions between calls.
11853
- A solo edit does not need writer acquisition; use it when concurrent checkout
11854
- writers need coordination. Record only observed facts and checks. Evidence can
11855
- become stale when its bound candidate changes; reconcile findings against the
11856
- current candidate before recording completion.
11857
-
11858
- Workit validates domain policy against the actual action target, configured
11859
- account, branch and commit conventions, protected refs, and current repository
11860
- state. The task directory is coordination state, not a boundary on which
11861
- repository may be changed. Use an action-time cwd target where a managed
11862
- Git/hosting action supports it; a non-Git directory remains valid for OS work.
11863
- GitHub/GitLab use the active gh/glab CLI identity; YouTrack uses its own token.
11864
- Preserve uncertain external outcomes and reconcile repository/provider state
11865
- before retrying. Internal reservations prevent duplicate or ambiguous effects;
11866
- they are not permission tickets for every edit.
11867
-
11868
- On OpenCode V1 and V2, use native host tools for external mutations. Workit
11869
- provides read-only workit_context; it has no managed external-action executor.
11870
- Do not create proposals or request Workit approvals merely to invoke native
11871
- tools. Old uncertain managed effects still require evidence before any retry.
11872
-
11873
- Use host-native authorization through the host's supported path. A native
11874
- question receipt records an actual question interaction; it is not automatic
11875
- host permission. Record a meaningful user choice once with provenance when
11876
- future retrieval helps. Never fabricate a receipt, re-ask only to mint one, or
11877
- let imported decisions grant authority. Never turn a host deny into allow or
11878
- claim enforcement/evidence a host cannot provide. A precise request with settled
11879
- constraints does not need an interview. Present genuine unresolved options with
11880
- evidence and a recommendation, then continue toward the requested delivery
11881
- endpoint: investigation, implementation, branch/commit/push, PR/MR-ready,
11882
- merge, or release. Run
11883
- applicable checks and safe repairs without repeated continuation questions;
11884
- stop for missing host authority, a new consequential choice, a conflicting edit,
11885
- or an unresolved blocker. A tracked record may close when actual evidence
11886
- supports its outcome; no final human closure ceremony is required.
11887
-
11888
- A completed native subagent run stops its bound worker by itself; if a worker
11889
- strands in cancelling with its run verifiably over, repeat worker.cancel to
11890
- confirm the stop. Preserve unresolved requirements, gaps, and uncertain workers.
11891
- When context changes, distinguish a quick question, same-task adjustment, and
11892
- separate request. Answer a quick question without pausing/resuming task state;
11893
- park a concise checkpoint only when substantial work needs to continue later.
11894
- For work spanning repositories, bind each unfinished item to its actual checkout,
11895
- branch, requested deliverables, and delivery endpoint. Preserve held items with
11896
- an explicit resume condition. Resolve competing plausible targets before a
11897
- mutation; ask only when available context cannot settle that consequential choice.
11898
- Before reporting delivery, reconcile every requested item and observe the actual
11899
- target result; a local commit alone is not evidence of a requested remote push.
11900
-
11901
- Skill routing: slash aliases /wk-* load on demand. Use workit-steer for a
11902
- substantial interruption or change of direction, workit-deslop when relevant
11903
- to a PR-ready endpoint, workit-green-run for failing CI, workit-blast-radius
11904
- when impact is uncertain, and workit-challenge for genuinely open consequential
11905
- choices. Load workit-plan when dependencies or handoff need durable next actions.
11906
- Load the skill; never act from memory of it.
11907
- `.trim();
11908
-
11909
- // packages/workit-core/src/core/task-context.ts
11910
- function reconcileResume(view, observations = []) {
11911
- if (observations.length > 0)
11912
- return failure("permission_denied", "worker observations require native host verification");
11913
- const candidate = captureCandidate(view.workspace.root, view.task.intent.data.scope, []);
11914
- if (!candidate.ok)
11915
- return candidate;
11916
- const staleEvidenceIds = evaluateEvidence(view.task, candidate.data).filter((entry) => entry.status === "stale").map((entry) => entry.evidenceId);
11917
- const blockers = [...view.task.progress.blockers];
11918
- if (view.task.workers.some((entry) => isUncertainWorker(entry.data.state)))
11919
- blockers.push({
11920
- reason: "worker state requires reconciliation",
11921
- dependentAction: "resume",
11922
- refs: []
11923
- });
11924
- return success(null, null, {
11925
- candidate: candidate.data,
11926
- staleEvidenceIds,
11927
- workerUpdates: [],
11928
- blockers,
11929
- reassessmentRequired: view.task.policy?.policyVersion !== POLICY_VERSION
11930
- });
11931
- }
11932
- var COMPACT_MAX_BYTES = 4096;
11933
- var COMPACT_MAX_ITEMS = 8;
11934
- var COMPACT_TEXT_BYTES = 128;
11935
- var sensitiveUrl = /\bhttps?:\/\/[^/\s:@]+:[^@\s]+@/gi;
11936
- var sensitiveValue = /(?:token|secret|password|passwd|api[-_ ]?key|private[-_ ]?key|authorization)\s*[:=]\s*(?:bearer\s+)?\S+|\bbearer\s+\S+/gi;
11937
- var privateKey = /-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/gi;
11938
- var compactText = (value, limit) => value === null ? null : value.replace(privateKey, "<redacted-private-key>").replace(sensitiveUrl, "<redacted-url>").replace(sensitiveValue, (match) => {
11939
- const separator = match.search(/[:=]/u);
11940
- if (separator >= 0)
11941
- return `${match.slice(0, separator)}=<redacted>`;
11942
- const space = match.search(/\s/u);
11943
- return `${match.slice(0, space)} <redacted>`;
11944
- }).slice(0, limit);
11945
- var compactBytes = (value) => new TextEncoder().encode(value).byteLength;
11946
- var compactTimestamp = (value) => `${value.slice(0, 19)}.${value.slice(20, -1).padEnd(9, "0")}`;
11947
- var compactDecisionChoice = (entry) => {
11948
- const stated = entry.data.binding.statedChoice?.text;
11949
- const approved = entry.data.response === "approved" ? entry.data.binding.approvedContent : "";
11950
- const source = stated?.trim() || approved.trim() || null;
11951
- return compactText(source, COMPACT_TEXT_BYTES);
11778
+ var excluded = (value, exclusions) => exclusions.some((item) => item === value || item !== "." && value.startsWith(`${item}/`));
11779
+ var scopeMatches = (value, scope) => {
11780
+ const normalized = canonicalScope(scope);
11781
+ if (!normalized)
11782
+ return false;
11783
+ const paths = normalized.paths;
11784
+ return paths.some((item) => item === "." || value === item || value.startsWith(`${item}/`)) && !excluded(value, normalized.exclusions);
11952
11785
  };
11953
- var compactReference = (ref) => {
11954
- if (ref.kind === "file")
11955
- return {
11956
- kind: "file",
11957
- path: compactText(ref.path, COMPACT_TEXT_BYTES) ?? ""
11958
- };
11959
- if (ref.kind === "record")
11786
+ var pathRelevant = (value, scope) => scopeMatches(value, scope);
11787
+ var compareCodeUnits3 = (left, right) => {
11788
+ const length = Math.min(left.length, right.length);
11789
+ for (let index = 0;index < length; index += 1) {
11790
+ const difference = left.charCodeAt(index) - right.charCodeAt(index);
11791
+ if (difference !== 0)
11792
+ return difference;
11793
+ }
11794
+ return left.length - right.length;
11795
+ };
11796
+ var gitPaths = (root) => {
11797
+ const result = spawnSync2("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
11798
+ cwd: root,
11799
+ encoding: "buffer"
11800
+ });
11801
+ if (result.status !== 0) {
11802
+ const stderr = result.stderr?.toString("utf8") ?? "";
11960
11803
  return {
11961
- kind: "record",
11962
- collection: ref.collection,
11963
- id: ref.id
11804
+ paths: [],
11805
+ uncertain: !/not a git repository/i.test(stderr),
11806
+ git: /not a git repository/i.test(stderr) ? false : true
11964
11807
  };
11965
- return { kind: ref.kind };
11808
+ }
11809
+ const paths = result.stdout ? result.stdout.toString("utf8").split("\x00").filter(Boolean).map((item) => item.split(path10.sep).join("/")) : [];
11810
+ const stagedDeleted = spawnSync2("git", ["diff", "--cached", "--name-only", "--diff-filter=D", "-z"], { cwd: root, encoding: "buffer" });
11811
+ if (stagedDeleted.status !== 0) {
11812
+ const stderr = stagedDeleted.stderr?.toString("utf8") ?? "";
11813
+ if (!/not a git repository/i.test(stderr))
11814
+ return { paths, uncertain: true, git: true };
11815
+ } else if (stagedDeleted.stdout) {
11816
+ paths.push(...stagedDeleted.stdout.toString("utf8").split("\x00").filter(Boolean).map((item) => item.split(path10.sep).join("/")));
11817
+ }
11818
+ return { paths: [...new Set(paths)], uncertain: false, git: true };
11966
11819
  };
11967
- function compactTaskContext(view) {
11968
- const decisions = view.task.decisions.slice().sort((left, right) => {
11969
- const leftAt = compactTimestamp(left.recordedAt);
11970
- const rightAt = compactTimestamp(right.recordedAt);
11971
- if (leftAt !== rightAt)
11972
- return leftAt > rightAt ? -1 : 1;
11973
- return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;
11974
- }).slice(0, COMPACT_MAX_ITEMS).map((entry) => ({
11975
- id: entry.id,
11976
- purpose: entry.data.purpose,
11977
- status: entry.data.response,
11978
- digest: entry.data.digest,
11979
- choice: compactDecisionChoice(entry) || `task.inspect taskId=${view.task.id} view=full; decision=${entry.id}`,
11980
- references: entry.data.binding.contentRefs.slice(0, 1).map(compactReference)
11981
- }));
11982
- const methods = view.task.policy ? selectMethods(view.task.policy, view.capabilities).map((method) => ({
11983
- id: method.id,
11984
- assurance: method.assurance,
11985
- reason: compactText(method.reason, COMPACT_TEXT_BYTES) ?? ""
11986
- })) : [];
11987
- const gaps = Array.from(new Set([
11988
- ...view.evidence.filter((entry) => entry.status === "stale").map((entry) => `stale evidence: ${entry.evidenceId}`),
11989
- ...view.requirements.filter((entry) => entry.status !== "satisfied").map((entry) => entry.reason),
11990
- ...view.task.progress.blockers.map((entry) => entry.reason)
11991
- ])).sort().slice(0, COMPACT_MAX_ITEMS).map((gap) => compactText(gap, COMPACT_TEXT_BYTES));
11992
- const context = {
11993
- objective: compactText(view.task.intent.data.objective, COMPACT_TEXT_BYTES) ?? "",
11994
- status: view.task.status,
11995
- decisions,
11996
- methods,
11997
- gaps,
11998
- nextAction: compactText(view.task.progress.nextAction, COMPACT_TEXT_BYTES)
11999
- };
12000
- let encoded = JSON.stringify(context);
12001
- while (compactBytes(encoded) > COMPACT_MAX_BYTES && (context.decisions.length || context.methods.length || context.gaps.length)) {
12002
- if (context.gaps.length)
12003
- context.gaps.pop();
12004
- else if (context.decisions.length)
12005
- context.decisions.pop();
12006
- else
12007
- context.methods.pop();
12008
- encoded = JSON.stringify(context);
11820
+ var walk = (root, directory, output) => {
11821
+ let names;
11822
+ try {
11823
+ names = fs7.readdirSync(directory);
11824
+ } catch {
11825
+ return true;
12009
11826
  }
12010
- if (compactBytes(encoded) > COMPACT_MAX_BYTES) {
12011
- context.objective = compactText(context.objective, 64) ?? "";
12012
- context.nextAction = compactText(context.nextAction, 64);
12013
- encoded = JSON.stringify(context);
11827
+ let uncertain = false;
11828
+ for (const name of names) {
11829
+ if (name === ".git" || name === ".workit")
11830
+ continue;
11831
+ const target = path10.join(directory, name);
11832
+ let stat;
11833
+ try {
11834
+ stat = fs7.lstatSync(target);
11835
+ } catch {
11836
+ uncertain = true;
11837
+ continue;
11838
+ }
11839
+ const item = relative(root, target);
11840
+ output.add(item);
11841
+ if (stat.isDirectory() && !stat.isSymbolicLink())
11842
+ uncertain = walk(root, target, output) || uncertain;
12014
11843
  }
12015
- return encoded;
12016
- }
12017
- var exportDigest = (bundle) => sha256({
12018
- schemaVersion: bundle.schemaVersion,
12019
- exportedAt: bundle.exportedAt,
12020
- sourceWorkspaceId: bundle.sourceWorkspaceId,
12021
- task: bundle.task
12022
- });
12023
- // packages/workit-core/src/core/external-action.ts
12024
- var chainStepSchema = union([
12025
- string2().min(1),
12026
- object({ branch: string2().min(1) }).strict(),
12027
- object({ pr: literal(true) }).strict()
12028
- ]);
12029
- var externalActionSchema = discriminatedUnion("operation", [
12030
- object({
12031
- operation: literal("git.branch_setup"),
12032
- payload: object({
12033
- action: _enum(["setup", "reapply_stash"]).optional(),
12034
- sdd_dir: string2().optional(),
12035
- target_branch: string2().optional(),
12036
- stash: _enum(["yes", "no"]).optional(),
12037
- cwd: string2().min(1).optional()
12038
- }).strict()
12039
- }).strict(),
12040
- object({
12041
- operation: literal("git.commit"),
12042
- payload: object({
12043
- message: string2().min(1).optional(),
12044
- plan_steps: array(chainStepSchema).min(1).max(32).optional(),
12045
- plan_branch: string2().min(1).optional(),
12046
- cwd: string2().min(1).optional()
12047
- }).strict()
12048
- }).strict(),
12049
- object({
12050
- operation: literal("git.push"),
12051
- payload: object({ branch: string2().min(1).optional(), cwd: string2().min(1).optional() }).strict()
12052
- }).strict(),
12053
- object({
12054
- operation: literal("hosting.pull_request"),
12055
- payload: object({
12056
- title: string2().min(1),
12057
- body: string2().optional(),
12058
- draft: boolean2().optional(),
12059
- target_branch: string2().optional(),
12060
- babysit: boolean2().optional(),
12061
- cwd: string2().min(1).optional()
12062
- }).strict()
12063
- }).strict(),
12064
- object({
12065
- operation: literal("hosting.merge"),
12066
- payload: object({
12067
- target_branch: string2().min(1).optional(),
12068
- source_branch: string2().min(1).optional(),
12069
- cwd: string2().min(1).optional()
12070
- }).strict()
12071
- }).strict(),
12072
- object({
12073
- operation: literal("hosting.delete_branch"),
12074
- payload: object({ branch: string2().min(1), cwd: string2().min(1).optional() }).strict()
12075
- }).strict(),
12076
- object({
12077
- operation: literal("youtrack.update"),
12078
- payload: object({
12079
- issueId: string2().min(1),
12080
- markdown: string2().min(1),
12081
- minutes: number2().positive().optional()
12082
- }).strict()
12083
- }).strict(),
12084
- object({
12085
- operation: literal("youtrack.time"),
12086
- payload: object({
12087
- issueId: string2().min(1),
12088
- minutes: number2().positive(),
12089
- text: string2().optional(),
12090
- dateMs: number2().finite().optional()
12091
- }).strict()
12092
- }).strict(),
12093
- object({
12094
- operation: literal("youtrack.meeting"),
12095
- payload: object({
12096
- issueId: string2().min(1),
12097
- minutes: number2().positive(),
12098
- text: string2().min(1)
12099
- }).strict()
12100
- }).strict(),
12101
- object({
12102
- operation: literal("changelog.apply"),
12103
- payload: object({
12104
- entries: union([
12105
- record(string2(), array(string2())),
12106
- array(object({ category: string2().min(1), text: string2().min(1) }).strict())
12107
- ]).optional(),
12108
- path: string2().optional(),
12109
- normalize_only: boolean2().optional()
12110
- }).strict()
12111
- }).strict(),
12112
- object({
12113
- operation: literal("context.read"),
12114
- payload: object({
12115
- kind: _enum([
12116
- "git",
12117
- "pr",
12118
- "youtrack",
12119
- "github_issue",
12120
- "gitlab_issue",
12121
- "changelog",
12122
- "release",
12123
- "affected"
12124
- ]),
12125
- range: string2().optional(),
12126
- issueId: string2().optional(),
12127
- issueUrl: string2().optional(),
12128
- issueRef: string2().optional(),
12129
- mode: string2().optional(),
12130
- specPath: string2().optional(),
12131
- planPath: string2().optional(),
12132
- cwd: string2().min(1).optional()
12133
- }).strict()
12134
- }).strict()
12135
- ]);
12136
- // packages/workit-core/src/core/task-engine.ts
12137
- import { realpathSync as realpathSync6 } from "node:fs";
12138
-
12139
- // packages/workit-core/src/core/policy-resolver.ts
12140
- var resolverInputSchema = object({
12141
- intent: intentSchema,
12142
- assessment: assessmentSchema,
12143
- constraints: array(constraintSchema),
12144
- prior: object({
12145
- decisions: array(decisionSchema),
12146
- findings: array(findingSchema),
12147
- requirements: array(requirementSchema)
12148
- }).strict(),
12149
- preferences: object({ fast: boolean2().optional(), thorough: boolean2().optional() }).strict().optional()
12150
- }).strict();
12151
- var compareCodeUnits3 = (left, right) => {
12152
- const length = Math.min(left.length, right.length);
12153
- for (let index = 0;index < length; index += 1) {
12154
- const difference = left.charCodeAt(index) - right.charCodeAt(index);
12155
- if (difference !== 0)
12156
- return difference;
11844
+ return uncertain;
11845
+ };
11846
+ var scopeRoots = (root, scope) => {
11847
+ const roots = [];
11848
+ for (const item of scope.paths.length ? scope.paths : ["."]) {
11849
+ const target = path10.resolve(root, item);
11850
+ if (!inside(root, target))
11851
+ 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` }] });
11852
+ let ancestor = target;
11853
+ while (!fs7.existsSync(ancestor) && ancestor !== root)
11854
+ ancestor = path10.dirname(ancestor);
11855
+ try {
11856
+ if (!inside(root, fs7.realpathSync(ancestor)))
11857
+ 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` }] });
11858
+ } catch {
11859
+ return failure("invalid_input", `candidate scope cannot be inspected: ${item}`);
11860
+ }
11861
+ roots.push(target);
12157
11862
  }
12158
- return left.length - right.length;
11863
+ return success(null, null, roots);
12159
11864
  };
12160
- var stableUnique = (values) => [...new Set(values)].sort(compareCodeUnits3);
12161
- var stableList = (values) => [...values].sort((left, right) => compareCodeUnits3(canonicalJson(left), canonicalJson(right)));
12162
- var normalizedScope = (scope) => ({
12163
- description: scope.description,
12164
- paths: stableUnique(scope.paths),
12165
- exclusions: stableUnique(scope.exclusions)
12166
- });
12167
- var normalizedRefList = (values) => stableList(values);
12168
- var normalizeAssessment = (assessment) => ({
12169
- facts: stableList(assessment.facts.map((fact) => ({ ...fact, refs: normalizedRefList(fact.refs) }))),
12170
- signals: Object.fromEntries(Object.entries(assessment.signals).map(([name, signal]) => [
11865
+ function captureCandidate(root, scope, environment = []) {
11866
+ let checkout;
11867
+ try {
11868
+ checkout = fs7.realpathSync(root);
11869
+ } catch {
11870
+ return failure("invalid_input", "candidate root does not exist");
11871
+ }
11872
+ const normalizedScope = canonicalScope(scope);
11873
+ if (!normalizedScope)
11874
+ 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" }] });
11875
+ const roots = scopeRoots(checkout, normalizedScope);
11876
+ if (!roots.ok)
11877
+ return roots;
11878
+ const git = gitPaths(checkout);
11879
+ const names = new Set;
11880
+ let uncertain = git.uncertain;
11881
+ for (const target of roots.data) {
11882
+ const item = relative(checkout, target);
11883
+ if (item === ".git" || item === ".workit")
11884
+ continue;
11885
+ names.add(item);
11886
+ if (!fs7.existsSync(target))
11887
+ continue;
11888
+ let stat;
11889
+ try {
11890
+ stat = fs7.lstatSync(target);
11891
+ } catch {
11892
+ uncertain = true;
11893
+ continue;
11894
+ }
11895
+ if (!git.git && stat.isDirectory() && !stat.isSymbolicLink())
11896
+ uncertain = walk(checkout, target, names) || uncertain;
11897
+ }
11898
+ for (const item of git.paths)
11899
+ if (scopeMatches(item, normalizedScope))
11900
+ names.add(item);
11901
+ const files = [];
11902
+ let completeness = uncertain ? "uncertain" : "known";
11903
+ for (const item of [...names].sort()) {
11904
+ if (!scopeMatches(item, normalizedScope))
11905
+ continue;
11906
+ const target = path10.join(checkout, item);
11907
+ try {
11908
+ const stat = fs7.lstatSync(target);
11909
+ if (stat.isSymbolicLink()) {
11910
+ const link = fs7.readlinkSync(target);
11911
+ files.push({ path: item, kind: "symlink", digest: digestBytes3(link), executable: null });
11912
+ } else if (stat.isFile()) {
11913
+ files.push({
11914
+ path: item,
11915
+ kind: "file",
11916
+ digest: digestBytes3(fs7.readFileSync(target)),
11917
+ executable: (stat.mode & 73) !== 0
11918
+ });
11919
+ } else if (!stat.isDirectory()) {
11920
+ completeness = "uncertain";
11921
+ } else if (git.git && git.paths.includes(item)) {
11922
+ completeness = "uncertain";
11923
+ }
11924
+ } catch (error) {
11925
+ if (error?.code === "ENOENT") {
11926
+ files.push({ path: item, kind: "absent", digest: null, executable: null });
11927
+ } else
11928
+ completeness = "uncertain";
11929
+ }
11930
+ }
11931
+ 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) => ({
12171
11932
  name,
12172
- { ...signal, refs: normalizedRefList(signal.refs) }
12173
- ])),
12174
- consequences: stableList(assessment.consequences.map((consequence) => ({
12175
- ...consequence,
12176
- fact: { ...consequence.fact, refs: normalizedRefList(consequence.fact.refs) }
12177
- }))),
12178
- verification: stableList(assessment.verification.map((verification) => ({
12179
- ...verification,
12180
- scope: normalizedScope(verification.scope),
12181
- availableChecks: normalizedRefList(verification.availableChecks),
12182
- gaps: stableUnique(verification.gaps)
12183
- })))
12184
- });
12185
- var normalizeConstraint = (constraint) => ({
12186
- ...constraint,
12187
- source: constraint.source,
12188
- requires: stableList(constraint.requires.map((requirement) => ({
12189
- ...requirement,
12190
- scope: normalizedScope(requirement.scope),
12191
- refs: normalizedRefList(requirement.refs)
12192
- })))
12193
- });
12194
- var normalizeDecision = (decision) => ({
12195
- ...decision,
12196
- binding: {
12197
- ...decision.binding,
12198
- scope: normalizedScope(decision.binding.scope),
12199
- contentRefs: normalizedRefList(decision.binding.contentRefs)
12200
- },
12201
- requirementIds: stableUnique(decision.requirementIds)
12202
- });
12203
- var normalizeIntent = (intent) => ({
12204
- ...intent,
12205
- scope: normalizedScope(intent.scope),
12206
- authorityRefs: normalizedRefList(intent.authorityRefs)
12207
- });
12208
- var normalizePrior = (prior) => ({
12209
- decisions: stableList(prior.decisions.map(normalizeDecision)),
12210
- findings: stableList(prior.findings.map((finding) => ({
12211
- ...finding,
12212
- scope: normalizedScope(finding.scope),
12213
- refs: normalizedRefList(finding.refs),
12214
- resolution: finding.resolution ? {
12215
- ...finding.resolution,
12216
- evidenceIds: stableUnique(finding.resolution.evidenceIds),
12217
- decisionIds: stableUnique(finding.resolution.decisionIds)
12218
- } : null
12219
- }))),
12220
- requirements: stableList(prior.requirements.map((requirement) => ({
12221
- ...requirement,
12222
- scope: normalizedScope(requirement.scope)
12223
- })))
12224
- });
12225
- var invalidFields = (error) => ({
12226
- fields: error.issues.map((issue) => ({
12227
- path: issue.code === "unrecognized_keys" ? issue.keys.join(".") : issue.path.join("."),
12228
- reason: issue.message
12229
- }))
12230
- });
12231
- function normalizeResolverInput(input) {
12232
- const parsed = resolverInputSchema.safeParse(input);
12233
- if (!parsed.success)
12234
- return failure("invalid_input", "resolver input is invalid", invalidFields(parsed.error));
12235
- const value = parsed.data;
12236
- const signals = value.assessment.signals;
12237
- if (signals.behaviorChange.value === true && signals.mechanicalLowRisk.value === true)
12238
- return failure("invalid_input", "behavioral change cannot be wholly mechanical", {
12239
- fields: [
12240
- {
12241
- path: "assessment.signals",
12242
- reason: "contradictory behaviorChange and mechanicalLowRisk"
12243
- }
12244
- ]
12245
- });
12246
- const ids = value.constraints.map((constraint) => constraint.id);
12247
- if (new Set(ids).size !== ids.length)
12248
- return failure("invalid_input", "constraint IDs must be unique", {
12249
- fields: [{ path: "constraints", reason: "duplicate constraint id" }]
12250
- });
12251
- if (value.preferences?.fast && value.preferences.thorough)
12252
- return failure("invalid_input", "fast and thorough preferences contradict", {
12253
- fields: [{ path: "preferences", reason: "fast and thorough cannot both be enabled" }]
12254
- });
12255
- const normalized = {
12256
- intent: normalizeIntent(value.intent),
12257
- assessment: normalizeAssessment(value.assessment),
12258
- constraints: stableList(value.constraints.map(normalizeConstraint)),
12259
- prior: normalizePrior(value.prior),
12260
- ...value.preferences ? { preferences: { ...value.preferences } } : {},
12261
- policyVersion: POLICY_VERSION
11933
+ value: environment[name] ?? null
11934
+ }));
11935
+ const namesByEnvironment = supplied.map(({ name }) => name);
11936
+ if (new Set(namesByEnvironment).size !== namesByEnvironment.length || namesByEnvironment.some((name) => typeof name !== "string" || !name))
11937
+ return failure("invalid_input", "candidate environment names must be unique and non-empty");
11938
+ const values = supplied.sort((left, right) => compareCodeUnits3(left.name, right.name)).map(({ name, value }) => ({ name, value, refs: [] }));
11939
+ if (values.some(({ value }) => value === null))
11940
+ completeness = "uncertain";
11941
+ const headResult = spawnSync2("git", ["rev-parse", "HEAD"], { cwd: checkout, encoding: "utf8" });
11942
+ if (headResult.status !== 0 && !/not a git repository/i.test(headResult.stderr ?? ""))
11943
+ completeness = "uncertain";
11944
+ const head = headResult.status === 0 ? headResult.stdout.trim() : null;
11945
+ const partial = {
11946
+ id: "0".repeat(64),
11947
+ scope: normalizedScope,
11948
+ completeness,
11949
+ files,
11950
+ environment: values,
11951
+ head
12262
11952
  };
12263
- return success(null, null, normalized);
11953
+ const candidate = { ...partial, id: candidateDigest(partial) };
11954
+ const parsed = candidateSchema.safeParse(candidate);
11955
+ return parsed.success ? success(null, null, parsed.data) : failure("invalid_input", "captured candidate is invalid");
12264
11956
  }
12265
- var requirement = (spec) => ({
12266
- ...spec,
12267
- id: requirementId({
12268
- ruleId: spec.ruleId,
12269
- scope: spec.scope,
12270
- satisfaction: spec.satisfaction,
12271
- before: spec.before,
12272
- dependentAction: spec.dependentAction
12273
- })
12274
- });
12275
- var signalReason = (input, name) => input.assessment.signals[name].reason;
12276
- function resolveRequirements(input) {
12277
- const { signals } = input.assessment;
12278
- const scope = input.intent.scope;
12279
- const requirements = [];
12280
- const hasUnknownSignal = Object.values(signals).some((signal) => signal.value === "unknown");
12281
- const hasUnknownFact = [
12282
- ...input.assessment.facts,
12283
- ...input.assessment.consequences.map(({ fact }) => fact)
12284
- ].some((fact) => fact.basis === "unknown");
12285
- if (hasUnknownSignal || hasUnknownFact)
12286
- requirements.push(requirement({
12287
- ruleId: "consequential-unknown",
12288
- dimension: "investigation",
12289
- scope,
12290
- reason: `Resolve consequential uncertainty before the dependent action: ${[
12291
- ...Object.entries(signals).filter(([, signal]) => signal.value === "unknown").map(([name]) => name),
12292
- ...hasUnknownFact ? ["unknown fact"] : []
12293
- ].join(", ")}`,
12294
- satisfaction: "An observed or inferred fact resolves the uncertainty and records its supporting references.",
12295
- before: "dependent_action",
12296
- dependentAction: null,
12297
- acceptanceAllowed: false
12298
- }));
12299
- if (signals.productChoiceOpen.value === true)
12300
- requirements.push(requirement({
12301
- ruleId: "product-decision",
12302
- dimension: "decisions",
12303
- scope,
12304
- reason: `A consequential product choice remains open: ${signalReason(input, "productChoiceOpen")}`,
12305
- satisfaction: "Present the material alternatives and record the user's decision before the dependent action.",
12306
- before: "dependent_action",
12307
- dependentAction: null,
12308
- acceptanceAllowed: false
11957
+ var fileMap = (candidate) => new Map(candidate.files.map((file) => [file.path, file]));
11958
+ var changedPaths = (before, after) => {
11959
+ const paths = new Set([...before.files, ...after.files].map((file) => file.path));
11960
+ const left = fileMap(before);
11961
+ const right = fileMap(after);
11962
+ const changed = [...paths].filter((item) => JSON.stringify(left.get(item) ?? null) !== JSON.stringify(right.get(item) ?? null));
11963
+ if (before.head !== after.head)
11964
+ changed.push(".");
11965
+ if (JSON.stringify(before.environment) !== JSON.stringify(after.environment))
11966
+ changed.push(".");
11967
+ return changed;
11968
+ };
11969
+ var sessionFromRef = (value) => {
11970
+ if (typeof value !== "object" || value === null || value.kind !== "host")
11971
+ return null;
11972
+ return typeof value.host === "string" && typeof value.handle === "string" ? { host: value.host, handle: value.handle } : null;
11973
+ };
11974
+ var sameSession = (left, right) => {
11975
+ const other = sessionFromRef(right);
11976
+ return left !== null && other !== null && left.host === other.host && left.handle === other.handle;
11977
+ };
11978
+ var evidenceScopes = (task, ids) => (task.policy?.requirements ?? []).filter((requirement) => ids.includes(requirement.id)).map((requirement) => requirement.scope);
11979
+ function evaluateEvidence(task, candidate) {
11980
+ const current = candidate ?? task.candidates.at(-1) ?? null;
11981
+ return task.evidence.map((entry) => {
11982
+ const evidence = entry.data;
11983
+ if (evidence.result === "failed")
11984
+ return {
11985
+ evidenceId: entry.id,
11986
+ status: "failed",
11987
+ reason: "failed evidence remains historical"
11988
+ };
11989
+ if (evidence.kind === "check" || evidence.kind === "review") {
11990
+ if (!evidence.beforeCandidateId || !evidence.candidateId)
11991
+ return {
11992
+ evidenceId: entry.id,
11993
+ status: "stale",
11994
+ reason: "check or review evidence lacks start and end candidates"
11995
+ };
11996
+ if (evidence.beforeCandidateId !== evidence.candidateId)
11997
+ return {
11998
+ evidenceId: entry.id,
11999
+ status: "stale",
12000
+ reason: "candidate changed during the check or review"
12001
+ };
12002
+ }
12003
+ if (!evidence.candidateId || !current)
12004
+ return {
12005
+ evidenceId: entry.id,
12006
+ status: evidence.result,
12007
+ reason: "evidence has no candidate binding"
12008
+ };
12009
+ const observed = task.candidates.find((item) => item.id === evidence.candidateId) ?? (current.id === evidence.candidateId ? current : undefined);
12010
+ if (!observed || observed.completeness === "uncertain" || current.completeness === "uncertain")
12011
+ return { evidenceId: entry.id, status: "stale", reason: "candidate is missing or uncertain" };
12012
+ if (observed.id === current.id)
12013
+ return { evidenceId: entry.id, status: evidence.result, reason: "candidate is unchanged" };
12014
+ const scopes = evidenceScopes(task, evidence.requirementIds);
12015
+ const changed = changedPaths(observed, current);
12016
+ const environmentChanged = JSON.stringify(observed.environment) !== JSON.stringify(current.environment);
12017
+ if (!scopes.length || environmentChanged || changed.some((item) => scopes.some((scope) => pathRelevant(item, scope))))
12018
+ return { evidenceId: entry.id, status: "stale", reason: "relevant candidate state changed" };
12019
+ return {
12020
+ evidenceId: entry.id,
12021
+ status: evidence.result,
12022
+ reason: "candidate changed outside evidence scope"
12023
+ };
12024
+ });
12025
+ }
12026
+ var scopeCovers2 = scopeCovers;
12027
+ var checkPin = (assignment, beforeCandidateId, candidateId) => {
12028
+ const pin = assignment.candidateId ?? null;
12029
+ if (pin === null)
12030
+ return true;
12031
+ return (beforeCandidateId ?? null) === pin || (candidateId ?? null) === pin;
12032
+ };
12033
+ var resolveBinding = (evidence, pin, currentCandidateId) => {
12034
+ const bound = evidence.kind === "check" || evidence.kind === "review";
12035
+ const fallback = bound ? pin ?? currentCandidateId : null;
12036
+ return {
12037
+ beforeCandidateId: evidence.beforeCandidateId ?? fallback,
12038
+ candidateId: evidence.candidateId ?? fallback
12039
+ };
12040
+ };
12041
+ var findingVerificationPasses = (findingCandidateId, evidence) => evidence.status === "passed" && (evidence.kind === "check" || evidence.kind === "review") && ((findingCandidateId ?? null) === null || evidence.candidateId != null);
12042
+ 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")));
12043
+ 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 }));
12044
+ var evidenceMatchesRequirement = (kind, evidenceKind, dimension, ruleId) => {
12045
+ if (kind !== "passed")
12046
+ return false;
12047
+ if (dimension === "testing" || dimension === "verification")
12048
+ return evidenceKind === "check" || ruleId === "pre-pr-cleanup" && evidenceKind === "artifact";
12049
+ if (dimension === "review")
12050
+ return evidenceKind === "review";
12051
+ if (dimension === "investigation" || dimension === "challenge")
12052
+ return evidenceKind === "investigation";
12053
+ if (dimension === "artifacts" || dimension === "continuity")
12054
+ return evidenceKind === "artifact";
12055
+ return false;
12056
+ };
12057
+ var expectedKinds = (dimension, ruleId) => {
12058
+ if (dimension === "testing")
12059
+ return "check";
12060
+ if (dimension === "verification")
12061
+ return ruleId === "pre-pr-cleanup" ? "check or artifact" : "check";
12062
+ if (dimension === "review")
12063
+ return "review";
12064
+ if (dimension === "investigation" || dimension === "challenge")
12065
+ return "investigation";
12066
+ if (dimension === "artifacts" || dimension === "continuity")
12067
+ return "artifact";
12068
+ if (dimension === "decisions")
12069
+ return "decision";
12070
+ return "worker report";
12071
+ };
12072
+ function evaluateRequirements(task, workspace, capabilities, candidate, checkoutRoot, _caller) {
12073
+ const evidence = evaluateEvidence(task, candidate);
12074
+ if (task.policy && task.policy.policyVersion !== POLICY_VERSION)
12075
+ return task.policy.requirements.map((requirement) => ({
12076
+ requirementId: requirement.id,
12077
+ status: "unsatisfied",
12078
+ evidenceIds: [],
12079
+ decisionIds: [],
12080
+ reason: "stored policy version is unsupported; reassessment is required"
12309
12081
  }));
12310
- const independentBehaviorReview = input.preferences?.thorough === true || input.assessment.consequences.some((consequence) => ["security", "data", "public_contract", "operations"].includes(consequence.area));
12311
- if (signals.behaviorChange.value === true)
12312
- requirements.push(requirement({
12313
- ruleId: "behavioral-verification",
12314
- dimension: "testing",
12315
- scope,
12316
- reason: `Behavior, side effects, permissions, or data handling may change: ${signalReason(input, "behaviorChange")}`,
12317
- satisfaction: "A useful behavioral check passes against the affected behavior and current candidate.",
12318
- before: "close",
12319
- dependentAction: null,
12320
- acceptanceAllowed: false
12321
- }), requirement({
12322
- ruleId: independentBehaviorReview ? "fresh-context-review" : "self-review",
12323
- dimension: "review",
12324
- scope,
12325
- 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.",
12326
- 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.",
12327
- before: "close",
12328
- dependentAction: null,
12329
- acceptanceAllowed: !independentBehaviorReview
12330
- }));
12331
- else if (signals.mechanicalLowRisk.value === true)
12332
- requirements.push(requirement({
12333
- ruleId: "mechanical-existing-checks",
12334
- dimension: "verification",
12335
- scope,
12336
- reason: `The change is demonstrably mechanical and low-risk: ${signalReason(input, "mechanicalLowRisk")}`,
12337
- satisfaction: "Run the relevant existing checks for affected consumers; do not add tautological tests.",
12338
- before: "close",
12339
- dependentAction: null,
12340
- acceptanceAllowed: true
12341
- }), requirement({
12342
- ruleId: input.preferences?.thorough ? "fresh-context-review" : "self-review",
12343
- dimension: "review",
12344
- scope,
12345
- 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.",
12346
- 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.",
12347
- before: "close",
12348
- dependentAction: null,
12349
- acceptanceAllowed: !input.preferences?.thorough
12350
- }));
12351
- if (signals.behaviorChange.value === true || signals.mechanicalLowRisk.value === true)
12352
- requirements.push(requirement({
12353
- ruleId: "pre-pr-cleanup",
12354
- dimension: "verification",
12355
- scope,
12356
- reason: "Implementation output must be deslopped before it is delivered.",
12357
- satisfaction: "Run the workit-deslop pass and record passing check evidence, or record an approved limitation decision waiving cleanup.",
12358
- before: "dependent_action",
12359
- dependentAction: "hosting.pull_request",
12360
- acceptanceAllowed: true
12361
- }));
12362
- if (signals.durableAgreementNeeded.value === true)
12363
- requirements.push(requirement({
12364
- ruleId: "durable-spec",
12365
- dimension: "artifacts",
12366
- scope,
12367
- reason: `The work needs a durable agreement about intended behavior: ${signalReason(input, "durableAgreementNeeded")}`,
12368
- satisfaction: "Record the agreed behavior in a durable specification before implementation writes.",
12369
- before: "write",
12370
- dependentAction: null,
12371
- acceptanceAllowed: true
12372
- }));
12373
- if (signals.coordinationPlanNeeded.value === true)
12374
- requirements.push(requirement({
12375
- ruleId: "coordination-plan",
12376
- dimension: "continuity",
12377
- scope,
12378
- reason: `Dependencies, sequencing, or resumption need durable coordination: ${signalReason(input, "coordinationPlanNeeded")}`,
12379
- satisfaction: "Record useful sequencing, dependencies, and the next action in a compact plan.",
12380
- before: "dependent_action",
12381
- dependentAction: null,
12382
- acceptanceAllowed: true
12383
- }));
12384
- if (signals.helperUseful.value === true && !input.preferences?.fast)
12385
- requirements.push(requirement({
12386
- ruleId: "helper-usefulness",
12387
- dimension: "delegation",
12388
- scope,
12389
- reason: `Independent judgment or investigation justifies a scoped helper: ${signalReason(input, "helperUseful")}`,
12390
- satisfaction: "Use a bounded helper only for the independent objective and reconcile its result.",
12391
- before: "dependent_action",
12392
- dependentAction: null,
12393
- acceptanceAllowed: true
12394
- }));
12395
- for (const constraint of input.constraints)
12396
- for (const obligation of constraint.requires) {
12397
- const dimension = obligation.method ?? (obligation.kind === "check" ? "verification" : obligation.kind === "decision" ? "decisions" : "challenge");
12398
- requirements.push(requirement({
12399
- ruleId: `project-constraint:${constraint.id}:${obligation.kind}:${sha256({
12400
- kind: obligation.kind,
12401
- scope: normalizedScope(obligation.scope),
12402
- refs: normalizedRefList(obligation.refs),
12403
- method: obligation.method,
12404
- before: obligation.before,
12405
- dependentAction: obligation.dependentAction
12406
- })}`,
12407
- dimension,
12408
- scope: obligation.scope,
12409
- reason: `${constraint.kind} constraint requires ${obligation.kind}: ${constraint.statement}`,
12410
- satisfaction: `Satisfy the constraint obligation using its referenced ${obligation.kind}.`,
12411
- before: obligation.before,
12412
- dependentAction: obligation.dependentAction,
12413
- acceptanceAllowed: constraint.acceptanceAllowed && obligation.kind !== "decision"
12414
- }));
12082
+ return (task.policy?.requirements ?? []).map((requirement) => {
12083
+ const related = task.evidence.map((entry, index) => ({ entry, evaluation: evidence[index] })).filter(({ entry }) => entry.data.requirementIds.includes(requirement.id));
12084
+ const passed = related.filter(({ entry, evaluation }) => {
12085
+ if (!evidenceMatchesRequirement(evaluation.status, entry.data.kind, requirement.dimension, requirement.ruleId))
12086
+ return false;
12087
+ if ((entry.data.kind === "check" || entry.data.kind === "review") && (!entry.data.beforeCandidateId || !entry.data.candidateId || entry.data.beforeCandidateId !== entry.data.candidateId))
12088
+ return false;
12089
+ if (requirement.dimension !== "review")
12090
+ return true;
12091
+ const reviewSession = sessionFromRef(entry.data.reviewContext);
12092
+ const sameImplementation = sameSession(reviewSession, task.intent.provenance.session);
12093
+ 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));
12094
+ return entry.data.kind === "review" && reviewSession !== null && sameSession(reviewSession, entry.provenance.session) && (requirement.ruleId === "self-review" || !sameImplementation && !sameEvidenceSession);
12095
+ });
12096
+ if (passed.length) {
12097
+ const currentId = candidate?.id ?? null;
12098
+ 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;
12099
+ if (withRed.length)
12100
+ return {
12101
+ requirementId: requirement.id,
12102
+ status: "satisfied",
12103
+ evidenceIds: withRed.map(({ entry }) => entry.id),
12104
+ decisionIds: [],
12105
+ reason: "fresh applicable evidence passed"
12106
+ };
12107
+ if (requirement.dimension === "testing")
12108
+ return {
12109
+ requirementId: requirement.id,
12110
+ status: "unsatisfied",
12111
+ evidenceIds: [],
12112
+ decisionIds: [],
12113
+ reason: "testing requirement has GREEN evidence but no preceding RED"
12114
+ };
12415
12115
  }
12416
- const seen = new Set;
12417
- return requirements.filter((item) => {
12418
- if (seen.has(item.id))
12116
+ if (requirement.dimension === "delegation") {
12117
+ const dot = (scope) => scope.paths.length > 0 ? scope : { ...scope, paths: ["."] };
12118
+ 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))));
12119
+ if (reconciled)
12120
+ return {
12121
+ requirementId: requirement.id,
12122
+ status: "satisfied",
12123
+ evidenceIds: [],
12124
+ decisionIds: [],
12125
+ reason: "bounded helper completed and its result is recorded"
12126
+ };
12127
+ }
12128
+ const decisions = requirement.dimension === "decisions" ? applicableRequirementDecision(task, workspace, requirement, checkoutRoot) : [];
12129
+ if (decisions.length)
12130
+ return {
12131
+ requirementId: requirement.id,
12132
+ status: "satisfied",
12133
+ evidenceIds: [],
12134
+ decisionIds: decisions.map((decision) => decision.id),
12135
+ reason: "an applicable approved or stated decision satisfies the requirement"
12136
+ };
12137
+ const limitations = requirement.acceptanceAllowed ? applicableDecision2(task, workspace, requirement, checkoutRoot) : [];
12138
+ if (limitations.length)
12139
+ return {
12140
+ requirementId: requirement.id,
12141
+ status: "accepted_limitation",
12142
+ evidenceIds: [],
12143
+ decisionIds: limitations.map((decision) => task.decisions.find((entry) => entry.data === decision).id),
12144
+ reason: "an applicable approved limitation permits the missing evidence"
12145
+ };
12146
+ const unavailable = capabilities.some((capability) => capability.assurance === "unavailable" && (capability.name === requirement.dimension || capability.surface === requirement.dimension));
12147
+ if (!unavailable && related.length > 0 && !passed.length)
12148
+ return {
12149
+ requirementId: requirement.id,
12150
+ status: "unsatisfied",
12151
+ evidenceIds: related.map(({ entry }) => entry.id),
12152
+ decisionIds: [],
12153
+ reason: `no passing evidence (needs kind:${expectedKinds(requirement.dimension, requirement.ruleId)})`
12154
+ };
12155
+ return {
12156
+ requirementId: requirement.id,
12157
+ status: unavailable ? "unavailable" : "unsatisfied",
12158
+ evidenceIds: related.map(({ entry }) => entry.id),
12159
+ decisionIds: [],
12160
+ reason: unavailable ? "required capability is unavailable" : "no fresh passing evidence"
12161
+ };
12162
+ });
12163
+ }
12164
+ function evaluateClosure(requestedOutcome, view) {
12165
+ if (requestedOutcome !== "stopped" && !view.task.policy)
12166
+ return failure("requirements_unsatisfied", "task has not been assessed");
12167
+ if (view.task.policy && view.task.policy.policyVersion !== POLICY_VERSION)
12168
+ return failure("requirements_unsatisfied", "stored policy version is unsupported; reassessment is required");
12169
+ const evaluations = view.requirements;
12170
+ const openFindings = view.task.findings.filter((entry) => entry.data.disposition === "open");
12171
+ if (requestedOutcome !== "stopped" && openFindings.length)
12172
+ return failure("requirements_unsatisfied", "open findings must be resolved before closure");
12173
+ if (requestedOutcome !== "stopped") {
12174
+ const evidenceById = new Map(view.evidence.map((entry) => [entry.evidenceId, entry.status]));
12175
+ for (const entry of view.task.findings) {
12176
+ if (entry.data.disposition === "fixed") {
12177
+ const verified = entry.data.resolution?.evidenceIds.some((id) => {
12178
+ const evidence = view.task.evidence.find((item) => item.id === id);
12179
+ if (!evidence)
12180
+ return false;
12181
+ return findingVerificationPasses(entry.data.candidateId, {
12182
+ kind: evidence.data.kind,
12183
+ candidateId: evidence.data.candidateId,
12184
+ status: evidenceById.get(id) ?? "missing"
12185
+ });
12186
+ });
12187
+ if (!verified)
12188
+ return failure("requirements_unsatisfied", "fixed findings require current verification");
12189
+ }
12190
+ if (entry.data.disposition === "deferred") {
12191
+ const valid = entry.data.resolution?.decisionIds.some((id) => {
12192
+ const decisionEntry = view.task.decisions.find((item) => item.id === id);
12193
+ const decision = decisionEntry?.data;
12194
+ 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)));
12195
+ });
12196
+ if (!valid)
12197
+ return failure("requirements_unsatisfied", "deferred findings require an approved limitation decision that references an acceptanceAllowed requirement and covers the finding scope");
12198
+ }
12199
+ }
12200
+ }
12201
+ const blocking = evaluations.filter((item) => {
12202
+ if (item.status !== "unsatisfied" && item.status !== "unavailable")
12419
12203
  return false;
12420
- seen.add(item.id);
12421
- return true;
12204
+ const requirement = view.task.policy?.requirements.find((candidate) => candidate.id === item.requirementId);
12205
+ return !requirement || requirement.before === "close";
12206
+ });
12207
+ if (requestedOutcome !== "stopped" && blocking.length)
12208
+ return failure("requirements_unsatisfied", "applicable requirements are unsatisfied", {
12209
+ requirementIds: blocking.map((item) => item.requirementId),
12210
+ requirements: blocking.map((item) => {
12211
+ const requirement = view.task.policy?.requirements.find((candidate) => candidate.id === item.requirementId);
12212
+ return {
12213
+ requirementId: item.requirementId,
12214
+ ruleId: requirement?.ruleId ?? "unknown",
12215
+ reason: item.reason,
12216
+ satisfaction: requirement?.satisfaction ?? "",
12217
+ dependentAction: requirement?.dependentAction ?? null
12218
+ };
12219
+ })
12220
+ });
12221
+ const accepted = evaluations.filter((item) => item.status === "accepted_limitation");
12222
+ if (requestedOutcome === "verified" && accepted.length)
12223
+ return failure("requirements_unsatisfied", "accepted limitations cannot be reported as verified", {
12224
+ requirementIds: accepted.map((item) => item.requirementId)
12225
+ });
12226
+ const evidenceIds = [
12227
+ ...new Set([
12228
+ ...evaluations.flatMap((item) => item.evidenceIds),
12229
+ ...view.task.findings.flatMap((item) => item.data.resolution?.evidenceIds ?? [])
12230
+ ])
12231
+ ];
12232
+ const decisionIds = [
12233
+ ...new Set([
12234
+ ...evaluations.flatMap((item) => item.decisionIds),
12235
+ ...view.task.findings.flatMap((item) => item.data.resolution?.decisionIds ?? [])
12236
+ ])
12237
+ ];
12238
+ return success(null, null, {
12239
+ outcome: requestedOutcome === "stopped" ? "stopped" : accepted.length ? "accepted_limitations" : "verified",
12240
+ evidenceIds,
12241
+ decisionIds,
12242
+ requirementIds: evaluations.map((item) => item.requirementId)
12243
+ });
12244
+ }
12245
+
12246
+ // packages/workit-core/src/core/methods.ts
12247
+ var METHODS = {
12248
+ "workit-challenge": { dimensions: ["challenge", "decisions"] },
12249
+ "workit-behavioral-tdd": { dimensions: ["testing"], ruleIds: ["mechanical-existing-checks"] },
12250
+ "workit-review": { dimensions: ["review"], ruleIds: ["fresh-context-review", "self-review"] },
12251
+ "workit-plan": { dimensions: ["artifacts", "continuity"] },
12252
+ "workit-implement": { dimensions: ["delegation"] },
12253
+ "workit-debug": {},
12254
+ "workit-handoff": {},
12255
+ "workit-deslop": { ruleIds: ["pre-pr-cleanup"] }
12256
+ };
12257
+ var methodMatches = (definition, requirement) => definition.dimensions?.includes(requirement.dimension) === true || definition.ruleIds?.includes(requirement.ruleId) === true;
12258
+ var assuranceFor = (id, definition, capabilities) => {
12259
+ const keys = new Set([
12260
+ id,
12261
+ ...definition.dimensions ?? [],
12262
+ ...definition.ruleIds ?? []
12263
+ ]);
12264
+ const matches = capabilities.filter((capability) => keys.has(capability.name) || keys.has(capability.surface));
12265
+ if (id === "workit-review" && matches.length === 0)
12266
+ return { assurance: "unavailable", reasons: ["independent review capability is unavailable"] };
12267
+ if (matches.some((capability) => capability.assurance === "unavailable"))
12268
+ return {
12269
+ assurance: "unavailable",
12270
+ reasons: matches.filter((capability) => capability.assurance === "unavailable").map((capability) => capability.reason)
12271
+ };
12272
+ if (matches.some((capability) => capability.assurance === "enforced"))
12273
+ return { assurance: "enforced", reasons: matches.map((capability) => capability.reason) };
12274
+ return { assurance: "agent_guided", reasons: matches.map((capability) => capability.reason) };
12275
+ };
12276
+ function selectMethods(policy, capabilities) {
12277
+ return Object.entries(METHODS).flatMap(([id, definition]) => {
12278
+ const requirements = policy.requirements.filter((requirement) => methodMatches(definition, requirement));
12279
+ if (requirements.length === 0)
12280
+ return [];
12281
+ const capability = assuranceFor(id, definition, capabilities);
12282
+ const reasons = [
12283
+ ...new Set(requirements.map((requirement) => requirement.reason)),
12284
+ ...capability.reasons
12285
+ ];
12286
+ if (capability.assurance === "unavailable")
12287
+ reasons.unshift("required capability is unavailable");
12288
+ return [{ id, reason: reasons.join("; "), assurance: capability.assurance }];
12289
+ });
12290
+ }
12291
+ var invariantBootstrap = () => `
12292
+ Workit is optional coordination and repository-policy tooling around the host,
12293
+ not a permission system or a mandatory workflow. Native host allow/ask/deny,
12294
+ sandbox, plan/read-only mode, and organization rules remain authoritative.
12295
+ Ordinary investigation, questions, non-Git work, and routine reversible edits
12296
+ need zero Workit task, assessment, or writer calls. Use one compact tracked
12297
+ record only when handoff, dependent steps, concurrent actors, or meaningful
12298
+ decisions make continuity useful; similar titles alone never merge tasks.
12299
+
12300
+ For a routine user-authorized branch or commit, prefer native host Git/shell
12301
+ tools from the outset when managed coordination or outcome reconciliation is
12302
+ not needed. Inspect the actual target checkout and its configured conventions;
12303
+ use Workit's read-only context/policy tools when needed. Do not start a task,
12304
+ acquire a writer, or mint a decision receipt solely for a native Git action.
12305
+ Native permissions still apply. Never switch execution paths to evade a denial
12306
+ or repeat an uncertain managed effect. A local-commit endpoint does not imply
12307
+ PR readiness, a fresh review, or post-commit assessment/closure paperwork.
12308
+
12309
+ For tracked work, inspect its current state and use the shared operations for
12310
+ task, policy, evidence, finding, decision, worker, writer, and state changes.
12311
+ Start a record once for an explicit tracked objective; assess or reassess only
12312
+ when policy selection or changed evidence/constraints requires it. Omitted
12313
+ expectedRevision and expectedWorkspaceRevision use current values; explicit
12314
+ values are still concurrency-checked, so never copy revisions between calls.
12315
+ A solo edit does not need writer acquisition; use it when concurrent checkout
12316
+ writers need coordination. Record only observed facts and checks. Evidence can
12317
+ become stale when its bound candidate changes; reconcile findings against the
12318
+ current candidate before recording completion.
12319
+
12320
+ Workit validates domain policy against the actual action target, configured
12321
+ account, branch and commit conventions, protected refs, and current repository
12322
+ state. The task directory is coordination state, not a boundary on which
12323
+ repository may be changed. Use an action-time cwd target where a managed
12324
+ Git/hosting action supports it; a non-Git directory remains valid for OS work.
12325
+ GitHub/GitLab use the active gh/glab CLI identity; YouTrack uses its own token.
12326
+ Preserve uncertain external outcomes and reconcile repository/provider state
12327
+ before retrying. Internal reservations prevent duplicate or ambiguous effects;
12328
+ they are not permission tickets for every edit.
12329
+
12330
+ On OpenCode V1 and V2, use native host tools for external mutations. Workit
12331
+ provides read-only workit_context; it has no managed external-action executor.
12332
+ Do not create proposals or request Workit approvals merely to invoke native
12333
+ tools. Old uncertain managed effects still require evidence before any retry.
12334
+
12335
+ Use host-native authorization through the host's supported path. A native
12336
+ question receipt records an actual question interaction; it is not automatic
12337
+ host permission. Record a meaningful user choice once with provenance when
12338
+ future retrieval helps. Never fabricate a receipt, re-ask only to mint one, or
12339
+ let imported decisions grant authority. Never turn a host deny into allow or
12340
+ claim enforcement/evidence a host cannot provide. A precise request with settled
12341
+ constraints does not need an interview. Present genuine unresolved options with
12342
+ evidence and a recommendation, then continue toward the requested delivery
12343
+ endpoint: investigation, implementation, branch/commit/push, PR/MR-ready,
12344
+ merge, or release. Run
12345
+ applicable checks and safe repairs without repeated continuation questions;
12346
+ stop for missing host authority, a new consequential choice, a conflicting edit,
12347
+ or an unresolved blocker. A tracked record may close when actual evidence
12348
+ supports its outcome; no final human closure ceremony is required.
12349
+
12350
+ A completed native subagent run stops its bound worker by itself; if a worker
12351
+ strands in cancelling with its run verifiably over, repeat worker.cancel to
12352
+ confirm the stop. Preserve unresolved requirements, gaps, and uncertain workers.
12353
+ When context changes, distinguish a quick question, same-task adjustment, and
12354
+ separate request. Answer a quick question without pausing/resuming task state;
12355
+ park a concise checkpoint only when substantial work needs to continue later.
12356
+ For work spanning repositories, bind each unfinished item to its actual checkout,
12357
+ branch, requested deliverables, and delivery endpoint. Preserve held items with
12358
+ an explicit resume condition. Resolve competing plausible targets before a
12359
+ mutation; ask only when available context cannot settle that consequential choice.
12360
+ Before reporting delivery, reconcile every requested item and observe the actual
12361
+ target result; a local commit alone is not evidence of a requested remote push.
12362
+
12363
+ Skill routing: slash aliases /wk-* load on demand. Use workit-steer for a
12364
+ substantial interruption or change of direction, workit-deslop when relevant
12365
+ to a PR-ready endpoint, workit-green-run for failing CI, workit-blast-radius
12366
+ when impact is uncertain, and workit-challenge for genuinely open consequential
12367
+ choices. Load workit-plan when dependencies or handoff need durable next actions.
12368
+ Load the skill; never act from memory of it.
12369
+ `.trim();
12370
+
12371
+ // packages/workit-core/src/core/task-context.ts
12372
+ function reconcileResume(view, observations = []) {
12373
+ if (observations.length > 0)
12374
+ return failure("permission_denied", "worker observations require native host verification");
12375
+ const candidate = captureCandidate(view.workspace.root, view.task.intent.data.scope, []);
12376
+ if (!candidate.ok)
12377
+ return candidate;
12378
+ const staleEvidenceIds = evaluateEvidence(view.task, candidate.data).filter((entry) => entry.status === "stale").map((entry) => entry.evidenceId);
12379
+ const blockers = [...view.task.progress.blockers];
12380
+ if (view.task.workers.some((entry) => isUncertainWorker(entry.data.state)))
12381
+ blockers.push({
12382
+ reason: "worker state requires reconciliation",
12383
+ dependentAction: "resume",
12384
+ refs: []
12385
+ });
12386
+ return success(null, null, {
12387
+ candidate: candidate.data,
12388
+ staleEvidenceIds,
12389
+ workerUpdates: [],
12390
+ blockers,
12391
+ reassessmentRequired: view.task.policy?.policyVersion !== POLICY_VERSION
12422
12392
  });
12423
12393
  }
12424
- function resolvePolicy(input) {
12425
- const normalized = normalizeResolverInput(input);
12426
- if (!normalized.ok)
12427
- return normalized;
12428
- const requirements = resolveRequirements(normalized.data);
12429
- const policy = {
12430
- policyVersion: POLICY_VERSION,
12431
- inputDigest: sha256(canonicalJson(normalized.data)),
12432
- requirements
12433
- };
12434
- const parsed = policySchema.safeParse(policy);
12435
- if (!parsed.success)
12436
- return failure("invalid_input", "resolved policy is invalid", invalidFields(parsed.error));
12437
- return success(null, null, parsed.data);
12438
- }
12439
- function diffPolicy(previous, next, reason, now) {
12440
- if (!policySchema.safeParse(previous).success && previous !== null)
12441
- throw new TypeError("previous policy is invalid");
12442
- if (!policySchema.safeParse(next).success)
12443
- throw new TypeError("next policy is invalid");
12444
- const oldIds = new Set(previous?.requirements.map((requirement) => requirement.id) ?? []);
12445
- const newIds = new Set(next.requirements.map((requirement) => requirement.id));
12446
- const added = [...newIds].filter((id) => !oldIds.has(id)).sort(compareCodeUnits3);
12447
- const retired = [...oldIds].filter((id) => !newIds.has(id)).sort(compareCodeUnits3);
12448
- if (added.length === 0 && retired.length === 0)
12449
- return null;
12450
- const normalizedReason = reason.trim();
12451
- const changeReason = retired.length ? `${normalizedReason || "policy reassessed"} (retired: ${retired.join(",")})` : normalizedReason || "policy reassessed";
12452
- const change = {
12453
- recordedAt: now,
12454
- fromInputDigest: previous?.inputDigest ?? null,
12455
- toInputDigest: next.inputDigest,
12456
- added,
12457
- retired,
12458
- reason: changeReason
12394
+ var COMPACT_MAX_BYTES = 4096;
12395
+ var COMPACT_MAX_ITEMS = 8;
12396
+ var COMPACT_TEXT_BYTES = 128;
12397
+ var sensitiveUrl = /\bhttps?:\/\/[^/\s:@]+:[^@\s]+@/gi;
12398
+ var sensitiveValue = /(?:token|secret|password|passwd|api[-_ ]?key|private[-_ ]?key|authorization)\s*[:=]\s*(?:bearer\s+)?\S+|\bbearer\s+\S+/gi;
12399
+ var privateKey = /-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/gi;
12400
+ var compactText = (value, limit) => value === null ? null : value.replace(privateKey, "<redacted-private-key>").replace(sensitiveUrl, "<redacted-url>").replace(sensitiveValue, (match) => {
12401
+ const separator = match.search(/[:=]/u);
12402
+ if (separator >= 0)
12403
+ return `${match.slice(0, separator)}=<redacted>`;
12404
+ const space = match.search(/\s/u);
12405
+ return `${match.slice(0, space)} <redacted>`;
12406
+ }).slice(0, limit);
12407
+ var compactBytes = (value) => new TextEncoder().encode(value).byteLength;
12408
+ var compactTimestamp = (value) => `${value.slice(0, 19)}.${value.slice(20, -1).padEnd(9, "0")}`;
12409
+ var compactDecisionChoice = (entry) => {
12410
+ const stated = entry.data.binding.statedChoice?.text;
12411
+ const approved = entry.data.response === "approved" ? entry.data.binding.approvedContent : "";
12412
+ const source = stated?.trim() || approved.trim() || null;
12413
+ return compactText(source, COMPACT_TEXT_BYTES);
12414
+ };
12415
+ var compactReference = (ref) => {
12416
+ if (ref.kind === "file")
12417
+ return {
12418
+ kind: "file",
12419
+ path: compactText(ref.path, COMPACT_TEXT_BYTES) ?? ""
12420
+ };
12421
+ if (ref.kind === "record")
12422
+ return {
12423
+ kind: "record",
12424
+ collection: ref.collection,
12425
+ id: ref.id
12426
+ };
12427
+ return { kind: ref.kind };
12428
+ };
12429
+ function compactTaskContext(view) {
12430
+ const decisions = view.task.decisions.slice().sort((left, right) => {
12431
+ const leftAt = compactTimestamp(left.recordedAt);
12432
+ const rightAt = compactTimestamp(right.recordedAt);
12433
+ if (leftAt !== rightAt)
12434
+ return leftAt > rightAt ? -1 : 1;
12435
+ return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;
12436
+ }).slice(0, COMPACT_MAX_ITEMS).map((entry) => ({
12437
+ id: entry.id,
12438
+ purpose: entry.data.purpose,
12439
+ status: entry.data.response,
12440
+ digest: entry.data.digest,
12441
+ choice: compactDecisionChoice(entry) || `task.inspect taskId=${view.task.id} view=full; decision=${entry.id}`,
12442
+ references: entry.data.binding.contentRefs.slice(0, 1).map(compactReference)
12443
+ }));
12444
+ const methods = view.task.policy ? selectMethods(view.task.policy, view.capabilities).map((method) => ({
12445
+ id: method.id,
12446
+ assurance: method.assurance,
12447
+ reason: compactText(method.reason, COMPACT_TEXT_BYTES) ?? ""
12448
+ })) : [];
12449
+ const gaps = Array.from(new Set([
12450
+ ...view.evidence.filter((entry) => entry.status === "stale").map((entry) => `stale evidence: ${entry.evidenceId}`),
12451
+ ...view.requirements.filter((entry) => entry.status !== "satisfied").map((entry) => entry.reason),
12452
+ ...view.task.progress.blockers.map((entry) => entry.reason)
12453
+ ])).sort().slice(0, COMPACT_MAX_ITEMS).map((gap) => compactText(gap, COMPACT_TEXT_BYTES));
12454
+ const context = {
12455
+ objective: compactText(view.task.intent.data.objective, COMPACT_TEXT_BYTES) ?? "",
12456
+ status: view.task.status,
12457
+ decisions,
12458
+ methods,
12459
+ gaps,
12460
+ nextAction: compactText(view.task.progress.nextAction, COMPACT_TEXT_BYTES)
12459
12461
  };
12460
- const parsed = policyChangeSchema.safeParse(change);
12461
- if (!parsed.success)
12462
- throw new TypeError("policy change is invalid");
12463
- return parsed.data;
12462
+ let encoded = JSON.stringify(context);
12463
+ while (compactBytes(encoded) > COMPACT_MAX_BYTES && (context.decisions.length || context.methods.length || context.gaps.length)) {
12464
+ if (context.gaps.length)
12465
+ context.gaps.pop();
12466
+ else if (context.decisions.length)
12467
+ context.decisions.pop();
12468
+ else
12469
+ context.methods.pop();
12470
+ encoded = JSON.stringify(context);
12471
+ }
12472
+ if (compactBytes(encoded) > COMPACT_MAX_BYTES) {
12473
+ context.objective = compactText(context.objective, 64) ?? "";
12474
+ context.nextAction = compactText(context.nextAction, 64);
12475
+ encoded = JSON.stringify(context);
12476
+ }
12477
+ return encoded;
12464
12478
  }
12479
+ var exportDigest = (bundle) => sha256({
12480
+ schemaVersion: bundle.schemaVersion,
12481
+ exportedAt: bundle.exportedAt,
12482
+ sourceWorkspaceId: bundle.sourceWorkspaceId,
12483
+ task: bundle.task
12484
+ });
12465
12485
 
12466
12486
  // packages/workit-core/src/core/task-engine.ts
12467
12487
  var provenance = (context, kind = context.provenanceKind ?? "host_observed") => ({
@@ -14149,14 +14169,29 @@ class WorkitCore {
14149
14169
  writer: evaluationWorkspace.writer
14150
14170
  });
14151
14171
  }
14152
- view(task) {
14172
+ compactContext(taskId) {
14173
+ const root = this.contextRootError();
14174
+ if (!root.ok)
14175
+ return root;
14176
+ const task = this.store.readTask(taskId);
14177
+ if (!task.ok)
14178
+ return task;
14179
+ const helper = this.helperTaskGuard(task.data, true);
14180
+ if (!helper.ok)
14181
+ return helper;
14182
+ const view = this.view(task.data, false);
14183
+ if (!view.ok)
14184
+ return view;
14185
+ return success(view.revision, view.workspaceRevision, compactTaskContext(view.data));
14186
+ }
14187
+ view(task, capture = true) {
14153
14188
  const workspace = this.store.readWorkspace();
14154
14189
  if (!workspace.ok)
14155
14190
  return workspace;
14156
14191
  if (!workspace.data)
14157
14192
  return failure("not_found", "workspace not found");
14158
14193
  const historical = task.status === "closed" ? task.candidates.at(-1) : undefined;
14159
- const current = historical ? success(null, null, historical) : captureCandidate(this.store.root, task.intent.data.scope, environment());
14194
+ 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);
14160
14195
  if (!current.ok)
14161
14196
  return current;
14162
14197
  const evaluationWorkspace = task.status === "closed" ? { ...workspace.data, writer: null } : workspace.data;
@@ -14428,6 +14463,122 @@ class WorkitCore {
14428
14463
  return this.summary(changed.data.task);
14429
14464
  }
14430
14465
  }
14466
+
14467
+ // packages/workit-core/src/core/session-context.ts
14468
+ var cache = new Map;
14469
+ // packages/workit-core/src/core/external-action.ts
14470
+ var chainStepSchema = union([
14471
+ string2().min(1),
14472
+ object({ branch: string2().min(1) }).strict(),
14473
+ object({ pr: literal(true) }).strict()
14474
+ ]);
14475
+ var externalActionSchema = discriminatedUnion("operation", [
14476
+ object({
14477
+ operation: literal("git.branch_setup"),
14478
+ payload: object({
14479
+ action: _enum(["setup", "reapply_stash"]).optional(),
14480
+ sdd_dir: string2().optional(),
14481
+ target_branch: string2().optional(),
14482
+ stash: _enum(["yes", "no"]).optional(),
14483
+ cwd: string2().min(1).optional()
14484
+ }).strict()
14485
+ }).strict(),
14486
+ object({
14487
+ operation: literal("git.commit"),
14488
+ payload: object({
14489
+ message: string2().min(1).optional(),
14490
+ plan_steps: array(chainStepSchema).min(1).max(32).optional(),
14491
+ plan_branch: string2().min(1).optional(),
14492
+ cwd: string2().min(1).optional()
14493
+ }).strict()
14494
+ }).strict(),
14495
+ object({
14496
+ operation: literal("git.push"),
14497
+ payload: object({ branch: string2().min(1).optional(), cwd: string2().min(1).optional() }).strict()
14498
+ }).strict(),
14499
+ object({
14500
+ operation: literal("hosting.pull_request"),
14501
+ payload: object({
14502
+ title: string2().min(1),
14503
+ body: string2().optional(),
14504
+ draft: boolean2().optional(),
14505
+ target_branch: string2().optional(),
14506
+ babysit: boolean2().optional(),
14507
+ cwd: string2().min(1).optional()
14508
+ }).strict()
14509
+ }).strict(),
14510
+ object({
14511
+ operation: literal("hosting.merge"),
14512
+ payload: object({
14513
+ target_branch: string2().min(1).optional(),
14514
+ source_branch: string2().min(1).optional(),
14515
+ cwd: string2().min(1).optional()
14516
+ }).strict()
14517
+ }).strict(),
14518
+ object({
14519
+ operation: literal("hosting.delete_branch"),
14520
+ payload: object({ branch: string2().min(1), cwd: string2().min(1).optional() }).strict()
14521
+ }).strict(),
14522
+ object({
14523
+ operation: literal("youtrack.update"),
14524
+ payload: object({
14525
+ issueId: string2().min(1),
14526
+ markdown: string2().min(1),
14527
+ minutes: number2().positive().optional()
14528
+ }).strict()
14529
+ }).strict(),
14530
+ object({
14531
+ operation: literal("youtrack.time"),
14532
+ payload: object({
14533
+ issueId: string2().min(1),
14534
+ minutes: number2().positive(),
14535
+ text: string2().optional(),
14536
+ dateMs: number2().finite().optional()
14537
+ }).strict()
14538
+ }).strict(),
14539
+ object({
14540
+ operation: literal("youtrack.meeting"),
14541
+ payload: object({
14542
+ issueId: string2().min(1),
14543
+ minutes: number2().positive(),
14544
+ text: string2().min(1)
14545
+ }).strict()
14546
+ }).strict(),
14547
+ object({
14548
+ operation: literal("changelog.apply"),
14549
+ payload: object({
14550
+ entries: union([
14551
+ record(string2(), array(string2())),
14552
+ array(object({ category: string2().min(1), text: string2().min(1) }).strict())
14553
+ ]).optional(),
14554
+ path: string2().optional(),
14555
+ normalize_only: boolean2().optional()
14556
+ }).strict()
14557
+ }).strict(),
14558
+ object({
14559
+ operation: literal("context.read"),
14560
+ payload: object({
14561
+ kind: _enum([
14562
+ "git",
14563
+ "pr",
14564
+ "youtrack",
14565
+ "github_issue",
14566
+ "gitlab_issue",
14567
+ "changelog",
14568
+ "release",
14569
+ "affected"
14570
+ ]),
14571
+ range: string2().optional(),
14572
+ issueId: string2().optional(),
14573
+ issueUrl: string2().optional(),
14574
+ issueRef: string2().optional(),
14575
+ mode: string2().optional(),
14576
+ specPath: string2().optional(),
14577
+ planPath: string2().optional(),
14578
+ cwd: string2().min(1).optional()
14579
+ }).strict()
14580
+ }).strict()
14581
+ ]);
14431
14582
  // packages/workit-cursor/hooks/workit-hook.ts
14432
14583
  var CURSOR_WRITE_TOOL_NAMES = [
14433
14584
  "write",
@@ -14570,7 +14721,7 @@ var activeTask = (store) => {
14570
14721
  return { ok: true, workspace: workspace.data, task: tasks[0] };
14571
14722
  };
14572
14723
  var historyOfferSessions = new Set;
14573
- var unfinishedTaskOffer = (root, session, excludedTaskId) => {
14724
+ var unfinishedTaskOffer2 = (root, session, excludedTaskId) => {
14574
14725
  try {
14575
14726
  const listed = new TaskStore(root).listTasks();
14576
14727
  if (!listed.ok)
@@ -14681,18 +14832,13 @@ var handleCursorHook = (raw) => {
14681
14832
  let compact = "";
14682
14833
  const store = new TaskStore(root);
14683
14834
  const state = activeTask(store);
14684
- const offer = historyOfferSessions.has(actor) ? null : unfinishedTaskOffer(root, actor, state.ok ? state.task.id : undefined);
14835
+ const offer = historyOfferSessions.has(actor) ? null : unfinishedTaskOffer2(root, actor, state.ok ? state.task.id : undefined);
14685
14836
  historyOfferSessions.add(actor);
14686
14837
  if (state.ok) {
14687
- const view = new WorkitCore(store, contextFor(root, actor, null, { sessionStart: true })).task({
14688
- schemaVersion: 1,
14689
- action: "inspect",
14690
- taskId: state.task.id,
14691
- view: "full"
14692
- });
14693
- if (view.ok)
14838
+ const context = new WorkitCore(store, contextFor(root, actor, null, { sessionStart: true })).compactContext(state.task.id);
14839
+ if (context.ok)
14694
14840
  compact = `
14695
- <workit-task-context>${compactTaskContext(view.data)}</workit-task-context>`;
14841
+ <workit-task-context>${context.data}</workit-task-context>`;
14696
14842
  }
14697
14843
  return {
14698
14844
  additional_context: `<workit-contract>