@brainervirus/workit-cursor 2.1.1 → 2.1.3

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