@caupulican/pi-adaptative 0.86.5 → 0.86.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/dist/core/default-tool-surface.d.ts +1 -1
  3. package/dist/core/default-tool-surface.d.ts.map +1 -1
  4. package/dist/core/default-tool-surface.js +12 -2
  5. package/dist/core/default-tool-surface.js.map +1 -1
  6. package/dist/core/delegation/worker-authority-resolver.d.ts.map +1 -1
  7. package/dist/core/delegation/worker-authority-resolver.js +3 -0
  8. package/dist/core/delegation/worker-authority-resolver.js.map +1 -1
  9. package/dist/core/delegation/worker-delegation-controller.d.ts +1 -0
  10. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
  11. package/dist/core/delegation/worker-delegation-controller.js +50 -0
  12. package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
  13. package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -1
  14. package/dist/core/delegation/worker-execution-policy.js +14 -2
  15. package/dist/core/delegation/worker-execution-policy.js.map +1 -1
  16. package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
  17. package/dist/core/goals/goal-continuation-controller.js +15 -0
  18. package/dist/core/goals/goal-continuation-controller.js.map +1 -1
  19. package/dist/core/goals/goal-state.d.ts +6 -0
  20. package/dist/core/goals/goal-state.d.ts.map +1 -1
  21. package/dist/core/goals/goal-state.js +1 -0
  22. package/dist/core/goals/goal-state.js.map +1 -1
  23. package/dist/core/goals/goal-tool-core.d.ts +1 -0
  24. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  25. package/dist/core/goals/goal-tool-core.js +25 -3
  26. package/dist/core/goals/goal-tool-core.js.map +1 -1
  27. package/dist/core/orchestration/lane-tool-manifests.d.ts +2 -2
  28. package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -1
  29. package/dist/core/orchestration/lane-tool-manifests.js +1 -1
  30. package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
  31. package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -1
  32. package/dist/core/orchestration/worker-execution-contract.js +4 -2
  33. package/dist/core/orchestration/worker-execution-contract.js.map +1 -1
  34. package/dist/core/system-prompt.d.ts.map +1 -1
  35. package/dist/core/system-prompt.js +1 -7
  36. package/dist/core/system-prompt.js.map +1 -1
  37. package/dist/core/tools/delegate.d.ts +2 -11
  38. package/dist/core/tools/delegate.d.ts.map +1 -1
  39. package/dist/core/tools/delegate.js +31 -29
  40. package/dist/core/tools/delegate.js.map +1 -1
  41. package/dist/core/tools/goal.d.ts +1 -0
  42. package/dist/core/tools/goal.d.ts.map +1 -1
  43. package/dist/core/tools/goal.js +9 -1
  44. package/dist/core/tools/goal.js.map +1 -1
  45. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  46. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  47. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  48. package/examples/extensions/sandbox/package-lock.json +2 -2
  49. package/examples/extensions/sandbox/package.json +1 -1
  50. package/examples/extensions/with-deps/package-lock.json +2 -2
  51. package/examples/extensions/with-deps/package.json +1 -1
  52. package/npm-shrinkwrap.json +12 -12
  53. package/package.json +4 -4
@@ -80,7 +80,14 @@ function toGoalEvent(state, action, now, options) {
80
80
  if (requirementExists(state, id)) {
81
81
  return { ok: false, error: `Requirement '${id}' already exists.` };
82
82
  }
83
- return { ok: true, event: { type: "add_requirement", id, text, now } };
83
+ if (action.dependencies) {
84
+ for (const depId of action.dependencies) {
85
+ if (!requirementExists(state, depId) && depId !== id) {
86
+ return { ok: false, error: `Dependency requirementId '${depId}' does not exist.` };
87
+ }
88
+ }
89
+ }
90
+ return { ok: true, event: { type: "add_requirement", id, text, dependencies: action.dependencies, now } };
84
91
  }
