@brainervirus/workit-mcp 2.1.0 → 2.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1283 -1001
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -21582,6 +21582,45 @@ var metadataLockSchema = object4({
21582
21582
  nonce: string5().min(1),
21583
21583
  externalAction: literal3(true).optional()
21584
21584
  }).strict();
21585
+ var INDEX_VERSION = 1;
21586
+ var hostSession = (value) => isObject3(value) && value.kind === "host" && typeof value.host === "string" && typeof value.handle === "string" ? { host: value.host, handle: value.handle } : null;
21587
+ var indexEntry = (task, file) => {
21588
+ const sessions = [];
21589
+ const intent = hostSession(task.intent.provenance.session);
21590
+ if (intent)
21591
+ sessions.push({ ...intent, workerId: null });
21592
+ for (const worker of task.workers) {
21593
+ const session = hostSession(worker.data.session);
21594
+ if (session)
21595
+ sessions.push({ ...session, workerId: worker.id });
21596
+ }
21597
+ return {
21598
+ id: task.id,
21599
+ revision: task.revision,
21600
+ status: task.status,
21601
+ createdAt: task.createdAt,
21602
+ updatedAt: task.updatedAt,
21603
+ objective: task.intent.data.objective,
21604
+ source: { host: task.intent.provenance.host, kind: task.intent.provenance.kind },
21605
+ progress: { summary: task.progress.summary, nextAction: task.progress.nextAction },
21606
+ sessions,
21607
+ file
21608
+ };
21609
+ };
21610
+ var fileSignature = (file) => {
21611
+ try {
21612
+ const stat = fs4.statSync(file, { bigint: true });
21613
+ return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
21614
+ } catch {
21615
+ return null;
21616
+ }
21617
+ };
21618
+ var RACY_WINDOW_NS = 2000000000n;
21619
+ var racySignature = (signature) => {
21620
+ const [mtime = 0n, ctime = 0n] = signature.split(":").slice(3, 5).map(BigInt);
21621
+ const changed = mtime > ctime ? mtime : ctime;
21622
+ return BigInt(Date.now()) * 1000000n - changed < RACY_WINDOW_NS;
21623
+ };
21585
21624
  var now = () => new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
21586
21625
  var cachedRuntimeVersion = null;
21587
21626
  var runtimeVersion = () => {
@@ -21710,6 +21749,57 @@ class TaskStore {
21710
21749
  }
21711
21750
  return success(null, null, tasks);
21712
21751
  }
21752
+ listTaskIndex() {
21753
+ if (!fs4.existsSync(this.tasksDir))
21754
+ return success(null, null, []);
21755
+ let names;
21756
+ try {
21757
+ names = fs4.readdirSync(this.tasksDir).filter((name) => name.endsWith(".json"));
21758
+ } catch (error) {
21759
+ return failure("storage_error", `unable to list tasks: ${String(error)}`, {
21760
+ path: this.tasksDir
21761
+ });
21762
+ }
21763
+ const workspace = this.readWorkspace();
21764
+ if (!workspace.ok)
21765
+ return workspace;
21766
+ if (!workspace.data)
21767
+ return failure("recovery_required", "task workspace binding is invalid", {
21768
+ path: this.workspacePath
21769
+ });
21770
+ const stored = this.readIndex(workspace.data.id);
21771
+ const entries = [];
21772
+ let changed = Object.keys(stored).length !== names.length;
21773
+ for (const name of names.sort()) {
21774
+ const file = path4.join(this.tasksDir, name);
21775
+ const signature = fileSignature(file);
21776
+ if (signature === null) {
21777
+ changed = true;
21778
+ continue;
21779
+ }
21780
+ const cached = stored[name.slice(0, -5)];
21781
+ if (cached && cached.file === signature && !racySignature(signature)) {
21782
+ entries.push(cached);
21783
+ continue;
21784
+ }
21785
+ const item = this.readRecord(file, taskRecordSchema);
21786
+ if (!item.exists)
21787
+ continue;
21788
+ if (!item.result.ok)
21789
+ return item.result;
21790
+ if (!validId(name.slice(0, -5)) || item.result.data.id !== name.slice(0, -5))
21791
+ return failure("recovery_required", "task filename and record ID differ", { path: name });
21792
+ if (item.result.data.workspaceId !== workspace.data.id)
21793
+ return failure("recovery_required", "task workspace binding is invalid", { path: name });
21794
+ const entry = indexEntry(item.result.data, signature);
21795
+ if (!cached || canonicalJson(cached) !== canonicalJson(entry))
21796
+ changed = true;
21797
+ entries.push(entry);
21798
+ }
21799
+ if (changed)
21800
+ this.writeIndex(workspace.data.id, entries);
21801
+ return success(null, null, entries);
21802
+ }
21713
21803
  readWorkspace() {
21714
21804
  const item = this.readRecord(this.workspacePath, workspaceRecordSchema);
21715
21805
  if (!item.exists)
@@ -22389,6 +22479,8 @@ class TaskStore {
22389
22479
  fs4.renameSync(temporary, file);
22390
22480
  temporary = undefined;
22391
22481
  this.fsyncDirectory(path4.dirname(file));
22482
+ if (path4.dirname(file) === this.tasksDir)
22483
+ this.indexTaskWrite(file, value);
22392
22484
  return success(null, null, value);
22393
22485
  } catch (error) {
22394
22486
  return failure("storage_error", `snapshot replacement failed: ${String(error)}`, {
@@ -22401,6 +22493,45 @@ class TaskStore {
22401
22493
  } catch {}
22402
22494
  }
22403
22495
  }
22496
+ readIndex(workspaceId) {
22497
+ try {
22498
+ const value = JSON.parse(fs4.readFileSync(this.indexPath, "utf8"));
22499
+ if (!isObject3(value) || value.version !== INDEX_VERSION || value.workspaceId !== workspaceId || !isObject3(value.tasks))
22500
+ return {};
22501
+ const tasks = {};
22502
+ for (const [id, entry] of Object.entries(value.tasks))
22503
+ if (isObject3(entry) && entry.id === id && typeof entry.file === "string" && typeof entry.status === "string" && typeof entry.updatedAt === "string" && Array.isArray(entry.sessions) && isObject3(entry.progress) && isObject3(entry.source))
22504
+ tasks[id] = entry;
22505
+ return tasks;
22506
+ } catch {
22507
+ return {};
22508
+ }
22509
+ }
22510
+ writeIndex(workspaceId, entries) {
22511
+ const temporary = `${this.indexPath}.${process.pid}.${randomUUID2()}.tmp`;
22512
+ try {
22513
+ fs4.writeFileSync(temporary, JSON.stringify({
22514
+ version: INDEX_VERSION,
22515
+ workspaceId,
22516
+ tasks: Object.fromEntries(entries.map((entry) => [entry.id, entry]))
22517
+ }), { mode: 384, flag: "wx" });
22518
+ fs4.renameSync(temporary, this.indexPath);
22519
+ } catch {
22520
+ try {
22521
+ fs4.unlinkSync(temporary);
22522
+ } catch {}
22523
+ }
22524
+ }
22525
+ indexTaskWrite(file, task) {
22526
+ try {
22527
+ const signature = fileSignature(file);
22528
+ if (signature === null)
22529
+ return;
22530
+ const tasks = this.readIndex(task.workspaceId);
22531
+ tasks[task.id] = indexEntry(task, signature);
22532
+ this.writeIndex(task.workspaceId, Object.values(tasks));
22533
+ } catch {}
22534
+ }
22404
22535
  saveRecovery(file, bytes) {
22405
22536
  const target = path4.basename(file) === "workspace.json" ? "workspace" : "task";
22406
22537
  const id = target === "task" ? path4.basename(file, ".json") : "workspace";
@@ -22559,6 +22690,9 @@ class TaskStore {
22559
22690
  get workspacePath() {
22560
22691
  return path4.join(this.workitDir, "workspace.json");
22561
22692
  }
22693
+ get indexPath() {
22694
+ return path4.join(this.workitDir, "index.json");
22695
+ }
22562
22696
  get lockPath() {
22563
22697
  return path4.join(this.workitDir, "metadata.lock");
22564
22698
  }
@@ -22566,71 +22700,8 @@ class TaskStore {
22566
22700
  return path4.join(this.workitDir, ".gitignore");
22567
22701
  }
22568
22702
  }
22569
- // packages/workit-core/src/core/workers.ts
22570
- var same = (left, right) => {
22571
- try {
22572
- return canonicalJson(left) === canonicalJson(right);
22573
- } catch {
22574
- return false;
22575
- }
22576
- };
22577
- var UNCERTAIN_WORKER_STATES = ["dispatching", "running", "cancelling", "unknown"];
22578
- var isUncertainWorker = (state) => UNCERTAIN_WORKER_STATES.includes(state);
22579
- var workerBlocksTransition = (transition, state) => transition === "pause" ? false : isUncertainWorker(state);
22580
- var callerSession = (caller) => caller.session ?? { kind: "host", host: caller.host, handle: caller.actor };
22581
- var validPath = (value) => typeof value === "string" && value.length > 0 && ![...value].some((char) => {
22582
- const code = char.charCodeAt(0);
22583
- return code < 32 || code === 127;
22584
- }) && !value.split(/[\\/]/).includes("..");
22585
- var callerValue = (value) => ({ host: value.host, actor: value.actor });
22586
- var workerIdOf = (value) => value.workerId ?? null;
22587
- var currentWriterOwnsTask = (task, workspace, caller) => {
22588
- const owner = workspace.writer?.owner;
22589
- return task.status === "active" && task.workspaceId === workspace.id && owner?.taskId === task.id && owner.session.host === caller.host && owner.session.handle === caller.actor;
22590
- };
22591
- function assertProductWriteAllowed(input) {
22592
- if (!Array.isArray(input.paths) || input.paths.some((path) => !validPath(path)))
22593
- return failure("invalid_input", "invalid product write path");
22594
- if (!input.store)
22595
- return failure("permission_denied", "write authorization requires core state");
22596
- const task = input.store.readTask(input.task.id);
22597
- if (!task.ok)
22598
- return task;
22599
- const workspace = input.store.readWorkspace();
22600
- if (!workspace.ok)
22601
- return workspace;
22602
- if (!workspace.data)
22603
- return failure("not_found", "workspace not found");
22604
- const workspaceRecord = workspace.data;
22605
- if (task.data.status !== "active")
22606
- return failure("invalid_transition", "paused or closed tasks cannot own product writes");
22607
- if (workspaceRecord.id !== task.data.workspaceId || workspaceRecord.root.length === 0)
22608
- return failure("recovery_required", "task and workspace bindings are invalid");
22609
- const writer = workspaceRecord.writer;
22610
- if (!writer)
22611
- return failure("permission_denied", "checkout has no writer owner");
22612
- if (writer.state === "uncertain")
22613
- return failure("recovery_required", "checkout writer requires recovery", {
22614
- owner: writer.owner
22615
- });
22616
- const caller = callerValue(input.caller);
22617
- const workerId = workerIdOf(input.caller);
22618
- const owner = writer.owner;
22619
- if (owner.taskId !== task.data.id || owner.workerId !== workerId || owner.session.host !== caller.host || owner.session.handle !== caller.actor)
22620
- return failure("writer_conflict", "checkout is owned by another validated actor", { owner });
22621
- const worker = workerId === null ? null : task.data.workers.find((entry) => entry.id === workerId);
22622
- if (workerId !== null && (!worker || worker.data.assignment.role !== "implementer"))
22623
- return failure("permission_denied", "only implementers can own product writes");
22624
- 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))))
22625
- return failure("recovery_required", "worker session is not an active writer");
22626
- return success(null, workspaceRecord.revision, owner);
22627
- }
22628
-
22629
- // packages/workit-core/src/core/task-evaluation.ts
22630
- import { createHash as createHash6 } from "node:crypto";
22631
- import * as fs7 from "node:fs";
22632
- import { spawnSync as spawnSync2 } from "node:child_process";
22633
- import path10 from "node:path";
22703
+ // packages/workit-core/src/core/task-engine.ts
22704
+ import { realpathSync as realpathSync6 } from "node:fs";
22634
22705
 
22635
22706
  // packages/workit-core/src/core/authority.ts
22636
22707
  import { createHash as createHash5 } from "node:crypto";
@@ -23637,6 +23708,66 @@ var verifyPushIdentity = (root, provider, account) => {
23637
23708
  return { ok: true };
23638
23709
  };
23639
23710
 
23711
+ // packages/workit-core/src/core/workers.ts
23712
+ var same = (left, right) => {
23713
+ try {
23714
+ return canonicalJson(left) === canonicalJson(right);
23715
+ } catch {
23716
+ return false;
23717
+ }
23718
+ };
23719
+ var UNCERTAIN_WORKER_STATES = ["dispatching", "running", "cancelling", "unknown"];
23720
+ var isUncertainWorker = (state) => UNCERTAIN_WORKER_STATES.includes(state);
23721
+ var workerBlocksTransition = (transition, state) => transition === "pause" ? false : isUncertainWorker(state);
23722
+ var callerSession = (caller) => caller.session ?? { kind: "host", host: caller.host, handle: caller.actor };
23723
+ var validPath = (value) => typeof value === "string" && value.length > 0 && ![...value].some((char) => {
23724
+ const code = char.charCodeAt(0);
23725
+ return code < 32 || code === 127;
23726
+ }) && !value.split(/[\\/]/).includes("..");
23727
+ var callerValue = (value) => ({ host: value.host, actor: value.actor });
23728
+ var workerIdOf = (value) => value.workerId ?? null;
23729
+ var currentWriterOwnsTask = (task, workspace, caller) => {
23730
+ const owner = workspace.writer?.owner;
23731
+ return task.status === "active" && task.workspaceId === workspace.id && owner?.taskId === task.id && owner.session.host === caller.host && owner.session.handle === caller.actor;
23732
+ };
23733
+ function assertProductWriteAllowed(input) {
23734
+ if (!Array.isArray(input.paths) || input.paths.some((path) => !validPath(path)))
23735
+ return failure("invalid_input", "invalid product write path");
23736
+ if (!input.store)
23737
+ return failure("permission_denied", "write authorization requires core state");
23738
+ const task = input.store.readTask(input.task.id);
23739
+ if (!task.ok)
23740
+ return task;
23741
+ const workspace = input.store.readWorkspace();
23742
+ if (!workspace.ok)
23743
+ return workspace;
23744
+ if (!workspace.data)
23745
+ return failure("not_found", "workspace not found");
23746
+ const workspaceRecord = workspace.data;
23747
+ if (task.data.status !== "active")
23748
+ return failure("invalid_transition", "paused or closed tasks cannot own product writes");
23749
+ if (workspaceRecord.id !== task.data.workspaceId || workspaceRecord.root.length === 0)
23750
+ return failure("recovery_required", "task and workspace bindings are invalid");
23751
+ const writer = workspaceRecord.writer;
23752
+ if (!writer)
23753
+ return failure("permission_denied", "checkout has no writer owner");
23754
+ if (writer.state === "uncertain")
23755
+ return failure("recovery_required", "checkout writer requires recovery", {
23756
+ owner: writer.owner
23757
+ });
23758
+ const caller = callerValue(input.caller);
23759
+ const workerId = workerIdOf(input.caller);
23760
+ const owner = writer.owner;
23761
+ if (owner.taskId !== task.data.id || owner.workerId !== workerId || owner.session.host !== caller.host || owner.session.handle !== caller.actor)
23762
+ return failure("writer_conflict", "checkout is owned by another validated actor", { owner });
23763
+ const worker = workerId === null ? null : task.data.workers.find((entry) => entry.id === workerId);
23764
+ if (workerId !== null && (!worker || worker.data.assignment.role !== "implementer"))
23765
+ return failure("permission_denied", "only implementers can own product writes");
23766
+ 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))))
23767
+ return failure("recovery_required", "worker session is not an active writer");
23768
+ return success(null, workspaceRecord.revision, owner);
23769
+ }
23770
+
23640
23771
  // packages/workit-core/src/core/auto-approval.ts
