@sema-agent/core 5.22.0 → 5.24.0

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 (59) hide show
  1. package/CHANGELOG.md +169 -1
  2. package/dist/agents/subagent.js +3 -2
  3. package/dist/core/checkpoint-store.d.ts +38 -3
  4. package/dist/core/checkpoint-store.js +2 -1
  5. package/dist/core/governance-codes.js +3 -0
  6. package/dist/core/hooks.d.ts +69 -2
  7. package/dist/core/hooks.js +100 -15
  8. package/dist/core/memory-engine/engine.d.ts +28 -1
  9. package/dist/core/memory-engine/engine.js +62 -3
  10. package/dist/core/memory-engine/index.d.ts +1 -1
  11. package/dist/core/memory-engine/index.js +1 -1
  12. package/dist/core/memory-engine/layout.d.ts +69 -3
  13. package/dist/core/memory-engine/layout.js +75 -6
  14. package/dist/core/permission-rule-consent.js +2 -1
  15. package/dist/core/permission-rule-org.d.ts +36 -2
  16. package/dist/core/permission-rule-org.js +23 -0
  17. package/dist/core/permission-rule-store.d.ts +25 -14
  18. package/dist/core/permission-rule-store.js +7 -2
  19. package/dist/core/permission-rule-sync.d.ts +8 -0
  20. package/dist/core/permission-rule-sync.js +35 -6
  21. package/dist/core/runner/prepare-task.d.ts +10 -2
  22. package/dist/core/runner/prepare-task.js +120 -11
  23. package/dist/core/runner/runtask.js +46 -1
  24. package/dist/core/runner/session-file-state-replay.js +3 -0
  25. package/dist/core/tool-policy.d.ts +37 -4
  26. package/dist/core/tool-policy.js +49 -19
  27. package/dist/core/tool-result-store.d.ts +17 -1
  28. package/dist/core/tool-result-store.js +79 -4
  29. package/dist/core/trace.d.ts +47 -0
  30. package/dist/core/types.d.ts +45 -5
  31. package/dist/core/wiring-manifest.d.ts +16 -1
  32. package/dist/core/wiring-manifest.js +7 -1
  33. package/dist/index.d.ts +18 -10
  34. package/dist/index.js +5 -3
  35. package/dist/orchestration/goal.d.ts +10 -0
  36. package/dist/orchestration/goal.js +6 -5
  37. package/dist/stores/file/adoption/adopt.d.ts +146 -0
  38. package/dist/stores/file/adoption/adopt.js +611 -0
  39. package/dist/stores/file/adoption/marker.d.ts +202 -0
  40. package/dist/stores/file/adoption/marker.js +205 -0
  41. package/dist/stores/file/background-agent-store.js +2 -0
  42. package/dist/stores/file/checkpoint-store.js +2 -0
  43. package/dist/stores/file/file-snapshot-store.js +2 -0
  44. package/dist/stores/file/index.d.ts +2 -0
  45. package/dist/stores/file/index.js +4 -0
  46. package/dist/stores/file/mailbox-store.js +2 -0
  47. package/dist/stores/file/memory-store.js +2 -0
  48. package/dist/stores/file/session-policy-store.d.ts +11 -1
  49. package/dist/stores/file/session-policy-store.js +9 -2
  50. package/dist/stores/file/session-store.js +2 -0
  51. package/dist/stores/file/task-list-store.js +2 -0
  52. package/dist/stores/file/tool-result-store.js +2 -0
  53. package/dist/stores/file/usage-window-store.js +2 -0
  54. package/dist/stores/file/workflow-journal-store.js +2 -0
  55. package/dist/stores/file/workflow-run-store.js +2 -0
  56. package/dist/tools/fs/bash-readonly-classifier.js +59 -10
  57. package/dist/tools/fs/fs-bash.js +7 -4
  58. package/dist/tools/monitor.js +3 -3
  59. package/package.json +3 -2
@@ -213,7 +213,15 @@ export declare function firstPartyOffloadPolicy(toolName: string): {
213
213
  };