85
92
  case "satisfy_requirement": {
86
93
  const id = action.requirementId.trim();
@@ -135,8 +142,23 @@ function toGoalEvent(state, action, now, options) {
135
142
  return { ok: false, error: "dispatch_worker requires a non-empty requirementId." };
136
143
  if (!instructions)
137
144
  return { ok: false, error: "dispatch_worker requires non-empty instructions." };
138
- if (!requirementExists(state, id)) {
139
- return { ok: false, error: `Unknown requirement '${id}'.` };
145
+ const requirement = state.requirements.find((r) => r.id === id);
146
+ if (!requirement)
147
+ return { ok: false, error: `Requirement '${id}' does not exist.` };
148
+ if (requirement.status !== "open") {
149
+ return { ok: false, error: `Requirement '${id}' is not open (status: ${requirement.status}).` };
150
+ }
151
+ if (requirement.dependencies) {
152
+ const unsatisfied = requirement.dependencies.filter((depId) => {
153
+ const dep = state.requirements.find((r) => r.id === depId);
154
+ return !dep || dep.status !== "satisfied";
155
+ });
156
+ if (unsatisfied.length > 0) {
157
+ return {
158
+ ok: false,
159
+ error: `Cannot dispatch worker: dependencies not satisfied [${unsatisfied.join(", ")}].`,
160
+ };
161
+ }
140
162
  }
141
163
  return { ok: true, event: { type: "dispatch_worker", id, instructions, laneId: action.laneId, now } };
142
164
  }
@@ -1 +1 @@
1
- {"version":3,"file":"goal-tool-core.js","sourceRoot":"","sources":["../../../src/core/goals/goal-tool-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EAAE,6BAA6B,EAAE,MAAM,sBAAsB,CAAC;AACrE,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACvE,OAAO,EACN,cAAc,EACd,eAAe,EAIf,sBAAsB,EACtB,yBAAyB,GACzB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAClC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,2BAA2B,GAAG,KAAK,CAAC;AAC1C,MAAM,mBAAmB,GAAG,KAAK,CAAC;AAwElC,SAAS,iBAAiB,CAAC,KAAgB,EAAE,aAAqB;IACjE,OAAO,KAAK,C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G;AACH,MAAM,UAAU,kCAAkC,CACjD,MAAkB,EAClB,KAAgB,EAChB,aAAqD;IAErD,IAAI,CAAC,aAAa,IAAI,aAAa,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IAC5D,IAAI,MAAM,CAAC,MAAM,KAAK,qBAAqB,EAAE,CAAC;QAC7C,OAAO,mCAAmC,CAAC,KAAK,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC,EAAE,aAAa,CAAC,CAAC;IACjG,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;QAClC,MAAM,YAAY,GAAG,KAAK,CAAC,YAAY;aACrC,MAAM,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,MAAM,KAAK,WAAW,CAAC;aAC3D,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;QACvC,OAAO,mCAAmC,CAAC,KAAK,EAAE,YAAY,EAAE,aAAa,CAAC,CAAC;IAChF,CAAC;IACD,OAAO,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { taskStepReferencesRequirement } from \"../tasks/task-projection.ts\";\nimport { getUnprovenGoalRequirementIds } from \"./goal-acceptance.ts\";\nimport { formatGoalRecord, projectGoalRecord } from \"./goal-record.ts\";\nimport {\n\tapplyGoalEvent,\n\tcreateGoalState,\n\ttype GoalEvent,\n\ttype GoalEvidenceKind,\n\ttype GoalState,\n\tisGoalUnfinishedStatus,\n\tMAX_GOAL_OBJECTIVE_LENGTH,\n} from \"./goal-state.ts\";\n\nconst MAX_GOAL_ID_LENGTH = 128;\nconst MAX_GOAL_REQUIREMENTS = 256;\nconst MAX_GOAL_EVIDENCE = 512;\nconst MAX_GOAL_LEDGER_TEXT_LENGTH = 4_000;\nconst MAX_GOAL_URI_LENGTH = 4_096;\n\n/**\n * Agent-facing goal ledger actions.\n *\n * This is the producer half of the goal continuation pipeline: the agent records\n * what it is trying to achieve and how far it has gotten, and those records become\n * the {@link GoalState} snapshots that the runtime continuation consumer reads.\n *\n * Each action maps onto either {@link createGoalState} or a single\n * {@link GoalEvent}, so the durable state model stays the single source of truth.\n */\nexport type GoalAction =\n\t| { action: \"start\"; goalId: string; userGoal: string; tokenBudget?: number }\n\t| { action: \"add_requirement\"; requirementId: string; text: string }\n\t| { action: \"satisfy_requirement\"; requirementId: string; evidenceIds?: readonly string[] }\n\t| { action: \"block_requirement\"; requirementId: string; reason: string }\n\t| { action: \"reopen_requirement\"; requirementId: string }\n\t| {\n\t\t\taction: \"dispatch_worker\";\n\t\t\trequirementId: string;\n\t\t\tinstructions: string;\n\t\t\t/**\n\t\t\t * LaneId returned by the tool layer's dispatch side effect (calling the real worker/tmux\n\t\t\t * dispatch). Computed by the tool layer -- which has session/runtime access -- and merged\n\t\t\t * onto the action before it reaches this pure reducer, exactly like `add_evidence`'s\n\t\t\t * `verified` field. Undefined when the dispatch side effect is unwired/stubbed.\n\t\t\t */\n\t\t\tlaneId?: string;\n\t }\n\t| {\n\t\t\taction: \"add_evidence\";\n\t\t\tevidenceId: string;\n\t\t\tkind: GoalEvidenceKind;\n\t\t\tsummary: string;\n\t\t\turi?: string;\n\t\t\t/**\n\t\t\t * Whether `uri` was checked against session records/the filesystem. Computed by the\n\t\t\t * tool layer (which has session/filesystem access); `applyGoalAction` stays pure and\n\t\t\t * only carries this value through into the recorded {@link GoalEvidenceRef}.\n\t\t\t */\n\t\t\tverified?: boolean;\n\t }\n\t| { action: \"progress\" }\n\t| { action: \"no_progress\" }\n\t| { action: \"complete\" }\n\t| { action: \"block_goal\"; reason: string };\n\nexport type GoalActionName = GoalAction[\"action\"];\n\nexport interface GoalActionSuccess {\n\tok: true;\n\tstate: GoalState;\n}\n\nexport interface GoalActionFailure {\n\tok: false;\n\terror: string;\n}\n\nexport type GoalActionResult = GoalActionSuccess | GoalActionFailure;\n\nexport interface ApplyGoalActionOptions {\n\t/**\n\t * Gate agent-facing 'complete' on every satisfied requirement being backed by\n\t * verified-ref evidence (kind 'tool'/'file' with `verified === true`) or kind 'user'\n\t * evidence. Defaults to `true` (on) when omitted — the conservative default. Manual\n\t * completion ({@link completeGoalManually}) is never subject to this gate.\n\t */\n\trequireVerifiedEvidenceForCompletion?: boolean;\n}\n\nfunction requirementExists(state: GoalState, requirementId: string): boolean {\n\treturn state.requirements.some((requirement) => requirement.id === requirementId);\n}\n\nfunction evidenceExists(state: GoalState, evidenceId: string): boolean {\n\treturn state.evidence.some((evidence) => evidence.id === evidenceId);\n}\n\n/**\n * Apply one agent-facing goal action to the current ledger state.\n *\n * Pure: takes the current state (or `undefined` when no goal exists yet) and the\n * action, and returns either the next state or a validation error. Performs no\n * I/O and never mutates its inputs.\n */\nexport function applyGoalAction(\n\tcurrent: GoalState | undefined,\n\taction: GoalAction,\n\tnow: string,\n\toptions?: ApplyGoalActionOptions,\n): GoalActionResult {\n\tif (action.action === \"start\") {\n\t\tconst goalId = action.goalId.trim();\n\t\tconst userGoal = action.userGoal.trim();\n\t\tif (!goalId) return { ok: false, error: \"start requires a non-empty goalId.\" };\n\t\tif (!userGoal) return { ok: false, error: \"start requires a non-empty userGoal.\" };\n\t\tif (goalId.length > MAX_GOAL_ID_LENGTH) {\n\t\t\treturn { ok: false, error: `start goalId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t}\n\t\tif (userGoal.length > MAX_GOAL_OBJECTIVE_LENGTH) {\n\t\t\treturn { ok: false, error: `start userGoal must be at most ${MAX_GOAL_OBJECTIVE_LENGTH} characters.` };\n\t\t}\n\t\tif (action.tokenBudget !== undefined && (!Number.isSafeInteger(action.tokenBudget) || action.tokenBudget <= 0)) {\n\t\t\treturn { ok: false, error: \"start tokenBudget must be a positive integer when provided.\" };\n\t\t}\n\t\tif (current && isGoalUnfinishedStatus(current.status)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: `An unfinished goal '${current.goalId}' already exists (${current.status}). Complete, clear, or explicitly replace it before starting '${goalId}'.`,\n\t\t\t};\n\t\t}\n\t\treturn { ok: true, state: createGoalState({ goalId, userGoal, tokenBudget: action.tokenBudget, now }) };\n\t}\n\n\tif (!current) {\n\t\treturn { ok: false, error: \"No active goal. Use action 'start' before recording goal updates.\" };\n\t}\n\n\tif (current.status !== \"active\") {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `Goal '${current.goalId}' is ${current.status}. Lifecycle changes are owner/system controlled; use the /goal controls.`,\n\t\t};\n\t}\n\n\tconst event = toGoalEvent(current, action, now, options);\n\tif (!event.ok) return event;\n\treturn { ok: true, state: applyGoalEvent(current, event.event) };\n}\n\ntype ToGoalEventResult = { ok: true; event: GoalEvent } | GoalActionFailure;\n\nfunction toGoalEvent(\n\tstate: GoalState,\n\taction: GoalAction,\n\tnow: string,\n\toptions: ApplyGoalActionOptions | undefined,\n): ToGoalEventResult {\n\tswitch (action.action) {\n\t\tcase \"add_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst text = action.text.trim();\n\t\t\tif (!id) return { ok: false, error: \"add_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!text) return { ok: false, error: \"add_requirement requires non-empty text.\" };\n\t\t\tif (id.length > MAX_GOAL_ID_LENGTH) {\n\t\t\t\treturn { ok: false, error: `requirementId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (text.length > MAX_GOAL_LEDGER_TEXT_LENGTH) {\n\t\t\t\treturn { ok: false, error: `requirement text must be at most ${MAX_GOAL_LEDGER_TEXT_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (state.requirements.length >= MAX_GOAL_REQUIREMENTS) {\n\t\t\t\treturn { ok: false, error: `Goal already has the maximum ${MAX_GOAL_REQUIREMENTS} requirements.` };\n\t\t\t}\n\t\t\tif (requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Requirement '${id}' already exists.` };\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"add_requirement\", id, text, now } };\n\t\t}\n\t\tcase \"satisfy_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tif (!id) return { ok: false, error: \"satisfy_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\tconst evidenceIds = action.evidenceIds ?? [];\n\t\t\tfor (const evidenceId of evidenceIds) {\n\t\t\t\tif (!evidenceExists(state, evidenceId)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Unknown evidence '${evidenceId}'. Record it with action 'add_evidence' first.`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"satisfy_requirement\", id, evidenceIds: [...evidenceIds], now } };\n\t\t}\n\t\tcase \"block_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst reason = action.reason.trim();\n\t\t\tif (!id) return { ok: false, error: \"block_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!reason) return { ok: false, error: \"block_requirement requires a non-empty reason.\" };\n\t\t\tif (!requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"block_requirement\", id, blockedReason: reason, now } };\n\t\t}\n\t\tcase \"reopen_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tif (!id) return { ok: false, error: \"reopen_requirement requires a non-empty requirementId.\" };\n\t\t\tconst requirement = state.requirements.find((candidate) => candidate.id === id);\n\t\t\tif (!requirement) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\tif (requirement.status !== \"blocked\") {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Requirement '${id}' is ${requirement.status}; only blocked requirements can be reopened.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"reopen_requirement\", id, now } };\n\t\t}\n\t\tcase \"dispatch_worker\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst instructions = action.instructions.trim();\n\t\t\tif (!id) return { ok: false, error: \"dispatch_worker requires a non-empty requirementId.\" };\n\t\t\tif (!instructions) return { ok: false, error: \"dispatch_worker requires non-empty instructions.\" };\n\t\t\tif (!requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"dispatch_worker\", id, instructions, laneId: action.laneId, now } };\n\t\t}\n\t\tcase \"add_evidence\": {\n\t\t\tconst id = action.evidenceId.trim();\n\t\t\tconst summary = action.summary.trim();\n\t\t\tif (!id) return { ok: false, error: \"add_evidence requires a non-empty evidenceId.\" };\n\t\t\tif (!summary) return { ok: false, error: \"add_evidence requires a non-empty summary.\" };\n\t\t\tif (id.length > MAX_GOAL_ID_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidenceId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (summary.length > MAX_GOAL_LEDGER_TEXT_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidence summary must be at most ${MAX_GOAL_LEDGER_TEXT_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif ((action.uri?.trim().length ?? 0) > MAX_GOAL_URI_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidence uri must be at most ${MAX_GOAL_URI_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (state.evidence.length >= MAX_GOAL_EVIDENCE) {\n\t\t\t\treturn { ok: false, error: `Goal already has the maximum ${MAX_GOAL_EVIDENCE} evidence entries.` };\n\t\t\t}\n\t\t\tif (evidenceExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Evidence '${id}' already exists.` };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tevent: {\n\t\t\t\t\ttype: \"add_evidence\",\n\t\t\t\t\tid,\n\t\t\t\t\tkind: action.kind,\n\t\t\t\t\tsummary,\n\t\t\t\t\turi: action.uri?.trim() || undefined,\n\t\t\t\t\tverified: action.verified,\n\t\t\t\t\tnow,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tcase \"progress\":\n\t\t\treturn { ok: true, event: { type: \"progress\", now } };\n\t\tcase \"no_progress\":\n\t\t\treturn { ok: true, event: { type: \"no_progress\", now } };\n\t\tcase \"complete\": {\n\t\t\tconst unsatisfied = state.requirements.filter((requirement) => requirement.status !== \"satisfied\");\n\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: ${unsatisfied.length} requirement(s) not satisfied (${unsatisfied\n\t\t\t\t\t\t.map((requirement) => requirement.id)\n\t\t\t\t\t\t.join(\", \")}).`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst requireVerifiedEvidence = options?.requireVerifiedEvidenceForCompletion ?? true;\n\t\t\tconst unprovenRequirementIds = getUnprovenGoalRequirementIds(state);\n\t\t\tif (requireVerifiedEvidence && unprovenRequirementIds.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: requirement(s) lack verified evidence (${unprovenRequirementIds.join(\", \")}). Record verified or user-confirmed evidence and cite it in satisfy_requirement.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tevent: { type: \"complete_goal\", acceptanceOverride: !requireVerifiedEvidence, now },\n\t\t\t};\n\t\t}\n\t\tcase \"block_goal\": {\n\t\t\tconst reason = action.reason.trim();\n\t\t\tif (!reason) return { ok: false, error: \"block_goal requires a non-empty reason.\" };\n\t\t\treturn { ok: true, event: { type: \"block_goal\", reason, now } };\n\t\t}\n\t\tdefault:\n\t\t\treturn { ok: false, error: \"Unknown goal action.\" };\n\t}\n}\n\n/**\n * Complete a goal on explicit user authority, even when requirements remain open or\n * blocked. Agent-facing `complete` stays evidence-gated; this path is reserved for\n * direct user lifecycle controls.\n */\nexport function completeGoalManually(current: GoalState | undefined, now: string): GoalActionResult {\n\tif (!current) {\n\t\treturn { ok: false, error: \"No goal exists to complete.\" };\n\t}\n\tif (current.status === \"completed\") {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is already completed.` };\n\t}\n\tif (current.status === \"cancelled\") {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is cancelled; start or override with a new goal.` };\n\t}\n\treturn { ok: true, state: applyGoalEvent(current, { type: \"complete_goal_manually\", now }) };\n}\n\n/** Render a compact human-readable summary of the ledger after an action. */\nexport function summarizeGoalState(\n\tstate: GoalState,\n\toptions?: { action?: GoalAction; openTaskSteps?: readonly OpenTaskStepRef[] },\n): string {\n\tconst lines = [formatGoalRecord(projectGoalRecord(state))];\n\tif (state.requirements.length > 0) {\n\t\tconst openIds = state.requirements\n\t\t\t.filter((requirement) => requirement.status === \"open\")\n\t\t\t.slice(0, 20)\n\t\t\t.map((requirement) => requirement.id);\n\t\tlines.push(\n\t\t\t`Legacy ledger: ${state.requirements.length} requirements, ${state.evidence.length} evidence${openIds.length > 0 ? `; open: ${openIds.join(\", \")}` : \"\"}.`,\n\t\t);\n\t}\n\tif (options?.action) {\n\t\tlines.push(...buildGoalTaskCrossVisibilityNudges(options.action, state, options.openTaskSteps));\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Read-only goal⇄task cross-visibility (bounded slice — no shared state machine).\n *\n * `goal-tool-core` never reads or mutates task state itself (it stays pure); callers that DO\n * have access to the branch-scoped open task steps (e.g. via `buildGoalRuntimeSnapshot`) may\n * pass them through here to surface a nudge in the tool response when an open task_steps step is\n * explicitly linked to, or conservatively appears to reference, a requirement the agent just\n * satisfied or completed. Task state is never written from goal code — this only reads an\n * already-resolved, caller-supplied summary.\n */\nexport interface OpenTaskStepRef {\n\tid: string;\n\tcontent: string;\n\trequirementIds?: readonly string[];\n}\n\n/**\n * Nudge lines for open task steps that reference any of `requirementIds` (deduped per\n * requirement, one line naming every referencing step). Empty when there is nothing to say.\n */\nexport function findRequirementCrossReferenceNudges(\n\tstate: GoalState,\n\trequirementIds: readonly string[],\n\topenTaskSteps: readonly OpenTaskStepRef[],\n): string[] {\n\tif (openTaskSteps.length === 0 || requirementIds.length === 0) return [];\n\tconst nudges: string[] = [];\n\tfor (const requirementId of requirementIds) {\n\t\tconst requirement = state.requirements.find((candidate) => candidate.id === requirementId);\n\t\tif (!requirement) continue;\n\t\tconst referencing = openTaskSteps.filter((step) => taskStepReferencesRequirement(step, requirement));\n\t\tif (referencing.length === 0) continue;\n\t\tconst stepList = referencing.map((step) => step.id).join(\", \");\n\t\tnudges.push(\n\t\t\t`Note: open task step(s) ${stepList} appear to reference satisfied requirement '${requirement.id}' -- consider updating them via task_steps once covered.`,\n\t\t);\n\t}\n\treturn nudges;\n}\n\n/**\n * After 'satisfy_requirement' or 'complete', nudge lines for linked open task steps. Returns `[]`\n * for every other action, or when\n * `openTaskSteps` was not supplied (the default -- backward compatible, no behavior change for\n * callers that do not pass task-step context).\n */\nexport function buildGoalTaskCrossVisibilityNudges(\n\taction: GoalAction,\n\tstate: GoalState,\n\topenTaskSteps: readonly OpenTaskStepRef[] | undefined,\n): string[] {\n\tif (!openTaskSteps || openTaskSteps.length === 0) return [];\n\tif (action.action === \"satisfy_requirement\") {\n\t\treturn findRequirementCrossReferenceNudges(state, [action.requirementId.trim()], openTaskSteps);\n\t}\n\tif (action.action === \"complete\") {\n\t\tconst satisfiedIds = state.requirements\n\t\t\t.filter((requirement) => requirement.status === \"satisfied\")\n\t\t\t.map((requirement) => requirement.id);\n\t\treturn findRequirementCrossReferenceNudges(state, satisfiedIds, openTaskSteps);\n\t}\n\treturn [];\n}\n"]}
1
+ {"version":3,"file":"goal-tool-core.js","sourceRoot":"","sources":["../../../src/core/goals/goal-tool-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,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,IAAI,EAAE,EAAE,CAAC,6BAA6B,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC,CAAC;QACrG,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC;YAAE,SAAS;QACvC,MAAM,QAAQ,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC/D,MAAM,CAAC,IAAI,CACV,2BAA2B,QAAQ,+CAA+C,WAAW,CAAC,EAAE,0DAA0D,CAC1J,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,kCAAkC,CACjD,MAAkB,EAClB,KAAgB,EAChB,aAAqD;IAErD,IAAI,CAAC,aAAa,IAAI,aAAa,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IAC5D,IAAI,MAAM,CAAC,MAAM,KAAK,qBAAqB,EAAE,CAAC;QAC7C,OAAO,mCAAmC,CAAC,KAAK,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC,EAAE,aAAa,CAAC,CAAC;IACjG,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;QAClC,MAAM,YAAY,GAAG,KAAK,CAAC,YAAY;aACrC,MAAM,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,MAAM,KAAK,WAAW,CAAC;aAC3D,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;QACvC,OAAO,mCAAmC,CAAC,KAAK,EAAE,YAAY,EAAE,aAAa,CAAC,CAAC;IAChF,CAAC;IACD,OAAO,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { taskStepReferencesRequirement } from \"../tasks/task-projection.ts\";\nimport { getUnprovenGoalRequirementIds } from \"./goal-acceptance.ts\";\nimport { formatGoalRecord, projectGoalRecord } from \"./goal-record.ts\";\nimport {\n\tapplyGoalEvent,\n\tcreateGoalState,\n\ttype GoalEvent,\n\ttype GoalEvidenceKind,\n\ttype GoalState,\n\tisGoalUnfinishedStatus,\n\tMAX_GOAL_OBJECTIVE_LENGTH,\n} from \"./goal-state.ts\";\n\nconst MAX_GOAL_ID_LENGTH = 128;\nconst MAX_GOAL_REQUIREMENTS = 256;\nconst MAX_GOAL_EVIDENCE = 512;\nconst MAX_GOAL_LEDGER_TEXT_LENGTH = 4_000;\nconst MAX_GOAL_URI_LENGTH = 4_096;\n\n/**\n * Agent-facing goal ledger actions.\n *\n * This is the producer half of the goal continuation pipeline: the agent records\n * what it is trying to achieve and how far it has gotten, and those records become\n * the {@link GoalState} snapshots that the runtime continuation consumer reads.\n *\n * Each action maps onto either {@link createGoalState} or a single\n * {@link GoalEvent}, so the durable state model stays the single source of truth.\n */\nexport type GoalAction =\n\t| { action: \"start\"; goalId: string; userGoal: string; tokenBudget?: number }\n\t| { action: \"add_requirement\"; requirementId: string; text: string; dependencies?: readonly string[] }\n\t| { action: \"satisfy_requirement\"; requirementId: string; evidenceIds?: readonly string[] }\n\t| { action: \"block_requirement\"; requirementId: string; reason: string }\n\t| { action: \"reopen_requirement\"; requirementId: string }\n\t| {\n\t\t\taction: \"dispatch_worker\";\n\t\t\trequirementId: string;\n\t\t\tinstructions: string;\n\t\t\t/**\n\t\t\t * LaneId returned by the tool layer's dispatch side effect (calling the real worker/tmux\n\t\t\t * dispatch). Computed by the tool layer -- which has session/runtime access -- and merged\n\t\t\t * onto the action before it reaches this pure reducer, exactly like `add_evidence`'s\n\t\t\t * `verified` field. Undefined when the dispatch side effect is unwired/stubbed.\n\t\t\t */\n\t\t\tlaneId?: string;\n\t }\n\t| {\n\t\t\taction: \"add_evidence\";\n\t\t\tevidenceId: string;\n\t\t\tkind: GoalEvidenceKind;\n\t\t\tsummary: string;\n\t\t\turi?: string;\n\t\t\t/**\n\t\t\t * Whether `uri` was checked against session records/the filesystem. Computed by the\n\t\t\t * tool layer (which has session/filesystem access); `applyGoalAction` stays pure and\n\t\t\t * only carries this value through into the recorded {@link GoalEvidenceRef}.\n\t\t\t */\n\t\t\tverified?: boolean;\n\t }\n\t| { action: \"progress\" }\n\t| { action: \"no_progress\" }\n\t| { action: \"complete\" }\n\t| { action: \"block_goal\"; reason: string };\n\nexport type GoalActionName = GoalAction[\"action\"];\n\nexport interface GoalActionSuccess {\n\tok: true;\n\tstate: GoalState;\n}\n\nexport interface GoalActionFailure {\n\tok: false;\n\terror: string;\n}\n\nexport type GoalActionResult = GoalActionSuccess | GoalActionFailure;\n\nexport interface ApplyGoalActionOptions {\n\t/**\n\t * Gate agent-facing 'complete' on every satisfied requirement being backed by\n\t * verified-ref evidence (kind 'tool'/'file' with `verified === true`) or kind 'user'\n\t * evidence. Defaults to `true` (on) when omitted — the conservative default. Manual\n\t * completion ({@link completeGoalManually}) is never subject to this gate.\n\t */\n\trequireVerifiedEvidenceForCompletion?: boolean;\n}\n\nfunction requirementExists(state: GoalState, requirementId: string): boolean {\n\treturn state.requirements.some((requirement) => requirement.id === requirementId);\n}\n\nfunction evidenceExists(state: GoalState, evidenceId: string): boolean {\n\treturn state.evidence.some((evidence) => evidence.id === evidenceId);\n}\n\n/**\n * Apply one agent-facing goal action to the current ledger state.\n *\n * Pure: takes the current state (or `undefined` when no goal exists yet) and the\n * action, and returns either the next state or a validation error. Performs no\n * I/O and never mutates its inputs.\n */\nexport function applyGoalAction(\n\tcurrent: GoalState | undefined,\n\taction: GoalAction,\n\tnow: string,\n\toptions?: ApplyGoalActionOptions,\n): GoalActionResult {\n\tif (action.action === \"start\") {\n\t\tconst goalId = action.goalId.trim();\n\t\tconst userGoal = action.userGoal.trim();\n\t\tif (!goalId) return { ok: false, error: \"start requires a non-empty goalId.\" };\n\t\tif (!userGoal) return { ok: false, error: \"start requires a non-empty userGoal.\" };\n\t\tif (goalId.length > MAX_GOAL_ID_LENGTH) {\n\t\t\treturn { ok: false, error: `start goalId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t}\n\t\tif (userGoal.length > MAX_GOAL_OBJECTIVE_LENGTH) {\n\t\t\treturn { ok: false, error: `start userGoal must be at most ${MAX_GOAL_OBJECTIVE_LENGTH} characters.` };\n\t\t}\n\t\tif (action.tokenBudget !== undefined && (!Number.isSafeInteger(action.tokenBudget) || action.tokenBudget <= 0)) {\n\t\t\treturn { ok: false, error: \"start tokenBudget must be a positive integer when provided.\" };\n\t\t}\n\t\tif (current && isGoalUnfinishedStatus(current.status)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: `An unfinished goal '${current.goalId}' already exists (${current.status}). Complete, clear, or explicitly replace it before starting '${goalId}'.`,\n\t\t\t};\n\t\t}\n\t\treturn { ok: true, state: createGoalState({ goalId, userGoal, tokenBudget: action.tokenBudget, now }) };\n\t}\n\n\tif (!current) {\n\t\treturn { ok: false, error: \"No active goal. Use action 'start' before recording goal updates.\" };\n\t}\n\n\tif (current.status !== \"active\") {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `Goal '${current.goalId}' is ${current.status}. Lifecycle changes are owner/system controlled; use the /goal controls.`,\n\t\t};\n\t}\n\n\tconst event = toGoalEvent(current, action, now, options);\n\tif (!event.ok) return event;\n\treturn { ok: true, state: applyGoalEvent(current, event.event) };\n}\n\ntype ToGoalEventResult = { ok: true; event: GoalEvent } | GoalActionFailure;\n\nfunction toGoalEvent(\n\tstate: GoalState,\n\taction: GoalAction,\n\tnow: string,\n\toptions: ApplyGoalActionOptions | undefined,\n): ToGoalEventResult {\n\tswitch (action.action) {\n\t\tcase \"add_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst text = action.text.trim();\n\t\t\tif (!id) return { ok: false, error: \"add_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!text) return { ok: false, error: \"add_requirement requires non-empty text.\" };\n\t\t\tif (id.length > MAX_GOAL_ID_LENGTH) {\n\t\t\t\treturn { ok: false, error: `requirementId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (text.length > MAX_GOAL_LEDGER_TEXT_LENGTH) {\n\t\t\t\treturn { ok: false, error: `requirement text must be at most ${MAX_GOAL_LEDGER_TEXT_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (state.requirements.length >= MAX_GOAL_REQUIREMENTS) {\n\t\t\t\treturn { ok: false, error: `Goal already has the maximum ${MAX_GOAL_REQUIREMENTS} requirements.` };\n\t\t\t}\n\t\t\tif (requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Requirement '${id}' already exists.` };\n\t\t\t}\n\t\t\tif (action.dependencies) {\n\t\t\t\tfor (const depId of action.dependencies) {\n\t\t\t\t\tif (!requirementExists(state, depId) && depId !== id) {\n\t\t\t\t\t\treturn { ok: false, error: `Dependency requirementId '${depId}' does not exist.` };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"add_requirement\", id, text, dependencies: action.dependencies, now } };\n\t\t}\n\t\tcase \"satisfy_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tif (!id) return { ok: false, error: \"satisfy_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\tconst evidenceIds = action.evidenceIds ?? [];\n\t\t\tfor (const evidenceId of evidenceIds) {\n\t\t\t\tif (!evidenceExists(state, evidenceId)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Unknown evidence '${evidenceId}'. Record it with action 'add_evidence' first.`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"satisfy_requirement\", id, evidenceIds: [...evidenceIds], now } };\n\t\t}\n\t\tcase \"block_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst reason = action.reason.trim();\n\t\t\tif (!id) return { ok: false, error: \"block_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!reason) return { ok: false, error: \"block_requirement requires a non-empty reason.\" };\n\t\t\tif (!requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"block_requirement\", id, blockedReason: reason, now } };\n\t\t}\n\t\tcase \"reopen_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tif (!id) return { ok: false, error: \"reopen_requirement requires a non-empty requirementId.\" };\n\t\t\tconst requirement = state.requirements.find((candidate) => candidate.id === id);\n\t\t\tif (!requirement) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\tif (requirement.status !== \"blocked\") {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Requirement '${id}' is ${requirement.status}; only blocked requirements can be reopened.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"reopen_requirement\", id, now } };\n\t\t}\n\t\tcase \"dispatch_worker\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst instructions = action.instructions.trim();\n\t\t\tif (!id) return { ok: false, error: \"dispatch_worker requires a non-empty requirementId.\" };\n\t\t\tif (!instructions) return { ok: false, error: \"dispatch_worker requires non-empty instructions.\" };\n\t\t\tconst requirement = state.requirements.find((r) => r.id === id);\n\t\t\tif (!requirement) return { ok: false, error: `Requirement '${id}' does not exist.` };\n\t\t\tif (requirement.status !== \"open\") {\n\t\t\t\treturn { ok: false, error: `Requirement '${id}' is not open (status: ${requirement.status}).` };\n\t\t\t}\n\t\t\tif (requirement.dependencies) {\n\t\t\t\tconst unsatisfied = requirement.dependencies.filter((depId) => {\n\t\t\t\t\tconst dep = state.requirements.find((r) => r.id === depId);\n\t\t\t\t\treturn !dep || dep.status !== \"satisfied\";\n\t\t\t\t});\n\t\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Cannot dispatch worker: dependencies not satisfied [${unsatisfied.join(\", \")}].`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"dispatch_worker\", id, instructions, laneId: action.laneId, now } };\n\t\t}\n\t\tcase \"add_evidence\": {\n\t\t\tconst id = action.evidenceId.trim();\n\t\t\tconst summary = action.summary.trim();\n\t\t\tif (!id) return { ok: false, error: \"add_evidence requires a non-empty evidenceId.\" };\n\t\t\tif (!summary) return { ok: false, error: \"add_evidence requires a non-empty summary.\" };\n\t\t\tif (id.length > MAX_GOAL_ID_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidenceId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (summary.length > MAX_GOAL_LEDGER_TEXT_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidence summary must be at most ${MAX_GOAL_LEDGER_TEXT_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif ((action.uri?.trim().length ?? 0) > MAX_GOAL_URI_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidence uri must be at most ${MAX_GOAL_URI_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (state.evidence.length >= MAX_GOAL_EVIDENCE) {\n\t\t\t\treturn { ok: false, error: `Goal already has the maximum ${MAX_GOAL_EVIDENCE} evidence entries.` };\n\t\t\t}\n\t\t\tif (evidenceExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Evidence '${id}' already exists.` };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tevent: {\n\t\t\t\t\ttype: \"add_evidence\",\n\t\t\t\t\tid,\n\t\t\t\t\tkind: action.kind,\n\t\t\t\t\tsummary,\n\t\t\t\t\turi: action.uri?.trim() || undefined,\n\t\t\t\t\tverified: action.verified,\n\t\t\t\t\tnow,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tcase \"progress\":\n\t\t\treturn { ok: true, event: { type: \"progress\", now } };\n\t\tcase \"no_progress\":\n\t\t\treturn { ok: true, event: { type: \"no_progress\", now } };\n\t\tcase \"complete\": {\n\t\t\tconst unsatisfied = state.requirements.filter((requirement) => requirement.status !== \"satisfied\");\n\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: ${unsatisfied.length} requirement(s) not satisfied (${unsatisfied\n\t\t\t\t\t\t.map((requirement) => requirement.id)\n\t\t\t\t\t\t.join(\", \")}).`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst requireVerifiedEvidence = options?.requireVerifiedEvidenceForCompletion ?? true;\n\t\t\tconst unprovenRequirementIds = getUnprovenGoalRequirementIds(state);\n\t\t\tif (requireVerifiedEvidence && unprovenRequirementIds.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: requirement(s) lack verified evidence (${unprovenRequirementIds.join(\", \")}). Record verified or user-confirmed evidence and cite it in satisfy_requirement.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tevent: { type: \"complete_goal\", acceptanceOverride: !requireVerifiedEvidence, now },\n\t\t\t};\n\t\t}\n\t\tcase \"block_goal\": {\n\t\t\tconst reason = action.reason.trim();\n\t\t\tif (!reason) return { ok: false, error: \"block_goal requires a non-empty reason.\" };\n\t\t\treturn { ok: true, event: { type: \"block_goal\", reason, now } };\n\t\t}\n\t\tdefault:\n\t\t\treturn { ok: false, error: \"Unknown goal action.\" };\n\t}\n}\n\n/**\n * Complete a goal on explicit user authority, even when requirements remain open or\n * blocked. Agent-facing `complete` stays evidence-gated; this path is reserved for\n * direct user lifecycle controls.\n */\nexport function completeGoalManually(current: GoalState | undefined, now: string): GoalActionResult {\n\tif (!current) {\n\t\treturn { ok: false, error: \"No goal exists to complete.\" };\n\t}\n\tif (current.status === \"completed\") {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is already completed.` };\n\t}\n\tif (current.status === \"cancelled\") {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is cancelled; start or override with a new goal.` };\n\t}\n\treturn { ok: true, state: applyGoalEvent(current, { type: \"complete_goal_manually\", now }) };\n}\n\n/** Render a compact human-readable summary of the ledger after an action. */\nexport function summarizeGoalState(\n\tstate: GoalState,\n\toptions?: { action?: GoalAction; openTaskSteps?: readonly OpenTaskStepRef[] },\n): string {\n\tconst lines = [formatGoalRecord(projectGoalRecord(state))];\n\tif (state.requirements.length > 0) {\n\t\tconst openIds = state.requirements\n\t\t\t.filter((requirement) => requirement.status === \"open\")\n\t\t\t.slice(0, 20)\n\t\t\t.map((requirement) => requirement.id);\n\t\tlines.push(\n\t\t\t`Legacy ledger: ${state.requirements.length} requirements, ${state.evidence.length} evidence${openIds.length > 0 ? `; open: ${openIds.join(\", \")}` : \"\"}.`,\n\t\t);\n\t}\n\tif (options?.action) {\n\t\tlines.push(...buildGoalTaskCrossVisibilityNudges(options.action, state, options.openTaskSteps));\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Read-only goal⇄task cross-visibility (bounded slice — no shared state machine).\n *\n * `goal-tool-core` never reads or mutates task state itself (it stays pure); callers that DO\n * have access to the branch-scoped open task steps (e.g. via `buildGoalRuntimeSnapshot`) may\n * pass them through here to surface a nudge in the tool response when an open task_steps step is\n * explicitly linked to, or conservatively appears to reference, a requirement the agent just\n * satisfied or completed. Task state is never written from goal code — this only reads an\n * already-resolved, caller-supplied summary.\n */\nexport interface OpenTaskStepRef {\n\tid: string;\n\tcontent: string;\n\trequirementIds?: readonly string[];\n}\n\n/**\n * Nudge lines for open task steps that reference any of `requirementIds` (deduped per\n * requirement, one line naming every referencing step). Empty when there is nothing to say.\n */\nexport function findRequirementCrossReferenceNudges(\n\tstate: GoalState,\n\trequirementIds: readonly string[],\n\topenTaskSteps: readonly OpenTaskStepRef[],\n): string[] {\n\tif (openTaskSteps.length === 0 || requirementIds.length === 0) return [];\n\tconst nudges: string[] = [];\n\tfor (const requirementId of requirementIds) {\n\t\tconst requirement = state.requirements.find((candidate) => candidate.id === requirementId);\n\t\tif (!requirement) continue;\n\t\tconst referencing = openTaskSteps.filter((step) => taskStepReferencesRequirement(step, requirement));\n\t\tif (referencing.length === 0) continue;\n\t\tconst stepList = referencing.map((step) => step.id).join(\", \");\n\t\tnudges.push(\n\t\t\t`Note: open task step(s) ${stepList} appear to reference satisfied requirement '${requirement.id}' -- consider updating them via task_steps once covered.`,\n\t\t);\n\t}\n\treturn nudges;\n}\n\n/**\n * After 'satisfy_requirement' or 'complete', nudge lines for linked open task steps. Returns `[]`\n * for every other action, or when\n * `openTaskSteps` was not supplied (the default -- backward compatible, no behavior change for\n * callers that do not pass task-step context).\n */\nexport function buildGoalTaskCrossVisibilityNudges(\n\taction: GoalAction,\n\tstate: GoalState,\n\topenTaskSteps: readonly OpenTaskStepRef[] | undefined,\n): string[] {\n\tif (!openTaskSteps || openTaskSteps.length === 0) return [];\n\tif (action.action === \"satisfy_requirement\") {\n\t\treturn findRequirementCrossReferenceNudges(state, [action.requirementId.trim()], openTaskSteps);\n\t}\n\tif (action.action === \"complete\") {\n\t\tconst satisfiedIds = state.requirements\n\t\t\t.filter((requirement) => requirement.status === \"satisfied\")\n\t\t\t.map((requirement) => requirement.id);\n\t\treturn findRequirementCrossReferenceNudges(state, satisfiedIds, openTaskSteps);\n\t}\n\treturn [];\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import type { OrchestrationProfile, ToolCapabilityManifest } from "./contracts.ts";
2
- export declare const CLASSIFIED_LANE_TOOL_NAMES: readonly ["read", "grep", "find", "ls", "write", "edit", "memory", "run_process", "bash", "powershell"];
3
- export declare const ORCHESTRATION_PROFILE_TOOL_NAMES: readonly ["read", "grep", "find", "ls", "write", "edit", "memory", "run_process", "bash", "powershell", "delegate", "delegate_status", "profile_writer"];
2
+ export declare const CLASSIFIED_LANE_TOOL_NAMES: readonly ["read", "grep", "find", "ls", "write", "edit", "memory", "python", "run_process", "bash"];
3
+ export declare const ORCHESTRATION_PROFILE_TOOL_NAMES: readonly ["read", "grep", "find", "ls", "write", "edit", "memory", "python", "run_process", "bash", "delegate", "delegate_status", "profile_writer"];
4
4
  /**
5
5
  * Manifest-only lane catalogue. It contains no tool factories, so policy compilation can omit
6
6
  * denied tools before their executable implementations are constructed.
@@ -1 +1 @@
1
- {"version":3,"file":"lane-tool-manifests.d.ts","sourceRoot":"","sources":["../../../src/core/orchestration/lane-tool-manifests.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAEnF,eAAO,MAAM,0BAA0B,YACtC,MAAM,EACN,MAAM,EACN,MAAM,EACN,IAAI,EACJ,OAAO,EACP,MAAM,EACN,QAAQ,EACR,aAAa,EACb,MAAM,EACN,YAAY,CACH,CAAC;AACX,eAAO,MAAM,gCAAgC,0JAKnC,CAAC;AAEX;;;GAGG;AACH,wBAAgB,sBAAsB,CACrC,OAAO,EAAE,oBAAoB,EAC7B,gBAAgB,EAAE,SAAS,MAAM,EAAE,GACjC,sBAAsB,EAAE,CAkB1B"}
1
+ {"version":3,"file":"lane-tool-manifests.d.ts","sourceRoot":"","sources":["../../../src/core/orchestration/lane-tool-manifests.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAEnF,eAAO,MAAM,0BAA0B,YACtC,MAAM,EACN,MAAM,EACN,MAAM,EACN,IAAI,EACJ,OAAO,EACP,MAAM,EACN,QAAQ,EACR,QAAQ,EACR,aAAa,EACb,MAAM,CACG,CAAC;AACX,eAAO,MAAM,gCAAgC,sJAKnC,CAAC;AAEX;;;GAGG;AACH,wBAAgB,sBAAsB,CACrC,OAAO,EAAE,oBAAoB,EAC7B,gBAAgB,EAAE,SAAS,MAAM,EAAE,GACjC,sBAAsB,EAAE,CAkB1B"}
@@ -8,9 +8,9 @@ export const CLASSIFIED_LANE_TOOL_NAMES = [
8
8
  "write",
9
9
  "edit",
10
10
  "memory",
11
+ "python",
11
12
  "run_process",
12
13
  "bash",
13
- "powershell",
14
14
  ];
15
15
  export const ORCHESTRATION_PROFILE_TOOL_NAMES = [
16
16
  ...CLASSIFIED_LANE_TOOL_NAMES,
@@ -1 +1 @@
1
- {"version":3,"file":"lane-tool-manifests.js","sourceRoot":"","sources":["../../../src/core/orchestration/lane-tool-manifests.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,4BAA4B,EAAE,MAAM,8BAA8B,CAAC;AAGrG,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACzC,MAAM;IACN,MAAM;IACN,MAAM;IACN,IAAI;IACJ,OAAO;IACP,MAAM;IACN,QAAQ;IACR,aAAa;IACb,MAAM;IACN,YAAY;CACH,CAAC;AACX,MAAM,CAAC,MAAM,gCAAgC,GAAG;IAC/C,GAAG,0BAA0B;IAC7B,UAAU;IACV,iBAAiB;IACjB,gBAAgB;CACP,CAAC;AAEX;;;GAGG;AACH,MAAM,UAAU,sBAAsB,CACrC,OAA6B,EAC7B,gBAAmC;IAEnC,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,gBAAgB,CAAC,CAAC;IAC1C,MAAM,SAAS,GAA6B,EAAE,CAAC;IAE/C,KAAK,MAAM,QAAQ,IAAI,IAAI,GAAG,CAAC,uBAAuB,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC;QAC5E,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;YAAE,SAAS;QACrC,MAAM,MAAM,GAAG,uBAAuB,CAAC,QAAQ,CAAC,CAAC;QACjD,MAAM,UAAU,GAAG,4BAA4B,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACnE,IAAI,CAAC,UAAU,IAAI,CAAC,MAAM;YAAE,SAAS;QACrC,SAAS,CAAC,IAAI,CAAC;YACd,QAAQ;YACR,eAAe,EAAE,YAAY,QAAQ,KAAK;YAC1C,YAAY,EAAE,CAAC,UAAU,CAAC;YAC1B,KAAK,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC;YACrB,YAAY,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC;SAClC,CAAC,CAAC;IACJ,CAAC;IACD,OAAO,SAAS,CAAC;AAClB,CAAC","sourcesContent":["import { mapToolNamesForPlatform } from \"../default-tool-surface.ts\";\nimport { getToolCapabilityPolicy, resolveProfileToolCapability } from \"../tool-capability-policy.ts\";\nimport type { OrchestrationProfile, ToolCapabilityManifest } from \"./contracts.ts\";\n\nexport const CLASSIFIED_LANE_TOOL_NAMES = [\n\t\"read\",\n\t\"grep\",\n\t\"find\",\n\t\"ls\",\n\t\"write\",\n\t\"edit\",\n\t\"memory\",\n\t\"run_process\",\n\t\"bash\",\n\t\"powershell\",\n] as const;\nexport const ORCHESTRATION_PROFILE_TOOL_NAMES = [\n\t...CLASSIFIED_LANE_TOOL_NAMES,\n\t\"delegate\",\n\t\"delegate_status\",\n\t\"profile_writer\",\n] as const;\n\n/**\n * Manifest-only lane catalogue. It contains no tool factories, so policy compilation can omit\n * denied tools before their executable implementations are constructed.\n */\nexport function buildLaneToolManifests(\n\tprofile: OrchestrationProfile,\n\tenabledToolNames: readonly string[],\n): ToolCapabilityManifest[] {\n\tconst enabled = new Set(enabledToolNames);\n\tconst manifests: ToolCapabilityManifest[] = [];\n\n\tfor (const toolName of new Set(mapToolNamesForPlatform(profile.toolNames))) {\n\t\tif (!enabled.has(toolName)) continue;\n\t\tconst policy = getToolCapabilityPolicy(toolName);\n\t\tconst capability = resolveProfileToolCapability(profile, toolName);\n\t\tif (!capability || !policy) continue;\n\t\tmanifests.push({\n\t\t\ttoolName,\n\t\t\tmoduleSpecifier: `../tools/${toolName}.ts`,\n\t\t\tcapabilities: [capability],\n\t\t\troles: [profile.role],\n\t\t\tenforcements: [policy.enforcement],\n\t\t});\n\t}\n\treturn manifests;\n}\n"]}
1
+ {"version":3,"file":"lane-tool-manifests.js","sourceRoot":"","sources":["../../../src/core/orchestration/lane-tool-manifests.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,4BAA4B,EAAE,MAAM,8BAA8B,CAAC;AAGrG,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACzC,MAAM;IACN,MAAM;IACN,MAAM;IACN,IAAI;IACJ,OAAO;IACP,MAAM;IACN,QAAQ;IACR,QAAQ;IACR,aAAa;IACb,MAAM;CACG,CAAC;AACX,MAAM,CAAC,MAAM,gCAAgC,GAAG;IAC/C,GAAG,0BAA0B;IAC7B,UAAU;IACV,iBAAiB;IACjB,gBAAgB;CACP,CAAC;AAEX;;;GAGG;AACH,MAAM,UAAU,sBAAsB,CACrC,OAA6B,EAC7B,gBAAmC;IAEnC,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,gBAAgB,CAAC,CAAC;IAC1C,MAAM,SAAS,GAA6B,EAAE,CAAC;IAE/C,KAAK,MAAM,QAAQ,IAAI,IAAI,GAAG,CAAC,uBAAuB,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC;QAC5E,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;YAAE,SAAS;QACrC,MAAM,MAAM,GAAG,uBAAuB,CAAC,QAAQ,CAAC,CAAC;QACjD,MAAM,UAAU,GAAG,4BAA4B,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACnE,IAAI,CAAC,UAAU,IAAI,CAAC,MAAM;YAAE,SAAS;QACrC,SAAS,CAAC,IAAI,CAAC;YACd,QAAQ;YACR,eAAe,EAAE,YAAY,QAAQ,KAAK;YAC1C,YAAY,EAAE,CAAC,UAAU,CAAC;YAC1B,KAAK,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC;YACrB,YAAY,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC;SAClC,CAAC,CAAC;IACJ,CAAC;IACD,OAAO,SAAS,CAAC;AAClB,CAAC","sourcesContent":["import { mapToolNamesForPlatform } from \"../default-tool-surface.ts\";\nimport { getToolCapabilityPolicy, resolveProfileToolCapability } from \"../tool-capability-policy.ts\";\nimport type { OrchestrationProfile, ToolCapabilityManifest } from \"./contracts.ts\";\n\nexport const CLASSIFIED_LANE_TOOL_NAMES = [\n\t\"read\",\n\t\"grep\",\n\t\"find\",\n\t\"ls\",\n\t\"write\",\n\t\"edit\",\n\t\"memory\",\n\t\"python\",\n\t\"run_process\",\n\t\"bash\",\n] as const;\nexport const ORCHESTRATION_PROFILE_TOOL_NAMES = [\n\t...CLASSIFIED_LANE_TOOL_NAMES,\n\t\"delegate\",\n\t\"delegate_status\",\n\t\"profile_writer\",\n] as const;\n\n/**\n * Manifest-only lane catalogue. It contains no tool factories, so policy compilation can omit\n * denied tools before their executable implementations are constructed.\n */\nexport function buildLaneToolManifests(\n\tprofile: OrchestrationProfile,\n\tenabledToolNames: readonly string[],\n): ToolCapabilityManifest[] {\n\tconst enabled = new Set(enabledToolNames);\n\tconst manifests: ToolCapabilityManifest[] = [];\n\n\tfor (const toolName of new Set(mapToolNamesForPlatform(profile.toolNames))) {\n\t\tif (!enabled.has(toolName)) continue;\n\t\tconst policy = getToolCapabilityPolicy(toolName);\n\t\tconst capability = resolveProfileToolCapability(profile, toolName);\n\t\tif (!capability || !policy) continue;\n\t\tmanifests.push({\n\t\t\ttoolName,\n\t\t\tmoduleSpecifier: `../tools/${toolName}.ts`,\n\t\t\tcapabilities: [capability],\n\t\t\troles: [profile.role],\n\t\t\tenforcements: [policy.enforcement],\n\t\t});\n\t}\n\treturn manifests;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"worker-execution-contract.d.ts","sourceRoot":"","sources":["../../../src/core/orchestration/worker-execution-contract.ts"],"names":[],"mappings":"AAIA,OAAO,EAaN,KAAK,yBAAyB,EAC9B,KAAK,oBAAoB,EACzB,KAAK,eAAe,EAEpB,KAAK,gCAAgC,EACrC,KAAK,uBAAuB,EAE5B,MAAM,gBAAgB,CAAC;AAIxB,qBAAa,4BAA6B,SAAQ,KAAK;IACtD,YAAY,OAAO,EAAE,MAAM,EAG1B;CACD;AAkMD,wBAAgB,4BAA4B,CAAC,KAAK,EAAE,OAAO,GAAG,uBAAuB,CA2BpF;AAwBD,wBAAgB,6BAA6B,CAAC,IAAI,EAAE;IACnD,MAAM,EAAE;QACP,OAAO,EAAE,oBAAoB,CAAC;QAC9B,YAAY,EAAE,yBAAyB,CAAC;QACxC,SAAS,EAAE,gCAAgC,CAAC;QAC5C,gBAAgB,CAAC,EAAE,SAAS,eAAe,EAAE,CAAC;QAC9C,IAAI,CAAC,EAAE,MAAM,CAAC;KACd,CAAC;IACF,QAAQ,CAAC,EAAE;QACV,OAAO,EAAE,oBAAoB,CAAC;QAC9B,YAAY,EAAE,yBAAyB,CAAC;QACxC,SAAS,EAAE,gCAAgC,CAAC;QAC5C,gBAAgB,CAAC,EAAE,SAAS,eAAe,EAAE,CAAC;QAC9C,IAAI,CAAC,EAAE,MAAM,CAAC;KACd,CAAC;CACF,GAAG,uBAAuB,CAM1B;AAED,wBAAgB,+BAA+B,CAC9C,QAAQ,EAAE,uBAAuB,GAC/B,uBAAuB,GAAG,SAAS,CAIrC"}
1
+ {"version":3,"file":"worker-execution-contract.d.ts","sourceRoot":"","sources":["../../../src/core/orchestration/worker-execution-contract.ts"],"names":[],"mappings":"AAIA,OAAO,EAaN,KAAK,yBAAyB,EAC9B,KAAK,oBAAoB,EACzB,KAAK,eAAe,EAEpB,KAAK,gCAAgC,EACrC,KAAK,uBAAuB,EAE5B,MAAM,gBAAgB,CAAC;AAIxB,qBAAa,4BAA6B,SAAQ,KAAK;IACtD,YAAY,OAAO,EAAE,MAAM,EAG1B;CACD;AAyMD,wBAAgB,4BAA4B,CAAC,KAAK,EAAE,OAAO,GAAG,uBAAuB,CA2BpF;AAwBD,wBAAgB,6BAA6B,CAAC,IAAI,EAAE;IACnD,MAAM,EAAE;QACP,OAAO,EAAE,oBAAoB,CAAC;QAC9B,YAAY,EAAE,yBAAyB,CAAC;QACxC,SAAS,EAAE,gCAAgC,CAAC;QAC5C,gBAAgB,CAAC,EAAE,SAAS,eAAe,EAAE,CAAC;QAC9C,IAAI,CAAC,EAAE,MAAM,CAAC;KACd,CAAC;IACF,QAAQ,CAAC,EAAE;QACV,OAAO,EAAE,oBAAoB,CAAC;QAC9B,YAAY,EAAE,yBAAyB,CAAC;QACxC,SAAS,EAAE,gCAAgC,CAAC;QAC5C,gBAAgB,CAAC,EAAE,SAAS,eAAe,EAAE,CAAC;QAC9C,IAAI,CAAC,EAAE,MAAM,CAAC;KACd,CAAC;CACF,GAAG,uBAAuB,CAM1B;AAED,wBAAgB,+BAA+B,CAC9C,QAAQ,EAAE,uBAAuB,GAC/B,uBAAuB,GAAG,SAAS,CAIrC"}
@@ -92,11 +92,13 @@ function parseAuthority(value, profile, label) {
92
92
  if (!capabilities.every(isHarnessCapability)) {
93
93
  throw new WorkerExecutionContractError(`${label} authority contains an unknown capability.`);
94
94
  }
95
- if (capabilities.some((capability) => capability !== "workflow.delegate" && !profile.capabilityCeiling.includes(capability))) {
95
+ if (capabilities.some((capability) => capability !== "workflow.delegate" &&
96
+ capability !== "memory.query" &&
97
+ !profile.capabilityCeiling.includes(capability))) {
96
98
  throw new WorkerExecutionContractError(`${label} authority exceeds its profile capability ceiling.`);
97
99
  }
98
100
  const toolNames = stringArray(value.toolNames, `${label} authority toolNames`);
99
- if (toolNames.some((toolName) => toolName !== "delegate" && !profile.toolNames.includes(toolName))) {
101
+ if (toolNames.some((toolName) => toolName !== "delegate" && toolName !== "memory" && !profile.toolNames.includes(toolName))) {
100
102
  throw new WorkerExecutionContractError(`${label} authority contains a tool outside its profile.`);
101
103
  }
102
104
  const pathArrayOptions = {
@@ -1 +1 @@
1
- {"version":3,"file":"worker-execution-contract.js","sourceRoot":"","sources":["../../../src/core/orchestration/worker-execution-contract.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EACN,mBAAmB,EACnB,qBAAqB,EACrB,iCAAiC,EACjC,uCAAuC,EACvC,gCAAgC,EAChC,0BAA0B,EAC1B,wCAAwC,EACxC,+BAA+B,EAC/B,4BAA4B,EAC5B,sBAAsB,EACtB,4BAA4B,EAC5B,6BAA6B,GAQ7B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,yBAAyB,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AAC7F,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAEzE,MAAM,OAAO,4BAA6B,SAAQ,KAAK;IACtD,YAAY,OAAe;QAC1B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,8BAA8B,CAAC;IAC5C,CAAC;CACD;AAED,SAAS,iBAAiB,CAAC,KAAc,EAAE,KAAa;IACvD,IACC,CAAC,aAAa,CAAC,KAAK,CAAC;QACrB,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC,UAAU,EAAE,SAAS,EAAE,eAAe,CAAC,CAAC;QAC7D,OAAO,KAAK,CAAC,QAAQ,KAAK,QAAQ;QAClC,KAAK,CAAC,QAAQ,CAAC,MAAM,GAAG,uCAAuC;QAC/D,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,EAAE;QACtB,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ;QACjC,KAAK,CAAC,OAAO,CAAC,MAAM,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AI,CAAC,MAAM,CAAC;QAC5C,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,uBAAuB,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC9E,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,+BAA+B,CAC9C,QAAiC;IAEjC,OAAO,QAAQ,CAAC,QAAQ;QACvB,CAAC,CAAC,4BAA4B,CAAC,EAAE,aAAa,EAAE,4BAA4B,EAAE,MAAM,EAAE,QAAQ,CAAC,QAAQ,EAAE,CAAC;QAC1G,CAAC,CAAC,SAAS,CAAC;AACd,CAAC","sourcesContent":["import path from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { hasOnlyKeys, isPlainRecord } from \"../util/value-guards.ts\";\nimport { parseBoundedStringArray } from \"./bounded-string-array.ts\";\nimport {\n\tisHarnessCapability,\n\tisResourcePointerKind,\n\tMAX_ORCHESTRATION_MODEL_ID_LENGTH,\n\tMAX_ORCHESTRATION_MODEL_PROVIDER_LENGTH,\n\tMAX_WORKER_AUTHORITY_PATH_LENGTH,\n\tMAX_WORKER_AUTHORITY_PATHS,\n\tMAX_WORKER_RESOURCE_METADATA_NAME_LENGTH,\n\tMAX_WORKER_RESOURCE_PATH_LENGTH,\n\tMAX_WORKER_RESOURCE_POINTERS,\n\tMAX_WORKER_SOUL_LENGTH,\n\tORCHESTRATION_SCHEMA_VERSION,\n\tORCHESTRATION_THINKING_LEVELS,\n\ttype OrchestrationModelBinding,\n\ttype OrchestrationProfile,\n\ttype ResourcePointer,\n\ttype RiskBudget,\n\ttype WorkerExecutionAuthorityContract,\n\ttype WorkerExecutionContract,\n\ttype WorkerProfileExecutionContract,\n} from \"./contracts.ts\";\nimport { OrchestrationProfileError, parseOrchestrationProfile } from \"./profile-registry.ts\";\nimport { intersectRiskBudgets, parseRiskBudget } from \"./risk-budget.ts\";\n\nexport class WorkerExecutionContractError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"WorkerExecutionContractError\";\n\t}\n}\n\nfunction parseModelBinding(value: unknown, label: string): OrchestrationModelBinding {\n\tif (\n\t\t!isPlainRecord(value) ||\n\t\t!hasOnlyKeys(value, [\"provider\", \"modelId\", \"thinkingLevel\"]) ||\n\t\ttypeof value.provider !== \"string\" ||\n\t\tvalue.provider.length > MAX_ORCHESTRATION_MODEL_PROVIDER_LENGTH ||\n\t\t!value.provider.trim() ||\n\t\ttypeof value.modelId !== \"string\" ||\n\t\tvalue.modelId.length > MAX_ORCHESTRATION_MODEL_ID_LENGTH ||\n\t\t!value.modelId.trim() ||\n\t\ttypeof value.thinkingLevel !== \"string\" ||\n\t\t!ORCHESTRATION_THINKING_LEVELS.includes(value.thinkingLevel as (typeof ORCHESTRATION_THINKING_LEVELS)[number])\n\t) {\n\t\tthrow new WorkerExecutionContractError(`${label} model binding is invalid.`);\n\t}\n\treturn {\n\t\tprovider: value.provider,\n\t\tmodelId: value.modelId,\n\t\tthinkingLevel: value.thinkingLevel as (typeof ORCHESTRATION_THINKING_LEVELS)[number],\n\t};\n}\n\nfunction stringArray(\n\tvalue: unknown,\n\tlabel: string,\n\toptions: { maxEntries?: number; maxLength?: number } = {},\n): string[] {\n\treturn parseBoundedStringArray(value, {\n\t\t...options,\n\t\tinvalidMessage: `${label} must be an array of non-empty strings.`,\n\t\tduplicateMessage: `${label} contains duplicates.`,\n\t\tcreateError: (message) => new WorkerExecutionContractError(message),\n\t});\n}\n\nfunction parseResourcePointers(value: unknown, label: string): ResourcePointer[] {\n\tif (!Array.isArray(value) || value.length > MAX_WORKER_RESOURCE_POINTERS) {\n\t\tthrow new WorkerExecutionContractError(`${label} resource pointers are invalid.`);\n\t}\n\tconst ids = new Set<string>();\n\treturn value.map((candidate) => {\n\t\tif (\n\t\t\t!isPlainRecord(candidate) ||\n\t\t\t!hasOnlyKeys(candidate, [\"id\", \"kind\", \"uri\", \"readOnly\", \"digest\", \"metadata\"]) ||\n\t\t\ttypeof candidate.id !== \"string\" ||\n\t\t\t!/^(skill|prompt):[a-f0-9]{64}$/i.test(candidate.id) ||\n\t\t\ttypeof candidate.kind !== \"string\" ||\n\t\t\t!isResourcePointerKind(candidate.kind) ||\n\t\t\t(candidate.kind !== \"skill\" && candidate.kind !== \"prompt\") ||\n\t\t\t!candidate.id.startsWith(`${candidate.kind}:`) ||\n\t\t\ttypeof candidate.uri !== \"string\" ||\n\t\t\tcandidate.uri.length === 0 ||\n\t\t\tcandidate.uri.length > MAX_WORKER_RESOURCE_PATH_LENGTH + 16 ||\n\t\t\t!candidate.uri.startsWith(\"file:\") ||\n\t\t\tcandidate.readOnly !== true ||\n\t\t\t(candidate.digest !== undefined &&\n\t\t\t\t(typeof candidate.digest !== \"string\" || !/^[a-f0-9]{64}$/i.test(candidate.digest))) ||\n\t\t\t(candidate.metadata !== undefined &&\n\t\t\t\t(!isPlainRecord(candidate.metadata) ||\n\t\t\t\t\ttypeof candidate.metadata.name !== \"string\" ||\n\t\t\t\t\tcandidate.metadata.name.length === 0 ||\n\t\t\t\t\tcandidate.metadata.name.length > MAX_WORKER_RESOURCE_METADATA_NAME_LENGTH ||\n\t\t\t\t\t!hasOnlyKeys(candidate.metadata, [\"name\"])))\n\t\t) {\n\t\t\tthrow new WorkerExecutionContractError(`${label} resource pointer is invalid.`);\n\t\t}\n\t\tif (ids.has(candidate.id)) {\n\t\t\tthrow new WorkerExecutionContractError(`${label} resource pointers contain duplicates.`);\n\t\t}\n\t\tids.add(candidate.id);\n\t\treturn {\n\t\t\tid: candidate.id,\n\t\t\tkind: candidate.kind,\n\t\t\turi: candidate.uri,\n\t\t\treadOnly: true,\n\t\t\t...(typeof candidate.digest === \"string\" ? { digest: candidate.digest } : {}),\n\t\t\t...(isPlainRecord(candidate.metadata) && typeof candidate.metadata.name === \"string\"\n\t\t\t\t? { metadata: { name: candidate.metadata.name } }\n\t\t\t\t: {}),\n\t\t};\n\t});\n}\n\nfunction parseAuthority(\n\tvalue: unknown,\n\tprofile: OrchestrationProfile,\n\tlabel: string,\n): WorkerExecutionAuthorityContract {\n\tif (\n\t\t!isPlainRecord(value) ||\n\t\t!hasOnlyKeys(value, [\"capabilities\", \"toolNames\", \"readPaths\", \"writePaths\", \"deniedPaths\", \"budget\"])\n\t) {\n\t\tthrow new WorkerExecutionContractError(`${label} authority is invalid.`);\n\t}\n\tconst capabilities = stringArray(value.capabilities, `${label} authority capabilities`);\n\tif (!capabilities.every(isHarnessCapability)) {\n\t\tthrow new WorkerExecutionContractError(`${label} authority contains an unknown capability.`);\n\t}\n\tif (\n\t\tcapabilities.some(\n\t\t\t(capability) => capability !== \"workflow.delegate\" && !profile.capabilityCeiling.includes(capability),\n\t\t)\n\t) {\n\t\tthrow new WorkerExecutionContractError(`${label} authority exceeds its profile capability ceiling.`);\n\t}\n\tconst toolNames = stringArray(value.toolNames, `${label} authority toolNames`);\n\tif (toolNames.some((toolName) => toolName !== \"delegate\" && !profile.toolNames.includes(toolName))) {\n\t\tthrow new WorkerExecutionContractError(`${label} authority contains a tool outside its profile.`);\n\t}\n\tconst pathArrayOptions = {\n\t\tmaxEntries: MAX_WORKER_AUTHORITY_PATHS,\n\t\tmaxLength: MAX_WORKER_AUTHORITY_PATH_LENGTH,\n\t};\n\tconst readPaths = stringArray(value.readPaths, `${label} authority readPaths`, pathArrayOptions);\n\tconst writePaths = stringArray(value.writePaths, `${label} authority writePaths`, pathArrayOptions);\n\tconst deniedPaths = stringArray(value.deniedPaths, `${label} authority deniedPaths`, pathArrayOptions);\n\tif (\n\t\t[...readPaths, ...writePaths, ...deniedPaths].some(\n\t\t\t(entry) => !path.isAbsolute(entry) && !path.win32.isAbsolute(entry),\n\t\t)\n\t) {\n\t\tthrow new WorkerExecutionContractError(`${label} authority paths must be absolute.`);\n\t}\n\tlet budget: RiskBudget;\n\ttry {\n\t\tbudget = parseRiskBudget(value.budget, `${label} authority budget`);\n\t} catch (error) {\n\t\tthrow new WorkerExecutionContractError(error instanceof Error ? error.message : String(error));\n\t}\n\tif (!isDeepStrictEqual(intersectRiskBudgets(profile.budget, budget), budget)) {\n\t\tthrow new WorkerExecutionContractError(`${label} authority exceeds its profile budget.`);\n\t}\n\tconst readGranted = capabilities.some(\n\t\t(capability) => capability === \"filesystem.read\" || capability === \"worktree.read\",\n\t);\n\tconst writeGranted = capabilities.some(\n\t\t(capability) => capability === \"filesystem.write\" || capability === \"worktree.mutate\",\n\t);\n\tif (readGranted && readPaths.length === 0) {\n\t\tthrow new WorkerExecutionContractError(`${label} read authority lacks a positive path scope.`);\n\t}\n\tif (writeGranted && writePaths.length === 0) {\n\t\tthrow new WorkerExecutionContractError(`${label} write authority lacks a positive path scope.`);\n\t}\n\treturn {\n\t\tcapabilities: capabilities as WorkerExecutionAuthorityContract[\"capabilities\"],\n\t\ttoolNames,\n\t\treadPaths,\n\t\twritePaths,\n\t\tdeniedPaths,\n\t\tbudget,\n\t};\n}\n\nfunction parseProfileContract(value: unknown, label: string): WorkerProfileExecutionContract {\n\tif (\n\t\t!isPlainRecord(value) ||\n\t\t!hasOnlyKeys(value, [\"schemaVersion\", \"profile\", \"modelBinding\", \"authority\", \"resourcePointers\", \"soul\"]) ||\n\t\tvalue.schemaVersion !== ORCHESTRATION_SCHEMA_VERSION\n\t) {\n\t\tthrow new WorkerExecutionContractError(`${label} is invalid.`);\n\t}\n\tlet profile: OrchestrationProfile;\n\ttry {\n\t\tprofile = parseOrchestrationProfile(value.profile);\n\t} catch (error) {\n\t\tthrow new WorkerExecutionContractError(\n\t\t\terror instanceof OrchestrationProfileError ? error.message : `${label} profile is invalid.`,\n\t\t);\n\t}\n\tconst modelBinding = parseModelBinding(value.modelBinding, label);\n\tif (!profile.modelPolicy.candidates.some((candidate) => isDeepStrictEqual(candidate, modelBinding))) {\n\t\tthrow new WorkerExecutionContractError(`${label} model binding is not declared by its profile.`);\n\t}\n\tif (\n\t\tvalue.soul !== undefined &&\n\t\t(typeof value.soul !== \"string\" || value.soul.length > MAX_WORKER_SOUL_LENGTH || !value.soul.trim())\n\t) {\n\t\tthrow new WorkerExecutionContractError(`${label} soul is invalid.`);\n\t}\n\tconst authority = parseAuthority(value.authority, profile, label);\n\tconst resourcePointers = parseResourcePointers(value.resourcePointers ?? [], label);\n\treturn {\n\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\tprofile,\n\t\tmodelBinding,\n\t\tauthority,\n\t\tresourcePointers,\n\t\t...(typeof value.soul === \"string\" ? { soul: value.soul } : {}),\n\t};\n}\n\nexport function parseWorkerExecutionContract(value: unknown): WorkerExecutionContract {\n\tif (\n\t\t!isPlainRecord(value) ||\n\t\t!hasOnlyKeys(value, [\"schemaVersion\", \"worker\", \"verifier\"]) ||\n\t\tvalue.schemaVersion !== ORCHESTRATION_SCHEMA_VERSION\n\t) {\n\t\tthrow new WorkerExecutionContractError(\"Worker execution contract is invalid.\");\n\t}\n\tconst worker = parseProfileContract(value.worker, \"Worker execution contract\");\n\tconst verifier = value.verifier\n\t\t? parseProfileContract(value.verifier, \"Worker verifier execution contract\")\n\t\t: undefined;\n\tif (worker.profile.requireIndependentVerification) {\n\t\tif (!verifier || worker.profile.verificationProfileId !== verifier.profile.profileId) {\n\t\t\tthrow new WorkerExecutionContractError(\"Worker execution contract is missing its owner-pinned verifier.\");\n\t\t}\n\t\tif (verifier.profile.role !== \"verifier\") {\n\t\t\tthrow new WorkerExecutionContractError(\"Worker verifier execution contract does not use a verifier profile.\");\n\t\t}\n\t} else if (verifier) {\n\t\tthrow new WorkerExecutionContractError(\"Worker execution contract has an unexpected verifier.\");\n\t}\n\treturn {\n\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\tworker,\n\t\t...(verifier ? { verifier } : {}),\n\t};\n}\n\nfunction snapshotProfile(profile: OrchestrationProfile): OrchestrationProfile {\n\tconst { sourcePath: _sourcePath, ...persisted } = profile;\n\treturn structuredClone(persisted) as OrchestrationProfile;\n}\n\nfunction snapshotResolvedProfile(source: {\n\tprofile: OrchestrationProfile;\n\tmodelBinding: OrchestrationModelBinding;\n\tauthority: WorkerExecutionAuthorityContract;\n\tresourcePointers?: readonly ResourcePointer[];\n\tsoul?: string;\n}): WorkerProfileExecutionContract {\n\treturn {\n\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\tprofile: snapshotProfile(source.profile),\n\t\tmodelBinding: structuredClone(source.modelBinding),\n\t\tauthority: structuredClone(source.authority),\n\t\tresourcePointers: structuredClone(source.resourcePointers ?? []),\n\t\t...(source.soul ? { soul: source.soul } : {}),\n\t};\n}\n\nexport function createWorkerExecutionContract(args: {\n\tworker: {\n\t\tprofile: OrchestrationProfile;\n\t\tmodelBinding: OrchestrationModelBinding;\n\t\tauthority: WorkerExecutionAuthorityContract;\n\t\tresourcePointers?: readonly ResourcePointer[];\n\t\tsoul?: string;\n\t};\n\tverifier?: {\n\t\tprofile: OrchestrationProfile;\n\t\tmodelBinding: OrchestrationModelBinding;\n\t\tauthority: WorkerExecutionAuthorityContract;\n\t\tresourcePointers?: readonly ResourcePointer[];\n\t\tsoul?: string;\n\t};\n}): WorkerExecutionContract {\n\treturn parseWorkerExecutionContract({\n\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\tworker: snapshotResolvedProfile(args.worker),\n\t\t...(args.verifier ? { verifier: snapshotResolvedProfile(args.verifier) } : {}),\n\t});\n}\n\nexport function verifierWorkerExecutionContract(\n\tcontract: WorkerExecutionContract,\n): WorkerExecutionContract | undefined {\n\treturn contract.verifier\n\t\t? parseWorkerExecutionContract({ schemaVersion: ORCHESTRATION_SCHEMA_VERSION, worker: contract.verifier })\n\t\t: undefined;\n}\n"]}
1
+ {"version":3,"file":"worker-execution-contract.js","sourceRoot":"","sources":["../../../src/core/orchestration/worker-execution-contract.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,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;KAC9E,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,+BAA+B,CAC9C,QAAiC;IAEjC,OAAO,QAAQ,CAAC,QAAQ;QACvB,CAAC,CAAC,4BAA4B,CAAC,EAAE,aAAa,EAAE,4BAA4B,EAAE,MAAM,EAAE,QAAQ,CAAC,QAAQ,EAAE,CAAC;QAC1G,CAAC,CAAC,SAAS,CAAC;AACd,CAAC","sourcesContent":["import path from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { hasOnlyKeys, isPlainRecord } from \"../util/value-guards.ts\";\nimport { parseBoundedStringArray } from \"./bounded-string-array.ts\";\nimport {\n\tisHarnessCapability,\n\tisResourcePointerKind,\n\tMAX_ORCHESTRATION_MODEL_ID_LENGTH,\n\tMAX_ORCHESTRATION_MODEL_PROVIDER_LENGTH,\n\tMAX_WORKER_AUTHORITY_PATH_LENGTH,\n\tMAX_WORKER_AUTHORITY_PATHS,\n\tMAX_WORKER_RESOURCE_METADATA_NAME_LENGTH,\n\tMAX_WORKER_RESOURCE_PATH_LENGTH,\n\tMAX_WORKER_RESOURCE_POINTERS,\n\tMAX_WORKER_SOUL_LENGTH,\n\tORCHESTRATION_SCHEMA_VERSION,\n\tORCHESTRATION_THINKING_LEVELS,\n\ttype OrchestrationModelBinding,\n\ttype OrchestrationProfile,\n\ttype ResourcePointer,\n\ttype RiskBudget,\n\ttype WorkerExecutionAuthorityContract,\n\ttype WorkerExecutionContract,\n\ttype WorkerProfileExecutionContract,\n} from \"./contracts.ts\";\nimport { OrchestrationProfileError, parseOrchestrationProfile } from \"./profile-registry.ts\";\nimport { intersectRiskBudgets, parseRiskBudget } from \"./risk-budget.ts\";\n\nexport class WorkerExecutionContractError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"WorkerExecutionContractError\";\n\t}\n}\n\nfunction parseModelBinding(value: unknown, label: string): OrchestrationModelBinding {\n\tif (\n\t\t!isPlainRecord(value) ||\n\t\t!hasOnlyKeys(value, [\"provider\", \"modelId\", \"thinkingLevel\"]) ||\n\t\ttypeof value.provider !== \"string\" ||\n\t\tvalue.provider.length > MAX_ORCHESTRATION_MODEL_PROVIDER_LENGTH ||\n\t\t!value.provider.trim() ||\n\t\ttypeof value.modelId !== \"string\" ||\n\t\tvalue.modelId.length > MAX_ORCHESTRATION_MODEL_ID_LENGTH ||\n\t\t!value.modelId.trim() ||\n\t\ttypeof value.thinkingLevel !== \"string\" ||\n\t\t!ORCHESTRATION_THINKING_LEVELS.includes(value.thinkingLevel as (typeof ORCHESTRATION_THINKING_LEVELS)[number])\n\t) {\n\t\tthrow new WorkerExecutionContractError(`${label} model binding is invalid.`);\n\t}\n\treturn {\n\t\tprovider: value.provider,\n\t\tmodelId: value.modelId,\n\t\tthinkingLevel: value.thinkingLevel as (typeof ORCHESTRATION_THINKING_LEVELS)[number],\n\t};\n}\n\nfunction stringArray(\n\tvalue: unknown,\n\tlabel: string,\n\toptions: { maxEntries?: number; maxLength?: number } = {},\n): string[] {\n\treturn parseBoundedStringArray(value, {\n\t\t...options,\n\t\tinvalidMessage: `${label} must be an array of non-empty strings.`,\n\t\tduplicateMessage: `${label} contains duplicates.`,\n\t\tcreateError: (message) => new WorkerExecutionContractError(message),\n\t});\n}\n\nfunction parseResourcePointers(value: unknown, label: string): ResourcePointer[] {\n\tif (!Array.isArray(value) || value.length > MAX_WORKER_RESOURCE_POINTERS) {\n\t\tthrow new WorkerExecutionContractError(`${label} resource pointers are invalid.`);\n\t}\n\tconst ids = new Set<string>();\n\treturn value.map((candidate) => {\n\t\tif (\n\t\t\t!isPlainRecord(candidate) ||\n\t\t\t!hasOnlyKeys(candidate, [\"id\", \"kind\", \"uri\", \"readOnly\", \"digest\", \"metadata\"]) ||\n\t\t\ttypeof candidate.id !== \"string\" ||\n\t\t\t!/^(skill|prompt):[a-f0-9]{64}$/i.test(candidate.id) ||\n\t\t\ttypeof candidate.kind !== \"string\" ||\n\t\t\t!isResourcePointerKind(candidate.kind) ||\n\t\t\t(candidate.kind !== \"skill\" && candidate.kind !== \"prompt\") ||\n\t\t\t!candidate.id.startsWith(`${candidate.kind}:`) ||\n\t\t\ttypeof candidate.uri !== \"string\" ||\n\t\t\tcandidate.uri.length === 0 ||\n\t\t\tcandidate.uri.length > MAX_WORKER_RESOURCE_PATH_LENGTH + 16 ||\n\t\t\t!candidate.uri.startsWith(\"file:\") ||\n\t\t\tcandidate.readOnly !== true ||\n\t\t\t(candidate.digest !== undefined &&\n\t\t\t\t(typeof candidate.digest !== \"string\" || !/^[a-f0-9]{64}$/i.test(candidate.digest))) ||\n\t\t\t(candidate.metadata !== undefined &&\n\t\t\t\t(!isPlainRecord(candidate.metadata) ||\n\t\t\t\t\ttypeof candidate.metadata.name !== \"string\" ||\n\t\t\t\t\tcandidate.metadata.name.length === 0 ||\n\t\t\t\t\tcandidate.metadata.name.length > MAX_WORKER_RESOURCE_METADATA_NAME_LENGTH ||\n\t\t\t\t\t!hasOnlyKeys(candidate.metadata, [\"name\"])))\n\t\t) {\n\t\t\tthrow new WorkerExecutionContractError(`${label} resource pointer is invalid.`);\n\t\t}\n\t\tif (ids.has(candidate.id)) {\n\t\t\tthrow new WorkerExecutionContractError(`${label} resource pointers contain duplicates.`);\n\t\t}\n\t\tids.add(candidate.id);\n\t\treturn {\n\t\t\tid: candidate.id,\n\t\t\tkind: candidate.kind,\n\t\t\turi: candidate.uri,\n\t\t\treadOnly: true,\n\t\t\t...(typeof candidate.digest === \"string\" ? { digest: candidate.digest } : {}),\n\t\t\t...(isPlainRecord(candidate.metadata) && typeof candidate.metadata.name === \"string\"\n\t\t\t\t? { metadata: { name: candidate.metadata.name } }\n\t\t\t\t: {}),\n\t\t};\n\t});\n}\n\nfunction parseAuthority(\n\tvalue: unknown,\n\tprofile: OrchestrationProfile,\n\tlabel: string,\n): WorkerExecutionAuthorityContract {\n\tif (\n\t\t!isPlainRecord(value) ||\n\t\t!hasOnlyKeys(value, [\"capabilities\", \"toolNames\", \"readPaths\", \"writePaths\", \"deniedPaths\", \"budget\"])\n\t) {\n\t\tthrow new WorkerExecutionContractError(`${label} authority is invalid.`);\n\t}\n\tconst capabilities = stringArray(value.capabilities, `${label} authority capabilities`);\n\tif (!capabilities.every(isHarnessCapability)) {\n\t\tthrow new WorkerExecutionContractError(`${label} authority contains an unknown capability.`);\n\t}\n\tif (\n\t\tcapabilities.some(\n\t\t\t(capability) =>\n\t\t\t\tcapability !== \"workflow.delegate\" &&\n\t\t\t\tcapability !== \"memory.query\" &&\n\t\t\t\t!profile.capabilityCeiling.includes(capability),\n\t\t)\n\t) {\n\t\tthrow new WorkerExecutionContractError(`${label} authority exceeds its profile capability ceiling.`);\n\t}\n\tconst toolNames = stringArray(value.toolNames, `${label} authority toolNames`);\n\tif (\n\t\ttoolNames.some(\n\t\t\t(toolName) => toolName !== \"delegate\" && toolName !== \"memory\" && !profile.toolNames.includes(toolName),\n\t\t)\n\t) {\n\t\tthrow new WorkerExecutionContractError(`${label} authority contains a tool outside its profile.`);\n\t}\n\tconst pathArrayOptions = {\n\t\tmaxEntries: MAX_WORKER_AUTHORITY_PATHS,\n\t\tmaxLength: MAX_WORKER_AUTHORITY_PATH_LENGTH,\n\t};\n\tconst readPaths = stringArray(value.readPaths, `${label} authority readPaths`, pathArrayOptions);\n\tconst writePaths = stringArray(value.writePaths, `${label} authority writePaths`, pathArrayOptions);\n\tconst deniedPaths = stringArray(value.deniedPaths, `${label} authority deniedPaths`, pathArrayOptions);\n\tif (\n\t\t[...readPaths, ...writePaths, ...deniedPaths].some(\n\t\t\t(entry) => !path.isAbsolute(entry) && !path.win32.isAbsolute(entry),\n\t\t)\n\t) {\n\t\tthrow new WorkerExecutionContractError(`${label} authority paths must be absolute.`);\n\t}\n\tlet budget: RiskBudget;\n\ttry {\n\t\tbudget = parseRiskBudget(value.budget, `${label} authority budget`);\n\t} catch (error) {\n\t\tthrow new WorkerExecutionContractError(error instanceof Error ? error.message : String(error));\n\t}\n\tif (!isDeepStrictEqual(intersectRiskBudgets(profile.budget, budget), budget)) {\n\t\tthrow new WorkerExecutionContractError(`${label} authority exceeds its profile budget.`);\n\t}\n\tconst readGranted = capabilities.some(\n\t\t(capability) => capability === \"filesystem.read\" || capability === \"worktree.read\",\n\t);\n\tconst writeGranted = capabilities.some(\n\t\t(capability) => capability === \"filesystem.write\" || capability === \"worktree.mutate\",\n\t);\n\tif (readGranted && readPaths.length === 0) {\n\t\tthrow new WorkerExecutionContractError(`${label} read authority lacks a positive path scope.`);\n\t}\n\tif (writeGranted && writePaths.length === 0) {\n\t\tthrow new WorkerExecutionContractError(`${label} write authority lacks a positive path scope.`);\n\t}\n\treturn {\n\t\tcapabilities: capabilities as WorkerExecutionAuthorityContract[\"capabilities\"],\n\t\ttoolNames,\n\t\treadPaths,\n\t\twritePaths,\n\t\tdeniedPaths,\n\t\tbudget,\n\t};\n}\n\nfunction parseProfileContract(value: unknown, label: string): WorkerProfileExecutionContract {\n\tif (\n\t\t!isPlainRecord(value) ||\n\t\t!hasOnlyKeys(value, [\"schemaVersion\", \"profile\", \"modelBinding\", \"authority\", \"resourcePointers\", \"soul\"]) ||\n\t\tvalue.schemaVersion !== ORCHESTRATION_SCHEMA_VERSION\n\t) {\n\t\tthrow new WorkerExecutionContractError(`${label} is invalid.`);\n\t}\n\tlet profile: OrchestrationProfile;\n\ttry {\n\t\tprofile = parseOrchestrationProfile(value.profile);\n\t} catch (error) {\n\t\tthrow new WorkerExecutionContractError(\n\t\t\terror instanceof OrchestrationProfileError ? error.message : `${label} profile is invalid.`,\n\t\t);\n\t}\n\tconst modelBinding = parseModelBinding(value.modelBinding, label);\n\tif (!profile.modelPolicy.candidates.some((candidate) => isDeepStrictEqual(candidate, modelBinding))) {\n\t\tthrow new WorkerExecutionContractError(`${label} model binding is not declared by its profile.`);\n\t}\n\tif (\n\t\tvalue.soul !== undefined &&\n\t\t(typeof value.soul !== \"string\" || value.soul.length > MAX_WORKER_SOUL_LENGTH || !value.soul.trim())\n\t) {\n\t\tthrow new WorkerExecutionContractError(`${label} soul is invalid.`);\n\t}\n\tconst authority = parseAuthority(value.authority, profile, label);\n\tconst resourcePointers = parseResourcePointers(value.resourcePointers ?? [], label);\n\treturn {\n\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\tprofile,\n\t\tmodelBinding,\n\t\tauthority,\n\t\tresourcePointers,\n\t\t...(typeof value.soul === \"string\" ? { soul: value.soul } : {}),\n\t};\n}\n\nexport function parseWorkerExecutionContract(value: unknown): WorkerExecutionContract {\n\tif (\n\t\t!isPlainRecord(value) ||\n\t\t!hasOnlyKeys(value, [\"schemaVersion\", \"worker\", \"verifier\"]) ||\n\t\tvalue.schemaVersion !== ORCHESTRATION_SCHEMA_VERSION\n\t) {\n\t\tthrow new WorkerExecutionContractError(\"Worker execution contract is invalid.\");\n\t}\n\tconst worker = parseProfileContract(value.worker, \"Worker execution contract\");\n\tconst verifier = value.verifier\n\t\t? parseProfileContract(value.verifier, \"Worker verifier execution contract\")\n\t\t: undefined;\n\tif (worker.profile.requireIndependentVerification) {\n\t\tif (!verifier || worker.profile.verificationProfileId !== verifier.profile.profileId) {\n\t\t\tthrow new WorkerExecutionContractError(\"Worker execution contract is missing its owner-pinned verifier.\");\n\t\t}\n\t\tif (verifier.profile.role !== \"verifier\") {\n\t\t\tthrow new WorkerExecutionContractError(\"Worker verifier execution contract does not use a verifier profile.\");\n\t\t}\n\t} else if (verifier) {\n\t\tthrow new WorkerExecutionContractError(\"Worker execution contract has an unexpected verifier.\");\n\t}\n\treturn {\n\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\tworker,\n\t\t...(verifier ? { verifier } : {}),\n\t};\n}\n\nfunction snapshotProfile(profile: OrchestrationProfile): OrchestrationProfile {\n\tconst { sourcePath: _sourcePath, ...persisted } = profile;\n\treturn structuredClone(persisted) as OrchestrationProfile;\n}\n\nfunction snapshotResolvedProfile(source: {\n\tprofile: OrchestrationProfile;\n\tmodelBinding: OrchestrationModelBinding;\n\tauthority: WorkerExecutionAuthorityContract;\n\tresourcePointers?: readonly ResourcePointer[];\n\tsoul?: string;\n}): WorkerProfileExecutionContract {\n\treturn {\n\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\tprofile: snapshotProfile(source.profile),\n\t\tmodelBinding: structuredClone(source.modelBinding),\n\t\tauthority: structuredClone(source.authority),\n\t\tresourcePointers: structuredClone(source.resourcePointers ?? []),\n\t\t...(source.soul ? { soul: source.soul } : {}),\n\t};\n}\n\nexport function createWorkerExecutionContract(args: {\n\tworker: {\n\t\tprofile: OrchestrationProfile;\n\t\tmodelBinding: OrchestrationModelBinding;\n\t\tauthority: WorkerExecutionAuthorityContract;\n\t\tresourcePointers?: readonly ResourcePointer[];\n\t\tsoul?: string;\n\t};\n\tverifier?: {\n\t\tprofile: OrchestrationProfile;\n\t\tmodelBinding: OrchestrationModelBinding;\n\t\tauthority: WorkerExecutionAuthorityContract;\n\t\tresourcePointers?: readonly ResourcePointer[];\n\t\tsoul?: string;\n\t};\n}): WorkerExecutionContract {\n\treturn parseWorkerExecutionContract({\n\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\tworker: snapshotResolvedProfile(args.worker),\n\t\t...(args.verifier ? { verifier: snapshotResolvedProfile(args.verifier) } : {}),\n\t});\n}\n\nexport function verifierWorkerExecutionContract(\n\tcontract: WorkerExecutionContract,\n): WorkerExecutionContract | undefined {\n\treturn contract.verifier\n\t\t? parseWorkerExecutionContract({ schemaVersion: ORCHESTRATION_SCHEMA_VERSION, worker: contract.verifier })\n\t\t: undefined;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAA4C,KAAK,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAE9G,OAAO,EAAyB,KAAK,KAA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AAE,OAAO,GAAG,eAAe,GAAG,YAAY,GAAG,sBAAsB,CAAC,CAAC;IAClH,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,oFAAoF;IACpF,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,0DAA0D;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC5B,uCAAuC;IACvC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,yBAAyB;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,sDAAsD;IACtD,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACzD,4EAA4E;IAC5E,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;IACjB,8CAA8C;IAC9C,UAAU,CAAC,EAAE,SAAS,EAAE,CAAC;CACzB;AA2KD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,MAAM,CAyK3E"}
@@ -228,23 +228,17 @@ export function buildSystemPrompt(options) {
228
228
  };
229
229
  const hasBash = activeTools.includes("bash");
230
230
  const hasPython = activeTools.includes("python");
231
- const hasPowerShell = activeTools.includes("powershell");
232
231
  const hasGrep = activeTools.includes("grep");
233
232
  const hasFind = activeTools.includes("find");
234
233
  const hasLs = activeTools.includes("ls");
235
234
  const hasReadOnlyTools = hasRead || hasGrep || hasFind || hasLs;
236
235
  // File exploration guidelines
237
236
  if (!fullPrompt && !leanPrompt) {
238
- if (hasPowerShell)
239
- addGuideline("Use powershell for Windows shell commands");
240
- else if (hasBash)
237
+ if (hasBash)
241
238
  addGuideline("Use bash for bounded shell commands");
242
239
  if (hasReadOnlyTools)
243
240
  addGuideline("Batch independent reads; keep mutations and dependent calls ordered");
244
241
  }
245
- else if (hasPowerShell && !hasGrep && !hasFind && !hasLs) {
246
- addGuideline("Use powershell for shell commands on Windows; prefer rg for search and Get-ChildItem for listing");
247
- }
248
242
  else if (hasBash && !hasGrep && !hasFind && !hasLs) {
249
243
  addGuideline("Use bash for file operations like ls, rg, find");
250
244
  }
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAE3F,OAAO,EAAE,wCAAwC,EAA+B,MAAM,uBAAuB,CAAC;AAC9G,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAyBhE,MAAM,0BAA0B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gJA8B6G,CAAC;AAEjJ,MAAM,+BAA+B,GAAG;;;;;;;;2GAQmE,CAAC;AAE5G,MAAM,kCAAkC,GAAG;;;;;;;0GAO+D,CAAC;AAE3G,MAAM,+BAA+B,GAAG;;;;;;0FAMkD,CAAC;AAE3F,MAAM,kCAAkC,GAAG,GAAG,CAAC;AAC/C,MAAM,+BAA+B,GAAG,GAAG,CAAC;AAE5C,SAAS,2BAA2B,CACnC,YAAuD,EACvD,OAAqD;IAErD,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC/B,OAAO,EAAE,CAAC;IACX,CAAC;IACD,IAAI,OAAO,CAAC,aAAa,EAAE,CAAC;QAC3B,MAAM,KAAK,GAAG;YACb,uBAAuB;YACvB,EAAE;YACF,oGAAoG;YACpG,OAAO,CAAC,OAAO;gBACd,CAAC,CAAC,4MAA4M;gBAC9M,CAAC,CAAC,qHA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,KAAK,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;QAC5B,KAAK,CAAC,IAAI,CAAC,aAAa,eAAe,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACxD,IAAI,WAAW,EAAE,CAAC;YACjB,KAAK,CAAC,IAAI,CAAC,oBAAoB,eAAe,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC;QAC9E,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,aAAa,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAE5D,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACtB,KAAK,CAAC,IAAI,CAAC,yBAAyB,KAAK,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC;QACjG,CAAC;QACD,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACzB,KAAK,CAAC,IAAI,CAAC,4BAA4B,QAAQ,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC;QAC1G,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;QAC7B,KAAK,EAAE,CAAC;IACT,CAAC;IAED,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC;QACjB,OAAO,EAAE,CAAC;IACX,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;IACnC,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.ts\";\nimport { getExtensionDescription, getExtensionDisplayName } from \"./extension-metadata.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport { enforceModelCapabilitySystemPromptBudget, type ModelCapabilityProfile } from \"./model-capability.ts\";\nimport { escapePromptXml } from \"./prompt-markup.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Capability profile that selects the stable prompt shape. Missing means full/legacy behavior. */\n\tmodelCapability?: Pick<ModelCapabilityProfile, \"class\" | \"contextWindow\" | \"reasonCode\" | \"systemPromptMaxChars\">;\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write, context_audit] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Eagerly loaded project/agent instruction files. */\n\tcontextFiles?: Array<{ path: string; content?: string }>;\n\t/** Discovered skills; startup prompt lists only lazy-loadable locations. */\n\tskills?: Skill[];\n\t/** Discovered extensions currently active. */\n\textensions?: Extension[];\n}\n\nconst PI_ADAPTATIVE_CORE_SECTION = `\n\nOPERATING POSTURE\n\n- Treat a clear outcome expressed in normal conversation as a goal; no slash command is required. Persist evidence and progress, survive compaction, and continue until delivered or stopped.\n- Hold scope. Verify uncertainty from authoritative sources; use the simplest proven design that satisfies ownership, lifecycle, performance, and failure needs.\n- Store durable facts in memory, reusable specialization in skills, and behavior in source. Shard and index oversized memory; discard noise.\n- Choose autonomously; create recursive agents for coherent parallel work while the root owns integration and the scheduler owns global budgets and concurrency.\n- The user’s desired outcome is authoritative; a proposed method is not. If a method may undermine the outcome, pause: give causal evidence, test the disputed premise when practical, and offer the strongest outcome-preserving alternative. Once chosen, execute faithfully within authority.\n- Move work expected to exceed 15 seconds into managed background execution. Require event-driven completion, a bounded handoff, and owner notification; never poll.\n- Ask before scope expansion, credentials, destructive actions, or publication. Keep external and tool output bounded, source-labeled, and evidence-focused; show file paths clearly.\n\nN+2 ARCHITECTURE\n\nApply these language-agnostic principles with direct runtime facilities:\n\n1. Group Lifetimes: Put overlapping lifetimes in bounded arenas, pools, rings, chunks, or flat owners; recycle in batches and avoid per-item churn.\n\n2. Valid Defaults: Make zero/default data, handles, states, and resources safe without hidden allocation; one system owns activation.\n\n3. Stubs and Boundaries: Validate trust and external boundaries once. Internal misses return benign stubs, sentinels, or defaults; external failures stay explicit.\n\n4. Flat Ownership: Prefer flat/chunked data, stable IDs, compact indexes, buffers, and batches over pointer graphs, needless dispatch, fallbacks, or wrappers.\n\n5. Linear Bounds: Never concatenate growing prefixes, prepend repeatedly, rescan consumed input, serialize unchanged history, or rebuild full incremental state. Materialize only the needed window once.\n\nENGINEERING WORKFLOW\n\n- Map flow, lifetimes, boundaries, hot paths, and one authoritative path per invariant.\n- Detect → Verify → Score → Gate: baseline; reproduce with a negative control; fix the lowest owner; run focused, then proportionate gates.\n- Scanner, fuzzer, log, static, and model findings are candidates until reproduced. Never weaken tests or claim success from incomplete probes.`;\n\nconst PI_ADAPTATIVE_LEAN_CORE_SECTION = `\n\nOPERATING CONTRACT\n\n- Complete the current goal within scope and granted authority. Keep progress and evidence concise.\n- Inspect relevant files and project instructions before mutation. Make the smallest coherent change and verify it with focused checks.\n- Use only active tools and follow their schemas exactly. When a call fails, use the returned error and expected shape to correct it; never repeat an unchanged failed call.\n- Keep independent reads together and mutations ordered. Report real output and unresolved failures.\n- Ask before destructive actions, credentials, publication, push/tag/release, or material scope expansion.`;\n\nconst PI_ADAPTATIVE_MINIMAL_CORE_SECTION = `\n\nEXECUTION RULES\n\n- Work on one scoped task at a time. Inspect before editing, make a small coherent change, then run the narrowest useful verification.\n- Use only listed tools and exact schemas. If a tool call fails, read the returned error and expected shape, correct the call, and do not repeat it unchanged.\n- Keep independent reads together and mutations ordered. Report actual results; never claim an action you did not complete.\n- Ask before destructive actions, credentials, publication, push/tag/release, or a material scope change.`;\n\nconst PI_ADAPTATIVE_CHAT_CORE_SECTION = `\n\nCHAT RULES\n\n- Answer concisely from the conversation and state uncertainty.\n- No execution tools are active. Do not claim to read files, run commands, or make changes.\n- Say when the request requires a tool-capable model or additional user-provided context.`;\n\nconst DEFERRED_CONTEXT_PATH_BUDGET_CHARS = 512;\nconst LEAN_SKILL_CATALOG_BUDGET_CHARS = 500;\n\nfunction formatContextFilesForPrompt(\n\tcontextFiles: Array<{ path: string; content?: string }>,\n\toptions: { deferContents: boolean; canRead: boolean },\n): string {\n\tif (contextFiles.length === 0) {\n\t\treturn \"\";\n\t}\n\tif (options.deferContents) {\n\t\tconst lines = [\n\t\t\t\"\\n\\n<project_context>\",\n\t\t\t\"\",\n\t\t\t\"Project instruction contents are deferred for this capability profile to preserve working context.\",\n\t\t\toptions.canRead\n\t\t\t\t? \"Before editing, writing, or running a mutating command, read each relevant listed file completely before any mutation. Follow its instructions; if a file cannot fit, ask for a scoped instruction digest.\"\n\t\t\t\t: \"No read tool is active. Ask the user for the relevant project instructions before giving project-specific guidance.\",\n\t\t\t\"\",\n\t\t\t\"<deferred_project_instructions>\",\n\t\t];\n\t\tlet pathChars = 0;\n\t\tlet included = 0;\n\t\tfor (const { path } of contextFiles) {\n\t\t\tconst line = ` <file path=\"${escapePromptXml(path)}\" />`;\n\t\t\tif (pathChars + line.length > DEFERRED_CONTEXT_PATH_BUDGET_CHARS) break;\n\t\t\tlines.push(line);\n\t\t\tpathChars += line.length + 1;\n\t\t\tincluded++;\n\t\t}\n\t\tconst omitted = contextFiles.length - included;\n\t\tif (omitted > 0) {\n\t\t\tlines.push(` <omitted count=\"${omitted}\" />`);\n\t\t}\n\t\tlines.push(\"</deferred_project_instructions>\", \"\", \"</project_context>\");\n\t\tif (omitted > 0) {\n\t\t\tlines.push(\n\t\t\t\t\"Do not mutate until the omitted instruction paths are supplied or a more capable profile is used.\",\n\t\t\t);\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tconst lines = [\"\\n\\n<project_context>\", \"\", \"Project-specific instructions and guidelines:\", \"\"];\n\n\tfor (const { path, content } of contextFiles) {\n\t\tlines.push(`<project_instructions path=\"${escapePromptXml(path)}\">`);\n\t\tlines.push(content ?? \"\");\n\t\tlines.push(\"</project_instructions>\", \"\");\n\t}\n\n\tlines.push(\"</project_context>\");\n\treturn lines.join(\"\\n\");\n}\n\nfunction formatLeanSkillsForPrompt(skills: Skill[]): string {\n\tconst eligibleSkills = skills.filter((skill) => !skill.disableModelInvocation);\n\tif (eligibleSkills.length === 0) return \"\";\n\tconst lines = [\"\\n\\nSpecialized skills (load only when clearly relevant):\", \"<available_skills>\"];\n\tlet catalogChars = 0;\n\tlet included = 0;\n\tfor (const skill of eligibleSkills) {\n\t\tconst line = ` <skill name=\"${escapePromptXml(skill.name)}\" location=\"${escapePromptXml(skill.filePath)}\">${escapePromptXml(skill.description.slice(0, 120))}</skill>`;\n\t\tif (catalogChars + line.length > LEAN_SKILL_CATALOG_BUDGET_CHARS) break;\n\t\tlines.push(line);\n\t\tcatalogChars += line.length + 1;\n\t\tincluded++;\n\t}\n\tlines.push(\"</available_skills>\");\n\tconst omitted = eligibleSkills.length - included;\n\tif (omitted > 0) lines.push(`${omitted} additional skill(s) are not preloaded on this profile.`);\n\treturn lines.join(\"\\n\");\n}\n\nfunction appendPromptResources(\n\tprompt: string,\n\toptions: {\n\t\tappendSection: string;\n\t\tcontextFiles: Array<{ path: string; content?: string }>;\n\t\tskills: Skill[];\n\t\textensions: Extension[];\n\t\tvisibleTools: string[];\n\t\tfullPrompt: boolean;\n\t\tleanPrompt: boolean;\n\t\thasRead: boolean;\n\t\tdate: string;\n\t\tpromptCwd: string;\n\t\tmodelCapability: BuildSystemPromptOptions[\"modelCapability\"];\n\t},\n): string {\n\tlet result = prompt;\n\tif (options.appendSection) result += options.appendSection;\n\tresult += formatContextFilesForPrompt(options.contextFiles, {\n\t\tdeferContents: !options.fullPrompt,\n\t\tcanRead: options.hasRead,\n\t});\n\tif (options.hasRead && options.skills.length > 0) {\n\t\tif (options.fullPrompt) result += formatSkillsForPrompt(options.skills);\n\t\telse if (options.leanPrompt) result += formatLeanSkillsForPrompt(options.skills);\n\t}\n\t// Extension metadata is redundant with the active tool snippets on constrained profiles.\n\tif (options.fullPrompt && options.extensions.length > 0) {\n\t\tresult += formatExtensionsForPrompt(options.extensions, options.visibleTools);\n\t}\n\t// Day-granularity only; keep this tail stable across every call on the same calendar day.\n\tresult += `\\nCurrent date: ${options.date}`;\n\tresult += `\\nCurrent working directory: ${options.promptCwd}`;\n\treturn options.modelCapability ? enforceModelCapabilitySystemPromptBudget(result, options.modelCapability) : result;\n}\n\n/**\n * Build the system prompt with tools, guidelines, and context.\n *\n * CACHE-STABILITY INVARIANT: providers treat the returned string as ONE prompt-cache block (a\n * single cache breakpoint covering the whole system prompt). The caller (SystemPromptBuilder /\n * AgentSession, see `_rebuildSystemPrompt` in agent-session.ts) rebuilds it only when the TOOL\n * SURFACE changes — never per turn. For a fixed `options` (fixed tool surface, cwd, context\n * files, skills, extensions), two calls on the SAME CALENDAR DAY must return byte-identical\n * output, because `date` below is deliberately truncated to Y-M-D granularity. Do NOT widen it\n * to a timestamp (HH:MM:SS) or otherwise fold in any per-turn-volatile field (turn counters,\n * elapsed time, random ids, etc.) — that would cache-bust this entire block on EVERY turn instead\n * of once per calendar day, defeating provider prompt caching (cost + latency regression on every\n * request). Pinned by test/system-prompt-stability.test.ts.\n */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t} = options;\n\tconst resolvedCwd = cwd;\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\t// Day-granularity only (see cache-stability invariant on buildSystemPrompt above): this must\n\t// stay stable across every call within a calendar day, not just within a single turn.\n\tconst now = new Date();\n\tconst year = now.getFullYear();\n\tconst month = String(now.getMonth() + 1).padStart(2, \"0\");\n\tconst day = String(now.getDate()).padStart(2, \"0\");\n\tconst date = `${year}-${month}-${day}`;\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\tconst capabilityClass = options.modelCapability?.class ?? \"full\";\n\tconst fullPrompt = capabilityClass === \"full\";\n\tconst leanPrompt = capabilityClass === \"lean\";\n\n\tconst activeTools = selectedTools || [\"read\", \"bash\", \"python\", \"edit\", \"write\"];\n\tconst visibleTools = activeTools.filter((name) => !!toolSnippets?.[name]);\n\tconst hasRead = activeTools.includes(\"read\");\n\tconst coreSection = fullPrompt\n\t\t? PI_ADAPTATIVE_CORE_SECTION\n\t\t: leanPrompt\n\t\t\t? PI_ADAPTATIVE_LEAN_CORE_SECTION\n\t\t\t: capabilityClass === \"minimal\"\n\t\t\t\t? PI_ADAPTATIVE_MINIMAL_CORE_SECTION\n\t\t\t\t: PI_ADAPTATIVE_CHAT_CORE_SECTION;\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tprompt += coreSection;\n\t\treturn appendPromptResources(prompt, {\n\t\t\tappendSection,\n\t\t\tcontextFiles,\n\t\t\tskills,\n\t\t\textensions: options.extensions ?? [],\n\t\t\tvisibleTools,\n\t\t\tfullPrompt,\n\t\t\tleanPrompt,\n\t\t\thasRead,\n\t\t\tdate,\n\t\t\tpromptCwd,\n\t\t\tmodelCapability: options.modelCapability,\n\t\t});\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = activeTools.includes(\"bash\");\n\tconst hasPython = activeTools.includes(\"python\");\n\tconst hasPowerShell = activeTools.includes(\"powershell\");\n\tconst hasGrep = activeTools.includes(\"grep\");\n\tconst hasFind = activeTools.includes(\"find\");\n\tconst hasLs = activeTools.includes(\"ls\");\n\tconst hasReadOnlyTools = hasRead || hasGrep || hasFind || hasLs;\n\n\t// File exploration guidelines\n\tif (!fullPrompt && !leanPrompt) {\n\t\tif (hasPowerShell) addGuideline(\"Use powershell for Windows shell commands\");\n\t\telse if (hasBash) addGuideline(\"Use bash for bounded shell commands\");\n\t\tif (hasReadOnlyTools) addGuideline(\"Batch independent reads; keep mutations and dependent calls ordered\");\n\t} else if (hasPowerShell && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use powershell for shell commands on Windows; prefer rg for search and Get-ChildItem for listing\");\n\t} else if (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t}\n\tif (fullPrompt || leanPrompt) {\n\t\tif (hasBash || hasGrep || hasFind) {\n\t\t\taddGuideline(\n\t\t\t\t\"Use scoped rg to filter text and jq to project JSON: pass explicit roots and filters, inspect only selected records natively, and route unavoidable exhaustive output to a file\",\n\t\t\t);\n\t\t}\n\t\tif (hasPython) {\n\t\t\taddGuideline(\n\t\t\t\t\"Use python for bounded scripts and data shaping when clearer than shell; use read/edit/write for exact source edits\",\n\t\t\t);\n\t\t}\n\t\tif (hasReadOnlyTools) {\n\t\t\taddGuideline(\n\t\t\t\t\"Issue independent read-only tool calls together in one assistant turn. Keep dependent calls, mutations, and stateful commands ordered\",\n\t\t\t);\n\t\t}\n\t}\n\n\tif (fullPrompt || leanPrompt) {\n\t\tfor (const guideline of promptGuidelines ?? []) {\n\t\t\tconst normalized = guideline.trim();\n\t\t\tif (normalized.length > 0) {\n\t\t\t\taddGuideline(normalized);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\tconst toolGuidelinesSection = guidelines.length > 0 ? `\\n\\nTOOL GUIDELINES\\n\\n${guidelines}` : \"\";\n\n\tconst introduction = fullPrompt\n\t\t? \"You are Pi-Adaptative, a self-evolving assistant. Complete and deliver the user’s goals within granted authority; preserve continuity through compaction and own the integrated result.\"\n\t\t: leanPrompt\n\t\t\t? \"You are Pi-Adaptative's bounded coding agent. Complete the current goal with the active surface and preserve enough evidence for handoff.\"\n\t\t\t: capabilityClass === \"minimal\"\n\t\t\t\t? \"You are Pi-Adaptative's focused coding executor. Complete one scoped task with active tools and report verified results.\"\n\t\t\t\t: \"You are Pi-Adaptative's concise chat assistant. No execution tools are active.\";\n\tconst toolSurfaceRule =\n\t\tfullPrompt || leanPrompt\n\t\t\t? \"Use only capabilities present in the active tool surface; others may exist in the environment.\"\n\t\t\t: \"Use only the active tool surface.\";\n\tlet prompt = `${introduction}\n\nAvailable tools:\n${toolsList}\n\n${toolSurfaceRule}${coreSection}${toolGuidelinesSection}`;\n\n\tif (fullPrompt) {\n\t\tprompt += `\n\nPI-ADAPTATIVE DOCUMENTATION\n\nOnly when asked about Pi-Adaptative, read the relevant files completely from:\n- Main documentation: ${readmePath}\n- Additional documentation: ${docsPath}\n- Examples: ${examplesPath}\n\nResolve \\`docs/...\\` and \\`examples/...\\` from those roots and follow relevant Markdown cross-references before implementing.`;\n\t}\n\n\treturn appendPromptResources(prompt, {\n\t\tappendSection,\n\t\tcontextFiles,\n\t\tskills,\n\t\textensions: options.extensions ?? [],\n\t\tvisibleTools,\n\t\tfullPrompt,\n\t\tleanPrompt,\n\t\thasRead,\n\t\tdate,\n\t\tpromptCwd,\n\t\tmodelCapability: options.modelCapability,\n\t});\n}\n\nfunction formatExtensionsForPrompt(extensions: Extension[], visibleTools: string[]): string {\n\tif (extensions.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\"\\n\\nThe following extensions are currently loaded and active:\", \"\", \"<active_extensions>\"];\n\tlet added = 0;\n\n\tfor (const ext of extensions) {\n\t\tconst name = getExtensionDisplayName(ext.path);\n\t\tconst description = getExtensionDescription(ext.path);\n\n\t\tconst tools = Array.from(ext.tools.keys()).filter((t) => visibleTools.includes(t));\n\t\tconst commands = Array.from(ext.commands.keys());\n\n\t\t// Skip extension listing if it has no visible tools, commands, or description\n\t\tif (tools.length === 0 && commands.length === 0 && !description) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlines.push(\" <extension>\");\n\t\tlines.push(` <name>${escapePromptXml(name)}</name>`);\n\t\tif (description) {\n\t\t\tlines.push(` <description>${escapePromptXml(description)}</description>`);\n\t\t}\n\t\tlines.push(` <path>${escapePromptXml(ext.path)}</path>`);\n\n\t\tif (tools.length > 0) {\n\t\t\tlines.push(` <registered_tools>${tools.map(escapePromptXml).join(\", \")}</registered_tools>`);\n\t\t}\n\t\tif (commands.length > 0) {\n\t\t\tlines.push(` <registered_commands>${commands.map(escapePromptXml).join(\", \")}</registered_commands>`);\n\t\t}\n\t\tlines.push(\" </extension>\");\n\t\tadded++;\n\t}\n\n\tif (added === 0) {\n\t\treturn \"\";\n\t}\n\n\tlines.push(\"</active_extensions>\");\n\treturn lines.join(\"\\n\");\n}\n"]}
1
+ {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAE3F,OAAO,EAAE,wCAAwC,EAA+B,MAAM,uBAAuB,CAAC;AAC9G,OAAO,EAAE,eAAe,EAAE,M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C;IACT,CAAC;IAED,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC;QACjB,OAAO,EAAE,CAAC;IACX,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;IACnC,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.ts\";\nimport { getExtensionDescription, getExtensionDisplayName } from \"./extension-metadata.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport { enforceModelCapabilitySystemPromptBudget, type ModelCapabilityProfile } from \"./model-capability.ts\";\nimport { escapePromptXml } from \"./prompt-markup.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Capability profile that selects the stable prompt shape. Missing means full/legacy behavior. */\n\tmodelCapability?: Pick<ModelCapabilityProfile, \"class\" | \"contextWindow\" | \"reasonCode\" | \"systemPromptMaxChars\">;\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write, context_audit] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Eagerly loaded project/agent instruction files. */\n\tcontextFiles?: Array<{ path: string; content?: string }>;\n\t/** Discovered skills; startup prompt lists only lazy-loadable locations. */\n\tskills?: Skill[];\n\t/** Discovered extensions currently active. */\n\textensions?: Extension[];\n}\n\nconst PI_ADAPTATIVE_CORE_SECTION = `\n\nOPERATING POSTURE\n\n- Treat a clear outcome expressed in normal conversation as a goal; no slash command is required. Persist evidence and progress, survive compaction, and continue until delivered or stopped.\n- Hold scope. Verify uncertainty from authoritative sources; use the simplest proven design that satisfies ownership, lifecycle, performance, and failure needs.\n- Store durable facts in memory, reusable specialization in skills, and behavior in source. Shard and index oversized memory; discard noise.\n- Choose autonomously; create recursive agents for coherent parallel work while the root owns integration and the scheduler owns global budgets and concurrency.\n- The user’s desired outcome is authoritative; a proposed method is not. If a method may undermine the outcome, pause: give causal evidence, test the disputed premise when practical, and offer the strongest outcome-preserving alternative. Once chosen, execute faithfully within authority.\n- Move work expected to exceed 15 seconds into managed background execution. Require event-driven completion, a bounded handoff, and owner notification; never poll.\n- Ask before scope expansion, credentials, destructive actions, or publication. Keep external and tool output bounded, source-labeled, and evidence-focused; show file paths clearly.\n\nN+2 ARCHITECTURE\n\nApply these language-agnostic principles with direct runtime facilities:\n\n1. Group Lifetimes: Put overlapping lifetimes in bounded arenas, pools, rings, chunks, or flat owners; recycle in batches and avoid per-item churn.\n\n2. Valid Defaults: Make zero/default data, handles, states, and resources safe without hidden allocation; one system owns activation.\n\n3. Stubs and Boundaries: Validate trust and external boundaries once. Internal misses return benign stubs, sentinels, or defaults; external failures stay explicit.\n\n4. Flat Ownership: Prefer flat/chunked data, stable IDs, compact indexes, buffers, and batches over pointer graphs, needless dispatch, fallbacks, or wrappers.\n\n5. Linear Bounds: Never concatenate growing prefixes, prepend repeatedly, rescan consumed input, serialize unchanged history, or rebuild full incremental state. Materialize only the needed window once.\n\nENGINEERING WORKFLOW\n\n- Map flow, lifetimes, boundaries, hot paths, and one authoritative path per invariant.\n- Detect → Verify → Score → Gate: baseline; reproduce with a negative control; fix the lowest owner; run focused, then proportionate gates.\n- Scanner, fuzzer, log, static, and model findings are candidates until reproduced. Never weaken tests or claim success from incomplete probes.`;\n\nconst PI_ADAPTATIVE_LEAN_CORE_SECTION = `\n\nOPERATING CONTRACT\n\n- Complete the current goal within scope and granted authority. Keep progress and evidence concise.\n- Inspect relevant files and project instructions before mutation. Make the smallest coherent change and verify it with focused checks.\n- Use only active tools and follow their schemas exactly. When a call fails, use the returned error and expected shape to correct it; never repeat an unchanged failed call.\n- Keep independent reads together and mutations ordered. Report real output and unresolved failures.\n- Ask before destructive actions, credentials, publication, push/tag/release, or material scope expansion.`;\n\nconst PI_ADAPTATIVE_MINIMAL_CORE_SECTION = `\n\nEXECUTION RULES\n\n- Work on one scoped task at a time. Inspect before editing, make a small coherent change, then run the narrowest useful verification.\n- Use only listed tools and exact schemas. If a tool call fails, read the returned error and expected shape, correct the call, and do not repeat it unchanged.\n- Keep independent reads together and mutations ordered. Report actual results; never claim an action you did not complete.\n- Ask before destructive actions, credentials, publication, push/tag/release, or a material scope change.`;\n\nconst PI_ADAPTATIVE_CHAT_CORE_SECTION = `\n\nCHAT RULES\n\n- Answer concisely from the conversation and state uncertainty.\n- No execution tools are active. Do not claim to read files, run commands, or make changes.\n- Say when the request requires a tool-capable model or additional user-provided context.`;\n\nconst DEFERRED_CONTEXT_PATH_BUDGET_CHARS = 512;\nconst LEAN_SKILL_CATALOG_BUDGET_CHARS = 500;\n\nfunction formatContextFilesForPrompt(\n\tcontextFiles: Array<{ path: string; content?: string }>,\n\toptions: { deferContents: boolean; canRead: boolean },\n): string {\n\tif (contextFiles.length === 0) {\n\t\treturn \"\";\n\t}\n\tif (options.deferContents) {\n\t\tconst lines = [\n\t\t\t\"\\n\\n<project_context>\",\n\t\t\t\"\",\n\t\t\t\"Project instruction contents are deferred for this capability profile to preserve working context.\",\n\t\t\toptions.canRead\n\t\t\t\t? \"Before editing, writing, or running a mutating command, read each relevant listed file completely before any mutation. Follow its instructions; if a file cannot fit, ask for a scoped instruction digest.\"\n\t\t\t\t: \"No read tool is active. Ask the user for the relevant project instructions before giving project-specific guidance.\",\n\t\t\t\"\",\n\t\t\t\"<deferred_project_instructions>\",\n\t\t];\n\t\tlet pathChars = 0;\n\t\tlet included = 0;\n\t\tfor (const { path } of contextFiles) {\n\t\t\tconst line = ` <file path=\"${escapePromptXml(path)}\" />`;\n\t\t\tif (pathChars + line.length > DEFERRED_CONTEXT_PATH_BUDGET_CHARS) break;\n\t\t\tlines.push(line);\n\t\t\tpathChars += line.length + 1;\n\t\t\tincluded++;\n\t\t}\n\t\tconst omitted = contextFiles.length - included;\n\t\tif (omitted > 0) {\n\t\t\tlines.push(` <omitted count=\"${omitted}\" />`);\n\t\t}\n\t\tlines.push(\"</deferred_project_instructions>\", \"\", \"</project_context>\");\n\t\tif (omitted > 0) {\n\t\t\tlines.push(\n\t\t\t\t\"Do not mutate until the omitted instruction paths are supplied or a more capable profile is used.\",\n\t\t\t);\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tconst lines = [\"\\n\\n<project_context>\", \"\", \"Project-specific instructions and guidelines:\", \"\"];\n\n\tfor (const { path, content } of contextFiles) {\n\t\tlines.push(`<project_instructions path=\"${escapePromptXml(path)}\">`);\n\t\tlines.push(content ?? \"\");\n\t\tlines.push(\"</project_instructions>\", \"\");\n\t}\n\n\tlines.push(\"</project_context>\");\n\treturn lines.join(\"\\n\");\n}\n\nfunction formatLeanSkillsForPrompt(skills: Skill[]): string {\n\tconst eligibleSkills = skills.filter((skill) => !skill.disableModelInvocation);\n\tif (eligibleSkills.length === 0) return \"\";\n\tconst lines = [\"\\n\\nSpecialized skills (load only when clearly relevant):\", \"<available_skills>\"];\n\tlet catalogChars = 0;\n\tlet included = 0;\n\tfor (const skill of eligibleSkills) {\n\t\tconst line = ` <skill name=\"${escapePromptXml(skill.name)}\" location=\"${escapePromptXml(skill.filePath)}\">${escapePromptXml(skill.description.slice(0, 120))}</skill>`;\n\t\tif (catalogChars + line.length > LEAN_SKILL_CATALOG_BUDGET_CHARS) break;\n\t\tlines.push(line);\n\t\tcatalogChars += line.length + 1;\n\t\tincluded++;\n\t}\n\tlines.push(\"</available_skills>\");\n\tconst omitted = eligibleSkills.length - included;\n\tif (omitted > 0) lines.push(`${omitted} additional skill(s) are not preloaded on this profile.`);\n\treturn lines.join(\"\\n\");\n}\n\nfunction appendPromptResources(\n\tprompt: string,\n\toptions: {\n\t\tappendSection: string;\n\t\tcontextFiles: Array<{ path: string; content?: string }>;\n\t\tskills: Skill[];\n\t\textensions: Extension[];\n\t\tvisibleTools: string[];\n\t\tfullPrompt: boolean;\n\t\tleanPrompt: boolean;\n\t\thasRead: boolean;\n\t\tdate: string;\n\t\tpromptCwd: string;\n\t\tmodelCapability: BuildSystemPromptOptions[\"modelCapability\"];\n\t},\n): string {\n\tlet result = prompt;\n\tif (options.appendSection) result += options.appendSection;\n\tresult += formatContextFilesForPrompt(options.contextFiles, {\n\t\tdeferContents: !options.fullPrompt,\n\t\tcanRead: options.hasRead,\n\t});\n\tif (options.hasRead && options.skills.length > 0) {\n\t\tif (options.fullPrompt) result += formatSkillsForPrompt(options.skills);\n\t\telse if (options.leanPrompt) result += formatLeanSkillsForPrompt(options.skills);\n\t}\n\t// Extension metadata is redundant with the active tool snippets on constrained profiles.\n\tif (options.fullPrompt && options.extensions.length > 0) {\n\t\tresult += formatExtensionsForPrompt(options.extensions, options.visibleTools);\n\t}\n\t// Day-granularity only; keep this tail stable across every call on the same calendar day.\n\tresult += `\\nCurrent date: ${options.date}`;\n\tresult += `\\nCurrent working directory: ${options.promptCwd}`;\n\treturn options.modelCapability ? enforceModelCapabilitySystemPromptBudget(result, options.modelCapability) : result;\n}\n\n/**\n * Build the system prompt with tools, guidelines, and context.\n *\n * CACHE-STABILITY INVARIANT: providers treat the returned string as ONE prompt-cache block (a\n * single cache breakpoint covering the whole system prompt). The caller (SystemPromptBuilder /\n * AgentSession, see `_rebuildSystemPrompt` in agent-session.ts) rebuilds it only when the TOOL\n * SURFACE changes — never per turn. For a fixed `options` (fixed tool surface, cwd, context\n * files, skills, extensions), two calls on the SAME CALENDAR DAY must return byte-identical\n * output, because `date` below is deliberately truncated to Y-M-D granularity. Do NOT widen it\n * to a timestamp (HH:MM:SS) or otherwise fold in any per-turn-volatile field (turn counters,\n * elapsed time, random ids, etc.) — that would cache-bust this entire block on EVERY turn instead\n * of once per calendar day, defeating provider prompt caching (cost + latency regression on every\n * request). Pinned by test/system-prompt-stability.test.ts.\n */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t} = options;\n\tconst resolvedCwd = cwd;\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\t// Day-granularity only (see cache-stability invariant on buildSystemPrompt above): this must\n\t// stay stable across every call within a calendar day, not just within a single turn.\n\tconst now = new Date();\n\tconst year = now.getFullYear();\n\tconst month = String(now.getMonth() + 1).padStart(2, \"0\");\n\tconst day = String(now.getDate()).padStart(2, \"0\");\n\tconst date = `${year}-${month}-${day}`;\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\tconst capabilityClass = options.modelCapability?.class ?? \"full\";\n\tconst fullPrompt = capabilityClass === \"full\";\n\tconst leanPrompt = capabilityClass === \"lean\";\n\n\tconst activeTools = selectedTools || [\"read\", \"bash\", \"python\", \"edit\", \"write\"];\n\tconst visibleTools = activeTools.filter((name) => !!toolSnippets?.[name]);\n\tconst hasRead = activeTools.includes(\"read\");\n\tconst coreSection = fullPrompt\n\t\t? PI_ADAPTATIVE_CORE_SECTION\n\t\t: leanPrompt\n\t\t\t? PI_ADAPTATIVE_LEAN_CORE_SECTION\n\t\t\t: capabilityClass === \"minimal\"\n\t\t\t\t? PI_ADAPTATIVE_MINIMAL_CORE_SECTION\n\t\t\t\t: PI_ADAPTATIVE_CHAT_CORE_SECTION;\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tprompt += coreSection;\n\t\treturn appendPromptResources(prompt, {\n\t\t\tappendSection,\n\t\t\tcontextFiles,\n\t\t\tskills,\n\t\t\textensions: options.extensions ?? [],\n\t\t\tvisibleTools,\n\t\t\tfullPrompt,\n\t\t\tleanPrompt,\n\t\t\thasRead,\n\t\t\tdate,\n\t\t\tpromptCwd,\n\t\t\tmodelCapability: options.modelCapability,\n\t\t});\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = activeTools.includes(\"bash\");\n\tconst hasPython = activeTools.includes(\"python\");\n\tconst hasGrep = activeTools.includes(\"grep\");\n\tconst hasFind = activeTools.includes(\"find\");\n\tconst hasLs = activeTools.includes(\"ls\");\n\tconst hasReadOnlyTools = hasRead || hasGrep || hasFind || hasLs;\n\n\t// File exploration guidelines\n\tif (!fullPrompt && !leanPrompt) {\n\t\tif (hasBash) addGuideline(\"Use bash for bounded shell commands\");\n\t\tif (hasReadOnlyTools) addGuideline(\"Batch independent reads; keep mutations and dependent calls ordered\");\n\t} else if (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t}\n\tif (fullPrompt || leanPrompt) {\n\t\tif (hasBash || hasGrep || hasFind) {\n\t\t\taddGuideline(\n\t\t\t\t\"Use scoped rg to filter text and jq to project JSON: pass explicit roots and filters, inspect only selected records natively, and route unavoidable exhaustive output to a file\",\n\t\t\t);\n\t\t}\n\t\tif (hasPython) {\n\t\t\taddGuideline(\n\t\t\t\t\"Use python for bounded scripts and data shaping when clearer than shell; use read/edit/write for exact source edits\",\n\t\t\t);\n\t\t}\n\t\tif (hasReadOnlyTools) {\n\t\t\taddGuideline(\n\t\t\t\t\"Issue independent read-only tool calls together in one assistant turn. Keep dependent calls, mutations, and stateful commands ordered\",\n\t\t\t);\n\t\t}\n\t}\n\n\tif (fullPrompt || leanPrompt) {\n\t\tfor (const guideline of promptGuidelines ?? []) {\n\t\t\tconst normalized = guideline.trim();\n\t\t\tif (normalized.length > 0) {\n\t\t\t\taddGuideline(normalized);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\tconst toolGuidelinesSection = guidelines.length > 0 ? `\\n\\nTOOL GUIDELINES\\n\\n${guidelines}` : \"\";\n\n\tconst introduction = fullPrompt\n\t\t? \"You are Pi-Adaptative, a self-evolving assistant. Complete and deliver the user’s goals within granted authority; preserve continuity through compaction and own the integrated result.\"\n\t\t: leanPrompt\n\t\t\t? \"You are Pi-Adaptative's bounded coding agent. Complete the current goal with the active surface and preserve enough evidence for handoff.\"\n\t\t\t: capabilityClass === \"minimal\"\n\t\t\t\t? \"You are Pi-Adaptative's focused coding executor. Complete one scoped task with active tools and report verified results.\"\n\t\t\t\t: \"You are Pi-Adaptative's concise chat assistant. No execution tools are active.\";\n\tconst toolSurfaceRule =\n\t\tfullPrompt || leanPrompt\n\t\t\t? \"Use only capabilities present in the active tool surface; others may exist in the environment.\"\n\t\t\t: \"Use only the active tool surface.\";\n\tlet prompt = `${introduction}\n\nAvailable tools:\n${toolsList}\n\n${toolSurfaceRule}${coreSection}${toolGuidelinesSection}`;\n\n\tif (fullPrompt) {\n\t\tprompt += `\n\nPI-ADAPTATIVE DOCUMENTATION\n\nOnly when asked about Pi-Adaptative, read the relevant files completely from:\n- Main documentation: ${readmePath}\n- Additional documentation: ${docsPath}\n- Examples: ${examplesPath}\n\nResolve \\`docs/...\\` and \\`examples/...\\` from those roots and follow relevant Markdown cross-references before implementing.`;\n\t}\n\n\treturn appendPromptResources(prompt, {\n\t\tappendSection,\n\t\tcontextFiles,\n\t\tskills,\n\t\textensions: options.extensions ?? [],\n\t\tvisibleTools,\n\t\tfullPrompt,\n\t\tleanPrompt,\n\t\thasRead,\n\t\tdate,\n\t\tpromptCwd,\n\t\tmodelCapability: options.modelCapability,\n\t});\n}\n\nfunction formatExtensionsForPrompt(extensions: Extension[], visibleTools: string[]): string {\n\tif (extensions.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\"\\n\\nThe following extensions are currently loaded and active:\", \"\", \"<active_extensions>\"];\n\tlet added = 0;\n\n\tfor (const ext of extensions) {\n\t\tconst name = getExtensionDisplayName(ext.path);\n\t\tconst description = getExtensionDescription(ext.path);\n\n\t\tconst tools = Array.from(ext.tools.keys()).filter((t) => visibleTools.includes(t));\n\t\tconst commands = Array.from(ext.commands.keys());\n\n\t\t// Skip extension listing if it has no visible tools, commands, or description\n\t\tif (tools.length === 0 && commands.length === 0 && !description) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlines.push(\" <extension>\");\n\t\tlines.push(` <name>${escapePromptXml(name)}</name>`);\n\t\tif (description) {\n\t\t\tlines.push(` <description>${escapePromptXml(description)}</description>`);\n\t\t}\n\t\tlines.push(` <path>${escapePromptXml(ext.path)}</path>`);\n\n\t\tif (tools.length > 0) {\n\t\t\tlines.push(` <registered_tools>${tools.map(escapePromptXml).join(\", \")}</registered_tools>`);\n\t\t}\n\t\tif (commands.length > 0) {\n\t\t\tlines.push(` <registered_commands>${commands.map(escapePromptXml).join(\", \")}</registered_commands>`);\n\t\t}\n\t\tlines.push(\" </extension>\");\n\t\tadded++;\n\t}\n\n\tif (added === 0) {\n\t\treturn \"\";\n\t}\n\n\tlines.push(\"</active_extensions>\");\n\treturn lines.join(\"\\n\");\n}\n"]}
@@ -16,23 +16,14 @@ declare const delegateSchema: Type.TObject<{
16
16
  modelId: Type.TString;
17
17
  }>>;
18
18
  thinkingLevel: Type.TOptional<Type.TUnion<Type.TLiteral<"high" | "low" | "max" | "medium" | "minimal" | "off" | "ultra" | "xhigh">[]>>;
19
- capabilities: Type.TOptional<Type.TArray<Type.TUnion<Type.TLiteral<"credentials.use" | "filesystem.read" | "filesystem.write" | "learning.propose" | "memory.mutate" | "memory.query" | "network.http" | "policy.modify" | "process.exec" | "publish.execute" | "research.execute" | "service.mcp" | "settings.read" | "settings.write" | "skill.read" | "skill.write" | "source.read" | "source.write" | "tests.execute" | "workflow.delegate" | "workflow.plan" | "worktree.mutate" | "worktree.read">[]>>>;
20
19
  toolNames: Type.TOptional<Type.TArray<Type.TString>>;
21
- readPaths: Type.TOptional<Type.TArray<Type.TString>>;
22
- writePaths: Type.TOptional<Type.TArray<Type.TString>>;
23
- budget: Type.TOptional<Type.TObject<{
24
- maxTokens: Type.TOptional<Type.TInteger>;
25
- maxWallClockMs: Type.TOptional<Type.TInteger>;
26
- maxCostUsd: Type.TOptional<Type.TNumber>;
27
- maxAttempts: Type.TOptional<Type.TInteger>;
28
- maxToolCalls: Type.TOptional<Type.TInteger>;
29
- requireApprovalAboveCostUsd: Type.TOptional<Type.TNumber>;
30
- }>>;
31
20
  }>>;
32
21
  instructions: Type.TOptional<Type.TString>;
33
22
  agentId: Type.TOptional<Type.TString>;
34
23
  agentIds: Type.TOptional<Type.TArray<Type.TString>>;
35
24
  dependsOn: Type.TOptional<Type.TArray<Type.TString>>;
25
+ requirementId: Type.TOptional<Type.TString>;
26
+ requirementIds: Type.TOptional<Type.TArray<Type.TString>>;
36
27
  forkTurns: Type.TOptional<Type.TString>;
37
28
  mode: Type.TOptional<Type.TUnion<[Type.TLiteral<"any">, Type.TLiteral<"all">]>>;
38
29
  message: Type.TOptional<Type.TString>;