23641
23772
  var AUTO_CLASSES = ["branch", "commit", "push", "pr", "merge"];
23642
23773
  var OPERATION_CLASS = {
@@ -24327,41 +24458,18 @@ function reconcileAction(input) {
24327
24458
  var bindingCovers = scopeCovers;
24328
24459
  var verifyDecisionContent = verifyContentRefs;
24329
24460
 
24330
- // packages/workit-core/src/core/task-evaluation.ts
24331
- var digestBytes3 = (value) => createHash6("sha256").update(value).digest("hex");
24332
- var inside = (root, candidate) => candidate === root || candidate.startsWith(`${root}${path10.sep}`);
24333
- var relative = (root, candidate) => path10.relative(root, candidate).split(path10.sep).join("/") || ".";
24334
- var canonicalPath = (value) => {
24335
- if (typeof value !== "string" || !value)
24336
- return null;
24337
- if (value.includes("\\") || value.split("/").includes(".."))
24338
- return null;
24339
- const normalized = path10.posix.normalize(value);
24340
- if (normalized === ".." || normalized.startsWith("../") || normalized.startsWith("/"))
24341
- return null;
24342
- return normalized === "." ? "." : normalized.replace(/\/$/, "");
24343
- };
24344
- var canonicalScope = (scope) => {
24345
- const paths = scope.paths.length ? scope.paths : ["."];
24346
- const normalizedPaths = paths.map(canonicalPath);
24347
- const normalizedExclusions = scope.exclusions.map(canonicalPath);
24348
- if (normalizedPaths.some((value) => value === null) || normalizedExclusions.some((value) => value === null))
24349
- return null;
24350
- return {
24351
- description: scope.description,
24352
- paths: [...new Set(normalizedPaths)],
24353
- exclusions: [...new Set(normalizedExclusions)]
24354
- };
24355
- };
24356
- var excluded = (value, exclusions) => exclusions.some((item) => item === value || item !== "." && value.startsWith(`${item}/`));
24357
- var scopeMatches = (value, scope) => {
24358
- const normalized = canonicalScope(scope);
24359
- if (!normalized)
24360
- return false;
24361
- const paths = normalized.paths;
24362
- return paths.some((item) => item === "." || value === item || value.startsWith(`${item}/`)) && !excluded(value, normalized.exclusions);
24363
- };
24364
- var pathRelevant = (value, scope) => scopeMatches(value, scope);
24461
+ // packages/workit-core/src/core/policy-resolver.ts
24462
+ var resolverInputSchema = object4({
24463
+ intent: intentSchema,
24464
+ assessment: assessmentSchema,
24465
+ constraints: array3(constraintSchema),
24466
+ prior: object4({
24467
+ decisions: array3(decisionSchema),
24468
+ findings: array3(findingSchema),
24469
+ requirements: array3(requirementSchema)
24470
+ }).strict(),
24471
+ preferences: object4({ fast: boolean5().optional(), thorough: boolean5().optional() }).strict().optional()
24472
+ }).strict();
24365
24473
  var compareCodeUnits2 = (left, right) => {
24366
24474
  const length = Math.min(left.length, right.length);
24367
24475
  for (let index = 0;index < length; index += 1) {
@@ -24371,927 +24479,970 @@ var compareCodeUnits2 = (left, right) => {
24371
24479
  }
24372
24480
  return left.length - right.length;
24373
24481
  };
24374
- var gitPaths = (root) => {
24375
- const result = spawnSync2("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
24376
- cwd: root,
24377
- encoding: "buffer"
24378
- });
24379
- if (result.status !== 0) {
24380
- const stderr = result.stderr?.toString("utf8") ?? "";
24381
- return {
24382
- paths: [],
24383
- uncertain: !/not a git repository/i.test(stderr),
24384
- git: /not a git repository/i.test(stderr) ? false : true
24385
- };
24386
- }
24387
- const paths = result.stdout ? result.stdout.toString("utf8").split("\x00").filter(Boolean).map((item) => item.split(path10.sep).join("/")) : [];
24388
- const stagedDeleted = spawnSync2("git", ["diff", "--cached", "--name-only", "--diff-filter=D", "-z"], { cwd: root, encoding: "buffer" });
24389
- if (stagedDeleted.status !== 0) {
24390
- const stderr = stagedDeleted.stderr?.toString("utf8") ?? "";
24391
- if (!/not a git repository/i.test(stderr))
24392
- return { paths, uncertain: true, git: true };
24393
- } else if (stagedDeleted.stdout) {
24394
- paths.push(...stagedDeleted.stdout.toString("utf8").split("\x00").filter(Boolean).map((item) => item.split(path10.sep).join("/")));
24395
- }
24396
- return { paths: [...new Set(paths)], uncertain: false, git: true };
24397
- };
24398
- var walk = (root, directory, output) => {
24399
- let names;
24400
- try {
24401
- names = fs7.readdirSync(directory);
24402
- } catch {
24403
- return true;
24404
- }
24405
- let uncertain = false;
24406
- for (const name of names) {
24407
- if (name === ".git" || name === ".workit")
24408
- continue;
24409
- const target = path10.join(directory, name);
24410
- let stat;
24411
- try {
24412
- stat = fs7.lstatSync(target);
24413
- } catch {
24414
- uncertain = true;
24415
- continue;
24416
- }
24417
- const item = relative(root, target);
24418
- output.add(item);
24419
- if (stat.isDirectory() && !stat.isSymbolicLink())
24420
- uncertain = walk(root, target, output) || uncertain;
24421
- }
24422
- return uncertain;
24423
- };
24424
- var scopeRoots = (root, scope) => {
24425
- const roots = [];
24426
- for (const item of scope.paths.length ? scope.paths : ["."]) {
24427
- const target = path10.resolve(root, item);
24428
- if (!inside(root, target))
24429
- 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` }] });
24430
- let ancestor = target;
24431
- while (!fs7.existsSync(ancestor) && ancestor !== root)
24432
- ancestor = path10.dirname(ancestor);
24433
- try {
24434
- if (!inside(root, fs7.realpathSync(ancestor)))
24435
- 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` }] });
24436
- } catch {
24437
- return failure("invalid_input", `candidate scope cannot be inspected: ${item}`);
24438
- }
24439
- roots.push(target);
24440
- }
24441
- return success(null, null, roots);
24442
- };
24443
- function captureCandidate(root, scope, environment = []) {
24444
- let checkout;
24445
- try {
24446
- checkout = fs7.realpathSync(root);
24447
- } catch {
24448
- return failure("invalid_input", "candidate root does not exist");
24449
- }
24450
- const normalizedScope = canonicalScope(scope);
24451
- if (!normalizedScope)
24452
- 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" }] });
24453
- const roots = scopeRoots(checkout, normalizedScope);
24454
- if (!roots.ok)
24455
- return roots;
24456
- const git = gitPaths(checkout);
24457
- const names = new Set;
24458
- let uncertain = git.uncertain;
24459
- for (const target of roots.data) {
24460
- const item = relative(checkout, target);
24461
- if (item === ".git" || item === ".workit")
24462
- continue;
24463
- names.add(item);
24464
- if (!fs7.existsSync(target))
24465
- continue;
24466
- let stat;
24467
- try {
24468
- stat = fs7.lstatSync(target);
24469
- } catch {
24470
- uncertain = true;
24471
- continue;
24472
- }
24473
- if (!git.git && stat.isDirectory() && !stat.isSymbolicLink())
24474
- uncertain = walk(checkout, target, names) || uncertain;
24475
- }
24476
- for (const item of git.paths)
24477
- if (scopeMatches(item, normalizedScope))
24478
- names.add(item);
24479
- const files = [];
24480
- let completeness = uncertain ? "uncertain" : "known";
24481
- for (const item of [...names].sort()) {
24482
- if (!scopeMatches(item, normalizedScope))
24483
- continue;
24484
- const target = path10.join(checkout, item);
24485
- try {
24486
- const stat = fs7.lstatSync(target);
24487
- if (stat.isSymbolicLink()) {
24488
- const link = fs7.readlinkSync(target);
24489
- files.push({ path: item, kind: "symlink", digest: digestBytes3(link), executable: null });
24490
- } else if (stat.isFile()) {
24491
- files.push({
24492
- path: item,
24493
- kind: "file",
24494
- digest: digestBytes3(fs7.readFileSync(target)),
24495
- executable: (stat.mode & 73) !== 0
24496
- });
24497
- } else if (!stat.isDirectory()) {
24498
- completeness = "uncertain";
24499
- } else if (git.git && git.paths.includes(item)) {
24500
- completeness = "uncertain";
24501
- }
24502
- } catch (error) {
24503
- if (error?.code === "ENOENT") {
24504
- files.push({ path: item, kind: "absent", digest: null, executable: null });
24505
- } else
24506
- completeness = "uncertain";
24507
- }
24508
- }
24509
- 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) => ({
24482
+ var stableUnique = (values) => [...new Set(values)].sort(compareCodeUnits2);
24483
+ var stableList = (values) => [...values].sort((left, right) => compareCodeUnits2(canonicalJson(left), canonicalJson(right)));
24484
+ var normalizedScope = (scope) => ({
24485
+ description: scope.description,
24486
+ paths: stableUnique(scope.paths),
24487
+ exclusions: stableUnique(scope.exclusions)
24488
+ });
24489
+ var normalizedRefList = (values) => stableList(values);
24490
+ var normalizeAssessment = (assessment) => ({
24491
+ facts: stableList(assessment.facts.map((fact) => ({ ...fact, refs: normalizedRefList(fact.refs) }))),
24492
+ signals: Object.fromEntries(Object.entries(assessment.signals).map(([name, signal]) => [
24510
24493
  name,
24511
- value: environment[name] ?? null
24512
- }));
24513
- const namesByEnvironment = supplied.map(({ name }) => name);
24514
- if (new Set(namesByEnvironment).size !== namesByEnvironment.length || namesByEnvironment.some((name) => typeof name !== "string" || !name))
24515
- return failure("invalid_input", "candidate environment names must be unique and non-empty");
24516
- const values = supplied.sort((left, right) => compareCodeUnits2(left.name, right.name)).map(({ name, value }) => ({ name, value, refs: [] }));
24517
- if (values.some(({ value }) => value === null))
24518
- completeness = "uncertain";
24519
- const headResult = spawnSync2("git", ["rev-parse", "HEAD"], { cwd: checkout, encoding: "utf8" });
24520
- if (headResult.status !== 0 && !/not a git repository/i.test(headResult.stderr ?? ""))
24521
- completeness = "uncertain";
24522
- const head = headResult.status === 0 ? headResult.stdout.trim() : null;
24523
- const partial = {
24524
- id: "0".repeat(64),
24525
- scope: normalizedScope,
24526
- completeness,
24527
- files,
24528
- environment: values,
24529
- head
24494
+ { ...signal, refs: normalizedRefList(signal.refs) }
24495
+ ])),
24496
+ consequences: stableList(assessment.consequences.map((consequence) => ({
24497
+ ...consequence,
24498
+ fact: { ...consequence.fact, refs: normalizedRefList(consequence.fact.refs) }
24499
+ }))),
24500
+ verification: stableList(assessment.verification.map((verification) => ({
24501
+ ...verification,
24502
+ scope: normalizedScope(verification.scope),
24503
+ availableChecks: normalizedRefList(verification.availableChecks),
24504
+ gaps: stableUnique(verification.gaps)
24505
+ })))
24506
+ });
24507
+ var normalizeConstraint = (constraint) => ({
24508
+ ...constraint,
24509
+ source: constraint.source,
24510
+ requires: stableList(constraint.requires.map((requirement) => ({
24511
+ ...requirement,
24512
+ scope: normalizedScope(requirement.scope),
24513
+ refs: normalizedRefList(requirement.refs)
24514
+ })))
24515
+ });
24516
+ var normalizeDecision = (decision) => ({
24517
+ ...decision,
24518
+ binding: {
24519
+ ...decision.binding,
24520
+ scope: normalizedScope(decision.binding.scope),
24521
+ contentRefs: normalizedRefList(decision.binding.contentRefs)
24522
+ },
24523
+ requirementIds: stableUnique(decision.requirementIds)
24524
+ });
24525
+ var normalizeIntent = (intent) => ({
24526
+ ...intent,
24527
+ scope: normalizedScope(intent.scope),
24528
+ authorityRefs: normalizedRefList(intent.authorityRefs)
24529
+ });
24530
+ var normalizePrior = (prior) => ({
24531
+ decisions: stableList(prior.decisions.map(normalizeDecision)),
24532
+ findings: stableList(prior.findings.map((finding) => ({
24533
+ ...finding,
24534
+ scope: normalizedScope(finding.scope),
24535
+ refs: normalizedRefList(finding.refs),
24536
+ resolution: finding.resolution ? {
24537
+ ...finding.resolution,
24538
+ evidenceIds: stableUnique(finding.resolution.evidenceIds),
24539
+ decisionIds: stableUnique(finding.resolution.decisionIds)
24540
+ } : null
24541
+ }))),
24542
+ requirements: stableList(prior.requirements.map((requirement) => ({
24543
+ ...requirement,
24544
+ scope: normalizedScope(requirement.scope)
24545
+ })))
24546
+ });
24547
+ var invalidFields = (error) => ({
24548
+ fields: error.issues.map((issue) => ({
24549
+ path: issue.code === "unrecognized_keys" ? issue.keys.join(".") : issue.path.join("."),
24550
+ reason: issue.message
24551
+ }))
24552
+ });
24553
+ function normalizeResolverInput(input) {
24554
+ const parsed = resolverInputSchema.safeParse(input);
24555
+ if (!parsed.success)
24556
+ return failure("invalid_input", "resolver input is invalid", invalidFields(parsed.error));
24557
+ const value = parsed.data;
24558
+ const signals = value.assessment.signals;
24559
+ if (signals.behaviorChange.value === true && signals.mechanicalLowRisk.value === true)
24560
+ return failure("invalid_input", "behavioral change cannot be wholly mechanical", {
24561
+ fields: [
24562
+ {
24563
+ path: "assessment.signals",
24564
+ reason: "contradictory behaviorChange and mechanicalLowRisk"
24565
+ }
24566
+ ]
24567
+ });
24568
+ const ids = value.constraints.map((constraint) => constraint.id);
24569
+ if (new Set(ids).size !== ids.length)
24570
+ return failure("invalid_input", "constraint IDs must be unique", {
24571
+ fields: [{ path: "constraints", reason: "duplicate constraint id" }]
24572
+ });
24573
+ if (value.preferences?.fast && value.preferences.thorough)
24574
+ return failure("invalid_input", "fast and thorough preferences contradict", {
24575
+ fields: [{ path: "preferences", reason: "fast and thorough cannot both be enabled" }]
24576
+ });
24577
+ const normalized = {
24578
+ intent: normalizeIntent(value.intent),
24579
+ assessment: normalizeAssessment(value.assessment),
24580
+ constraints: stableList(value.constraints.map(normalizeConstraint)),
24581
+ prior: normalizePrior(value.prior),
24582
+ ...value.preferences ? { preferences: { ...value.preferences } } : {},
24583
+ policyVersion: POLICY_VERSION
24530
24584
  };
24531
- const candidate = { ...partial, id: candidateDigest(partial) };
24532
- const parsed = candidateSchema.safeParse(candidate);
24533
- return parsed.success ? success(null, null, parsed.data) : failure("invalid_input", "captured candidate is invalid");
24585
+ return success(null, null, normalized);
24534
24586
  }
