@brainervirus/workit-cursor 2.1.1 → 2.1.2

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