214
214
  /** Head+tail preview of an offloaded result, pointing at {@link OFFLOAD_TOOL_NAME} via `ref`. Exported so
215
215
  * the per-message aggregate budget (design/64 §17.2) produces the SAME preview format (deterministic →
216
- * byte-identical across queries → prompt-cache safe). */
216
+ * byte-identical across queries → prompt-cache safe).
217
+ *
218
+ * #115 (2026-08-09) — the truncation line states WHERE the rest is, not what anyone can do with it.
219
+ * "read more" alone reads as a promise that the full output is retrievable, and the model relays that
220
+ * promise to the person it is talking to; what is actually guaranteed is narrower and exactly two
221
+ * things: the text is retained in this run's tool-result store, and THIS chain can page it back. A
222
+ * host-side read face (an HTTP route that hands the user the whole output) is a separate deployment
223
+ * feature that may or may not exist — so the line names it as a deployment fact instead of implying
224
+ * it, and the model can answer "can I get the full log?" without guessing. */
217
225
  export declare function buildPreview(full: string, ref: string, sizes?: {
218
226
  head: number;
219
227
  tail: number;
@@ -232,5 +240,13 @@ export declare function withToolResultOffload(tool: AgentTool, store: ToolResult
232
240
  * ⇒ byte-identical historic preview. An accessor (not a snapshot) because the wrap happens at
233
241
  * prepare time, before the deferred classification exists and before any activation can. */
234
242
  reachableTools?: () => ReadonlySet<string> | undefined): AgentTool;
243
+ /** The machine-recognizable start of an offloaded-detail replacement notice. Exported for consumers
244
+ * that treat a `details` string as SEMANTIC INPUT (not display) — e.g. the session-continuation
245
+ * read-state replay — so they can tell "this member was offloaded, the bytes here are a preview"
246
+ * and degrade honestly instead of consuming preview bytes as the real value. */
247
+ export declare const OFFLOADED_DETAIL_NOTICE_PREFIX = "\u2026[offloaded \u2014 ";
248
+ /** True when `s` carries an offloaded-detail replacement notice (the newline-anchored prefix form the
249
+ * walk emits). A semantic consumer treats such a string as NOT the member's real bytes. */
250
+ export declare function isOffloadedDetailReplacement(s: string): boolean;
235
251
  /** The injected `read_tool_result` tool: pages through an offloaded result. `effect:"read"` (verifier/reconcile-safe). */
236
252
  export declare function createReadToolResultTool(store: ToolResultStore): AgentTool;
@@ -121,6 +121,8 @@ export function firstPartyOffloadPolicy(toolName) {
121
121
  switch (toolName) {
122
122
  case "Read":
123
123
  return { offload: false };
124
+ case "Write":
125
+ return { offload: false };
124
126
  case "Bash":
125
127
  return { offloadThresholdChars: 30_000 };
126
128
  case "Grep":
@@ -154,7 +156,8 @@ export function buildPreview(full, ref, sizes, reachableTools) {
154
156
  const tail = full.slice(tailStart);
155
157
  return (`${PERSISTED_OUTPUT_PREFIX}"${ref}" chars="${total}">\n` +
156
158
  `${head}\n` +
157
- `…[truncated — ${total} chars total. ${offloadPagebackHint(ref, "preview", reachableTools)}]\n` +
159
+ `…[truncated — ${total} chars total, retained in this run's tool-result store; a user-facing read face is a deployment fact. ` +
160
+ `${offloadPagebackHint(ref, "preview", reachableTools)}]\n` +
158
161
  `${tail}\n` +
159
162
  `</persisted-output>`);
160
163
  }
@@ -163,21 +166,93 @@ export function withToolResultOffload(tool, store, thresholdChars, sessionId, re
163
166
  return tool;
164
167
  const wrappedExecute = async (toolCallId, params, signal, onUpdate) => {
165
168
  const res = await tool.execute(toolCallId, params, signal, onUpdate);
169
+ const offloadedDetails = res.details === undefined ? undefined : await offloadOversizedDetailStrings(res.details, store, thresholdChars, sessionId, toolCallId);
170
+ const withDetails = (r) => offloadedDetails === undefined || offloadedDetails.value === res.details ? r : { ...r, details: offloadedDetails.value };
166
171
  if (totalTextChars(res.content) <= thresholdChars)
167
- return res;
172
+ return withDetails(res);
168
173
  const full = res.content
169
174
  .filter((b) => b.type === "text")
170
175
  .map((b) => b.text)
171
176
  .join("\n");
172
177
  if (full.length <= PREVIEW_HEAD_CHARS + PREVIEW_TAIL_CHARS)
173
- return res;
178
+ return withDetails(res);
174
179
  const ref = buildToolResultRef(sessionId, toolCallId);
175
180
  await store.put(ref, full);
176
181
  const images = res.content.filter((b) => b.type !== "text");
177
- return { ...res, content: [{ type: "text", text: buildPreview(full, ref, undefined, reachableTools?.()) }, ...images] };
182
+ return withDetails({ ...res, content: [{ type: "text", text: buildPreview(full, ref, undefined, reachableTools?.()) }, ...images] });
178
183
  };
179
184
  return { ...tool, execute: wrappedExecute };
180
185
  }
186
+ const OFFLOADED_DETAIL_HEAD_CHARS = 2_000;
187
+ const OFFLOADED_DETAIL_NOTICE_ALLOWANCE_CHARS = 400;
188
+ export const OFFLOADED_DETAIL_NOTICE_PREFIX = "…[offloaded — ";
189
+ export function isOffloadedDetailReplacement(s) {
190
+ return s.includes(`\n${OFFLOADED_DETAIL_NOTICE_PREFIX}`);
191
+ }
192
+ async function offloadOversizedDetailStrings(details, store, thresholdChars, sessionId, toolCallId) {
193
+ const puts = [];
194
+ const onStack = new Set();
195
+ const isPlainObject = (v) => {
196
+ if (typeof v !== "object" || v === null)
197
+ return false;
198
+ const p = Object.getPrototypeOf(v);
199
+ return p === Object.prototype || p === null;
200
+ };
201
+ const replace = (full, path) => {
202
+ const detailRef = buildToolResultRef(sessionId, toolCallId + " " + path);
203
+ puts.push(Promise.resolve(store.put(detailRef, full)));
204
+ return (`${full.slice(0, OFFLOADED_DETAIL_HEAD_CHARS)}\n` +
205
+ `${OFFLOADED_DETAIL_NOTICE_PREFIX}${full.length} chars total; ref "${detailRef}"; the remainder is retained in this run's tool-result store and reads back through the deployment's tool-results face]`);
206
+ };
207
+ const memo = new Map();
208
+ const walk = (v, segs) => {
209
+ if (typeof v === "string")
210
+ return v.length > thresholdChars && v.length > OFFLOADED_DETAIL_HEAD_CHARS + OFFLOADED_DETAIL_NOTICE_ALLOWANCE_CHARS ? replace(v, JSON.stringify(segs)) : v;
211
+ if (Array.isArray(v)) {
212
+ if (onStack.has(v))
213
+ return v;
214
+ const done = memo.get(v);
215
+ if (done !== undefined)
216
+ return done;
217
+ onStack.add(v);
218
+ let changed = false;
219
+ const next = v.map((item, i) => {
220
+ const w = walk(item, [...segs, i]);
221
+ if (w !== item)
222
+ changed = true;
223
+ return w;
224
+ });
225
+ onStack.delete(v);
226
+ const result = changed ? next : v;
227
+ memo.set(v, result);
228
+ return result;
229
+ }
230
+ if (isPlainObject(v)) {
231
+ if (onStack.has(v))
232
+ return v;
233
+ const done = memo.get(v);
234
+ if (done !== undefined)
235
+ return done;
236
+ onStack.add(v);
237
+ let changed = false;
238
+ const next = {};
239
+ for (const [k, item] of Object.entries(v)) {
240
+ const w = walk(item, [...segs, k]);
241
+ if (w !== item)
242
+ changed = true;
243
+ Object.defineProperty(next, k, { value: w, enumerable: true, writable: true, configurable: true });
244
+ }
245
+ onStack.delete(v);
246
+ const result = changed ? next : v;
247
+ memo.set(v, result);
248
+ return result;
249
+ }
250
+ return v;
251
+ };
252
+ const value = walk(details, []);
253
+ await Promise.all(puts);
254
+ return { value };
255
+ }
181
256
  export function createReadToolResultTool(store) {
182
257
  return defineTool({
183
258
  name: OFFLOAD_TOOL_NAME,
@@ -382,6 +382,53 @@ export type TraceEvent = {
382
382
  taskId: string;
383
383
  message: string;
384
384
  ts: number;
385
+ } | {
386
+ /**
387
+ * design/182 §4.6 — a cloud-sync round moved a (rule, scope) from REMOVED back to LIVE: another
388
+ * replica's add outlived the local tombstone (add-wins is the locked merge semantic, so the
389
+ * transition itself is not news — its VISIBILITY is). The person who deleted the rule has to be
390
+ * able to learn that it came back, and to delete it again. Metadata only: the canonical rule
391
+ * text and the scope KIND — a project scope's root path stays out of the trace.
392
+ */
393
+ kind: "permission.rule_sync_resurrected";
394
+ version: 1;
395
+ /** The bucket this round synced. A local-owner bucket cannot sync, so this is always a principal. */
396
+ principal: string;
397
+ rule: string;
398
+ scopeKind: "global" | "project";
399
+ ts: number;
400
+ } | {
401
+ /**
402
+ * design/182 §4.3/§5.2 — a cloud-sync round REFUSED an inbound row, or quarantined a local one.
403
+ * The reason is a closed code from the governance-codes family (never free text): the machine
404
+ * reads the table. One event per dropped row — a silently refused row is indistinguishable from
405
+ * a row that never existed, which is the failure this event exists to prevent.
406
+ */
407
+ kind: "permission.rule_sync_dropped";
408
+ version: 1;
409
+ principal: string;
410
+ rule: string;
411
+ scopeKind: "global" | "project";
412
+ /** Closed reason code ({@link import("./governance-codes.js").RuleSyncDropReason}). */
413
+ reason: string;
414
+ ts: number;
415
+ } | {
416
+ /**
417
+ * design/182 §7.4 — an org-governed deployment could NOT adjudicate against an org snapshot
418
+ * (never installed, provider failed past the staleness bound, or the persisted state was
419
+ * refused). The gate answered by failing the WHOLE decision boundary closed: every terminal
420
+ * allow became a real-approval ask. This is the operator-facing half of that tighten — the
421
+ * deployment is paying the "ask about everything" price and has to be able to see why.
422
+ */
423
+ kind: "permission.org_snapshot_unavailable";
424
+ version: 1;
425
+ taskId: string;
426
+ toolName: string;
427
+ toolCallId: string;
428
+ /** The overlay's own disclosure lines (deployment-authored/engine-authored, never model text),
429
+ * joined — provider failure, refused snapshot, rollback refusal, missing durable persistence. */
430
+ message: string;
431
+ ts: number;
385
432
  } | {
386
433
  /**
387
434
  * F-012 L2 — a pending ask was AUTO-ADMITTED by the sandbox-admission leg: the deployment's
@@ -4188,11 +4188,13 @@ export interface RunnerDeps {
4188
4188
  * they confirmed once is not asked about again.
4189
4189
  *
4190
4190
  * This is the one seam in this file that LOOSENS, and it is shaped so it can only do so within limits
4191
- * the engine holds. The provider hands out a READ face anchored to one verified principal; the write
4192
- * face is core-private, so a deployment has no API path to put a rule in — that goes through the
4193
- * approval-record protocol, which requires a confirmed human decision. Rules are consumed post-fold, in
4194
- * the gate's ask branch, and never resolve an ask carrying `requiresRealApproval` or one a PreToolUse
4195
- * hook raised.
4191
+ * the engine holds. The provider hands out a READ face anchored to one verified principal. The write
4192
+ * face is an exported BACKEND CONTRACT (ruled 2026-08-10: an out-of-repo store twin builds against the
4193
+ * same definitions instead of mirroring them), but the ENGINE reaches it only on the consent lanes
4194
+ * redemption of a confirmed human decision, the tighten-delete, and the sync join a wiring invariant
4195
+ * pinned by a registered-caller scan (test/permission-rule-writer-callers); no exported convenience
4196
+ * mints a rule around consent. Rules are consumed post-fold, in the gate's ask branch, and never
4197
+ * resolve an ask carrying `requiresRealApproval` or one a PreToolUse hook raised.
4196
4198
  *
4197
4199
  * Omitted ⇒ the lane does not exist: no rules are read, no field is added to any ask, and the decision
4198
4200
  * path is byte-identical to a build without it. An unauthenticated task (no `principal`) resolves to
@@ -4200,6 +4202,44 @@ export interface RunnerDeps {
4200
4202
  * disclosure — a loosening face fails toward asking.
4201
4203
  */
4202
4204
  permissionRuleStore?: import("./permission-rule-store.js").PermissionRuleStoreProvider;
4205
+ /**
4206
+ * design/182 §4.5 (F-011) — declare that this deployment keeps its permission rules in the
4207
+ * IDENTITY-LESS local bucket: a task with no `principal` resolves rules through the provider's
4208
+ * `forLocalOwner()` face instead of resolving to zero rules.
4209
+ *
4210
+ * A DECLARATION, never an inference (same rule as {@link permissionRuleOrg}): the local bucket is
4211
+ * "this machine's owner", a fact only the deployment knows. Omitted/`false` ⇒ v1 exactly — an
4212
+ * unauthenticated task reads no rules. Declared `true` while the wired provider has no local-owner
4213
+ * face (or while no provider is wired at all) is a configuration contradiction and is refused loudly
4214
+ * at prepare, rather than silently degrading to "the rules this person approved stopped applying".
4215
+ *
4216
+ * A local-owner bucket cannot cloud-sync (syncing is an authenticated act); it is adopted into a
4217
+ * principal bucket by `adoptFilePermissionRuleStore`, after which the local-owner face resolves the
4218
+ * adopted principal's bucket forever.
4219
+ */
4220
+ localOwnerRules?: boolean;
4221
+ /**
4222
+ * design/182 §7 — the ORG rule overlay for an org-GOVERNED deployment. Constructed with
4223
+ * `createOrgRuleOverlay` (that constructor is the boot gate: a governed declaration with no snapshot
4224
+ * provider refuses to boot), so a value here IS the declaration — nothing is inferred from wiring.
4225
+ *
4226
+ * Present ⇒ every tool call is adjudicated against the org's published deny/ask snapshot BEFORE the
4227
+ * ask-resolution chain (org deny > org ask > personal allow rule > bare ask), and while the overlay
4228
+ * cannot adjudicate (never installed / past the staleness bound / a refused rollback) the WHOLE
4229
+ * decision boundary fails closed: every terminal allow becomes a real-approval ask and both
4230
+ * ask→allow seams are disarmed. Omitted ⇒ the org layer does not exist and the decision path is
4231
+ * byte-identical to a build without it.
4232
+ */
4233
+ permissionRuleOrg?: import("./permission-rule-org.js").OrgRuleOverlay;
4234
+ /**
4235
+ * design/182 §9 — DECLARE that this deployment drives cloud sync (`syncPermissionRules`) for the
4236
+ * wired rule store. Purely a disclosure input: it is reported as `permissionRules.syncWired` on the
4237
+ * wiring manifest and changes no decision. It exists because the sync loop is HOST-driven (core
4238
+ * bundles no fetch and owns no timer), so there is nothing for the engine to infer — and "are this
4239
+ * machine's standing approvals shared with other devices and a server?" is exactly the trust-domain
4240
+ * fact an operator must be able to read off the manifest instead of guessing.
4241
+ */
4242
+ permissionRuleSyncWired?: boolean;
4203
4243
  /**
4204
4244
  * design/99 §K — resolve the **per-principal runtime ENTITLEMENTS** the engine
4205
4245
  * ENFORCES server-side, keyed by `spec.principal`. A deployment (the SERVICE) implements it over center's
@@ -136,6 +136,17 @@ export interface WiringManifest {
136
136
  * "this build has no such feature", and a present-and-false one says "it exists and is off here". */
137
137
  permissionRules: {
138
138
  storeWired: boolean;
139
+ /** design/182 §9 — this deployment DECLARED that it drives cloud sync for the wired rule store
140
+ * (`RunnerDeps.permissionRuleSyncWired`). Connecting a bucket to a sync endpoint merges every
141
+ * device, the transport and the server into ONE consent trust domain, which is a fact an operator
142
+ * reads off the manifest rather than infers. `false` on a deployment that does not sync — same
143
+ * present-and-false shape as `storeWired`, for the same reason. */
144
+ syncWired: boolean;
145
+ /** design/182 §7 — this deployment DECLARED org governance (`RunnerDeps.permissionRuleOrg`, whose
146
+ * constructor refuses to boot a governed declaration with no snapshot provider). `true` also means
147
+ * the fail-closed availability contract is armed: while no org snapshot can be adjudicated
148
+ * against, every terminal allow tightens to a real-approval ask. */
149
+ orgGoverned: boolean;
139
150
  };
140
151
  /**
141
152
  * Governance surfaces (presence facts only). `audience: "operator"` is the MACHINE-READABLE
@@ -192,6 +203,10 @@ export interface WiringFacts {
192
203
  backgroundAgentStoreWired: boolean;
193
204
  /** design/179 — a persisted allow-rule store provider is wired. */
194
205
  permissionRuleStoreWired: boolean;
206
+ /** design/182 §9 — the deployment declared that it drives cloud sync for that store. */
207
+ permissionRuleSyncWired: boolean;
208
+ /** design/182 §7 — the deployment declared org governance (an org rule overlay is wired). */
209
+ permissionRuleOrgGoverned: boolean;
195
210
  hostChildEventSinkWired: boolean;
196
211
  lockedConfigWired: boolean;
197
212
  complianceWired: boolean;
@@ -200,7 +215,7 @@ export interface WiringFacts {
200
215
  }
201
216
  /** Named view of the deps seats the static half reads (a `Pick` of the real {@link RunnerDeps} —
202
217
  * single-source shapes, no parallel hand-copied interface). */
203
- export type StaticWiringDeps = Pick<RunnerDeps, "onAsk" | "onQuestion" | "interactionPosture" | "onElicit" | "checkpointStore" | "sessionStore" | "backgroundAgentStore" | "onBackgroundChildEvent" | "lockedConfig" | "compliancePostureResolver" | "memoryScopeAdmission" | "retentionPolicy" | "permissionRuleStore">;
218
+ export type StaticWiringDeps = Pick<RunnerDeps, "onAsk" | "onQuestion" | "interactionPosture" | "onElicit" | "checkpointStore" | "sessionStore" | "backgroundAgentStore" | "onBackgroundChildEvent" | "lockedConfig" | "compliancePostureResolver" | "memoryScopeAdmission" | "retentionPolicy" | "permissionRuleStore" | "permissionRuleSyncWired" | "permissionRuleOrg">;
204
219
  /** Named view of the spec seats the static half reads (a `Pick` of the real {@link TaskSpec}). */
205
220
  export type StaticWiringSpec = Pick<TaskSpec, "onAsk" | "onQuestion" | "checkpointStore" | "durableApproval" | "mcp" | "interactiveTools" | "interactionPosture">;
206
221
  /**
@@ -86,7 +86,11 @@ export function deriveWiringManifest(facts) {
86
86
  parkLane,
87
87
  session: { store: manifestDurabilityOf(facts.sessionDurability) },
88
88
  fleet: { backgroundAgentStore: facts.backgroundAgentStoreWired, hostChildEventSink: facts.hostChildEventSinkWired },
89
- permissionRules: { storeWired: facts.permissionRuleStoreWired },
89
+ permissionRules: {
90
+ storeWired: facts.permissionRuleStoreWired,
91
+ syncWired: facts.permissionRuleSyncWired,
92
+ orgGoverned: facts.permissionRuleOrgGoverned,
93
+ },
90
94
  governance: {
91
95
  audience: "operator",
92
96
  lockedConfig: facts.lockedConfigWired,
@@ -179,6 +183,8 @@ export function describeStaticWiring(deps, spec = {}) {
179
183
  sessionDurability: resolveDeclaredDurability(deps.sessionStore, "sessionStore"),
180
184
  backgroundAgentStoreWired: deps.backgroundAgentStore !== undefined,
181
185
  permissionRuleStoreWired: deps.permissionRuleStore !== undefined,
186
+ permissionRuleSyncWired: deps.permissionRuleSyncWired === true,
187
+ permissionRuleOrgGoverned: deps.permissionRuleOrg !== undefined,
182
188
  hostChildEventSinkWired: deps.onBackgroundChildEvent !== undefined,
183
189
  lockedConfigWired: deps.lockedConfig !== undefined,
184
190
  complianceWired: deps.compliancePostureResolver !== undefined,
package/dist/index.d.ts CHANGED
@@ -88,7 +88,7 @@ export { HAND_TOOL_EFFECTS, bashReversibilityProbe, BASH_READONLY_DEFAULT_ALLOW,
88
88
  export { classifyCompoundReadonlyDetailed, formatOutOfRootReadApprovalOption, type BashReadonlyRootBoundary, type CompoundReadonlyVerdict, } from "./tools/fs/index.js";
89
89
  export { resolveBashTimeoutCaps } from "./tools/fs/index.js";
90
90
  export { InMemoryToolResultStore, OFFLOAD_TOOL_NAME, DEFAULT_TOOL_RESULT_THRESHOLD_CHARS, assertSafeToolResultRef, buildToolResultRef, type ToolResultStore, type ToolResultSlice, } from "./core/tool-result-store.js";
91
- export { InMemoryCheckpointStore, CheckpointError, mintCheckpointToken, checkpointVersionOf, CURRENT_CHECKPOINT_VERSION, MAX_SUPPORTED_CHECKPOINT_VERSION, ORG_ADMISSION_CHECKPOINT_VERSION, F012_CHECKPOINT_VERSION, RESOURCE_CHECKPOINT_VERSION, TOKEN_CHECKPOINT_VERSION, debitLedger, remainingBudgetMicroUsd, remainingTokens, winnerFromOutcome, validatePendingSteer, readPendingSteerQueue, appendPendingSteer, MAX_PENDING_STEER_CHARS, MAX_PENDING_STEER_ENTRIES, PENDING_STEER_QUEUE_BYTE_BUDGET_BYTES, PENDING_STEER_FROZEN_FIELDS, ACTOR_ASSERTION_FROZEN_FIELDS, MAX_ACTOR_FIELD_CHARS, MAX_STEER_INPUT_ID_CHARS, LEGACY_PENDING_STEER_INPUT_ID, type ActorAssertion, type PendingSteerEntry, type PendingSteerInput, riskSeverity, buildRiskDescriptor, summarizeCheckpoint, type RiskDescriptor, type CheckpointStore, type CheckpointSummary, type Checkpoint, type CheckpointToken, type CheckpointGate, type CheckpointState, type SerializedCheckpointState, type CheckpointFaultMode, type PendingAction, type ResumeOutcome, type ResolvedOutcome, type ReopenReason, type ResolveExpectation, type SafetyAxis, type ResourceLedger, type ResourceLimitReason, type PlatformLimitReason, } from "./core/checkpoint-store.js";
91
+ export { InMemoryCheckpointStore, CheckpointError, mintCheckpointToken, checkpointVersionOf, CURRENT_CHECKPOINT_VERSION, MAX_SUPPORTED_CHECKPOINT_VERSION, ORG_ADMISSION_CHECKPOINT_VERSION, F012_CHECKPOINT_VERSION, RESOURCE_CHECKPOINT_VERSION, TOKEN_CHECKPOINT_VERSION, debitLedger, remainingBudgetMicroUsd, remainingTokens, winnerFromOutcome, validatePendingSteer, readPendingSteerQueue, appendPendingSteer, MAX_PENDING_STEER_CHARS, MAX_PENDING_STEER_ENTRIES, PENDING_STEER_QUEUE_BYTE_BUDGET_BYTES, PENDING_STEER_FROZEN_FIELDS, ACTOR_ASSERTION_FROZEN_FIELDS, MAX_ACTOR_FIELD_CHARS, MAX_STEER_INPUT_ID_CHARS, LEGACY_PENDING_STEER_INPUT_ID, type ActorAssertion, type PendingSteerEntry, type PendingSteerInput, riskSeverity, buildRiskDescriptor, summarizeCheckpoint, type RiskDescriptor, type CheckpointStore, type CheckpointSummary, type Checkpoint, type CheckpointToken, type CheckpointGate, type CheckpointState, type SerializedCheckpointState, type CheckpointFaultMode, type PendingAction, type ResumeOutcome, type ResolvedOutcome, type ReopenReason, type ResolveExpectation, type SafetyAxis, type RealApprovalGateBit, type ResourceLedger, type ResourceLimitReason, type PlatformLimitReason, } from "./core/checkpoint-store.js";
92
92
  export { InMemoryUsageWindowStore, GLOBAL_USAGE_KEY, EMPTY_USAGE_WINDOW_RECORD, chargeUsageRecord, readUsageRecord, usageRetryAfterMs, resolveUsageWindows, type UsageWindow, type UsageWindowStore, type UsageWindowReading, type UsageWindowRecord, type UsageSlot, type UsageBucketRow, } from "./core/usage-window-store.js";
93
93
  export { FileUsageWindowStore } from "./stores/file/usage-window-store.js";
94
94
  export { ENV_LIFETIME_SUSPEND_MARGIN_MS, USAGE_WINDOW_REAP_MARGIN_MS } from "./core/runner/prepare-task.js";
@@ -136,23 +136,31 @@ export { createPermissionRulePolicy, validatePermissionRules, parsePermissionRul
136
136
  /**
137
137
  * design/179 — persisted ALLOW rules: the standing form of approvals a person already gave.
138
138
  *
139
- * Note what is NOT here. `PermissionRuleWriter` is core-private and never exported, so a deployment has
140
- * no API path that puts a rule in the store; every rule that enters through the engine comes out of the
141
- * consent protocol below (a durable approval record, an authenticated confirmation, a principal-bound
142
- * redemption). Removal is exported without that ceremony, because narrowing on a user's behalf is allowed
143
- * and widening is not.
139
+ * The consent boundary, restated precisely (ruled 2026-08-10): the ENGINE's only write
140
+ * path into a rule store is the consent protocol below (a durable approval record, an authenticated
141
+ * confirmation, a principal-bound redemption). That fact is a property of the engine's wiring, not of
142
+ * what this file exports a deployment always owned its own storage bytes. The BACKEND CONTRACT
143
+ * (writer types, the writer handle key, and the fold pure functions) is therefore exported further
144
+ * down, so an out-of-repo store implementation (the server's SQL twin) is built against the same
145
+ * definitions as the file backend instead of mirroring them — mirrored types are how comment/contract
146
+ * drift starts. What stays deliberately absent is any convenience that mints rules AROUND consent:
147
+ * exporting the contract gives a store implementer the same powers it already had over its own bytes,
148
+ * and nothing more. Removal is exported without ceremony, because narrowing on a user's behalf is
149
+ * allowed and widening is not.
144
150
  */
145
151
  export { parseAllowRuleText, formatAllowRuleText, ruleAdmitsCommand, findAdmittingRule, suggestRulesForCommand, scopeCoversCwd, pathWithinRoot, isRuleLive, BARE_INTERPRETER_NAMES, MAX_RULE_TEXT_CHARS, type PersistedAllowRule, type RuleTombstone, type RuleScope, type RuleDot, type RuleAdd, type RuleAddOrigin, type RuleSuggestion, type RuleReject, type RuleRejectCode, type ParsedAllowRule, type PersistedRuleTool, type PersistedRuleMatch, } from "./core/permission-rule-model.js";
146
- export { removePersistedRule, applyTombstones, sameScope, InMemoryPermissionRuleStore, EMPTY_RULE_STORE, type PermissionRuleStore, type PermissionRuleStoreProvider, type StoredAllowRules, type RemoveResult, type PutResult, joinRuleStates, screenRuleSyncState, collectBelowFrontier, ruleSyncVector, joinFrontiers, dotAtOrBelowFrontier, sameRuleOwner, type RuleSyncState, type RuleSyncFrontier, type RuleSyncDrop, type RuleSyncLandingReport, type RuleOwner, type QuarantinedRuleAdd, } from "./core/permission-rule-store.js";
152
+ export { removePersistedRule, applyTombstones, sameScope, InMemoryPermissionRuleStore, EMPTY_RULE_STORE, type PermissionRuleStore, type PermissionRuleStoreProvider, type StoredAllowRules, type RemoveResult, type PutResult, joinRuleStates, screenRuleSyncState, collectBelowFrontier, ruleSyncVector, joinFrontiers, dotAtOrBelowFrontier, sameRuleOwner, type RuleSyncState, type RuleSyncFrontier, type RuleSyncDrop, type RuleSyncLandingReport, type RuleOwner, type QuarantinedRuleAdd, PERMISSION_RULE_WRITER, writerOf, foldDelta, addDotsOf, assertDeleteDeltaCarriesNoAdd, assertRedemptionNotQuarantined, type PermissionRuleWriter, type WritablePermissionRuleStore, type RuleWriteDelta, type RuleAddDelta, type RuleDeleteDelta, type RuleSyncJoinDelta, type RawRuleSyncState, type RedemptionAuthorization, } from "./core/permission-rule-store.js";
147
153
  export { syncPermissionRules, parseRuleSyncResponse, PERMISSION_RULE_SYNC_PATH, LOCAL_OWNER_UNSYNCABLE_CODE, type PermissionRuleSyncTransport, type PermissionRuleSyncResult, type RuleSyncRequestBody, type RuleSyncResponseBody, } from "./core/permission-rule-sync.js";
148
- export { createOrgRuleOverlay, orgRuleVerdictFor, effectivePermissionRules, orgRuleStatePersistenceOf, ORG_UNAVAILABLE_DECISION_REASON, type OrgPermissionRule, type OrgRuleSnapshot, type OrgRuleSnapshotProvider, type OrgRuleStatePersistence, type PersistedOrgRuleState, type OrgRuleOverlay, type OrgOverlayResolution, type OrgOverlayStatus, type EffectivePermissionRule, } from "./core/permission-rule-org.js";
154
+ export { createOrgRuleOverlay, orgRuleVerdictFor, effectivePermissionRules, orgRuleStatePersistenceOf, ORG_UNAVAILABLE_DECISION_REASON, ORG_RULE_DECISION_REASON, ORG_ADJUDICATION_TIMEOUT_MS, type OrgPermissionRule, type OrgRuleSnapshot, type OrgRuleSnapshotProvider, type OrgRuleStatePersistence, type PersistedOrgRuleState, type OrgRuleOverlay, type OrgOverlayResolution, type OrgOverlayStatus, type EffectivePermissionRule, } from "./core/permission-rule-org.js";
149
155
  export { RULE_SYNC_DROP_CODES, type RuleSyncDropReason, type RuleQuarantineReason } from "./core/governance-codes.js";
150
156
  export { prepareCardApproval, confirmRuleApproval, type ConfirmResult, type ConfirmRefusalReason, redeemRuleTicket, redeemRuleBatch, prepareCcImport, prepareStarterBatch, mintRuleTicket, STARTER_RULES, InMemoryRuleApprovalRecordStore, type RuleTicket, type RuleCandidate, type RuleApprovalKind, type RuleApprovalRecord, type RuleApprovalRecordStore, type RuleConsentDeps, type RedeemResult, type CcImportLayer, type ImportedSettingsLayer, type ImportPreview, type ImportResult, } from "./core/permission-rule-consent.js";
151
157
  export { FilePermissionRuleStoreProvider } from "./stores/file/permission-rule-store.js";
152
158
  export { adoptFilePermissionRuleStore, type AdoptFileRuleStoreResult } from "./stores/file/permission-rule-adopt.js";
159
+ export { AdoptionError, assertAdoptionBootGate, readRootAdoptionFile, writeRootAdoptionFile, ROOT_ADOPTION_FILE, type AdoptionErrorCode, type AdoptionSource, type AdoptionReport, type AdoptionReceipt, type AdoptionLegReport, type AffectedDeploymentConfig, type RootAdoptionFile, } from "./stores/file/adoption/marker.js";
160
+ export { adoptLocalDataRoot, ackAdoptionConfig, witnessAdoptionConfig, listAdoptionQuarantine, readAdoptionStatus, type AdoptionStatus, type AdoptLocalDataRootOptions, type AdoptLocalDataRootResult, type AdoptionCarriageLeg, type AdoptionCarriageLegContext, type AdoptionConfigWitnessReceipt, } from "./stores/file/adoption/adopt.js";
153
161
  export { formatHookFeedback, runToolGate, createHookEnvCapabilities, createPreToolUseConstraintPolicy, type Hooks, type HookToolContext, type HookEnvCapabilities, type HookToolOutput, type PreToolUseResult, type PostToolUseResult, type UserPromptSubmitResult, type HookToolFailure, type PostToolUseFailureResult, type PostToolBatchCall, type PostToolBatchResult, type PreCompactContext, type PreCompactResult, type PostCompactContext, type StopFailureContext, type PermissionDeniedPayload, type PermissionDeniedSource, } from "./core/hooks.js";
154
162
  export { InMemoryMemoryStore, composeMemoryBlock, composeLayeredMemoryBlock, normalizeMemorySpec, type NormalizedMemorySpec, type MemorySpecInput, supportsConsolidation, supportsPeriodicConsolidation, firstSentence, expandLexicalTerms, lexicalSearchMatch, type Embedder, classifyPromotable, enforcePromotableWriteGate, guardedMemoryStore, MemoryGateError, detectSecret, enforceSecretWriteGate, enforceStructuredNoteSecretGate, type UtilityGate, type MemoryStore, type MemoryVectorMode, type ScoredMemory, type MemoryNoteHeader, type MemoryNoteRecord, type MemoryNoteType, type StructuredNoteInput, } from "./core/memory.js";
155
- export { MemoryEngine, FileMemoryEngineBackend, memoryBackendContract, assertMemoryBackendSearchEquivalence, type MemoryBackendContractHooks, buildMemoryInstruction, truncateIndex, scanEntryFiles, deriveRepoKey, deriveRepoMemoryDir, deriveControlPlaneDir, deriveRepoControlPlaneDir, resolveMemoryEngineRoot, scopeDirName, ControlPlaneCorruptError, parseEntryFile, serializeEntryFile, computeEntryRev, entryFromFile, MEMORY_INSTRUCTION_TEMPLATE, MEMORY_RECALL_DISCIPLINE, MEMORY_PREFERENCE_DISCIPLINE, readV2HeaderHints, type V2HeaderHints, LINEAGE_FILE, CHALLENGES_FILE, CHALLENGED_HISTORY_FILE, type ChallengeAssignment, type ChallengeEvent, type ChallengedHistoryRow, type LineagePendingTxn, type LineagePromotion, MEMORY_INDEX_FILENAME, MEMORY_INDEX_MAX_LINES, MEMORY_INDEX_MAX_BYTES, MEMORY_SEARCH_TOOL_NAME, MEMORY_GET_TOOL_NAME, MEMORY_ENGINE_TOOL_NAMES, type MemorySearchDetails, type MemorySearchHit, type MemoryGetDetails, STUB_ARCHIVED_LINE, DEFAULT_MAX_MEMORY_FILES, DEFAULT_MAX_ENTRY_DEPTH, DEFAULT_HARVEST_DEADLINE_MS, DEFAULT_HARVEST_FILE_BUDGET, MASS_DELETION_FUSE_RATIO, scanMemoryWrite, scanMemoryFileName, scanRemediation, MEMORY_FILENAME_SEGMENT_RE, renderAnnouncements, enqueueMemoryAnnouncement, drainMemoryAnnouncements, peekMemoryAnnouncements, bumpScanFuse, scanFuseCount, clearScanFuse, ANNOUNCEMENTS_FILE, MEMORY_ANNOUNCEMENTS_MAX, SCAN_FUSE_FILE, SCAN_FUSE_THRESHOLD, type MemoryAnnouncement, type ScanFinding, type MemoryEngineOptions, type MemoryInjection, type MemoryBackend, type MemoryEntry, type MemoryEntryFrontmatter, type MemoryEntryHeader, type ScoredMemoryEntry, type NotePatch, type PatchReport, type MaterializedFile, type MemorySessionHandle, type HarvestReport, type HarvestRejection, type HarvestRejectionCode, type ParsedEntryFile, type ScannedEntryFile, SCOPE_SEGMENT_MAX_ENCODED, PROJECT_MARKER_PATH, encodeScopeSegment, decodeScopeSegment, parseScopeKey, formatUserScope, formatOrgScope, formatProjScope, formatUserProjScope, isPersonalScope, assertScopeContractPlacement, formatProjectMarker, parseProjectMarker, resolveProjectId, PROJECT_ID_REGEX, type ParsedScopeKey, migrateScope, type MigrateScopeReport, materializeEntriesToFiles, harvestFilesToPatches, projectionsToWriteBack, screenInboundEntries, REMOTE_HARVEST_PER_FILE_BYTES, REMOTE_MASS_DELETION_FUSE_RATIO, type RemoteMemoryFile, type RemoteMemoryBaseline, type RemoteMaterialization, type RemoteHarvestResult, type InboundEntryFinding, deriveProjectMemoryDir, deriveProjectControlDir, recordProjectIdHint, lookupProjectIdHint, PROJECT_ID_HINTS_FILE, reconcileMemoryEntries, nextSyncBaseline, mergeRecallHits, type MemorySyncCursor, type MemorySyncConflict, type MemorySyncPlan, type RecallSource, syncMemoryScope, type MemorySyncTransport, type MemorySyncRequestBody, type MemorySyncResponseBody, type MemorySyncClientConflict, type SyncMemoryScopeOptions, type MemorySyncClientResult, } from "./core/memory-engine/index.js";
163
+ export { MemoryEngine, FileMemoryEngineBackend, memoryBackendContract, assertMemoryBackendSearchEquivalence, type MemoryBackendContractHooks, buildMemoryInstruction, truncateIndex, scanEntryFiles, deriveRepoKey, deriveRepoMemoryDir, deriveControlPlaneDir, deriveRepoControlPlaneDir, resolveMemoryEngineRoot, scopeDirName, ControlPlaneCorruptError, parseEntryFile, serializeEntryFile, computeEntryRev, entryFromFile, MEMORY_INSTRUCTION_TEMPLATE, MEMORY_RECALL_DISCIPLINE, MEMORY_PREFERENCE_DISCIPLINE, readV2HeaderHints, type V2HeaderHints, LINEAGE_FILE, CHALLENGES_FILE, CHALLENGED_HISTORY_FILE, CHALLENGE_LEDGER_MAX_EVENTS, rebuildStrictControlPlaneLedger, type ControlPlaneRebuildReceipt, type StrictControlPlaneLedger, type ChallengeAssignment, type ChallengeEvent, type ChallengedHistoryRow, type LineagePendingTxn, type LineagePromotion, MEMORY_INDEX_FILENAME, MEMORY_INDEX_MAX_LINES, MEMORY_INDEX_MAX_BYTES, MEMORY_SEARCH_TOOL_NAME, MEMORY_GET_TOOL_NAME, MEMORY_ENGINE_TOOL_NAMES, type MemorySearchDetails, type MemorySearchHit, type MemoryGetDetails, STUB_ARCHIVED_LINE, DEFAULT_MAX_MEMORY_FILES, DEFAULT_MAX_ENTRY_DEPTH, DEFAULT_HARVEST_DEADLINE_MS, DEFAULT_HARVEST_FILE_BUDGET, MASS_DELETION_FUSE_RATIO, scanMemoryWrite, scanMemoryFileName, scanRemediation, MEMORY_FILENAME_SEGMENT_RE, renderAnnouncements, enqueueMemoryAnnouncement, drainMemoryAnnouncements, peekMemoryAnnouncements, bumpScanFuse, scanFuseCount, clearScanFuse, ANNOUNCEMENTS_FILE, MEMORY_ANNOUNCEMENTS_MAX, SCAN_FUSE_FILE, SCAN_FUSE_THRESHOLD, type MemoryAnnouncement, type ScanFinding, type MemoryEngineOptions, type MemoryInjection, type MemoryBackend, type MemoryEntry, type MemoryEntryFrontmatter, type MemoryEntryHeader, type ScoredMemoryEntry, type NotePatch, type PatchReport, type MaterializedFile, type MemorySessionHandle, type HarvestReport, type HarvestRejection, type HarvestRejectionCode, type ParsedEntryFile, type ScannedEntryFile, SCOPE_SEGMENT_MAX_ENCODED, PROJECT_MARKER_PATH, encodeScopeSegment, decodeScopeSegment, parseScopeKey, formatUserScope, formatOrgScope, formatProjScope, formatUserProjScope, isPersonalScope, assertScopeContractPlacement, formatProjectMarker, parseProjectMarker, resolveProjectId, PROJECT_ID_REGEX, type ParsedScopeKey, migrateScope, type MigrateScopeReport, materializeEntriesToFiles, harvestFilesToPatches, projectionsToWriteBack, screenInboundEntries, REMOTE_HARVEST_PER_FILE_BYTES, REMOTE_MASS_DELETION_FUSE_RATIO, type RemoteMemoryFile, type RemoteMemoryBaseline, type RemoteMaterialization, type RemoteHarvestResult, type InboundEntryFinding, deriveProjectMemoryDir, deriveProjectControlDir, recordProjectIdHint, lookupProjectIdHint, PROJECT_ID_HINTS_FILE, reconcileMemoryEntries, nextSyncBaseline, mergeRecallHits, type MemorySyncCursor, type MemorySyncConflict, type MemorySyncPlan, type RecallSource, syncMemoryScope, type MemorySyncTransport, type MemorySyncRequestBody, type MemorySyncResponseBody, type MemorySyncClientConflict, type SyncMemoryScopeOptions, type MemorySyncClientResult, } from "./core/memory-engine/index.js";
156
164
  export { SHARED_MEMORY_READ_CAP_BYTES, SHARED_MEMORY_LIST_PAGE_SIZE, SharedMemoryStoreError, type SharedMemoryStoreProvider, type SharedMemoryStoreReader, type SharedMemoryPagedList, type SharedMemoryStoreInfo, type SharedMemoryDocumentEntry, type SharedMemorySnapshot, type SharedMemoryRequestContext, type MemoryListDetails, type MemoryReadDetails, } from "./core/shared-memory/types.js";
157
165
  export { sharedMemoryStoreContract, type SharedMemoryFixture, type SharedMemoryStoreContractHooks, } from "./core/shared-memory/contract.js";
158
166
  export { termSet, jaccardDistance, cosineDistance } from "./core/memory-vector.js";
@@ -178,7 +186,7 @@ export { teacherMode, TEACHER_PROFILE, type TeacherModePair, type TeacherProfile
178
186
  export { loadOrchestrationEnv, DEFAULT_REASONING_INTENSITY, type OrchestrationMode, type OrchestrationEnv, } from "./scenarios/env.js";
179
187
  export { runWorkflow, startWorkflow, workflowAgentCallKey, WorkflowBudgetExceededError, WorkflowNestingError, WorkflowAgentSchemaError, WorkflowAgentStalledError, WorkflowAgentBlockedError, WORKFLOW_SPAWN_BLOCKED_ERROR_CODE, type WorkflowFanOutSlotError, type WorkflowFanOutOptions, WORKFLOW_SUBAGENT_PROMPT, WORKFLOW_SUBAGENT_PROMPT_SCHEMA, WORKFLOW_SUBAGENT_APPEND, WORKFLOW_SUBAGENT_APPEND_SCHEMA, type WorkflowHandle, MAX_WORKFLOW_ITEMS, type WorkflowRun, type WorkflowRunStatus, type WorkflowItemStatus, type WorkflowPhase, type WorkflowGroup, type WorkflowAgentRun, type WorkflowAgentHandle, type WorkflowRunStats, type WorkflowEvent, type WorkflowBudget, type WorkflowAgentOptions, type WorkflowRunContext, type WorkflowInternals, type RunWorkflowOptions, type RunWorkflowResult, type WorkflowTimers, } from "./orchestration/workflow.js";
180
188
  export { listWorkflowRuns, getWorkflowRun, subscribeWorkflow, deriveAgentDisplayStatus, type AgentDisplayStatus } from "./orchestration/workflow-observe.js";
181
- export { runGoal, DECLARE_DONE_TOOL_NAME, type GoalSpec, type GoalResult, type GoalStatus, type GoalVerdict, type GoalTurnState, type GoalVerificationKind, } from "./orchestration/goal.js";
189
+ export { runGoal, DECLARE_DONE_TOOL_NAME, type GoalSpec, type GoalResult, type GoalStatus, type GoalBudgetCause, type GoalVerdict, type GoalTurnState, type GoalVerificationKind, } from "./orchestration/goal.js";
182
190
  export { emitTaskOutcome, type TaskOutcome } from "./core/task-outcome.js";
183
191
  export { runOracle, captureBaseline, resolveFrozenPaths, snapshotFrozenPaths, restoreFrozenPaths, specError, type SpecContract, type OracleGateSpec, type OracleGreenSpec, type OracleVerdict, type OracleGateResult, type OracleRunReport, type OracleBaseline, } from "./core/spec-contract.js";
184
192
  export { runSpec, type RunSpecOptions, type RunSpecResult, type RunSpecOracleReport } from "./orchestration/run-spec.js";
package/dist/index.js CHANGED
@@ -112,16 +112,18 @@ export { buildAutoModePrompt, renderAutoModeWindow, renderAutoModeAction, AUTO_M
112
112
  export { AUTO_MODE_BASE_PROMPT, AUTO_MODE_PERMISSIONS_EXTERNAL } from "./core/auto-mode-prompt-assets.js";
113
113
  export { createPermissionRulePolicy, validatePermissionRules, parsePermissionRule, wildcardMatch, } from "./core/permission-rules.js";
114
114
  export { parseAllowRuleText, formatAllowRuleText, ruleAdmitsCommand, findAdmittingRule, suggestRulesForCommand, scopeCoversCwd, pathWithinRoot, isRuleLive, BARE_INTERPRETER_NAMES, MAX_RULE_TEXT_CHARS, } from "./core/permission-rule-model.js";
115
- export { removePersistedRule, applyTombstones, sameScope, InMemoryPermissionRuleStore, EMPTY_RULE_STORE, joinRuleStates, screenRuleSyncState, collectBelowFrontier, ruleSyncVector, joinFrontiers, dotAtOrBelowFrontier, sameRuleOwner, } from "./core/permission-rule-store.js";
115
+ export { removePersistedRule, applyTombstones, sameScope, InMemoryPermissionRuleStore, EMPTY_RULE_STORE, joinRuleStates, screenRuleSyncState, collectBelowFrontier, ruleSyncVector, joinFrontiers, dotAtOrBelowFrontier, sameRuleOwner, PERMISSION_RULE_WRITER, writerOf, foldDelta, addDotsOf, assertDeleteDeltaCarriesNoAdd, assertRedemptionNotQuarantined, } from "./core/permission-rule-store.js";
116
116
  export { syncPermissionRules, parseRuleSyncResponse, PERMISSION_RULE_SYNC_PATH, LOCAL_OWNER_UNSYNCABLE_CODE, } from "./core/permission-rule-sync.js";
117
- export { createOrgRuleOverlay, orgRuleVerdictFor, effectivePermissionRules, orgRuleStatePersistenceOf, ORG_UNAVAILABLE_DECISION_REASON, } from "./core/permission-rule-org.js";
117
+ export { createOrgRuleOverlay, orgRuleVerdictFor, effectivePermissionRules, orgRuleStatePersistenceOf, ORG_UNAVAILABLE_DECISION_REASON, ORG_RULE_DECISION_REASON, ORG_ADJUDICATION_TIMEOUT_MS, } from "./core/permission-rule-org.js";
118
118
  export { RULE_SYNC_DROP_CODES } from "./core/governance-codes.js";
119
119
  export { prepareCardApproval, confirmRuleApproval, redeemRuleTicket, redeemRuleBatch, prepareCcImport, prepareStarterBatch, mintRuleTicket, STARTER_RULES, InMemoryRuleApprovalRecordStore, } from "./core/permission-rule-consent.js";
120
120
  export { FilePermissionRuleStoreProvider } from "./stores/file/permission-rule-store.js";
121
121
  export { adoptFilePermissionRuleStore } from "./stores/file/permission-rule-adopt.js";
122
+ export { AdoptionError, assertAdoptionBootGate, readRootAdoptionFile, writeRootAdoptionFile, ROOT_ADOPTION_FILE, } from "./stores/file/adoption/marker.js";
123
+ export { adoptLocalDataRoot, ackAdoptionConfig, witnessAdoptionConfig, listAdoptionQuarantine, readAdoptionStatus, } from "./stores/file/adoption/adopt.js";
122
124
  export { formatHookFeedback, runToolGate, createHookEnvCapabilities, createPreToolUseConstraintPolicy, } from "./core/hooks.js";
123
125
  export { InMemoryMemoryStore, composeMemoryBlock, composeLayeredMemoryBlock, normalizeMemorySpec, supportsConsolidation, supportsPeriodicConsolidation, firstSentence, expandLexicalTerms, lexicalSearchMatch, classifyPromotable, enforcePromotableWriteGate, guardedMemoryStore, MemoryGateError, detectSecret, enforceSecretWriteGate, enforceStructuredNoteSecretGate, } from "./core/memory.js";
124
- export { MemoryEngine, FileMemoryEngineBackend, memoryBackendContract, assertMemoryBackendSearchEquivalence, buildMemoryInstruction, truncateIndex, scanEntryFiles, deriveRepoKey, deriveRepoMemoryDir, deriveControlPlaneDir, deriveRepoControlPlaneDir, resolveMemoryEngineRoot, scopeDirName, ControlPlaneCorruptError, parseEntryFile, serializeEntryFile, computeEntryRev, entryFromFile, MEMORY_INSTRUCTION_TEMPLATE, MEMORY_RECALL_DISCIPLINE, MEMORY_PREFERENCE_DISCIPLINE, readV2HeaderHints, LINEAGE_FILE, CHALLENGES_FILE, CHALLENGED_HISTORY_FILE, MEMORY_INDEX_FILENAME, MEMORY_INDEX_MAX_LINES, MEMORY_INDEX_MAX_BYTES, MEMORY_SEARCH_TOOL_NAME, MEMORY_GET_TOOL_NAME, MEMORY_ENGINE_TOOL_NAMES, STUB_ARCHIVED_LINE, DEFAULT_MAX_MEMORY_FILES, DEFAULT_MAX_ENTRY_DEPTH, DEFAULT_HARVEST_DEADLINE_MS, DEFAULT_HARVEST_FILE_BUDGET, MASS_DELETION_FUSE_RATIO, scanMemoryWrite, scanMemoryFileName, scanRemediation, MEMORY_FILENAME_SEGMENT_RE, renderAnnouncements, enqueueMemoryAnnouncement, drainMemoryAnnouncements, peekMemoryAnnouncements, bumpScanFuse, scanFuseCount, clearScanFuse, ANNOUNCEMENTS_FILE, MEMORY_ANNOUNCEMENTS_MAX, SCAN_FUSE_FILE, SCAN_FUSE_THRESHOLD, SCOPE_SEGMENT_MAX_ENCODED, PROJECT_MARKER_PATH, encodeScopeSegment, decodeScopeSegment, parseScopeKey, formatUserScope, formatOrgScope, formatProjScope, formatUserProjScope, isPersonalScope, assertScopeContractPlacement, formatProjectMarker, parseProjectMarker, resolveProjectId, PROJECT_ID_REGEX, migrateScope, materializeEntriesToFiles, harvestFilesToPatches, projectionsToWriteBack, screenInboundEntries, REMOTE_HARVEST_PER_FILE_BYTES, REMOTE_MASS_DELETION_FUSE_RATIO, deriveProjectMemoryDir, deriveProjectControlDir, recordProjectIdHint, lookupProjectIdHint, PROJECT_ID_HINTS_FILE, reconcileMemoryEntries, nextSyncBaseline, mergeRecallHits, syncMemoryScope, } from "./core/memory-engine/index.js";
126
+ export { MemoryEngine, FileMemoryEngineBackend, memoryBackendContract, assertMemoryBackendSearchEquivalence, buildMemoryInstruction, truncateIndex, scanEntryFiles, deriveRepoKey, deriveRepoMemoryDir, deriveControlPlaneDir, deriveRepoControlPlaneDir, resolveMemoryEngineRoot, scopeDirName, ControlPlaneCorruptError, parseEntryFile, serializeEntryFile, computeEntryRev, entryFromFile, MEMORY_INSTRUCTION_TEMPLATE, MEMORY_RECALL_DISCIPLINE, MEMORY_PREFERENCE_DISCIPLINE, readV2HeaderHints, LINEAGE_FILE, CHALLENGES_FILE, CHALLENGED_HISTORY_FILE, CHALLENGE_LEDGER_MAX_EVENTS, rebuildStrictControlPlaneLedger, MEMORY_INDEX_FILENAME, MEMORY_INDEX_MAX_LINES, MEMORY_INDEX_MAX_BYTES, MEMORY_SEARCH_TOOL_NAME, MEMORY_GET_TOOL_NAME, MEMORY_ENGINE_TOOL_NAMES, STUB_ARCHIVED_LINE, DEFAULT_MAX_MEMORY_FILES, DEFAULT_MAX_ENTRY_DEPTH, DEFAULT_HARVEST_DEADLINE_MS, DEFAULT_HARVEST_FILE_BUDGET, MASS_DELETION_FUSE_RATIO, scanMemoryWrite, scanMemoryFileName, scanRemediation, MEMORY_FILENAME_SEGMENT_RE, renderAnnouncements, enqueueMemoryAnnouncement, drainMemoryAnnouncements, peekMemoryAnnouncements, bumpScanFuse, scanFuseCount, clearScanFuse, ANNOUNCEMENTS_FILE, MEMORY_ANNOUNCEMENTS_MAX, SCAN_FUSE_FILE, SCAN_FUSE_THRESHOLD, SCOPE_SEGMENT_MAX_ENCODED, PROJECT_MARKER_PATH, encodeScopeSegment, decodeScopeSegment, parseScopeKey, formatUserScope, formatOrgScope, formatProjScope, formatUserProjScope, isPersonalScope, assertScopeContractPlacement, formatProjectMarker, parseProjectMarker, resolveProjectId, PROJECT_ID_REGEX, migrateScope, materializeEntriesToFiles, harvestFilesToPatches, projectionsToWriteBack, screenInboundEntries, REMOTE_HARVEST_PER_FILE_BYTES, REMOTE_MASS_DELETION_FUSE_RATIO, deriveProjectMemoryDir, deriveProjectControlDir, recordProjectIdHint, lookupProjectIdHint, PROJECT_ID_HINTS_FILE, reconcileMemoryEntries, nextSyncBaseline, mergeRecallHits, syncMemoryScope, } from "./core/memory-engine/index.js";
125
127
  export { SHARED_MEMORY_READ_CAP_BYTES, SHARED_MEMORY_LIST_PAGE_SIZE, SharedMemoryStoreError, } from "./core/shared-memory/types.js";
126
128
  export { sharedMemoryStoreContract, } from "./core/shared-memory/contract.js";
127
129
  export { termSet, jaccardDistance, cosineDistance } from "./core/memory-vector.js";
@@ -66,6 +66,13 @@ export interface GoalSpec {
66
66
  taskSignature?: string;
67
67
  }
68
68
  export type GoalStatus = "achieved" | "max_iterations" | "budget" | "blocked" | "suspended" | "needs_review" | "failed" | "aborted";
69
+ /**
70
+ * #111 — which ceiling ended a `status:"budget"` run. The status set stays CLOSED (a consumer
71
+ * switching on it keeps compiling); this is the terminating FACTOR beside it, because the two
72
+ * ceilings ask the caller for opposite corrections: `"tokens"` = the allowance is spent (narrow the
73
+ * objective / raise `budgetTokens`), `"walltime"` = `totalTimeoutMs` elapsed (give it more time).
74
+ */
75
+ export type GoalBudgetCause = "tokens" | "walltime";
69
76
  export interface GoalResult {
70
77
  readonly status: GoalStatus;
71
78
  /** Last iteration's result; absent on a preflight-terminate (a stop BEFORE iteration 1 ran). */
@@ -83,6 +90,9 @@ export interface GoalResult {
83
90
  readonly checkpointToken?: CheckpointToken;
84
91
  /** Set on `failed` (incl. `goal.donecheck_error`). */
85
92
  readonly errorCode?: string;
93
+ /** #111 — present IFF `status === "budget"` (the KEY is absent otherwise, so presence alone reads
94
+ * as "stopped on a ceiling"). See {@link GoalBudgetCause}. */
95
+ readonly budgetCause?: GoalBudgetCause;
86
96
  }
87
97
  /** Reserved name of the goal-completion signal tool (injected by `runGoal` when there is no outputSchema). */
88
98
  export declare const DECLARE_DONE_TOOL_NAME = "DeclareDone";
@@ -89,7 +89,7 @@ export async function runGoal(runner, spec) {
89
89
  const goalSignal = spec.signal
90
90
  ? AbortSignal.any([spec.signal, deadlineCtl.signal])
91
91
  : deadlineCtl.signal;
92
- const classifyStop = () => spec.signal?.aborted ? "aborted" : deadlineCtl.signal.aborted ? "budget" : null;
92
+ const classifyStop = () => spec.signal?.aborted ? { status: "aborted" } : deadlineCtl.signal.aborted ? { status: "budget", budgetCause: "walltime" } : null;
93
93
  const mk = (status, iterations, over) => {
94
94
  const r = {
95
95
  status,
@@ -101,6 +101,7 @@ export async function runGoal(runner, spec) {
101
101
  cumulativeTokens,
102
102
  checkpointToken: over?.checkpointToken,
103
103
  errorCode: over?.errorCode,
104
+ ...(status === "budget" && over?.budgetCause !== undefined ? { budgetCause: over.budgetCause } : {}),
104
105
  };
105
106
  if (verificationKind === "mechanical" && status !== "suspended" && status !== "needs_review") {
106
107
  runner.emitTaskOutcome?.({
@@ -129,9 +130,9 @@ export async function runGoal(runner, spec) {
129
130
  for (let iteration = 1; iteration <= spec.maxIterations; iteration++) {
130
131
  const preStop = classifyStop();
131
132
  if (preStop)
132
- return mk(preStop, iteration - 1);
133
+ return mk(preStop.status, iteration - 1, { budgetCause: preStop.budgetCause });
133
134
  if (spec.budgetTokens !== undefined && cumulativeTokens >= spec.budgetTokens)
134
- return mk("budget", iteration - 1);
135
+ return mk("budget", iteration - 1, { budgetCause: "tokens" });
135
136
  const objective = iteration === 1 ? spec.objective : continuationPrompt(spec.objective, lastFeedback, hasOutputSchema);
136
137
  const doneRef = {};
137
138
  const tools = hasOutputSchema
@@ -147,7 +148,7 @@ export async function runGoal(runner, spec) {
147
148
  }
148
149
  const midStop = classifyStop();
149
150
  if (midStop)
150
- return mk(midStop, iteration, { result });
151
+ return mk(midStop.status, iteration, { result, budgetCause: midStop.budgetCause });
151
152
  if (result.status === "blocked")
152
153
  return mk("blocked", iteration, { result });
153
154
  if (result.status === "failed") {
@@ -169,7 +170,7 @@ export async function runGoal(runner, spec) {
169
170
  catch {
170
171
  const s = classifyStop();
171
172
  if (s)
172
- return mk(s, iteration, { result });
173
+ return mk(s.status, iteration, { result, budgetCause: s.budgetCause });
173
174
  return mk("failed", iteration, { result, errorCode: "goal.donecheck_error" });
174
175
  }
175
176
  lastVerdict = verdict;