24535
- var fileMap = (candidate) => new Map(candidate.files.map((file) => [file.path, file]));
24536
- var changedPaths = (before, after) => {
24537
- const paths = new Set([...before.files, ...after.files].map((file) => file.path));
24538
- const left = fileMap(before);
24539
- const right = fileMap(after);
24540
- const changed = [...paths].filter((item) => JSON.stringify(left.get(item) ?? null) !== JSON.stringify(right.get(item) ?? null));
24541
- if (before.head !== after.head)
24542
- changed.push(".");
24543
- if (JSON.stringify(before.environment) !== JSON.stringify(after.environment))
24544
- changed.push(".");
24545
- return changed;
24546
- };
24547
- var sessionFromRef = (value) => {
24548
- if (typeof value !== "object" || value === null || value.kind !== "host")
24549
- return null;
24550
- return typeof value.host === "string" && typeof value.handle === "string" ? { host: value.host, handle: value.handle } : null;
24551
- };
24552
- var sameSession = (left, right) => {
24553
- const other = sessionFromRef(right);
24554
- return left !== null && other !== null && left.host === other.host && left.handle === other.handle;
24555
- };
24556
- var evidenceScopes = (task, ids) => (task.policy?.requirements ?? []).filter((requirement) => ids.includes(requirement.id)).map((requirement) => requirement.scope);
24557
- function evaluateEvidence(task, candidate) {
24558
- const current = candidate ?? task.candidates.at(-1) ?? null;
24559
- return task.evidence.map((entry) => {
24560
- const evidence = entry.data;
24561
- if (evidence.result === "failed")
24562
- return {
24563
- evidenceId: entry.id,
24564
- status: "failed",
24565
- reason: "failed evidence remains historical"
24566
- };
24567
- if (evidence.kind === "check" || evidence.kind === "review") {
24568
- if (!evidence.beforeCandidateId || !evidence.candidateId)
24569
- return {
24570
- evidenceId: entry.id,
24571
- status: "stale",
24572
- reason: "check or review evidence lacks start and end candidates"
24573
- };
24574
- if (evidence.beforeCandidateId !== evidence.candidateId)
24575
- return {
24576
- evidenceId: entry.id,
24577
- status: "stale",
24578
- reason: "candidate changed during the check or review"
24579
- };
24587
+ var requirement = (spec) => ({
24588
+ ...spec,
24589
+ id: requirementId({
24590
+ ruleId: spec.ruleId,
24591
+ scope: spec.scope,
24592
+ satisfaction: spec.satisfaction,
24593
+ before: spec.before,
24594
+ dependentAction: spec.dependentAction
24595
+ })
24596
+ });
24597
+ var signalReason = (input, name) => input.assessment.signals[name].reason;
24598
+ function resolveRequirements(input) {
24599
+ const { signals } = input.assessment;
24600
+ const scope = input.intent.scope;
24601
+ const requirements = [];
24602
+ const hasUnknownSignal = Object.values(signals).some((signal) => signal.value === "unknown");
24603
+ const hasUnknownFact = [
24604
+ ...input.assessment.facts,
24605
+ ...input.assessment.consequences.map(({ fact }) => fact)
24606
+ ].some((fact) => fact.basis === "unknown");
24607
+ if (hasUnknownSignal || hasUnknownFact)
24608
+ requirements.push(requirement({
24609
+ ruleId: "consequential-unknown",
24610
+ dimension: "investigation",
24611
+ scope,
24612
+ reason: `Resolve consequential uncertainty before the dependent action: ${[
24613
+ ...Object.entries(signals).filter(([, signal]) => signal.value === "unknown").map(([name]) => name),
24614
+ ...hasUnknownFact ? ["unknown fact"] : []
24615
+ ].join(", ")}`,
24616
+ satisfaction: "An observed or inferred fact resolves the uncertainty and records its supporting references.",
24617
+ before: "dependent_action",
24618
+ dependentAction: null,
24619
+ acceptanceAllowed: false
24620
+ }));
24621
+ if (signals.productChoiceOpen.value === true)
24622
+ requirements.push(requirement({
24623
+ ruleId: "product-decision",
24624
+ dimension: "decisions",
24625
+ scope,
24626
+ reason: `A consequential product choice remains open: ${signalReason(input, "productChoiceOpen")}`,
24627
+ satisfaction: "Present the material alternatives and record the user's decision before the dependent action.",
24628
+ before: "dependent_action",
24629
+ dependentAction: null,
24630
+ acceptanceAllowed: false
24631
+ }));
24632
+ const independentBehaviorReview = input.preferences?.thorough === true || input.assessment.consequences.some((consequence) => ["security", "data", "public_contract", "operations"].includes(consequence.area));
24633
+ if (signals.behaviorChange.value === true)
24634
+ requirements.push(requirement({
24635
+ ruleId: "behavioral-verification",
24636
+ dimension: "testing",
24637
+ scope,
24638
+ reason: `Behavior, side effects, permissions, or data handling may change: ${signalReason(input, "behaviorChange")}`,
24639
+ satisfaction: "A useful behavioral check passes against the affected behavior and current candidate.",
24640
+ before: "close",
24641
+ dependentAction: null,
24642
+ acceptanceAllowed: false
24643
+ }), requirement({
24644
+ ruleId: independentBehaviorReview ? "fresh-context-review" : "self-review",
24645
+ dimension: "review",
24646
+ scope,
24647
+ 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.",
24648
+ 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.",
24649
+ before: "close",
24650
+ dependentAction: null,
24651
+ acceptanceAllowed: !independentBehaviorReview
24652
+ }));
24653
+ else if (signals.mechanicalLowRisk.value === true)
24654
+ requirements.push(requirement({
24655
+ ruleId: "mechanical-existing-checks",
24656
+ dimension: "verification",
24657
+ scope,
24658
+ reason: `The change is demonstrably mechanical and low-risk: ${signalReason(input, "mechanicalLowRisk")}`,
24659
+ satisfaction: "Run the relevant existing checks for affected consumers; do not add tautological tests.",
24660
+ before: "close",
24661
+ dependentAction: null,
24662
+ acceptanceAllowed: true
24663
+ }), requirement({
24664
+ ruleId: input.preferences?.thorough ? "fresh-context-review" : "self-review",
24665
+ dimension: "review",
24666
+ scope,
24667
+ 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.",
24668
+ 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.",
24669
+ before: "close",
24670
+ dependentAction: null,
24671
+ acceptanceAllowed: !input.preferences?.thorough
24672
+ }));
24673
+ if (signals.behaviorChange.value === true || signals.mechanicalLowRisk.value === true)
24674
+ requirements.push(requirement({
24675
+ ruleId: "pre-pr-cleanup",
24676
+ dimension: "verification",
24677
+ scope,
24678
+ reason: "Implementation output must be deslopped before it is delivered.",
24679
+ satisfaction: "Run the workit-deslop pass and record passing check evidence, or record an approved limitation decision waiving cleanup.",
24680
+ before: "dependent_action",
24681
+ dependentAction: "hosting.pull_request",
24682
+ acceptanceAllowed: true
24683
+ }));
24684
+ if (signals.durableAgreementNeeded.value === true)
24685
+ requirements.push(requirement({
24686
+ ruleId: "durable-spec",
24687
+ dimension: "artifacts",
24688
+ scope,
24689
+ reason: `The work needs a durable agreement about intended behavior: ${signalReason(input, "durableAgreementNeeded")}`,
24690
+ satisfaction: "Record the agreed behavior in a durable specification before implementation writes.",
24691
+ before: "write",
24692
+ dependentAction: null,
24693
+ acceptanceAllowed: true
24694
+ }));
24695
+ if (signals.coordinationPlanNeeded.value === true)
24696
+ requirements.push(requirement({
24697
+ ruleId: "coordination-plan",
24698
+ dimension: "continuity",
24699
+ scope,
24700
+ reason: `Dependencies, sequencing, or resumption need durable coordination: ${signalReason(input, "coordinationPlanNeeded")}`,
24701
+ satisfaction: "Record useful sequencing, dependencies, and the next action in a compact plan.",
24702
+ before: "dependent_action",
24703
+ dependentAction: null,
24704
+ acceptanceAllowed: true
24705
+ }));
24706
+ if (signals.helperUseful.value === true && !input.preferences?.fast)
24707
+ requirements.push(requirement({
24708
+ ruleId: "helper-usefulness",
24709
+ dimension: "delegation",
24710
+ scope,
24711
+ reason: `Independent judgment or investigation justifies a scoped helper: ${signalReason(input, "helperUseful")}`,
24712
+ satisfaction: "Use a bounded helper only for the independent objective and reconcile its result.",
24713
+ before: "dependent_action",
24714
+ dependentAction: null,
24715
+ acceptanceAllowed: true
24716
+ }));
24717
+ for (const constraint of input.constraints)
24718
+ for (const obligation of constraint.requires) {
24719
+ const dimension = obligation.method ?? (obligation.kind === "check" ? "verification" : obligation.kind === "decision" ? "decisions" : "challenge");
24720
+ requirements.push(requirement({
24721
+ ruleId: `project-constraint:${constraint.id}:${obligation.kind}:${sha256({
24722
+ kind: obligation.kind,
24723
+ scope: normalizedScope(obligation.scope),
24724
+ refs: normalizedRefList(obligation.refs),
24725
+ method: obligation.method,
24726
+ before: obligation.before,
24727
+ dependentAction: obligation.dependentAction
24728
+ })}`,
24729
+ dimension,
24730
+ scope: obligation.scope,
24731
+ reason: `${constraint.kind} constraint requires ${obligation.kind}: ${constraint.statement}`,
24732
+ satisfaction: `Satisfy the constraint obligation using its referenced ${obligation.kind}.`,
24733
+ before: obligation.before,
24734
+ dependentAction: obligation.dependentAction,
24735
+ acceptanceAllowed: constraint.acceptanceAllowed && obligation.kind !== "decision"
24736
+ }));
24580
24737
  }
24581
- if (!evidence.candidateId || !current)
24582
- return {
24583
- evidenceId: entry.id,
24584
- status: evidence.result,
24585
- reason: "evidence has no candidate binding"
24586
- };
24587
- const observed = task.candidates.find((item) => item.id === evidence.candidateId) ?? (current.id === evidence.candidateId ? current : undefined);
24588
- if (!observed || observed.completeness === "uncertain" || current.completeness === "uncertain")
24589
- return { evidenceId: entry.id, status: "stale", reason: "candidate is missing or uncertain" };
24590
- if (observed.id === current.id)
24591
- return { evidenceId: entry.id, status: evidence.result, reason: "candidate is unchanged" };
24592
- const scopes = evidenceScopes(task, evidence.requirementIds);
24593
- const changed = changedPaths(observed, current);
24594
- const environmentChanged = JSON.stringify(observed.environment) !== JSON.stringify(current.environment);
24595
- if (!scopes.length || environmentChanged || changed.some((item) => scopes.some((scope) => pathRelevant(item, scope))))
24596
- return { evidenceId: entry.id, status: "stale", reason: "relevant candidate state changed" };
24597
- return {
24598
- evidenceId: entry.id,
24599
- status: evidence.result,
24600
- reason: "candidate changed outside evidence scope"
24601
- };
24738
+ const seen = new Set;
24739
+ return requirements.filter((item) => {
24740
+ if (seen.has(item.id))
24741
+ return false;
24742
+ seen.add(item.id);
24743
+ return true;
24602
24744
  });
24603
24745
  }
24604
- var scopeCovers2 = scopeCovers;
24605
- var checkPin = (assignment, beforeCandidateId, candidateId) => {
24606
- const pin = assignment.candidateId ?? null;
24607
- if (pin === null)
24608
- return true;
24609
- return (beforeCandidateId ?? null) === pin || (candidateId ?? null) === pin;
24610
- };
24611
- var resolveBinding = (evidence, pin, currentCandidateId) => {
24612
- const bound = evidence.kind === "check" || evidence.kind === "review";
24613
- const fallback = bound ? pin ?? currentCandidateId : null;
24614
- return {
24615
- beforeCandidateId: evidence.beforeCandidateId ?? fallback,
24616
- candidateId: evidence.candidateId ?? fallback
24746
+ function resolvePolicy(input) {
24747
+ const normalized = normalizeResolverInput(input);
24748
+ if (!normalized.ok)
24749
+ return normalized;
24750
+ const requirements = resolveRequirements(normalized.data);
24751
+ const policy = {
24752
+ policyVersion: POLICY_VERSION,
24753
+ inputDigest: sha256(canonicalJson(normalized.data)),
24754
+ requirements
24617
24755
  };
24618
- };
24619
- var findingVerificationPasses = (findingCandidateId, evidence) => evidence.status === "passed" && (evidence.kind === "check" || evidence.kind === "review") && ((findingCandidateId ?? null) === null || evidence.candidateId != null);
24620
- 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")));
24621
- 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 }));
24622
- var evidenceMatchesRequirement = (kind, evidenceKind, dimension, ruleId) => {
24623
- if (kind !== "passed")
24624
- return false;
24625
- if (dimension === "testing" || dimension === "verification")
24626
- return evidenceKind === "check" || ruleId === "pre-pr-cleanup" && evidenceKind === "artifact";
24627
- if (dimension === "review")
24628
- return evidenceKind === "review";
24629
- if (dimension === "investigation" || dimension === "challenge")
24630
- return evidenceKind === "investigation";
24631
- if (dimension === "artifacts" || dimension === "continuity")
24632
- return evidenceKind === "artifact";
24633
- return false;
24634
- };
24635
- var expectedKinds = (dimension, ruleId) => {
24636
- if (dimension === "testing")
24637
- return "check";
24638
- if (dimension === "verification")
24639
- return ruleId === "pre-pr-cleanup" ? "check or artifact" : "check";
24640
- if (dimension === "review")
24641
- return "review";
24642
- if (dimension === "investigation" || dimension === "challenge")
24643
- return "investigation";
24644
- if (dimension === "artifacts" || dimension === "continuity")
24645
- return "artifact";
24646
- if (dimension === "decisions")
24647
- return "decision";
24648
- return "worker report";
24649
- };
24650
- function evaluateRequirements(task, workspace, capabilities, candidate, checkoutRoot, _caller) {
24651
- const evidence = evaluateEvidence(task, candidate);
24652
- if (task.policy && task.policy.policyVersion !== POLICY_VERSION)
24653
- return task.policy.requirements.map((requirement) => ({
24654
- requirementId: requirement.id,
24655
- status: "unsatisfied",
24656
- evidenceIds: [],
24657
- decisionIds: [],
24658
- reason: "stored policy version is unsupported; reassessment is required"
24659
- }));
24660
- return (task.policy?.requirements ?? []).map((requirement) => {
24661
- const related = task.evidence.map((entry, index) => ({ entry, evaluation: evidence[index] })).filter(({ entry }) => entry.data.requirementIds.includes(requirement.id));
24662
- const passed = related.filter(({ entry, evaluation }) => {
24663
- if (!evidenceMatchesRequirement(evaluation.status, entry.data.kind, requirement.dimension, requirement.ruleId))
24664
- return false;
24665
- if ((entry.data.kind === "check" || entry.data.kind === "review") && (!entry.data.beforeCandidateId || !entry.data.candidateId || entry.data.beforeCandidateId !== entry.data.candidateId))
24666
- return false;
24667
- if (requirement.dimension !== "review")
24668
- return true;
24669
- const reviewSession = sessionFromRef(entry.data.reviewContext);
24670
- const sameImplementation = sameSession(reviewSession, task.intent.provenance.session);
24671
- 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));
24672
- return entry.data.kind === "review" && reviewSession !== null && sameSession(reviewSession, entry.provenance.session) && (requirement.ruleId === "self-review" || !sameImplementation && !sameEvidenceSession);
24673
- });
24674
- if (passed.length) {
24675
- const currentId = candidate?.id ?? null;
24676
- 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;
24677
- if (withRed.length)
24678
- return {
24679
- requirementId: requirement.id,
24680
- status: "satisfied",
24681
- evidenceIds: withRed.map(({ entry }) => entry.id),
24682
- decisionIds: [],
24683
- reason: "fresh applicable evidence passed"
24684
- };
24685
- if (requirement.dimension === "testing")
24686
- return {
24687
- requirementId: requirement.id,
24688
- status: "unsatisfied",
24689
- evidenceIds: [],
24690
- decisionIds: [],
24691
- reason: "testing requirement has GREEN evidence but no preceding RED"
24692
- };
24693
- }
24694
- if (requirement.dimension === "delegation") {
24695
- const dot = (scope) => scope.paths.length > 0 ? scope : { ...scope, paths: ["."] };
24696
- 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))));
24697
- if (reconciled)
24698
- return {
24699
- requirementId: requirement.id,
24700
- status: "satisfied",
24701
- evidenceIds: [],
24702
- decisionIds: [],
24703
- reason: "bounded helper completed and its result is recorded"
24704
- };
24705
- }
24706
- const decisions = requirement.dimension === "decisions" ? applicableRequirementDecision(task, workspace, requirement, checkoutRoot) : [];
24707
- if (decisions.length)
24708
- return {
24709
- requirementId: requirement.id,
24710
- status: "satisfied",
24711
- evidenceIds: [],
24712
- decisionIds: decisions.map((decision) => decision.id),
24713
- reason: "an applicable approved or stated decision satisfies the requirement"
24714
- };
24715
- const limitations = requirement.acceptanceAllowed ? applicableDecision2(task, workspace, requirement, checkoutRoot) : [];
24716
- if (limitations.length)
24717
- return {
24718
- requirementId: requirement.id,
24719
- status: "accepted_limitation",
24720
- evidenceIds: [],
24721
- decisionIds: limitations.map((decision) => task.decisions.find((entry) => entry.data === decision).id),
24722
- reason: "an applicable approved limitation permits the missing evidence"
24723
- };
24724
- const unavailable = capabilities.some((capability) => capability.assurance === "unavailable" && (capability.name === requirement.dimension || capability.surface === requirement.dimension));
24725
- if (!unavailable && related.length > 0 && !passed.length)
24726
- return {
24727
- requirementId: requirement.id,
24728
- status: "unsatisfied",
24729
- evidenceIds: related.map(({ entry }) => entry.id),
24730
- decisionIds: [],
24731
- reason: `no passing evidence (needs kind:${expectedKinds(requirement.dimension, requirement.ruleId)})`
24732
- };
24756
+ const parsed = policySchema.safeParse(policy);
24757
+ if (!parsed.success)
24758
+ return failure("invalid_input", "resolved policy is invalid", invalidFields(parsed.error));
24759
+ return success(null, null, parsed.data);
24760
+ }
24761
+ function diffPolicy(previous, next, reason, now) {
24762
+ if (!policySchema.safeParse(previous).success && previous !== null)
24763
+ throw new TypeError("previous policy is invalid");
24764
+ if (!policySchema.safeParse(next).success)
24765
+ throw new TypeError("next policy is invalid");
24766
+ const oldIds = new Set(previous?.requirements.map((requirement) => requirement.id) ?? []);
24767
+ const newIds = new Set(next.requirements.map((requirement) => requirement.id));
24768
+ const added = [...newIds].filter((id) => !oldIds.has(id)).sort(compareCodeUnits2);
24769
+ const retired = [...oldIds].filter((id) => !newIds.has(id)).sort(compareCodeUnits2);
24770
+ if (added.length === 0 && retired.length === 0)
24771
+ return null;
24772
+ const normalizedReason = reason.trim();
24773
+ const changeReason = retired.length ? `${normalizedReason || "policy reassessed"} (retired: ${retired.join(",")})` : normalizedReason || "policy reassessed";
24774
+ const change = {
24775
+ recordedAt: now,
24776
+ fromInputDigest: previous?.inputDigest ?? null,
24777
+ toInputDigest: next.inputDigest,
24778
+ added,
24779
+ retired,
24780
+ reason: changeReason
24781
+ };
24782
+ const parsed = policyChangeSchema.safeParse(change);
24783
+ if (!parsed.success)
24784
+ throw new TypeError("policy change is invalid");
24785
+ return parsed.data;
24786
+ }
24787
+
24788
+ // packages/workit-core/src/core/task-evaluation.ts
24789
+ import { createHash as createHash6 } from "node:crypto";
24790
+ import * as fs7 from "node:fs";
24791
+ import { spawnSync as spawnSync2 } from "node:child_process";
24792
+ import path10 from "node:path";
24793
+ var digestBytes3 = (value) => createHash6("sha256").update(value).digest("hex");
24794
+ var inside = (root, candidate) => candidate === root || candidate.startsWith(`${root}${path10.sep}`);
24795
+ var relative = (root, candidate) => path10.relative(root, candidate).split(path10.sep).join("/") || ".";
24796
+ var canonicalPath = (value) => {
24797
+ if (typeof value !== "string" || !value)
24798
+ return null;
24799
+ if (value.includes("\\") || value.split("/").includes(".."))
24800
+ return null;
24801
+ const normalized = path10.posix.normalize(value);
24802
+ if (normalized === ".." || normalized.startsWith("../") || normalized.startsWith("/"))
24803
+ return null;
24804
+ return normalized === "." ? "." : normalized.replace(/\/$/, "");
24805
+ };
24806
+ var canonicalScope = (scope) => {
24807
+ const paths = scope.paths.length ? scope.paths : ["."];
24808
+ const normalizedPaths = paths.map(canonicalPath);
24809
+ const normalizedExclusions = scope.exclusions.map(canonicalPath);
24810
+ if (normalizedPaths.some((value) => value === null) || normalizedExclusions.some((value) => value === null))
24811
+ return null;
24812
+ return {
24813
+ description: scope.description,
24814
+ paths: [...new Set(normalizedPaths)],
24815
+ exclusions: [...new Set(normalizedExclusions)]
24816
+ };
24817
+ };
24818
+ var excluded = (value, exclusions) => exclusions.some((item) => item === value || item !== "." && value.startsWith(`${item}/`));
24819
+ var scopeMatches = (value, scope) => {
24820
+ const normalized = canonicalScope(scope);
24821
+ if (!normalized)
24822
+ return false;
24823
+ const paths = normalized.paths;
24824
+ return paths.some((item) => item === "." || value === item || value.startsWith(`${item}/`)) && !excluded(value, normalized.exclusions);
24825
+ };
24826
+ var pathRelevant = (value, scope) => scopeMatches(value, scope);
24827
+ var compareCodeUnits3 = (left, right) => {
24828
+ const length = Math.min(left.length, right.length);
24829
+ for (let index = 0;index < length; index += 1) {
24830
+ const difference = left.charCodeAt(index) - right.charCodeAt(index);
24831
+ if (difference !== 0)
24832
+ return difference;
24833
+ }
24834
+ return left.length - right.length;
24835
+ };
24836
+ var gitPaths = (root) => {
24837
+ const result = spawnSync2("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
24838
+ cwd: root,
24839
+ encoding: "buffer"
24840
+ });
24841
+ if (result.status !== 0) {
24842
+ const stderr = result.stderr?.toString("utf8") ?? "";
24733
24843
  return {
24734
- requirementId: requirement.id,
24735
- status: unavailable ? "unavailable" : "unsatisfied",
24736
- evidenceIds: related.map(({ entry }) => entry.id),
24737
- decisionIds: [],
24738
- reason: unavailable ? "required capability is unavailable" : "no fresh passing evidence"
24844
+ paths: [],
24845
+ uncertain: !/not a git repository/i.test(stderr),
24846
+ git: /not a git repository/i.test(stderr) ? false : true
24739
24847
  };
24740
- });
24741
- }
24742
- function evaluateClosure(requestedOutcome, view) {
24743
- if (requestedOutcome !== "stopped" && !view.task.policy)
24744
- return failure("requirements_unsatisfied", "task has not been assessed");
24745
- if (view.task.policy && view.task.policy.policyVersion !== POLICY_VERSION)
24746
- return failure("requirements_unsatisfied", "stored policy version is unsupported; reassessment is required");
24747
- const evaluations = view.requirements;
24748
- const openFindings = view.task.findings.filter((entry) => entry.data.disposition === "open");
24749
- if (requestedOutcome !== "stopped" && openFindings.length)
24750
- return failure("requirements_unsatisfied", "open findings must be resolved before closure");
24751
- if (requestedOutcome !== "stopped") {
24752
- const evidenceById = new Map(view.evidence.map((entry) => [entry.evidenceId, entry.status]));
24753
- for (const entry of view.task.findings) {
24754
- if (entry.data.disposition === "fixed") {
24755
- const verified = entry.data.resolution?.evidenceIds.some((id) => {
24756
- const evidence = view.task.evidence.find((item) => item.id === id);
24757
- if (!evidence)
24758
- return false;
24759
- return findingVerificationPasses(entry.data.candidateId, {
24760
- kind: evidence.data.kind,
24761
- candidateId: evidence.data.candidateId,
24762
- status: evidenceById.get(id) ?? "missing"
24763
- });
24764
- });
24765
- if (!verified)
24766
- return failure("requirements_unsatisfied", "fixed findings require current verification");
24767
- }
24768
- if (entry.data.disposition === "deferred") {
24769
- const valid = entry.data.resolution?.decisionIds.some((id) => {
24770
- const decisionEntry = view.task.decisions.find((item) => item.id === id);
24771
- const decision = decisionEntry?.data;
24772
- 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)));
24773
- });
24774
- if (!valid)
24775
- return failure("requirements_unsatisfied", "deferred findings require an approved limitation decision that references an acceptanceAllowed requirement and covers the finding scope");
24776
- }
24848
+ }
24849
+ const paths = result.stdout ? result.stdout.toString("utf8").split("\x00").filter(Boolean).map((item) => item.split(path10.sep).join("/")) : [];
24850
+ const stagedDeleted = spawnSync2("git", ["diff", "--cached", "--name-only", "--diff-filter=D", "-z"], { cwd: root, encoding: "buffer" });
24851
+ if (stagedDeleted.status !== 0) {
24852
+ const stderr = stagedDeleted.stderr?.toString("utf8") ?? "";
24853
+ if (!/not a git repository/i.test(stderr))
24854
+ return { paths, uncertain: true, git: true };
24855
+ } else if (stagedDeleted.stdout) {
24856
+ paths.push(...stagedDeleted.stdout.toString("utf8").split("\x00").filter(Boolean).map((item) => item.split(path10.sep).join("/")));
24857
+ }
24858
+ return { paths: [...new Set(paths)], uncertain: false, git: true };
24859
+ };
24860
+ var walk = (root, directory, output) => {
24861
+ let names;
24862
+ try {
24863
+ names = fs7.readdirSync(directory);
24864
+ } catch {
24865
+ return true;
24866
+ }
24867
+ let uncertain = false;
24868
+ for (const name of names) {
24869
+ if (name === ".git" || name === ".workit")
24870
+ continue;
24871
+ const target = path10.join(directory, name);
24872
+ let stat;
24873
+ try {
24874
+ stat = fs7.lstatSync(target);
24875
+ } catch {
24876
+ uncertain = true;
24877
+ continue;
24777
24878
  }
24879
+ const item = relative(root, target);
24880
+ output.add(item);
24881
+ if (stat.isDirectory() && !stat.isSymbolicLink())
24882
+ uncertain = walk(root, target, output) || uncertain;
24778
24883
  }
24779
- const blocking = evaluations.filter((item) => {
24780
- if (item.status !== "unsatisfied" && item.status !== "unavailable")
24781
- return false;
24782
- const requirement = view.task.policy?.requirements.find((candidate) => candidate.id === item.requirementId);
24783
- return !requirement || requirement.before === "close";
24784
- });
24785
- if (requestedOutcome !== "stopped" && blocking.length)
24786
- return failure("requirements_unsatisfied", "applicable requirements are unsatisfied", {
24787
- requirementIds: blocking.map((item) => item.requirementId),
24788
- requirements: blocking.map((item) => {
24789
- const requirement = view.task.policy?.requirements.find((candidate) => candidate.id === item.requirementId);
24884
+ return uncertain;
24885
+ };
24886
+ var scopeRoots = (root, scope) => {
24887
+ const roots = [];
24888
+ for (const item of scope.paths.length ? scope.paths : ["."]) {
24889
+ const target = path10.resolve(root, item);
24890
+ if (!inside(root, target))
24891
+ 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` }] });
24892
+ let ancestor = target;
24893
+ while (!fs7.existsSync(ancestor) && ancestor !== root)
24894
+ ancestor = path10.dirname(ancestor);
24895
+ try {
24896
+ if (!inside(root, fs7.realpathSync(ancestor)))
24897
+ 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` }] });
24898
+ } catch {
24899
+ return failure("invalid_input", `candidate scope cannot be inspected: ${item}`);
24900
+ }
24901
+ roots.push(target);
24902
+ }
24903
+ return success(null, null, roots);
24904
+ };
24905
+ function captureCandidate(root, scope, environment = []) {
24906
+ let checkout;
24907
+ try {
24908
+ checkout = fs7.realpathSync(root);
24909
+ } catch {
24910
+ return failure("invalid_input", "candidate root does not exist");
24911
+ }
24912
+ const normalizedScope = canonicalScope(scope);
24913
+ if (!normalizedScope)
24914
+ 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" }] });
24915
+ const roots = scopeRoots(checkout, normalizedScope);
24916
+ if (!roots.ok)
24917
+ return roots;
24918
+ const git = gitPaths(checkout);
24919
+ const names = new Set;
24920
+ let uncertain = git.uncertain;
24921
+ for (const target of roots.data) {
24922
+ const item = relative(checkout, target);
24923
+ if (item === ".git" || item === ".workit")
24924
+ continue;
24925
+ names.add(item);
24926
+ if (!fs7.existsSync(target))
24927
+ continue;
24928
+ let stat;
24929
+ try {
24930
+ stat = fs7.lstatSync(target);
24931
+ } catch {
24932
+ uncertain = true;
24933
+ continue;
24934
+ }
24935
+ if (!git.git && stat.isDirectory() && !stat.isSymbolicLink())
24936
+ uncertain = walk(checkout, target, names) || uncertain;
24937
+ }
24938
+ for (const item of git.paths)
24939
+ if (scopeMatches(item, normalizedScope))
24940
+ names.add(item);
24941
+ const files = [];
24942
+ let completeness = uncertain ? "uncertain" : "known";
24943
+ for (const item of [...names].sort()) {
24944
+ if (!scopeMatches(item, normalizedScope))
24945
+ continue;
24946
+ const target = path10.join(checkout, item);
24947
+ try {
24948
+ const stat = fs7.lstatSync(target);
24949
+ if (stat.isSymbolicLink()) {
24950
+ const link = fs7.readlinkSync(target);
24951
+ files.push({ path: item, kind: "symlink", digest: digestBytes3(link), executable: null });
24952
+ } else if (stat.isFile()) {
24953
+ files.push({
24954
+ path: item,
24955
+ kind: "file",
24956
+ digest: digestBytes3(fs7.readFileSync(target)),
24957
+ executable: (stat.mode & 73) !== 0
24958
+ });
24959
+ } else if (!stat.isDirectory()) {
24960
+ completeness = "uncertain";
24961
+ } else if (git.git && git.paths.includes(item)) {
24962
+ completeness = "uncertain";
24963
+ }
24964
+ } catch (error) {
24965
+ if (error?.code === "ENOENT") {
24966
+ files.push({ path: item, kind: "absent", digest: null, executable: null });
24967
+ } else
24968
+ completeness = "uncertain";
24969
+ }
24970
+ }
24971
+ 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) => ({
24972
+ name,
24973
+ value: environment[name] ?? null
24974
+ }));
24975
+ const namesByEnvironment = supplied.map(({ name }) => name);
24976
+ if (new Set(namesByEnvironment).size !== namesByEnvironment.length || namesByEnvironment.some((name) => typeof name !== "string" || !name))
24977
+ return failure("invalid_input", "candidate environment names must be unique and non-empty");
24978
+ const values = supplied.sort((left, right) => compareCodeUnits3(left.name, right.name)).map(({ name, value }) => ({ name, value, refs: [] }));
24979
+ if (values.some(({ value }) => value === null))
24980
+ completeness = "uncertain";
24981
+ const headResult = spawnSync2("git", ["rev-parse", "HEAD"], { cwd: checkout, encoding: "utf8" });
24982
+ if (headResult.status !== 0 && !/not a git repository/i.test(headResult.stderr ?? ""))
24983
+ completeness = "uncertain";
24984
+ const head = headResult.status === 0 ? headResult.stdout.trim() : null;
24985
+ const partial = {
24986
+ id: "0".repeat(64),
24987
+ scope: normalizedScope,
24988
+ completeness,
24989
+ files,
24990
+ environment: values,
24991
+ head
24992
+ };
24993
+ const candidate = { ...partial, id: candidateDigest(partial) };
24994
+ const parsed = candidateSchema.safeParse(candidate);
24995
+ return parsed.success ? success(null, null, parsed.data) : failure("invalid_input", "captured candidate is invalid");
24996
+ }
24997
+ var fileMap = (candidate) => new Map(candidate.files.map((file) => [file.path, file]));
24998
+ var changedPaths = (before, after) => {
24999
+ const paths = new Set([...before.files, ...after.files].map((file) => file.path));
25000
+ const left = fileMap(before);
25001
+ const right = fileMap(after);
25002
+ const changed = [...paths].filter((item) => JSON.stringify(left.get(item) ?? null) !== JSON.stringify(right.get(item) ?? null));
25003
+ if (before.head !== after.head)
25004
+ changed.push(".");
25005
+ if (JSON.stringify(before.environment) !== JSON.stringify(after.environment))
25006
+ changed.push(".");
25007
+ return changed;
25008
+ };
25009
+ var sessionFromRef = (value) => {
25010
+ if (typeof value !== "object" || value === null || value.kind !== "host")
25011
+ return null;
25012
+ return typeof value.host === "string" && typeof value.handle === "string" ? { host: value.host, handle: value.handle } : null;
25013
+ };
25014
+ var sameSession = (left, right) => {
25015
+ const other = sessionFromRef(right);
25016
+ return left !== null && other !== null && left.host === other.host && left.handle === other.handle;
25017
+ };
25018
+ var evidenceScopes = (task, ids) => (task.policy?.requirements ?? []).filter((requirement) => ids.includes(requirement.id)).map((requirement) => requirement.scope);
25019
+ function evaluateEvidence(task, candidate) {
25020
+ const current = candidate ?? task.candidates.at(-1) ?? null;
25021
+ return task.evidence.map((entry) => {
25022
+ const evidence = entry.data;
25023
+ if (evidence.result === "failed")
25024
+ return {
25025
+ evidenceId: entry.id,
25026
+ status: "failed",
25027
+ reason: "failed evidence remains historical"
25028
+ };
25029
+ if (evidence.kind === "check" || evidence.kind === "review") {
25030
+ if (!evidence.beforeCandidateId || !evidence.candidateId)
24790
25031
  return {
24791
- requirementId: item.requirementId,
24792
- ruleId: requirement?.ruleId ?? "unknown",
24793
- reason: item.reason,
24794
- satisfaction: requirement?.satisfaction ?? "",
24795
- dependentAction: requirement?.dependentAction ?? null
25032
+ evidenceId: entry.id,
25033
+ status: "stale",
25034
+ reason: "check or review evidence lacks start and end candidates"
24796
25035
  };
24797
- })
24798
- });
24799
- const accepted = evaluations.filter((item) => item.status === "accepted_limitation");
24800
- if (requestedOutcome === "verified" && accepted.length)
24801
- return failure("requirements_unsatisfied", "accepted limitations cannot be reported as verified", {
24802
- requirementIds: accepted.map((item) => item.requirementId)
24803
- });
24804
- const evidenceIds = [
24805
- ...new Set([
24806
- ...evaluations.flatMap((item) => item.evidenceIds),
24807
- ...view.task.findings.flatMap((item) => item.data.resolution?.evidenceIds ?? [])
24808
- ])
24809
- ];
24810
- const decisionIds = [
24811
- ...new Set([
24812
- ...evaluations.flatMap((item) => item.decisionIds),
24813
- ...view.task.findings.flatMap((item) => item.data.resolution?.decisionIds ?? [])
24814
- ])
24815
- ];
24816
- return success(null, null, {
24817
- outcome: requestedOutcome === "stopped" ? "stopped" : accepted.length ? "accepted_limitations" : "verified",
24818
- evidenceIds,
24819
- decisionIds,
24820
- requirementIds: evaluations.map((item) => item.requirementId)
24821
- });
24822
- }
24823
-
24824
- // packages/workit-core/src/core/task-context.ts
24825
- function reconcileResume(view, observations = []) {
24826
- if (observations.length > 0)
24827
- return failure("permission_denied", "worker observations require native host verification");
24828
- const candidate = captureCandidate(view.workspace.root, view.task.intent.data.scope, []);
24829
- if (!candidate.ok)
24830
- return candidate;
24831
- const staleEvidenceIds = evaluateEvidence(view.task, candidate.data).filter((entry) => entry.status === "stale").map((entry) => entry.evidenceId);
24832
- const blockers = [...view.task.progress.blockers];
24833
- if (view.task.workers.some((entry) => isUncertainWorker(entry.data.state)))
24834
- blockers.push({
24835
- reason: "worker state requires reconciliation",
24836
- dependentAction: "resume",
24837
- refs: []
24838
- });
24839
- return success(null, null, {
24840
- candidate: candidate.data,
24841
- staleEvidenceIds,
24842
- workerUpdates: [],
24843
- blockers,
24844
- reassessmentRequired: view.task.policy?.policyVersion !== POLICY_VERSION
25036
+ if (evidence.beforeCandidateId !== evidence.candidateId)
25037
+ return {
25038
+ evidenceId: entry.id,
25039
+ status: "stale",
25040
+ reason: "candidate changed during the check or review"
25041
+ };
25042
+ }
25043
+ if (!evidence.candidateId || !current)
25044
+ return {
25045
+ evidenceId: entry.id,
25046
+ status: evidence.result,
25047
+ reason: "evidence has no candidate binding"
25048
+ };
25049
+ const observed = task.candidates.find((item) => item.id === evidence.candidateId) ?? (current.id === evidence.candidateId ? current : undefined);
25050
+ if (!observed || observed.completeness === "uncertain" || current.completeness === "uncertain")
25051
+ return { evidenceId: entry.id, status: "stale", reason: "candidate is missing or uncertain" };
25052
+ if (observed.id === current.id)
25053
+ return { evidenceId: entry.id, status: evidence.result, reason: "candidate is unchanged" };
25054
+ const scopes = evidenceScopes(task, evidence.requirementIds);
25055
+ const changed = changedPaths(observed, current);
25056
+ const environmentChanged = JSON.stringify(observed.environment) !== JSON.stringify(current.environment);
25057
+ if (!scopes.length || environmentChanged || changed.some((item) => scopes.some((scope) => pathRelevant(item, scope))))
25058
+ return { evidenceId: entry.id, status: "stale", reason: "relevant candidate state changed" };
25059
+ return {
25060
+ evidenceId: entry.id,
25061
+ status: evidence.result,
25062
+ reason: "candidate changed outside evidence scope"
25063
+ };
24845
25064
  });
24846
25065
  }
24847
- var exportDigest = (bundle) => sha256({
24848
- schemaVersion: bundle.schemaVersion,
24849
- exportedAt: bundle.exportedAt,
24850
- sourceWorkspaceId: bundle.sourceWorkspaceId,
24851
- task: bundle.task
24852
- });
24853
- // packages/workit-core/src/core/external-action.ts
24854
- var chainStepSchema = union3([
24855
- string5().min(1),
24856
- object4({ branch: string5().min(1) }).strict(),
24857
- object4({ pr: literal3(true) }).strict()
24858
- ]);
24859
- var externalActionSchema = discriminatedUnion2("operation", [
24860
- object4({
24861
- operation: literal3("git.branch_setup"),
24862
- payload: object4({
24863
- action: _enum2(["setup", "reapply_stash"]).optional(),
24864
- sdd_dir: string5().optional(),
24865
- target_branch: string5().optional(),
24866
- stash: _enum2(["yes", "no"]).optional(),
24867
- cwd: string5().min(1).optional()
24868
- }).strict()
24869
- }).strict(),
24870
- object4({
24871
- operation: literal3("git.commit"),
24872
- payload: object4({
24873
- message: string5().min(1).optional(),
24874
- plan_steps: array3(chainStepSchema).min(1).max(32).optional(),
24875
- plan_branch: string5().min(1).optional(),
24876
- cwd: string5().min(1).optional()
24877
- }).strict()
24878
- }).strict(),
24879
- object4({
24880
- operation: literal3("git.push"),
24881
- payload: object4({ branch: string5().min(1).optional(), cwd: string5().min(1).optional() }).strict()
24882
- }).strict(),
24883
- object4({
24884
- operation: literal3("hosting.pull_request"),
24885
- payload: object4({
24886
- title: string5().min(1),
24887
- body: string5().optional(),
24888
- draft: boolean5().optional(),
24889
- target_branch: string5().optional(),
24890
- babysit: boolean5().optional(),
24891
- cwd: string5().min(1).optional()
24892
- }).strict()
24893
- }).strict(),
24894
- object4({
24895
- operation: literal3("hosting.merge"),
24896
- payload: object4({
24897
- target_branch: string5().min(1).optional(),
24898
- source_branch: string5().min(1).optional(),
24899
- cwd: string5().min(1).optional()
24900
- }).strict()
24901
- }).strict(),
24902
- object4({
24903
- operation: literal3("hosting.delete_branch"),
24904
- payload: object4({ branch: string5().min(1), cwd: string5().min(1).optional() }).strict()
24905
- }).strict(),
24906
- object4({
24907
- operation: literal3("youtrack.update"),
24908
- payload: object4({
24909
- issueId: string5().min(1),
24910
- markdown: string5().min(1),
24911
- minutes: number5().positive().optional()
24912
- }).strict()
24913
- }).strict(),
24914
- object4({
24915
- operation: literal3("youtrack.time"),
24916
- payload: object4({
24917
- issueId: string5().min(1),
24918
- minutes: number5().positive(),
24919
- text: string5().optional(),
24920
- dateMs: number5().finite().optional()
24921
- }).strict()
24922
- }).strict(),
24923
- object4({
24924
- operation: literal3("youtrack.meeting"),
24925
- payload: object4({
24926
- issueId: string5().min(1),
24927
- minutes: number5().positive(),
24928
- text: string5().min(1)
24929
- }).strict()
24930
- }).strict(),
24931
- object4({
24932
- operation: literal3("changelog.apply"),
24933
- payload: object4({
24934
- entries: union3([
24935
- record3(string5(), array3(string5())),
24936
- array3(object4({ category: string5().min(1), text: string5().min(1) }).strict())
24937
- ]).optional(),
24938
- path: string5().optional(),
24939
- normalize_only: boolean5().optional()
24940
- }).strict()
24941
- }).strict(),
24942
- object4({
24943
- operation: literal3("context.read"),
24944
- payload: object4({
24945
- kind: _enum2([
24946
- "git",
24947
- "pr",
24948
- "youtrack",
24949
- "github_issue",
24950
- "gitlab_issue",
24951
- "changelog",
24952
- "release",
24953
- "affected"
24954
- ]),
24955
- range: string5().optional(),
24956
- issueId: string5().optional(),
24957
- issueUrl: string5().optional(),
24958
- issueRef: string5().optional(),
24959
- mode: string5().optional(),
24960
- specPath: string5().optional(),
24961
- planPath: string5().optional(),
24962
- cwd: string5().min(1).optional()
24963
- }).strict()
24964
- }).strict()
24965
- ]);
24966
- // packages/workit-core/src/core/task-engine.ts
24967
- import { realpathSync as realpathSync6 } from "node:fs";
24968
-
24969
- // packages/workit-core/src/core/policy-resolver.ts
24970
- var resolverInputSchema = object4({
24971
- intent: intentSchema,
24972
- assessment: assessmentSchema,
24973
- constraints: array3(constraintSchema),
24974
- prior: object4({
24975
- decisions: array3(decisionSchema),
24976
- findings: array3(findingSchema),
24977
- requirements: array3(requirementSchema)
24978
- }).strict(),
24979
- preferences: object4({ fast: boolean5().optional(), thorough: boolean5().optional() }).strict().optional()
24980
- }).strict();
24981
- var compareCodeUnits3 = (left, right) => {
24982
- const length = Math.min(left.length, right.length);
24983
- for (let index = 0;index < length; index += 1) {
24984
- const difference = left.charCodeAt(index) - right.charCodeAt(index);
24985
- if (difference !== 0)
24986
- return difference;
24987
- }
24988
- return left.length - right.length;
24989
- };
24990
- var stableUnique = (values) => [...new Set(values)].sort(compareCodeUnits3);
24991
- var stableList = (values) => [...values].sort((left, right) => compareCodeUnits3(canonicalJson(left), canonicalJson(right)));
24992
- var normalizedScope = (scope) => ({
24993
- description: scope.description,
24994
- paths: stableUnique(scope.paths),
24995
- exclusions: stableUnique(scope.exclusions)
24996
- });
24997
- var normalizedRefList = (values) => stableList(values);
24998
- var normalizeAssessment = (assessment) => ({
24999
- facts: stableList(assessment.facts.map((fact) => ({ ...fact, refs: normalizedRefList(fact.refs) }))),
25000
- signals: Object.fromEntries(Object.entries(assessment.signals).map(([name, signal]) => [
25001
- name,
25002
- { ...signal, refs: normalizedRefList(signal.refs) }
25003
- ])),
25004
- consequences: stableList(assessment.consequences.map((consequence) => ({
25005
- ...consequence,
25006
- fact: { ...consequence.fact, refs: normalizedRefList(consequence.fact.refs) }
25007
- }))),
25008
- verification: stableList(assessment.verification.map((verification) => ({
25009
- ...verification,
25010
- scope: normalizedScope(verification.scope),
25011
- availableChecks: normalizedRefList(verification.availableChecks),
25012
- gaps: stableUnique(verification.gaps)
25013
- })))
25014
- });
25015
- var normalizeConstraint = (constraint) => ({
25016
- ...constraint,
25017
- source: constraint.source,
25018
- requires: stableList(constraint.requires.map((requirement) => ({
25019
- ...requirement,
25020
- scope: normalizedScope(requirement.scope),
25021
- refs: normalizedRefList(requirement.refs)
25022
- })))
25023
- });
25024
- var normalizeDecision = (decision) => ({
25025
- ...decision,
25026
- binding: {
25027
- ...decision.binding,
25028
- scope: normalizedScope(decision.binding.scope),
25029
- contentRefs: normalizedRefList(decision.binding.contentRefs)
25030
- },
25031
- requirementIds: stableUnique(decision.requirementIds)
25032
- });
25033
- var normalizeIntent = (intent) => ({
25034
- ...intent,
25035
- scope: normalizedScope(intent.scope),
25036
- authorityRefs: normalizedRefList(intent.authorityRefs)
25037
- });
25038
- var normalizePrior = (prior) => ({
25039
- decisions: stableList(prior.decisions.map(normalizeDecision)),
25040
- findings: stableList(prior.findings.map((finding) => ({
25041
- ...finding,
25042
- scope: normalizedScope(finding.scope),
25043
- refs: normalizedRefList(finding.refs),
25044
- resolution: finding.resolution ? {
25045
- ...finding.resolution,
25046
- evidenceIds: stableUnique(finding.resolution.evidenceIds),
25047
- decisionIds: stableUnique(finding.resolution.decisionIds)
25048
- } : null
25049
- }))),
25050
- requirements: stableList(prior.requirements.map((requirement) => ({
25051
- ...requirement,
25052
- scope: normalizedScope(requirement.scope)
25053
- })))
25054
- });
25055
- var invalidFields = (error) => ({
25056
- fields: error.issues.map((issue) => ({
25057
- path: issue.code === "unrecognized_keys" ? issue.keys.join(".") : issue.path.join("."),
25058
- reason: issue.message
25059
- }))
25060
- });
25061
- function normalizeResolverInput(input) {
25062
- const parsed = resolverInputSchema.safeParse(input);
25063
- if (!parsed.success)
25064
- return failure("invalid_input", "resolver input is invalid", invalidFields(parsed.error));
25065
- const value = parsed.data;
25066
- const signals = value.assessment.signals;
25067
- if (signals.behaviorChange.value === true && signals.mechanicalLowRisk.value === true)
25068
- return failure("invalid_input", "behavioral change cannot be wholly mechanical", {
25069
- fields: [
25070
- {
25071
- path: "assessment.signals",
25072
- reason: "contradictory behaviorChange and mechanicalLowRisk"
25073
- }
25074
- ]
25075
- });
25076
- const ids = value.constraints.map((constraint) => constraint.id);
25077
- if (new Set(ids).size !== ids.length)
25078
- return failure("invalid_input", "constraint IDs must be unique", {
25079
- fields: [{ path: "constraints", reason: "duplicate constraint id" }]
25080
- });
25081
- if (value.preferences?.fast && value.preferences.thorough)
25082
- return failure("invalid_input", "fast and thorough preferences contradict", {
25083
- fields: [{ path: "preferences", reason: "fast and thorough cannot both be enabled" }]
25084
- });
25085
- const normalized = {
25086
- intent: normalizeIntent(value.intent),
25087
- assessment: normalizeAssessment(value.assessment),
25088
- constraints: stableList(value.constraints.map(normalizeConstraint)),
25089
- prior: normalizePrior(value.prior),
25090
- ...value.preferences ? { preferences: { ...value.preferences } } : {},
25091
- policyVersion: POLICY_VERSION
25092
- };
25093
- return success(null, null, normalized);
25094
- }
25095
- var requirement = (spec) => ({
25096
- ...spec,
25097
- id: requirementId({
25098
- ruleId: spec.ruleId,
25099
- scope: spec.scope,
25100
- satisfaction: spec.satisfaction,
25101
- before: spec.before,
25102
- dependentAction: spec.dependentAction
25103
- })
25104
- });
25105
- var signalReason = (input, name) => input.assessment.signals[name].reason;
25106
- function resolveRequirements(input) {
25107
- const { signals } = input.assessment;
25108
- const scope = input.intent.scope;
25109
- const requirements = [];
25110
- const hasUnknownSignal = Object.values(signals).some((signal) => signal.value === "unknown");
25111
- const hasUnknownFact = [
25112
- ...input.assessment.facts,
25113
- ...input.assessment.consequences.map(({ fact }) => fact)
25114
- ].some((fact) => fact.basis === "unknown");
25115
- if (hasUnknownSignal || hasUnknownFact)
25116
- requirements.push(requirement({
25117
- ruleId: "consequential-unknown",
25118
- dimension: "investigation",
25119
- scope,
25120
- reason: `Resolve consequential uncertainty before the dependent action: ${[
25121
- ...Object.entries(signals).filter(([, signal]) => signal.value === "unknown").map(([name]) => name),
25122
- ...hasUnknownFact ? ["unknown fact"] : []
25123
- ].join(", ")}`,
25124
- satisfaction: "An observed or inferred fact resolves the uncertainty and records its supporting references.",
25125
- before: "dependent_action",
25126
- dependentAction: null,
25127
- acceptanceAllowed: false
25128
- }));
25129
- if (signals.productChoiceOpen.value === true)
25130
- requirements.push(requirement({
25131
- ruleId: "product-decision",
25132
- dimension: "decisions",
25133
- scope,
25134
- reason: `A consequential product choice remains open: ${signalReason(input, "productChoiceOpen")}`,
25135
- satisfaction: "Present the material alternatives and record the user's decision before the dependent action.",
25136
- before: "dependent_action",
25137
- dependentAction: null,
25138
- acceptanceAllowed: false
25139
- }));
25140
- const independentBehaviorReview = input.preferences?.thorough === true || input.assessment.consequences.some((consequence) => ["security", "data", "public_contract", "operations"].includes(consequence.area));
25141
- if (signals.behaviorChange.value === true)
25142
- requirements.push(requirement({
25143
- ruleId: "behavioral-verification",
25144
- dimension: "testing",
25145
- scope,
25146
- reason: `Behavior, side effects, permissions, or data handling may change: ${signalReason(input, "behaviorChange")}`,
25147
- satisfaction: "A useful behavioral check passes against the affected behavior and current candidate.",
25148
- before: "close",
25149
- dependentAction: null,
25150
- acceptanceAllowed: false
25151
- }), requirement({
25152
- ruleId: independentBehaviorReview ? "fresh-context-review" : "self-review",
25153
- dimension: "review",
25154
- scope,
25155
- 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.",
25156
- 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.",
25157
- before: "close",
25158
- dependentAction: null,
25159
- acceptanceAllowed: !independentBehaviorReview
25160
- }));
25161
- else if (signals.mechanicalLowRisk.value === true)
25162
- requirements.push(requirement({
25163
- ruleId: "mechanical-existing-checks",
25164
- dimension: "verification",
25165
- scope,
25166
- reason: `The change is demonstrably mechanical and low-risk: ${signalReason(input, "mechanicalLowRisk")}`,
25167
- satisfaction: "Run the relevant existing checks for affected consumers; do not add tautological tests.",
25168
- before: "close",
25169
- dependentAction: null,
25170
- acceptanceAllowed: true
25171
- }), requirement({
25172
- ruleId: input.preferences?.thorough ? "fresh-context-review" : "self-review",
25173
- dimension: "review",
25174
- scope,
25175
- 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.",
25176
- 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.",
25177
- before: "close",
25178
- dependentAction: null,
25179
- acceptanceAllowed: !input.preferences?.thorough
25180
- }));
25181
- if (signals.behaviorChange.value === true || signals.mechanicalLowRisk.value === true)
25182
- requirements.push(requirement({
25183
- ruleId: "pre-pr-cleanup",
25184
- dimension: "verification",
25185
- scope,
25186
- reason: "Implementation output must be deslopped before it is delivered.",
25187
- satisfaction: "Run the workit-deslop pass and record passing check evidence, or record an approved limitation decision waiving cleanup.",
25188
- before: "dependent_action",
25189
- dependentAction: "hosting.pull_request",
25190
- acceptanceAllowed: true
25191
- }));
25192
- if (signals.durableAgreementNeeded.value === true)
25193
- requirements.push(requirement({
25194
- ruleId: "durable-spec",
25195
- dimension: "artifacts",
25196
- scope,
25197
- reason: `The work needs a durable agreement about intended behavior: ${signalReason(input, "durableAgreementNeeded")}`,
25198
- satisfaction: "Record the agreed behavior in a durable specification before implementation writes.",
25199
- before: "write",
25200
- dependentAction: null,
25201
- acceptanceAllowed: true
25202
- }));
25203
- if (signals.coordinationPlanNeeded.value === true)
25204
- requirements.push(requirement({
25205
- ruleId: "coordination-plan",
25206
- dimension: "continuity",
25207
- scope,
25208
- reason: `Dependencies, sequencing, or resumption need durable coordination: ${signalReason(input, "coordinationPlanNeeded")}`,
25209
- satisfaction: "Record useful sequencing, dependencies, and the next action in a compact plan.",
25210
- before: "dependent_action",
25211
- dependentAction: null,
25212
- acceptanceAllowed: true
25213
- }));
25214
- if (signals.helperUseful.value === true && !input.preferences?.fast)
25215
- requirements.push(requirement({
25216
- ruleId: "helper-usefulness",
25217
- dimension: "delegation",
25218
- scope,
25219
- reason: `Independent judgment or investigation justifies a scoped helper: ${signalReason(input, "helperUseful")}`,
25220
- satisfaction: "Use a bounded helper only for the independent objective and reconcile its result.",
25221
- before: "dependent_action",
25222
- dependentAction: null,
25223
- acceptanceAllowed: true
25066
+ var scopeCovers2 = scopeCovers;
25067
+ var checkPin = (assignment, beforeCandidateId, candidateId) => {
25068
+ const pin = assignment.candidateId ?? null;
25069
+ if (pin === null)
25070
+ return true;
25071
+ return (beforeCandidateId ?? null) === pin || (candidateId ?? null) === pin;
25072
+ };
25073
+ var resolveBinding = (evidence, pin, currentCandidateId) => {
25074
+ const bound = evidence.kind === "check" || evidence.kind === "review";
25075
+ const fallback = bound ? pin ?? currentCandidateId : null;
25076
+ return {
25077
+ beforeCandidateId: evidence.beforeCandidateId ?? fallback,
25078
+ candidateId: evidence.candidateId ?? fallback
25079
+ };
25080
+ };
25081
+ var findingVerificationPasses = (findingCandidateId, evidence) => evidence.status === "passed" && (evidence.kind === "check" || evidence.kind === "review") && ((findingCandidateId ?? null) === null || evidence.candidateId != null);
25082
+ 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")));
25083
+ 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 }));
25084
+ var evidenceMatchesRequirement = (kind, evidenceKind, dimension, ruleId) => {
25085
+ if (kind !== "passed")
25086
+ return false;
25087
+ if (dimension === "testing" || dimension === "verification")
25088
+ return evidenceKind === "check" || ruleId === "pre-pr-cleanup" && evidenceKind === "artifact";
25089
+ if (dimension === "review")
25090
+ return evidenceKind === "review";
25091
+ if (dimension === "investigation" || dimension === "challenge")
25092
+ return evidenceKind === "investigation";
25093
+ if (dimension === "artifacts" || dimension === "continuity")
25094
+ return evidenceKind === "artifact";
25095
+ return false;
25096
+ };
25097
+ var expectedKinds = (dimension, ruleId) => {
25098
+ if (dimension === "testing")
25099
+ return "check";
25100
+ if (dimension === "verification")
25101
+ return ruleId === "pre-pr-cleanup" ? "check or artifact" : "check";
25102
+ if (dimension === "review")
25103
+ return "review";
25104
+ if (dimension === "investigation" || dimension === "challenge")
25105
+ return "investigation";
25106
+ if (dimension === "artifacts" || dimension === "continuity")
25107
+ return "artifact";
25108
+ if (dimension === "decisions")
25109
+ return "decision";
25110
+ return "worker report";
25111
+ };
25112
+ function evaluateRequirements(task, workspace, capabilities, candidate, checkoutRoot, _caller) {
25113
+ const evidence = evaluateEvidence(task, candidate);
25114
+ if (task.policy && task.policy.policyVersion !== POLICY_VERSION)
25115
+ return task.policy.requirements.map((requirement) => ({
25116
+ requirementId: requirement.id,
25117
+ status: "unsatisfied",
25118
+ evidenceIds: [],
25119
+ decisionIds: [],
25120
+ reason: "stored policy version is unsupported; reassessment is required"
25224
25121
  }));
25225
- for (const constraint of input.constraints)
25226
- for (const obligation of constraint.requires) {
25227
- const dimension = obligation.method ?? (obligation.kind === "check" ? "verification" : obligation.kind === "decision" ? "decisions" : "challenge");
25228
- requirements.push(requirement({
25229
- ruleId: `project-constraint:${constraint.id}:${obligation.kind}:${sha256({
25230
- kind: obligation.kind,
25231
- scope: normalizedScope(obligation.scope),
25232
- refs: normalizedRefList(obligation.refs),
25233
- method: obligation.method,
25234
- before: obligation.before,
25235
- dependentAction: obligation.dependentAction
25236
- })}`,
25237
- dimension,
25238
- scope: obligation.scope,
25239
- reason: `${constraint.kind} constraint requires ${obligation.kind}: ${constraint.statement}`,
25240
- satisfaction: `Satisfy the constraint obligation using its referenced ${obligation.kind}.`,
25241
- before: obligation.before,
25242
- dependentAction: obligation.dependentAction,
25243
- acceptanceAllowed: constraint.acceptanceAllowed && obligation.kind !== "decision"
25244
- }));
25122
+ return (task.policy?.requirements ?? []).map((requirement) => {
25123
+ const related = task.evidence.map((entry, index) => ({ entry, evaluation: evidence[index] })).filter(({ entry }) => entry.data.requirementIds.includes(requirement.id));
25124
+ const passed = related.filter(({ entry, evaluation }) => {
25125
+ if (!evidenceMatchesRequirement(evaluation.status, entry.data.kind, requirement.dimension, requirement.ruleId))
25126
+ return false;
25127
+ if ((entry.data.kind === "check" || entry.data.kind === "review") && (!entry.data.beforeCandidateId || !entry.data.candidateId || entry.data.beforeCandidateId !== entry.data.candidateId))
25128
+ return false;
25129
+ if (requirement.dimension !== "review")
25130
+ return true;
25131
+ const reviewSession = sessionFromRef(entry.data.reviewContext);
25132
+ const sameImplementation = sameSession(reviewSession, task.intent.provenance.session);
25133
+ 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));
25134
+ return entry.data.kind === "review" && reviewSession !== null && sameSession(reviewSession, entry.provenance.session) && (requirement.ruleId === "self-review" || !sameImplementation && !sameEvidenceSession);
25135
+ });
25136
+ if (passed.length) {
25137
+ const currentId = candidate?.id ?? null;
25138
+ 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;
25139
+ if (withRed.length)
25140
+ return {
25141
+ requirementId: requirement.id,
25142
+ status: "satisfied",
25143
+ evidenceIds: withRed.map(({ entry }) => entry.id),
25144
+ decisionIds: [],
25145
+ reason: "fresh applicable evidence passed"
25146
+ };
25147
+ if (requirement.dimension === "testing")
25148
+ return {
25149
+ requirementId: requirement.id,
25150
+ status: "unsatisfied",
25151
+ evidenceIds: [],
25152
+ decisionIds: [],
25153
+ reason: "testing requirement has GREEN evidence but no preceding RED"
25154
+ };
25245
25155
  }
25246
- const seen = new Set;
25247
- return requirements.filter((item) => {
25248
- if (seen.has(item.id))
25156
+ if (requirement.dimension === "delegation") {
25157
+ const dot = (scope) => scope.paths.length > 0 ? scope : { ...scope, paths: ["."] };
25158
+ 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))));
25159
+ if (reconciled)
25160
+ return {
25161
+ requirementId: requirement.id,
25162
+ status: "satisfied",
25163
+ evidenceIds: [],
25164
+ decisionIds: [],
25165
+ reason: "bounded helper completed and its result is recorded"
25166
+ };
25167
+ }
25168
+ const decisions = requirement.dimension === "decisions" ? applicableRequirementDecision(task, workspace, requirement, checkoutRoot) : [];
25169
+ if (decisions.length)
25170
+ return {
25171
+ requirementId: requirement.id,
25172
+ status: "satisfied",
25173
+ evidenceIds: [],
25174
+ decisionIds: decisions.map((decision) => decision.id),
25175
+ reason: "an applicable approved or stated decision satisfies the requirement"
25176
+ };
25177
+ const limitations = requirement.acceptanceAllowed ? applicableDecision2(task, workspace, requirement, checkoutRoot) : [];
25178
+ if (limitations.length)
25179
+ return {
25180
+ requirementId: requirement.id,
25181
+ status: "accepted_limitation",
25182
+ evidenceIds: [],
25183
+ decisionIds: limitations.map((decision) => task.decisions.find((entry) => entry.data === decision).id),
25184
+ reason: "an applicable approved limitation permits the missing evidence"
25185
+ };
25186
+ const unavailable = capabilities.some((capability) => capability.assurance === "unavailable" && (capability.name === requirement.dimension || capability.surface === requirement.dimension));
25187
+ if (!unavailable && related.length > 0 && !passed.length)
25188
+ return {
25189
+ requirementId: requirement.id,
25190
+ status: "unsatisfied",
25191
+ evidenceIds: related.map(({ entry }) => entry.id),
25192
+ decisionIds: [],
25193
+ reason: `no passing evidence (needs kind:${expectedKinds(requirement.dimension, requirement.ruleId)})`
25194
+ };
25195
+ return {
25196
+ requirementId: requirement.id,
25197
+ status: unavailable ? "unavailable" : "unsatisfied",
25198
+ evidenceIds: related.map(({ entry }) => entry.id),
25199
+ decisionIds: [],
25200
+ reason: unavailable ? "required capability is unavailable" : "no fresh passing evidence"
25201
+ };
25202
+ });
25203
+ }
25204
+ function evaluateClosure(requestedOutcome, view) {
25205
+ if (requestedOutcome !== "stopped" && !view.task.policy)
25206
+ return failure("requirements_unsatisfied", "task has not been assessed");
25207
+ if (view.task.policy && view.task.policy.policyVersion !== POLICY_VERSION)
25208
+ return failure("requirements_unsatisfied", "stored policy version is unsupported; reassessment is required");
25209
+ const evaluations = view.requirements;
25210
+ const openFindings = view.task.findings.filter((entry) => entry.data.disposition === "open");
25211
+ if (requestedOutcome !== "stopped" && openFindings.length)
25212
+ return failure("requirements_unsatisfied", "open findings must be resolved before closure");
25213
+ if (requestedOutcome !== "stopped") {
25214
+ const evidenceById = new Map(view.evidence.map((entry) => [entry.evidenceId, entry.status]));
25215
+ for (const entry of view.task.findings) {
25216
+ if (entry.data.disposition === "fixed") {
25217
+ const verified = entry.data.resolution?.evidenceIds.some((id) => {
25218
+ const evidence = view.task.evidence.find((item) => item.id === id);
25219
+ if (!evidence)
25220
+ return false;
25221
+ return findingVerificationPasses(entry.data.candidateId, {
25222
+ kind: evidence.data.kind,
25223
+ candidateId: evidence.data.candidateId,
25224
+ status: evidenceById.get(id) ?? "missing"
25225
+ });
25226
+ });
25227
+ if (!verified)
25228
+ return failure("requirements_unsatisfied", "fixed findings require current verification");
25229
+ }
25230
+ if (entry.data.disposition === "deferred") {
25231
+ const valid = entry.data.resolution?.decisionIds.some((id) => {
25232
+ const decisionEntry = view.task.decisions.find((item) => item.id === id);
25233
+ const decision = decisionEntry?.data;
25234
+ 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)));
25235
+ });
25236
+ if (!valid)
25237
+ return failure("requirements_unsatisfied", "deferred findings require an approved limitation decision that references an acceptanceAllowed requirement and covers the finding scope");
25238
+ }
25239
+ }
25240
+ }
25241
+ const blocking = evaluations.filter((item) => {
25242
+ if (item.status !== "unsatisfied" && item.status !== "unavailable")
25249
25243
  return false;
25250
- seen.add(item.id);
25251
- return true;
25244
+ const requirement = view.task.policy?.requirements.find((candidate) => candidate.id === item.requirementId);
25245
+ return !requirement || requirement.before === "close";
25246
+ });
25247
+ if (requestedOutcome !== "stopped" && blocking.length)
25248
+ return failure("requirements_unsatisfied", "applicable requirements are unsatisfied", {
25249
+ requirementIds: blocking.map((item) => item.requirementId),
25250
+ requirements: blocking.map((item) => {
25251
+ const requirement = view.task.policy?.requirements.find((candidate) => candidate.id === item.requirementId);
25252
+ return {
25253
+ requirementId: item.requirementId,
25254
+ ruleId: requirement?.ruleId ?? "unknown",
25255
+ reason: item.reason,
25256
+ satisfaction: requirement?.satisfaction ?? "",
25257
+ dependentAction: requirement?.dependentAction ?? null
25258
+ };
25259
+ })
25260
+ });
25261
+ const accepted = evaluations.filter((item) => item.status === "accepted_limitation");
25262
+ if (requestedOutcome === "verified" && accepted.length)
25263
+ return failure("requirements_unsatisfied", "accepted limitations cannot be reported as verified", {
25264
+ requirementIds: accepted.map((item) => item.requirementId)
25265
+ });
25266
+ const evidenceIds = [
25267
+ ...new Set([
25268
+ ...evaluations.flatMap((item) => item.evidenceIds),
25269
+ ...view.task.findings.flatMap((item) => item.data.resolution?.evidenceIds ?? [])
25270
+ ])
25271
+ ];
25272
+ const decisionIds = [
25273
+ ...new Set([
25274
+ ...evaluations.flatMap((item) => item.decisionIds),
25275
+ ...view.task.findings.flatMap((item) => item.data.resolution?.decisionIds ?? [])
25276
+ ])
25277
+ ];
25278
+ return success(null, null, {
25279
+ outcome: requestedOutcome === "stopped" ? "stopped" : accepted.length ? "accepted_limitations" : "verified",
25280
+ evidenceIds,
25281
+ decisionIds,
25282
+ requirementIds: evaluations.map((item) => item.requirementId)
25252
25283
  });
25253
25284
  }
25254
- function resolvePolicy(input) {
25255
- const normalized = normalizeResolverInput(input);
25256
- if (!normalized.ok)
25257
- return normalized;
25258
- const requirements = resolveRequirements(normalized.data);
25259
- const policy = {
25260
- policyVersion: POLICY_VERSION,
25261
- inputDigest: sha256(canonicalJson(normalized.data)),
25262
- requirements
25263
- };
25264
- const parsed = policySchema.safeParse(policy);
25265
- if (!parsed.success)
25266
- return failure("invalid_input", "resolved policy is invalid", invalidFields(parsed.error));
25267
- return success(null, null, parsed.data);
25285
+
25286
+ // packages/workit-core/src/core/methods.ts
25287
+ var METHODS = {
25288
+ "workit-challenge": { dimensions: ["challenge", "decisions"] },
25289
+ "workit-behavioral-tdd": { dimensions: ["testing"], ruleIds: ["mechanical-existing-checks"] },
25290
+ "workit-review": { dimensions: ["review"], ruleIds: ["fresh-context-review", "self-review"] },
25291
+ "workit-plan": { dimensions: ["artifacts", "continuity"] },
25292
+ "workit-implement": { dimensions: ["delegation"] },
25293
+ "workit-debug": {},
25294
+ "workit-handoff": {},
25295
+ "workit-deslop": { ruleIds: ["pre-pr-cleanup"] }
25296
+ };
25297
+ var methodMatches = (definition, requirement) => definition.dimensions?.includes(requirement.dimension) === true || definition.ruleIds?.includes(requirement.ruleId) === true;
25298
+ var assuranceFor = (id, definition, capabilities) => {
25299
+ const keys = new Set([
25300
+ id,
25301
+ ...definition.dimensions ?? [],
25302
+ ...definition.ruleIds ?? []
25303
+ ]);
25304
+ const matches = capabilities.filter((capability) => keys.has(capability.name) || keys.has(capability.surface));
25305
+ if (id === "workit-review" && matches.length === 0)
25306
+ return { assurance: "unavailable", reasons: ["independent review capability is unavailable"] };
25307
+ if (matches.some((capability) => capability.assurance === "unavailable"))
25308
+ return {
25309
+ assurance: "unavailable",
25310
+ reasons: matches.filter((capability) => capability.assurance === "unavailable").map((capability) => capability.reason)
25311
+ };
25312
+ if (matches.some((capability) => capability.assurance === "enforced"))
25313
+ return { assurance: "enforced", reasons: matches.map((capability) => capability.reason) };
25314
+ return { assurance: "agent_guided", reasons: matches.map((capability) => capability.reason) };
25315
+ };
25316
+ function selectMethods(policy, capabilities) {
25317
+ return Object.entries(METHODS).flatMap(([id, definition]) => {
25318
+ const requirements = policy.requirements.filter((requirement) => methodMatches(definition, requirement));
25319
+ if (requirements.length === 0)
25320
+ return [];
25321
+ const capability = assuranceFor(id, definition, capabilities);
25322
+ const reasons = [
25323
+ ...new Set(requirements.map((requirement) => requirement.reason)),
25324
+ ...capability.reasons
25325
+ ];
25326
+ if (capability.assurance === "unavailable")
25327
+ reasons.unshift("required capability is unavailable");
25328
+ return [{ id, reason: reasons.join("; "), assurance: capability.assurance }];
25329
+ });
25268
25330
  }
25269
- function diffPolicy(previous, next, reason, now) {
25270
- if (!policySchema.safeParse(previous).success && previous !== null)
25271
- throw new TypeError("previous policy is invalid");
25272
- if (!policySchema.safeParse(next).success)
25273
- throw new TypeError("next policy is invalid");
25274
- const oldIds = new Set(previous?.requirements.map((requirement) => requirement.id) ?? []);
25275
- const newIds = new Set(next.requirements.map((requirement) => requirement.id));
25276
- const added = [...newIds].filter((id) => !oldIds.has(id)).sort(compareCodeUnits3);
25277
- const retired = [...oldIds].filter((id) => !newIds.has(id)).sort(compareCodeUnits3);
25278
- if (added.length === 0 && retired.length === 0)
25279
- return null;
25280
- const normalizedReason = reason.trim();
25281
- const changeReason = retired.length ? `${normalizedReason || "policy reassessed"} (retired: ${retired.join(",")})` : normalizedReason || "policy reassessed";
25282
- const change = {
25283
- recordedAt: now,
25284
- fromInputDigest: previous?.inputDigest ?? null,
25285
- toInputDigest: next.inputDigest,
25286
- added,
25287
- retired,
25288
- reason: changeReason
25289
- };
25290
- const parsed = policyChangeSchema.safeParse(change);
25291
- if (!parsed.success)
25292
- throw new TypeError("policy change is invalid");
25293
- return parsed.data;
25331
+
25332
+ // packages/workit-core/src/core/task-context.ts
25333
+ function reconcileResume(view, observations = []) {
25334
+ if (observations.length > 0)
25335
+ return failure("permission_denied", "worker observations require native host verification");
25336
+ const candidate = captureCandidate(view.workspace.root, view.task.intent.data.scope, []);
25337
+ if (!candidate.ok)
25338
+ return candidate;
25339
+ const staleEvidenceIds = evaluateEvidence(view.task, candidate.data).filter((entry) => entry.status === "stale").map((entry) => entry.evidenceId);
25340
+ const blockers = [...view.task.progress.blockers];
25341
+ if (view.task.workers.some((entry) => isUncertainWorker(entry.data.state)))
25342
+ blockers.push({
25343
+ reason: "worker state requires reconciliation",
25344
+ dependentAction: "resume",
25345
+ refs: []
25346
+ });
25347
+ return success(null, null, {
25348
+ candidate: candidate.data,
25349
+ staleEvidenceIds,
25350
+ workerUpdates: [],
25351
+ blockers,
25352
+ reassessmentRequired: view.task.policy?.policyVersion !== POLICY_VERSION
25353
+ });
25354
+ }
25355
+ var COMPACT_MAX_BYTES = 4096;
25356
+ var COMPACT_MAX_ITEMS = 8;
25357
+ var COMPACT_TEXT_BYTES = 128;
25358
+ var sensitiveUrl = /\bhttps?:\/\/[^/\s:@]+:[^@\s]+@/gi;
25359
+ var sensitiveValue = /(?:token|secret|password|passwd|api[-_ ]?key|private[-_ ]?key|authorization)\s*[:=]\s*(?:bearer\s+)?\S+|\bbearer\s+\S+/gi;
25360
+ var privateKey = /-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/gi;
25361
+ var compactText = (value, limit) => value === null ? null : value.replace(privateKey, "<redacted-private-key>").replace(sensitiveUrl, "<redacted-url>").replace(sensitiveValue, (match) => {
25362
+ const separator = match.search(/[:=]/u);
25363
+ if (separator >= 0)
25364
+ return `${match.slice(0, separator)}=<redacted>`;
25365
+ const space = match.search(/\s/u);
25366
+ return `${match.slice(0, space)} <redacted>`;
25367
+ }).slice(0, limit);
25368
+ var compactBytes = (value) => new TextEncoder().encode(value).byteLength;
25369
+ var compactTimestamp = (value) => `${value.slice(0, 19)}.${value.slice(20, -1).padEnd(9, "0")}`;
25370
+ var compactDecisionChoice = (entry) => {
25371
+ const stated = entry.data.binding.statedChoice?.text;
25372
+ const approved = entry.data.response === "approved" ? entry.data.binding.approvedContent : "";
25373
+ const source = stated?.trim() || approved.trim() || null;
25374
+ return compactText(source, COMPACT_TEXT_BYTES);
25375
+ };
25376
+ var compactReference = (ref) => {
25377
+ if (ref.kind === "file")
25378
+ return {
25379
+ kind: "file",
25380
+ path: compactText(ref.path, COMPACT_TEXT_BYTES) ?? ""
25381
+ };
25382
+ if (ref.kind === "record")
25383
+ return {
25384
+ kind: "record",
25385
+ collection: ref.collection,
25386
+ id: ref.id
25387
+ };
25388
+ return { kind: ref.kind };
25389
+ };
25390
+ function compactTaskContext(view) {
25391
+ const decisions = view.task.decisions.slice().sort((left, right) => {
25392
+ const leftAt = compactTimestamp(left.recordedAt);
25393
+ const rightAt = compactTimestamp(right.recordedAt);
25394
+ if (leftAt !== rightAt)
25395
+ return leftAt > rightAt ? -1 : 1;
25396
+ return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;
25397
+ }).slice(0, COMPACT_MAX_ITEMS).map((entry) => ({
25398
+ id: entry.id,
25399
+ purpose: entry.data.purpose,
25400
+ status: entry.data.response,
25401
+ digest: entry.data.digest,
25402
+ choice: compactDecisionChoice(entry) || `task.inspect taskId=${view.task.id} view=full; decision=${entry.id}`,
25403
+ references: entry.data.binding.contentRefs.slice(0, 1).map(compactReference)
25404
+ }));
25405
+ const methods = view.task.policy ? selectMethods(view.task.policy, view.capabilities).map((method) => ({
25406
+ id: method.id,
25407
+ assurance: method.assurance,
25408
+ reason: compactText(method.reason, COMPACT_TEXT_BYTES) ?? ""
25409
+ })) : [];
25410
+ const gaps = Array.from(new Set([
25411
+ ...view.evidence.filter((entry) => entry.status === "stale").map((entry) => `stale evidence: ${entry.evidenceId}`),
25412
+ ...view.requirements.filter((entry) => entry.status !== "satisfied").map((entry) => entry.reason),
25413
+ ...view.task.progress.blockers.map((entry) => entry.reason)
25414
+ ])).sort().slice(0, COMPACT_MAX_ITEMS).map((gap) => compactText(gap, COMPACT_TEXT_BYTES));
25415
+ const context = {
25416
+ objective: compactText(view.task.intent.data.objective, COMPACT_TEXT_BYTES) ?? "",
25417
+ status: view.task.status,
25418
+ decisions,
25419
+ methods,
25420
+ gaps,
25421
+ nextAction: compactText(view.task.progress.nextAction, COMPACT_TEXT_BYTES)
25422
+ };
25423
+ let encoded = JSON.stringify(context);
25424
+ while (compactBytes(encoded) > COMPACT_MAX_BYTES && (context.decisions.length || context.methods.length || context.gaps.length)) {
25425
+ if (context.gaps.length)
25426
+ context.gaps.pop();
25427
+ else if (context.decisions.length)
25428
+ context.decisions.pop();
25429
+ else
25430
+ context.methods.pop();
25431
+ encoded = JSON.stringify(context);
25432
+ }
25433
+ if (compactBytes(encoded) > COMPACT_MAX_BYTES) {
25434
+ context.objective = compactText(context.objective, 64) ?? "";
25435
+ context.nextAction = compactText(context.nextAction, 64);
25436
+ encoded = JSON.stringify(context);
25437
+ }
25438
+ return encoded;
25294
25439
  }
25440
+ var exportDigest = (bundle) => sha256({
25441
+ schemaVersion: bundle.schemaVersion,
25442
+ exportedAt: bundle.exportedAt,
25443
+ sourceWorkspaceId: bundle.sourceWorkspaceId,
25444
+ task: bundle.task
25445
+ });
25295
25446
 
25296
25447
  // packages/workit-core/src/core/task-engine.ts
25297
25448
  var provenance = (context, kind = context.provenanceKind ?? "host_observed") => ({
@@ -26979,14 +27130,29 @@ class WorkitCore {
26979
27130
  writer: evaluationWorkspace.writer
26980
27131
  });
26981
27132
  }
26982
- view(task) {
27133
+ compactContext(taskId) {
27134
+ const root = this.contextRootError();
27135
+ if (!root.ok)
27136
+ return root;
27137
+ const task = this.store.readTask(taskId);
27138
+ if (!task.ok)
27139
+ return task;
27140
+ const helper = this.helperTaskGuard(task.data, true);
27141
+ if (!helper.ok)
27142
+ return helper;
27143
+ const view = this.view(task.data, false);
27144
+ if (!view.ok)
27145
+ return view;
27146
+ return success(view.revision, view.workspaceRevision, compactTaskContext(view.data));
27147
+ }
27148
+ view(task, capture = true) {
26983
27149
  const workspace = this.store.readWorkspace();
26984
27150
  if (!workspace.ok)
26985
27151
  return workspace;
26986
27152
  if (!workspace.data)
26987
27153
  return failure("not_found", "workspace not found");
26988
27154
  const historical = task.status === "closed" ? task.candidates.at(-1) : undefined;
26989
- const current = historical ? success(null, null, historical) : captureCandidate(this.store.root, task.intent.data.scope, environment());
27155
+ 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);
26990
27156
  if (!current.ok)
26991
27157
  return current;
26992
27158
  const evaluationWorkspace = task.status === "closed" ? { ...workspace.data, writer: null } : workspace.data;
@@ -27258,6 +27424,122 @@ class WorkitCore {
27258
27424
  return this.summary(changed.data.task);
27259
27425
  }
27260
27426
  }
27427
+
27428
+ // packages/workit-core/src/core/session-context.ts
27429
+ var cache = new Map;
27430
+ // packages/workit-core/src/core/external-action.ts
27431
+ var chainStepSchema = union3([
27432
+ string5().min(1),
27433
+ object4({ branch: string5().min(1) }).strict(),
27434
+ object4({ pr: literal3(true) }).strict()
27435
+ ]);
27436
+ var externalActionSchema = discriminatedUnion2("operation", [
27437
+ object4({
27438
+ operation: literal3("git.branch_setup"),
27439
+ payload: object4({
27440
+ action: _enum2(["setup", "reapply_stash"]).optional(),
27441
+ sdd_dir: string5().optional(),
27442
+ target_branch: string5().optional(),
27443
+ stash: _enum2(["yes", "no"]).optional(),
27444
+ cwd: string5().min(1).optional()
27445
+ }).strict()
27446
+ }).strict(),
27447
+ object4({
27448
+ operation: literal3("git.commit"),
27449
+ payload: object4({
27450
+ message: string5().min(1).optional(),
27451
+ plan_steps: array3(chainStepSchema).min(1).max(32).optional(),
27452
+ plan_branch: string5().min(1).optional(),
27453
+ cwd: string5().min(1).optional()
27454
+ }).strict()
27455
+ }).strict(),
27456
+ object4({
27457
+ operation: literal3("git.push"),
27458
+ payload: object4({ branch: string5().min(1).optional(), cwd: string5().min(1).optional() }).strict()
27459
+ }).strict(),
27460
+ object4({
27461
+ operation: literal3("hosting.pull_request"),
27462
+ payload: object4({
27463
+ title: string5().min(1),
27464
+ body: string5().optional(),
27465
+ draft: boolean5().optional(),
27466
+ target_branch: string5().optional(),
27467
+ babysit: boolean5().optional(),
27468
+ cwd: string5().min(1).optional()
27469
+ }).strict()
27470
+ }).strict(),
27471
+ object4({
27472
+ operation: literal3("hosting.merge"),
27473
+ payload: object4({
27474
+ target_branch: string5().min(1).optional(),
27475
+ source_branch: string5().min(1).optional(),
27476
+ cwd: string5().min(1).optional()
27477
+ }).strict()
27478
+ }).strict(),
27479
+ object4({
27480
+ operation: literal3("hosting.delete_branch"),
27481
+ payload: object4({ branch: string5().min(1), cwd: string5().min(1).optional() }).strict()
27482
+ }).strict(),
27483
+ object4({
27484
+ operation: literal3("youtrack.update"),
27485
+ payload: object4({
27486
+ issueId: string5().min(1),
27487
+ markdown: string5().min(1),
27488
+ minutes: number5().positive().optional()
27489
+ }).strict()
27490
+ }).strict(),
27491
+ object4({
27492
+ operation: literal3("youtrack.time"),
27493
+ payload: object4({
27494
+ issueId: string5().min(1),
27495
+ minutes: number5().positive(),
27496
+ text: string5().optional(),
27497
+ dateMs: number5().finite().optional()
27498
+ }).strict()
27499
+ }).strict(),
27500
+ object4({
27501
+ operation: literal3("youtrack.meeting"),
27502
+ payload: object4({
27503
+ issueId: string5().min(1),
27504
+ minutes: number5().positive(),
27505
+ text: string5().min(1)
27506
+ }).strict()
27507
+ }).strict(),
27508
+ object4({
27509
+ operation: literal3("changelog.apply"),
27510
+ payload: object4({
27511
+ entries: union3([
27512
+ record3(string5(), array3(string5())),
27513
+ array3(object4({ category: string5().min(1), text: string5().min(1) }).strict())
27514
+ ]).optional(),
27515
+ path: string5().optional(),
27516
+ normalize_only: boolean5().optional()
27517
+ }).strict()
27518
+ }).strict(),
27519
+ object4({
27520
+ operation: literal3("context.read"),
27521
+ payload: object4({
27522
+ kind: _enum2([
27523
+ "git",
27524
+ "pr",
27525
+ "youtrack",
27526
+ "github_issue",
27527
+ "gitlab_issue",
27528
+ "changelog",
27529
+ "release",
27530
+ "affected"
27531
+ ]),
27532
+ range: string5().optional(),
27533
+ issueId: string5().optional(),
27534
+ issueUrl: string5().optional(),
27535
+ issueRef: string5().optional(),
27536
+ mode: string5().optional(),
27537
+ specPath: string5().optional(),
27538
+ planPath: string5().optional(),
27539
+ cwd: string5().min(1).optional()
27540
+ }).strict()
27541
+ }).strict()
27542
+ ]);
27261
27543
  // packages/workit-core/src/core.ts
27262
27544
  var revision2 = /^[A-Za-z0-9@][A-Za-z0-9@._/~^{}-]*$/;
27263
27545
  function gitRevisionParts(value) {