@agentpro/scroll 0.0.0-stage → 2.5.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 (61) hide show
  1. package/AGENTS.md +55 -0
  2. package/LICENSE +21 -0
  3. package/README.md +293 -2
  4. package/SPEC.md +1079 -0
  5. package/bin/scroll.js +8 -0
  6. package/docs/prompt-caching.md +128 -0
  7. package/index.js +33 -0
  8. package/lib/audit.js +358 -0
  9. package/lib/auth.js +849 -0
  10. package/lib/chat-sdk/admin-controller.js +289 -0
  11. package/lib/chat-sdk/debouncer.js +94 -0
  12. package/lib/chat-sdk/group-grants.js +150 -0
  13. package/lib/chat-sdk/index.js +222 -0
  14. package/lib/chat-sdk/long-task-runner.js +413 -0
  15. package/lib/chat-session.js +1788 -0
  16. package/lib/chat-telemetry.js +557 -0
  17. package/lib/codex-app-server.js +851 -0
  18. package/lib/digest.js +112 -0
  19. package/lib/effects.js +157 -0
  20. package/lib/eval.js +408 -0
  21. package/lib/grounding.js +356 -0
  22. package/lib/installers.js +176 -0
  23. package/lib/knowledge.js +335 -0
  24. package/lib/ledger.js +38 -0
  25. package/lib/loop.js +197 -0
  26. package/lib/mcp-client.js +926 -0
  27. package/lib/memory-cli.js +66 -0
  28. package/lib/memory-tracker.js +1472 -0
  29. package/lib/memory.js +1279 -0
  30. package/lib/people-cli.js +81 -0
  31. package/lib/people.js +534 -0
  32. package/lib/permissions.js +272 -0
  33. package/lib/providers.js +1572 -0
  34. package/lib/runtime.js +928 -0
  35. package/lib/sandbox.js +744 -0
  36. package/lib/scheduler.js +402 -0
  37. package/lib/scroll.js +1225 -0
  38. package/lib/skill-cli.js +120 -0
  39. package/lib/skill-eval.js +156 -0
  40. package/lib/skills.js +860 -0
  41. package/lib/style.js +126 -0
  42. package/lib/tool-retriever.js +489 -0
  43. package/lib/tools.js +1833 -0
  44. package/lib/user.js +711 -0
  45. package/lib/vault.js +151 -0
  46. package/package.json +88 -4
  47. package/templates/agent/IDENTITY.md +56 -0
  48. package/templates/agent/SOUL.md +23 -0
  49. package/templates/agent/TOOLS.md +25 -0
  50. package/templates/agent/evals/case-02-citation-discipline.md +29 -0
  51. package/templates/agent/evals/case-03-boundary.md +27 -0
  52. package/templates/agent/evals/case-example.md +43 -0
  53. package/templates/agent/hard-rules.md +11 -0
  54. package/templates/agent/memory/lessons.md +5 -0
  55. package/templates/agent/memory/log/.gitkeep +0 -0
  56. package/templates/external-safety-contract.md +5 -0
  57. package/templates/long-task-planner.md +17 -0
  58. package/templates/work/LOOP.md +37 -0
  59. package/templates/work/WORK.md +50 -0
  60. package/types/chat.d.ts +61 -0
  61. package/types/index.d.ts +112 -0
package/SPEC.md ADDED
@@ -0,0 +1,1079 @@
1
+ # SCROLL Specification
2
+
3
+ **Version:** 2.5 · **Status:** Stable (runtime built; §28–§50 & §47.2 implemented) · **Date:** 2026-11-21 · **Reference impl:** `@agentpro/scroll` 2.5.0
4
+
5
+ > **v2.5 (production chat harness, §47.2 Portable Tool Retriever & 2-package monorepo):**
6
+ > - **Hardened Action Boundary:** `fs.realpathSync.native` + case-insensitive & dotfile deny-list (`USER.md`, `.env`, `.scroll/**`, `.mcp.json`), OS kernel sandboxing (`sandbox-exec` / `bwrap`) with minimal env allowlist for `exec` & MCP subprocesses, AES-256-GCM vault (`${vault:KEY}` fail-closed), DNS/IPv6/CGNAT `100.64.0.0/10` + manual-redirect SSRF & `egress_allow`, provenance-tagged §22 grounding (untrusted `web_fetch` cannot launder claims), buffered streaming on external grounded turns, single-use per-call approval tokens + `canApprove()`, and fail-closed read-only `confirmEffect` probes.
7
+ > - **§47.2 Portable Tool Retriever (Zero-Dep):** 3-set architecture (deployment-frozen Catalog `C`, per-turn Visible `V`, per-call Executable `E`) with multi-field BM25F + batch `queries[]` `tool_search`, Transparent Unwrap `tool_invoke` with host JSON Schema validation, Room-Sticky group prompt-cache invariance (`<turn_speaker>` in Region C), `.scroll/mcp.lock.json` TOFU pinning, ASI04 quarantine, and `scroll check` ban on unpinned `npx …@latest`.
8
+ > - **D16 Observability, Budget & Concurrency:** OTel GenAI-aligned `events.jsonl`, hash-chained `audit.jsonl` (`scroll audit --verify-chain`), `IDENTITY.budget` + loop/error circuit breakers, single-writer PID lock, per-conversation turn mutex, per-round JSONL crash recovery, and §34 `openSkills()` wired into live chat sessions.
9
+ > - **4-Provider Parity & Streamable HTTP MCP:** Real SSE streaming, parallel tool calling, `thoughtSignature`/`thinking` preservation, `images`, and `authStore` failover across OpenAI, Anthropic, Gemini, and Codex App-Server (`base64` vision temp-file bridge + turn-bound RPC callbacks); Streamable HTTP MCP (`Mcp-Session-Id` + HTTP `404` re-init + `Promise.allSettled` isolation); token-aware compaction + `400 context_length_exceeded` auto-recovery; multi-turn `runChatEvals()` (`pass^k`); and lockstep 2-package monorepo (`@agentpro/scroll` with `./chat` + `@agentpro/scroll-telegram`).
10
+
11
+ > **v1.9 (people in the agent team):** §38 a person card per person (`people/<slug>.md`), written by that person, outside every agent folder, with a body capped by code · §39 agents bind to people by role (`serves`, `reports_to: role:<r>`); the deployment maps roles to people and every agent of the team loads the same card · §40 a person can own a `WORK.md` step, and an approval names its approver, whose card the runner checks before the gate opens, with a hash-chained audit trail · §41 audit fails when a card, a `USER.md` or a `people/` folder travels inside an agent folder, a skill or a plugin. §3, §9, §13, §18.3 and §20.5 are updated to match; `pronoun` and `reports_to: user` remain valid as legacy.
12
+ >
13
+ > **v1.8 (skills):** §34 a skill loader — the open Agent Skills format, ordered sources including read-only folders of other tools, a byte-stable index, `skill_list` / `skill_view` · §35 one skill, many runtimes: foreign tool names map to capabilities, and a skill built around tools the agent lacks is hidden · §36 skills are validated, scanned for secrets, exfiltration, remote code and injection before any model sees them, and evaluated with and without the skill on every model they run on. §19.3 now points here; `triggers` is no longer required.
14
+ >
15
+ > **v1.7 (subject memory):** §31 per-subject facts behind one five-layer gate · §32 episodic sessions, cards and day notes with a frozen, hashed load contract, deterministic search and a forget that reaches every copy · §33 groups and many surfaces. §7 stays the agent's own memory.
16
+ >
17
+ > **v1.4 (the harness + loop-engineering layer):** §21 risk-tiered permission matrix (5 tiers, enforced at the action boundary) · §22 grounding pre-check · §23 `LOOP.md` outer loop. Plus record corrections: `scroll eval` is **built** (not roadmap); the approval file lives under `control/approvals/<id>` (§18.3).
18
+
19
+ This document is the normative reference for SCROLL agents. A tool is **SCROLL-conformant** if it reads and writes agent folders exactly as defined here.
20
+
21
+ The key words **MUST**, **MUST NOT**, **REQUIRED**, **SHOULD**, **SHOULD NOT**, **RECOMMENDED**, **MAY**, and **OPTIONAL** are to be interpreted as in RFC 2119.
22
+
23
+ ---
24
+
25
+ ## 1 · Overview & terminology
26
+
27
+ - **Agent** — a directory containing the files defined in §2. The directory name is the agent's local id.
28
+ - **Source** — the canonical agent files a human/AI authors (`IDENTITY.md`, `SOUL.md`, etc.). The single source of truth.
29
+ - **Rendering** — a runtime-specific artifact produced from the source by a transpiler (§15). Renderings are generated; they MUST NOT be hand-edited.
30
+ - **Loader** — a SCROLL-conformant program that reads an agent folder and assembles its context.
31
+ - **Controller** — the single agent that owns a `WORK.md` in a multi-agent run (§9).
32
+ - **Conformant tool** — a program (CLI, library, plugin) implementing this spec.
33
+
34
+ A SCROLL **repository** MAY contain many agents under `agents/` and SHOULD contain a root `AGENTS.md` (§17) and a `scroll.config.*` (§16).
35
+
36
+ ---
37
+
38
+ ## 2 · The agent folder
39
+
40
+ ```
41
+ agents/<name>/
42
+ ├── IDENTITY.md REQUIRED identity + machine-readable frontmatter (§3)
43
+ ├── SOUL.md REQUIRED persona prose (§4)
44
+ ├── TOOLS.md OPTIONAL capability → tool wiring (§5)
45
+ ├── hard-rules.md OPTIONAL inviolable rules (§6)
46
+ ├── memory/ OPTIONAL recall, archival, layered (§7)
47
+ └── evals/ RECOMMENDED gold test cases (§8)
48
+ ```
49
+
50
+ - `<name>` **MUST** match `^[a-z][a-z0-9-]*$` and be unique within its `agents/` directory.
51
+ - An agent **MUST** contain `IDENTITY.md` and `SOUL.md`. All other files are OPTIONAL but a conformant loader MUST honor them when present.
52
+ - Unknown files in the folder **MUST** be ignored by loaders (forward compatibility).
53
+ - An agent folder **MUST NOT** carry anything about a person — no person card, no `USER.md`, no `people/` folder (§41). People are described by cards outside `agents/` (§38).
54
+
55
+ ---
56
+
57
+ ## 3 · `IDENTITY.md`
58
+
59
+ `IDENTITY.md` consists of YAML frontmatter (between `---` fences) followed by free-form body prose.
60
+
61
+ ### 3.1 Frontmatter (normative)
62
+
63
+ | Field | Req | Type | Notes |
64
+ |---|---|---|---|
65
+ | `name` | MUST | string | `^[a-z][a-z0-9-]*$`, equals folder name |
66
+ | `title` | MUST | string | human-readable label |
67
+ | `version` | MUST | string | semver `MAJOR.MINOR.PATCH` |
68
+ | `serves` | SHOULD | string[] | v1.9: roles this agent serves (`owner` or `role:owner`), never a person (§39) |
69
+ | `pronoun` | OPTIONAL | string | legacy: how the agent addresses the user. From v1.9 the address lives on each person's card (§38); `pronoun` is only the last fallback and `scroll check` warns |
70
+ | `language` | SHOULD | string | BCP-47 (e.g. `en`, `vi-VN`) |
71
+ | `runtimes` | MUST | string[] | non-empty; values from the runtime registry (§15) |
72
+ | `model` | MUST | object | `{ primary, fallback?, voice?, voice_id? }`; `primary` REQUIRED |
73
+ | `capabilities` | MUST | string[] | logical capabilities (§5.1); MAY be empty |
74
+ | `dispatch` | OPTIONAL | object | `{ authority, can_dispatch?, spawn_template? }` |
75
+ | `position` | OPTIONAL | enum | `c-suite \| above-c-suite \| outside-org \| runtime` |
76
+ | `reports_to` | OPTIONAL | string | another agent's name, or `role:<role>` (v1.9). `user` is legacy (warning); `person:<slug>` is an error (§39) |
77
+ | `hard_rules` | OPTIONAL | path | relative path to a rules file (§6) |
78
+ | `memory` | OPTIONAL | object | overrides default memory layout (§7) |
79
+ | `a2a` | OPTIONAL | object | A2A Agent Card export hints (§15) |
80
+ | `skills` | OPTIONAL | string[] | skills pinned to the top of this agent's index (§34.6) |
81
+ | `skills_external` | OPTIONAL | boolean | `false` keeps external skill folders away from this agent (§34.2) |
82
+
83
+ - `dispatch.authority` **MUST** be one of `none | low | medium | high`. Default `none`.
84
+ - Fields not listed here are **OPTIONAL extensions**; a conformant validator MUST treat unknown fields as a **warning**, never an error.
85
+ - The full JSON Schema is **Appendix A**.
86
+
87
+ ### 3.2 Body
88
+
89
+ Everything after the closing `---` is appended to the agent's assembled context (§13) after `SOUL.md`. It MAY be empty. It MUST NOT contain secrets; secret references use `${vault:KEY}` syntax, resolved at load time.
90
+
91
+ ---
92
+
93
+ ## 4 · `SOUL.md`
94
+
95
+ Free-form prose defining voice, values, and behavior. There is **no required structure** — this is the human-authored heart of the agent. A loader **MUST** include the full contents of `SOUL.md` in the assembled context (§13). Tools **MUST NOT** auto-generate `SOUL.md` from frontmatter.
96
+
97
+ ---
98
+
99
+ ## 5 · `TOOLS.md`
100
+
101
+ ### 5.1 Capabilities (logical, runtime-agnostic)
102
+ Capabilities are dot-namespaced verbs. Reserved roots: `fs`, `web`, `shell`, `mcp`, `vision`, `voice`, `dispatch`, `memory` (v1.7, §31), `skills`, `ask`, `message`, `tasks` (v1.8, §35). Example: `web.search`, `fs.read`, `shell.exec`, `dispatch.agents`, `memory.subject`.
103
+
104
+ The `capabilities` array in `IDENTITY.md` is the source of truth; `TOOLS.md` **MUST NOT** declare a capability absent from `IDENTITY.md`. A validator MUST flag the mismatch.
105
+
106
+ ### 5.2 Tool bindings (per runtime)
107
+ `TOOLS.md` MAY contain a YAML block mapping each capability to a runtime-specific tool name:
108
+ ```yaml
109
+ web.search:
110
+ cowork: WebSearch
111
+ codex: web_search
112
+ gemini: google_search
113
+ ```
114
+ Tool **implementations** live in application code, never in the agent folder. Only the **wiring** is specified here.
115
+
116
+ ---
117
+
118
+ ## 6 · `hard-rules.md`
119
+ A list of rules the agent **MUST NOT** violate, in prose or bullets. Referenced by `IDENTITY.md:hard_rules` (which MAY be a shared file used by multiple agents). A conformant loader **MUST** place `hard-rules` in the cached prefix (§13) so they are always present, and **SHOULD** support an automated rule-check.
120
+
121
+ ---
122
+
123
+ ## 7 · `memory/`
124
+
125
+ | Path | Role | Notes |
126
+ |---|---|---|
127
+ | `memory/lessons.md` | recall | scanned at session start; append-only |
128
+ | `memory/log/` | archival | one file per session, **race-safe** |
129
+ | `memory/private/` | private | visible only to this agent |
130
+ | `memory/team/` | team | visible to agents sharing a `team_id` |
131
+ | `memory/global/` | global | visible to all agents |
132
+
133
+ - Archival log files **MUST** be named `YYYY-MM-DD-<topic>.md` and **MUST NOT** be appended to concurrently by two processes (race-safe rule: one file per session).
134
+ - Visibility is determined by **folder**, not metadata. Promotion between layers is a file **move**.
135
+ - A loader **MUST** only surface memory an agent is permitted to read (its own `private`, its `team`, and `global`).
136
+ - §7 holds the agent's **own** memory (procedure, lessons). Facts about the people, groups and projects an agent serves **MUST NOT** be written here — they belong in subject memory (§31–§33), outside the repo. What a person says about themselves is their card (§38), also outside the agent folder.
137
+
138
+ ---
139
+
140
+ ## 8 · `evals/`
141
+
142
+ An agent SHOULD ship at least three **gold cases**. Each gold case is a markdown file with frontmatter:
143
+
144
+ ```yaml
145
+ ---
146
+ id: case-01-...
147
+ runs: 10 # times to execute (consistency measurement)
148
+ ---
149
+ ```
150
+ The body **MUST** contain: an **Input**, a **checklist** of programmatically-verifiable requirements (including at least one **planted trap** the agent must not fall for), an OPTIONAL **rubric** for LLM-judging, and **pass thresholds**.
151
+
152
+ `evals/rubric.md` MAY hold a shared rubric. A conformant `eval` runner (§ tooling) **MUST**:
153
+ 1. run each case `runs` times,
154
+ 2. apply programmatic checks and (if present) an LLM-judge,
155
+ 3. grade the **end state / output**, never the execution path,
156
+ 4. report a score per case plus a **diff against the previous run**,
157
+ 5. compute a consistency metric (pass^k) for customer-facing reliability.
158
+
159
+ ---
160
+
161
+ ## 9 · Multi-agent — `WORK.md`
162
+
163
+ `WORK.md` is the work-chain for a multi-agent run, expressed as a **declarative DAG**.
164
+
165
+ ### 9.1 Task record
166
+ Each task **MUST** declare:
167
+
168
+ | Field | Req | Notes |
169
+ |---|---|---|
170
+ | `id` | MUST | unique within the file |
171
+ | `title` | MUST | short imperative |
172
+ | `status` | MUST | `todo \| doing \| done \| blocked` |
173
+ | `owner` | MUST | exactly one owner: an agent (`<name>` or `agent:<name>`) or, v1.9, a person (`person:<slug>`, §40) |
174
+ | `blockedBy` | OPTIONAL | list of task ids (dependencies) |
175
+ | `objective` | MUST | what "done" means |
176
+ | `output_format` | MUST | expected shape of the result |
177
+ | `tool_guidance` | SHOULD | which tools/sources to use |
178
+ | `boundaries` | MUST | what NOT to do / scope limits |
179
+
180
+ The last four fields are the **four-part task contract**. Omitting any of `objective`, `output_format`, `boundaries` **MUST** be a validation error (under-specified tasks cause agent drift).
181
+
182
+ ### 9.2 Ownership & advancement (normative)
183
+ - A `WORK.md` **MUST** have exactly one **controller**, and it **MUST** be an agent (a person may own steps, never the chain — §40); only the controller writes `WORK.md`. Sub-agents **MUST NOT** reassign tasks to each other (this prevents infinite handoff loops).
184
+ - Advancement **MUST** be deterministic: a runner reads dependencies and dispatches every task whose `blockedBy` is satisfied. An LLM **MUST NOT** freely decide task ordering; LLM autonomy is confined to *within a step* and to explicitly open-ended routing tasks.
185
+ - Independent tasks **MAY** be dispatched in parallel (fork-join). Each parallel task **MUST** write to its own files (race-safe); no two tasks write the same file.
186
+
187
+ ---
188
+
189
+ ## 10 · `blackboard/`
190
+
191
+ A shared information space. Each entry is **one append-only file**:
192
+ ```
193
+ blackboard/<YYYY-MM-DD>-<author>-<slug>.md
194
+ ```
195
+ with frontmatter `type` (`discovery | decision | request | progress | warning`), `author`, `visibility` (`team | global`), and OPTIONAL `expires_at`.
196
+
197
+ - Writers **MUST NOT** modify another agent's entry (append-only).
198
+ - On task start, a loader **SHOULD** surface entries relevant to the task (entity/keyword match), placed in the **volatile** context region (§13).
199
+ - Entries without `expires_at` default to a 7-day lifetime; `scroll prune` removes expired entries.
200
+
201
+ ---
202
+
203
+ ## 11 · `registry.md`
204
+
205
+ A generated table of agent track-record, used for capability-aware dispatch:
206
+ `agent · task_type · runs · success_rate · avg_tokens · avg_duration`.
207
+
208
+ It is **derived** from `memory/log/` by a conformant tool and **MUST NOT** be hand-maintained as the source of truth. Dispatch logic MAY weight by success rate, recency, and token efficiency.
209
+
210
+ ---
211
+
212
+ ## 12 · Token governance
213
+
214
+ A SCROLL repo **MUST** support hard caps, configured in `scroll.config.*`:
215
+
216
+ ```yaml
217
+ budget:
218
+ per_run_usd: 25
219
+ per_iteration_tokens: 4000
220
+ max_iterations: 50
221
+ recursion_depth: 2
222
+ wall_clock_minutes: 60
223
+ on_exceed: pause # pause | downgrade | abort
224
+ ```
225
+
226
+ - A conformant runner **MUST** enforce these as **hard** limits with a circuit breaker. On breach it **MUST** take `on_exceed` action and **SHOULD** notify a human.
227
+ - A token **ledger** (running tally) **SHOULD** be written to `ledger.md` (or the storage backend) and is the basis for cost reporting.
228
+ - Before spawning multiple agents, a runner **SHOULD** estimate single-vs-multi cost and prefer single-agent unless the task is parallel and read-heavy.
229
+
230
+ ---
231
+
232
+ ## 13 · Context assembly & caching (normative)
233
+
234
+ A loader **MUST** assemble an agent's context in two regions, in this order:
235
+
236
+ ```
237
+ [ STABLE PREFIX ] → cache breakpoint → [ VOLATILE SUFFIX ]
238
+ tool/MCP definitions current task (WORK.md)
239
+ hard-rules fresh blackboard entries
240
+ IDENTITY (frontmatter + body) timestamps, prior step output
241
+ SOUL retrieved memory
242
+ pinned skill indexes
243
+ people block (§39)
244
+ ```
245
+
246
+ - The stable prefix **MUST** be byte-identical across ticks of the same agent so provider prompt-caching hits. Tools **MUST NOT** interleave volatile content into the prefix.
247
+ - Where a provider's default cache lifetime is short, loaders **MUST** set an explicit cache TTL; cached reads are typically billed at a small fraction of fresh input. Consult the provider's caching documentation — this spec fixes no vendor's numbers. See [`docs/prompt-caching.md`](./docs/prompt-caching.md) for the reference chat-session layout and per-provider adapter behavior (Anthropic 3-breakpoint caching, OpenAI `prompt_cache_key`, Codex App-Server persistent `threadId` reuse, and Gemini explicit `cachedContent`).
248
+ - Skills are referenced by **index** (name + one-line description) in the prefix; full skill bodies load **on demand** (progressive disclosure). §34 specifies the loader, the index and the read tools; skill *content* is out of scope.
249
+
250
+ ---
251
+
252
+ ## 14 · The Runner
253
+
254
+ A conformant runner drives one heartbeat loop:
255
+ ```
256
+ wake → load context → pick ready task(s) → dispatch → write result + checkpoint → stop-check → sleep|halt
257
+ ```
258
+
259
+ - **Checkpoint:** after each tick the runner **MUST** persist state durably (a git commit locally, or a write to the storage backend) such that a crashed run resumes from the last checkpoint.
260
+ - **Decomposition:** long objectives **MUST** be split into short, individually-verifiable units; the runner **SHOULD** verify per step and track per-step success.
261
+ - **Human gates:** any irreversible external action (send, pay, delete, post) **MUST** halt and await an approval file under `gates/`.
262
+ - **Stop conditions:** the runner **MUST** halt on objective-complete, budget breach (§12), or a watchdog timeout.
263
+
264
+ ---
265
+
266
+ ## 15 · Transpilation
267
+
268
+ `scroll build` renders the source to one artifact per declared runtime. Runtime registry (extensible): `cowork`, `codex`, `gemini`, `claude-subagent`, `voice`, `a2a`.
269
+
270
+ - Transpilers **MUST** be deterministic: identical source ⇒ identical output.
271
+ - Renderings **MUST** carry a generated-file marker and **MUST NOT** be edited by hand; a conformant tool **SHOULD** warn on drift between source and rendering.
272
+ - A2A export produces a static Agent Card JSON from frontmatter; it does not require a running endpoint.
273
+
274
+ ---
275
+
276
+ ## 16 · Storage adapters
277
+
278
+ State access is abstracted behind a path-addressed read/write interface. A conformant loader **MUST** support at least `local-fs` and **SHOULD** support an object-store driver.
279
+
280
+ ```yaml
281
+ # scroll.config.yaml
282
+ storage:
283
+ driver: s3 # local-fs | s3 | gcs | repo
284
+ bucket: my-agents
285
+ prefix: ${TENANT} # multi-tenant isolation
286
+ ```
287
+
288
+ - Agent **definitions** are read-only config shipped with the deployment.
289
+ - Runtime **state** (`WORK.md`, `blackboard/`, `memory/`, `ledger`) is addressed by path and stored via the driver. Agent code **MUST NOT** assume a local filesystem.
290
+ - Multi-tenant deployments **MUST** namespace state by tenant/run prefix.
291
+
292
+ ---
293
+
294
+ ## 17 · Conformance levels & validation
295
+
296
+ `scroll check` reports against three levels:
297
+
298
+ | Level | Requires |
299
+ |---|---|
300
+ | **L0 — Valid agent** | `IDENTITY.md` frontmatter valid; `SOUL.md` present; capabilities consistent with `TOOLS.md` |
301
+ | **L1 — Gradeable** | L0 + ≥3 gold cases in `evals/`; `hard-rules` present |
302
+ | **L2 — Multi-agent ready** | L1 + any `WORK.md` satisfies the four-part contract and single-controller rule |
303
+
304
+ - Validation is **linter-style**: structural violations are **errors**; style/extension issues are **warnings**. A conformant tool SHOULD run `check` in pre-commit and CI.
305
+ - The repo root SHOULD contain `AGENTS.md` instructing AI tools to follow this spec.
306
+
307
+ ---
308
+
309
+ ## 18 · Observability & control
310
+
311
+ A conformant runner **MUST** emit an event stream and **MUST** honor control files. This is the surface through which users observe and steer a run.
312
+
313
+ ### 18.1 Event stream
314
+ Events are written append-only to `runs/<run-id>/events.jsonl`, one JSON object per line:
315
+ ```json
316
+ { "ts": "<iso8601>", "run": "<run-id>", "agent": "<name>", "type": "<type>", "data": { } }
317
+ ```
318
+ `type` **MUST** be one of: `run_started`, `step_started`, `thought`, `tool_call`, `tool_result`, `message`, `state_update`, `gate_request`, `cost_update`, `run_completed`, `error`. Events **MUST** be append-only. Consumers tail the file (local) or subscribe via an SSE/WebSocket gateway (cloud). Event types **SHOULD** map to the **AG-UI** protocol so standard frontends can render them.
319
+
320
+ ### 18.2 State polling
321
+ Current run state **MUST** be derivable by reading `WORK.md` (task statuses) plus the ledger (tokens/cost) — without replaying the event stream. Polling is a cheap file read.
322
+
323
+ ### 18.3 Control
324
+ A runner **MUST** check `control/` at the start of every tick and honor:
325
+ - `control/pause`, `control/resume`, `control/stop` — presence-based signals
326
+ - `control/steer.md` — guidance injected into the next step's context
327
+ - `control/approvals/<gate-id>` — approval for a pending must-approve gate (§21). From v1.9 the file names its approver (`{ "by": "<slug>" }`); with a team configured the runner checks that person's card (§40.2).
328
+ - `control/done/<task-id>.json` — v1.9: the person who owns a step marks it done (`{ "by": "<slug>" }`, §40.1). The runner writes the matching request to `control/requests/<task-id>.json`. (The v1.3 draft wrote this as `gates/<id>.approved`; `control/approvals/` is normative from v1.4. A conformant runner SHOULD also accept the legacy `control/<id>.approved` for back-compat.)
329
+
330
+ `thought` (chain-of-thought) events are **advisory transparency**, not authoritative; consumers **MUST NOT** treat them as ground truth.
331
+
332
+ ### 18.4 Backend tracing
333
+ A runner **SHOULD** emit **OpenTelemetry GenAI** spans (LLM client, agent, tool) for backend observability, independently of the user-facing event stream.
334
+
335
+ ---
336
+
337
+ ## 19 · Tools, MCP, connectors, skills & plugins
338
+
339
+ SCROLL specifies how capabilities **attach** to an agent; it does not ship their implementations. It is **MCP-first** and reuses standard formats. The wiring is installed by `scroll mcp add` / `scroll skill add` / `scroll plugin add` (implemented in impl 0.8.0) — they only edit `.mcp.json`, `skills/`, and `agents/`; the runtime reads those files.
340
+
341
+ ### 19.1 Tools & MCP
342
+ - An agent declares logical `capabilities` in `IDENTITY.md` and per-runtime `tool_bindings` in `TOOLS.md` (§5).
343
+ - MCP servers are declared in a standard **`.mcp.json`** (repo-level or under `agents/<name>/.mcp.json`). A loader **MUST** connect to declared servers and expose their tools to the agent when the agent has the `mcp.client` capability. Tool *implementations* come from the MCP server, not the agent folder.
344
+
345
+ ### 19.2 Connectors
346
+ A connector (Gmail, Slack, Notion, …) is an MCP server plus credentials. Credentials **MUST** be referenced via `${vault:KEY}` and resolved at load time; they **MUST NOT** appear in any agent file. A conformant tool **SHOULD** integrate an MCP/connector registry for discovery (`scroll mcp add`).
347
+
348
+ ### 19.3 Skills
349
+ - A skill is a directory containing **`SKILL.md`** in the open Agent Skills format: frontmatter `name` and `description` (REQUIRED), `license`, `compatibility`, `metadata`, `allowed-tools` (OPTIONAL), then a markdown body; optional `scripts/`, `references/`, `assets/`. (v1.8: `triggers` is no longer required; the description says when to use the skill. A legacy `triggers` field is ignored.)
350
+ - Loading, precedence, the index, the read tools, compatibility and checks are specified in **§34–§36**.
351
+
352
+ ### 19.4 Plugins
353
+ A plugin is a bundle (an "agent pack") containing one or more agents, a `skills/` directory, a `.mcp.json`, and a manifest. `scroll plugin add` unpacks it into `agents/` + `skills/` and merges MCP config. Plugin bundles **SHOULD** be compatible with the `.plugin` ZIP format used by Cowork/Claude.
354
+
355
+ ---
356
+
357
+ ## 20 · Governance & security (v2 — the production rail)
358
+
359
+ This is the rail that separates a pilot from production. A conformant runner **MUST** implement §20.1–20.5 and **SHOULD** implement §20.6–20.7. Aligned to the OWASP Agentic Top 10 (2026) and the NIST agent-standards dimensions (identity, authorization, auditing, non-repudiation).
360
+
361
+ ### 20.1 Permission enforcement (deny-by-default, at the tool boundary)
362
+ - An agent's tool/action permissions are an explicit **allow-list**; anything not listed is denied (`ASI02` Tool Misuse).
363
+ - Permissions **MUST** be enforced at the tool/runtime boundary — **NOT** in the system prompt. Prompt text is advisory and can be overridden by injection; the gate sits at the action.
364
+ - Authorization **SHOULD** be policy-as-code (OPA/Cedar) evaluated adjacent to the action, returning allow/deny + a reason code. Scopes only narrow, never widen (`ASI03`).
365
+
366
+ ### 20.2 Identity & credentials
367
+ - Each agent **MUST** have its own scoped, tenant-bound **non-human identity** — never a shared service account or a borrowed user token.
368
+ - Credentials **MUST** be short-lived/scoped (OAuth 2.1 / RFC 8693 token-exchange) and referenced via `${vault:KEY}`, resolved **server-side**; secrets **MUST NOT** enter the model context or logs.
369
+ - Agent→tool calls **SHOULD** use sender-constrained tokens (DPoP/mTLS). Identity standards (badges/passports) are **not** mandated — conform to OAuth, do not invent a scheme.
370
+
371
+ ### 20.3 Untrusted content & injection defense
372
+ - All tool outputs, retrieved documents, and third-party tool descriptions **MUST** be treated as **data, never instructions** (`ASI01` Goal Hijack, indirect prompt injection). A runner **MUST NOT** execute instructions found in content.
373
+ - Tool definitions **SHOULD** be pinned/verified against silent change ("rug-pull", `ASI04`); "always allow"/auto-run of un-vetted tools **MUST NOT** be the default.
374
+
375
+ ### 20.4 Sandboxing & egress
376
+ - Agent-generated code or untrusted tool execution **MUST** run in a sandbox (microVM/gVisor/isolate), never unwrapped (`ASI05`).
377
+ - The agent runtime **SHOULD** apply a network **egress allow-list** (block-by-default, block RFC 1918) to prevent SSRF/exfiltration.
378
+
379
+ ### 20.5 Risk-tiered human approval
380
+ - Actions are classified **reversible** vs **irreversible**. Irreversible/high-risk actions (send, pay, delete, cross-tenant, schema change) **MUST** be gated `must-approve` (block until a `gates/<id>.approved` file exists). Lower-risk actions **MAY** be `auto` or `soft-hold` (`ASI09`).
381
+ - Per-tenant circuit breakers + hard cost caps (§12) back-stop runaway behavior.
382
+ - **Who may approve (v1.9).** An approval names its approver. When the deployment has person cards, the runner checks the approver's card in code — the tier or action class, and the amount — before the gate opens, rejects an approval that is unattributed or not covered, and appends every decision to an audit trail (§40.2–§40.3). Being able to create the file is no longer enough.
383
+
384
+ ### 20.6 Audit & provenance
385
+ - A runner **SHOULD** write a tamper-evident, per-action audit record binding `actor (agent+tenant) · authority/scope · action/resource · SHA-256(input,output) · policy decision · approver`, hash-chained (aligned to the IETF Agent Audit Trail draft), correlated by OpenTelemetry trace-id.
386
+
387
+ ### 20.7 Data governance
388
+ - A runner **SHOULD** redact/mask PII at the tool boundary before data enters context, tag data residency, and apply per-class retention. Inadvertently logged secrets **MUST** be purged.
389
+
390
+ ### 20.8 Frontmatter additions (v2)
391
+ `IDENTITY.md` MAY declare:
392
+ ```yaml
393
+ security:
394
+ tools_allow: [web.search, fs.read] # deny-by-default allow-list
395
+ egress_allow: ["api.example.com"] # network allow-list
396
+ identity: scoped # scoped non-human identity
397
+ risk_defaults: # v1.4 — capability → tier (§21.3)
398
+ fs.read: read_only
399
+ shell.exec: destructive
400
+ mcp.*: external_comm
401
+ approval: # v1.4 — tier → policy (§21.2)
402
+ external_comm: soft-hold # auto | auto-log | soft-hold | must-approve
403
+ financial: must-approve
404
+ destructive: must-approve
405
+ ```
406
+
407
+ ---
408
+
409
+ ## 21 · Risk-tiered permission matrix (v1.4)
410
+
411
+ This refines §20.5 from a binary (reversible/irreversible) into a five-tier matrix, and fixes the **enforcement point at the action boundary** — a conformant runner evaluates it in code, immediately before an action, **never** by asking the model to self-restrain.
412
+
413
+ ### 21.1 Tiers
414
+ Every action **MUST** be classified into exactly one tier (lowest → highest consequence):
415
+ `read_only` · `reversible_write` · `external_comm` · `financial` · `destructive`.
416
+ An action whose tier cannot be determined **MUST** be treated as `destructive` (fail-safe / deny-by-default).
417
+
418
+ ### 21.2 Matrix (default policies, overridable)
419
+ | tier | default policy |
420
+ |---|---|
421
+ | `read_only` | `auto` |
422
+ | `reversible_write` | `auto-log` (execute + audit record §20.6) |
423
+ | `external_comm` | `soft-hold` |
424
+ | `financial` | `must-approve` **+ grounding (§22)** |
425
+ | `destructive` | `must-approve` **+ grounding (§22)** |
426
+
427
+ - `must-approve` **MUST** block until an approval file exists at `control/approvals/<gate-id>` (§18.3).
428
+ - `soft-hold` **MAY** execute after a configurable hold; `auto`/`auto-log` execute immediately.
429
+ - A `financial` policy **MAY** carry a `threshold` so amounts below it are `soft-hold` and above it `must-approve`.
430
+
431
+ ### 21.3 Where risk is declared (data, not prose)
432
+ Risk is **machine-readable** and resolved by the runner, in precedence order: (1) a per-tool `risk` in `.mcp.json`; (2) `IDENTITY.security.risk_defaults` keyed by capability (exact, then namespace glob like `mcp.*`); (3) the `destructive` fallback. A risk label **MUST NOT** be taken from a markdown body — prompt text is advisory and injectable (§20.1).
433
+
434
+ ### 21.4 Decision & events
435
+ The runner emits `permission_decision { tool, tier, policy, decision: allow|await|deny, reason }`. `deny` (e.g. grounding failure) **MUST** take precedence over an approval — an approved-but-ungrounded action still does not run. Legacy `gate_requested`/`gate_approved`/`gate_blocked` events remain for back-compat; the v1.3 task risk `irreversible` is an alias for `destructive`.
436
+
437
+ ---
438
+
439
+ ## 22 · Grounding pre-check (v1.4)
440
+
441
+ Before any `financial` or `destructive` action, a runner **SHOULD** verify that every **critical parameter** declared for it (e.g. a product code, an amount, a customer id) traces to a real source already present in the run — the `blackboard/`, a prior `tool_result`, `control/steer.md`, or the task objective.
442
+
443
+ - The check is **deterministic**: it matches parameters by exact/regex token (codes, ids) or digits (amounts). It **MUST NOT** rely on an LLM judgment of "semantic" grounding — that would re-introduce model trust.
444
+ - Parameters to ground are declared per-tool in `.mcp.json` (`{ "issue_invoice": { "risk": "financial", "ground": ["code","amount"] } }`) or on a `WORK.md` task (`ground:`).
445
+ - On a missing trace the runner **MUST** emit `grounding_failed` and **MUST NOT** execute the action. A passing check emits `grounding_checked { traced, missing, passed }`.
446
+
447
+ ---
448
+
449
+ ## 23 · `LOOP.md` — the outer loop (v1.4)
450
+
451
+ `scroll run` is the **inner loop** (one harnessed execution). `LOOP.md` defines the **outer loop**: when to start an inner loop, where it finds work, and when to stop. A conformant `scroll loop` rides the host scheduler; it introduces **no engine, DB, or daemon runtime**.
452
+
453
+ ### 23.1 Frontmatter (normative)
454
+ | Field | Req | Notes |
455
+ |---|---|---|
456
+ | `id` | MUST | unique loop id |
457
+ | `controller` | MUST | exactly one owner |
458
+ | `work_source` | MUST | `{ type: work_file \| inline \| glob, query }` — where each iteration's work comes from |
459
+ | `stop_conditions` | MUST | at least one of `max_runs`, `max_runs_per_day`, `budget_usd_per_day`, `until`, or a non-empty `halt_on[]` |
460
+ | `schedule` | SHOULD | `{ cron }` or `{ interval_ms }` or `{ on_event }` |
461
+ | `budget` | SHOULD | per-loop and per-run caps |
462
+ | `digest` | SHOULD | `required` to write a digest (§18) after each inner run |
463
+
464
+ ### 23.2 Rules
465
+ - A `LOOP.md` with **no** stop condition **MUST** be refused (a loop that can't stop is unsafe).
466
+ - The outer loop **MUST NOT** escalate privilege: every action in each inner run is still subject to §21.
467
+ - Loop state (runs today, spend today) **MUST** persist (e.g. `runs/loop-<id>/state.json`) so stop conditions hold across process restarts.
468
+
469
+ ---
470
+
471
+ ## Appendix A · `IDENTITY.md` frontmatter JSON Schema
472
+
473
+ ```json
474
+ {
475
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
476
+ "$id": "https://agentpro.dev/scroll/identity-1.9.json",
477
+ "title": "SCROLL IDENTITY frontmatter",
478
+ "type": "object",
479
+ "required": ["name", "title", "version", "runtimes", "model", "capabilities"],
480
+ "additionalProperties": true,
481
+ "properties": {
482
+ "name": { "type": "string", "pattern": "^[a-z][a-z0-9-]*$" },
483
+ "title": { "type": "string", "minLength": 1 },
484
+ "version": { "type": "string", "pattern": "^\\d+\\.\\d+\\.\\d+$" },
485
+ "pronoun": { "type": "string" },
486
+ "language":{ "type": "string" },
487
+ "position":{ "enum": ["c-suite", "above-c-suite", "outside-org", "runtime"] },
488
+ "reports_to": { "type": "string", "pattern": "^(user|role:[a-z][a-z0-9_-]*|[a-z][a-z0-9-]*)$" },
489
+ "serves": { "type": "array", "items": { "type": "string", "pattern": "^(role:)?[a-z][a-z0-9_-]*$" } },
490
+ "runtimes": {
491
+ "type": "array", "minItems": 1,
492
+ "items": { "enum": ["cowork", "codex", "gemini", "claude-subagent", "voice", "a2a"] }
493
+ },
494
+ "model": {
495
+ "type": "object",
496
+ "required": ["primary"],
497
+ "properties": {
498
+ "primary": { "type": "string" },
499
+ "fallback": { "type": "string" },
500
+ "voice": { "type": "string" },
501
+ "voice_id": { "type": "string" }
502
+ }
503
+ },
504
+ "capabilities": {
505
+ "type": "array",
506
+ "items": { "type": "string", "pattern": "^(fs|web|shell|mcp|vision|voice|dispatch|memory|skills|ask|message|tasks)\\.[a-z_]+$" }
507
+ },
508
+ "dispatch": {
509
+ "type": "object",
510
+ "properties": {
511
+ "authority": { "enum": ["none", "low", "medium", "high"] },
512
+ "can_dispatch": { "type": "array", "items": { "type": "string" } },
513
+ "spawn_template":{ "type": "string" }
514
+ }
515
+ },
516
+ "hard_rules": { "type": "string" },
517
+ "memory": { "type": "object" },
518
+ "a2a": { "type": "object" }
519
+ }
520
+ }
521
+ ```
522
+
523
+ ---
524
+
525
+ ## Appendix B · Minimal valid agent (L0)
526
+
527
+ ```
528
+ agents/echo/
529
+ ├── IDENTITY.md
530
+ └── SOUL.md
531
+ ```
532
+ `IDENTITY.md`:
533
+ ```yaml
534
+ ---
535
+ name: echo
536
+ title: Echo
537
+ version: 0.1.0
538
+ runtimes: [cowork]
539
+ model: { primary: claude-haiku-4-5 }
540
+ capabilities: []
541
+ ---
542
+ ```
543
+ `SOUL.md`:
544
+ ```
545
+ You repeat the user's message back, clearly and briefly.
546
+ ```
547
+
548
+ ---
549
+
550
+ ## Versioning
551
+
552
+ This spec is versioned with semver. Renderings and validators declare the spec version they target. Backward-incompatible changes increment MAJOR. Agents declare their own `version` independently of the spec version.
553
+
554
+ | Spec | Reference impl | Adds |
555
+ |---|---|---|
556
+ | 1.9 | 0.14.0 | §38–§41 people in the agent team: person cards, binding by role, person-owned steps, approvals checked against the approver's card, privacy audit. Backward compatible: `pronoun` and `reports_to: user` still validate (warnings); without person cards, approvals behave as in 1.8. |
557
+ | 1.8 | 0.13.0 | §34–§36 skills |
558
+ | 1.7 | 0.12.0 | §31–§33 subject memory |
559
+ | 1.6 | 0.11.0 | §28–§30 effect confirmation, ungraded ≠ pass, fixture provenance |
560
+ | 1.5 | 0.9.0 | §24–§27 ledger, planner, try-budget, proof |
561
+ | 1.4 | 0.8.0 | §21–§23 risk tiers, grounding, `LOOP.md` |
562
+
563
+ *SCROLL Specification v1.9 · reference implementation `@agentpro/scroll` 0.14.0 — Agent Pro. Companion: `README.md`, `AGENTS.md`, `templates/agent/`, `templates/work/LOOP.md`.*
564
+
565
+ ---
566
+
567
+ ## §24–27 — v1.5 · Trackable · Self-Driving · Honest-on-Failure
568
+
569
+ New `LOOP.md` fields (all OPTIONAL — backward compatible; `validateLoop` type-checks them only when present):
570
+
571
+ - **§24 `ledger:`** — a human-readable tracking table that spans runs. `local://path.csv|md` (core, zero-dep), or an external URI scheme resolved by an **app-layer adapter** reading `runs/loop-<id>/ledger.jsonl` (the core ships no third-party client). After **every** output — pass or fail — a runner **MUST** append one row: `ts · loop · iteration · task · status · tries · proof · digest`. If `ledger` is unset and the loop is driven through an agent or skill, the runner **MUST** ask the operator where to store it and **MUST NOT** silently default to a remote store. A bare CLI defaults to `local://runs/ledger.csv`.
572
+ - **§25 `planner:`** — a command executed **once, before** the loop, that **generates** the backlog (self-planning: study a reference → enumerate outstanding work → emit `WORK`). It is a plain command, deterministic, outside the model. Absent → v1.4 behaviour (consume pre-existing work).
573
+ - **§26 `max_tries_per_task:`** (default 3) — each task gets N tries of its own; pass → stop early. Exhausted and still failing → record ledger `status: failed` + proof, then **CONTINUE to the next task**. Halt only on `gate_denied` (immediately, no retry) or when `verify_fail ∈ halt_on` (after exhausting N — backward compat). A try-budget is **per task**, never global.
574
+ - **§27 Proof-pack** — `result.proof` (a path/URI to inspectable evidence) is recorded in the ledger. A **failure MUST carry proof** of what was attempted; silent failure is non-conformant. Rendering visual evidence is app-layer; the core mandates only that proof **exists** and is **recorded**.
575
+
576
+ Reference impl: `lib/loop.js` (`validateLoop` + `runLoop`) + `lib/ledger.js`.
577
+
578
+ ---
579
+
580
+ ## §28 — Effect confirmation (v1.6)
581
+
582
+ > Reference impl: `lib/effects.js` (`confirmEffect` · `evalExpect` · `rejectUnknownFields`), audited by `scroll audit`.
583
+
584
+ A write that *reports* success is not evidence that the write *happened*.
585
+
586
+ - A runner **MUST** classify an action as a WRITE when it mutates state outside the run's own memory (tiers `reversible_write | external_comm | financial | destructive`, §21).
587
+ - A WRITE **MUST NOT** be considered successful merely because the call returned a non-error status. Self-reported success is not evidence.
588
+ - The runner **MUST** confirm the effect with an **independent read-back**. The read-back **MUST** be a separate read operation; the write's own response **MUST NOT** be used as its confirmation.
589
+ - If the write reports success but the read-back does not satisfy `expect`, the runner **MUST** emit `effect_unconfirmed` and mark the step **failed**. This is a failure, not a warning.
590
+ - A WRITE at tier `financial | destructive` with no declared `confirm` **MUST** be flagged by `scroll audit`; a conformant runner blocks by default (fail-closed).
591
+
592
+ Declared as data, alongside `risk`/`ground` (§21.3, §22) — never in prose:
593
+
594
+ ```json
595
+ "issue_invoice": {
596
+ "risk": "financial",
597
+ "ground": ["product_code", "amount"],
598
+ "confirm": { "probe": "lookup_invoice", "expect": "$.status == 'issued'" }
599
+ }
600
+ ```
601
+
602
+ Events: `effect_confirmed { tool, probe, ok, observed }` · `effect_unconfirmed { tool, expected, observed }`.
603
+
604
+ **Corollary — fail-closed on unknown input.** An interface that receives a field it does not understand **MUST** reject the request (a 4xx-equivalent carrying `rejected[]`) and **MUST NOT** ignore it silently. Silently dropping input is how a system comes to report success for work it never did; an agent reading that success will then report it onward in perfect good faith. The agent is not lying — the interface is.
605
+
606
+ ---
607
+
608
+ ## §29 — Ungraded is not pass (v1.6)
609
+
610
+ > Reference impl: `lib/eval.js` — `case.verdict` is `'pass' | 'fail' | 'ungraded'`; `report.ungraded` counts them; `ok` requires ≥1 graded case and every graded case passing.
611
+
612
+ A verdict is **ternary**, never boolean:
613
+
614
+ | verdict | meaning |
615
+ |---|---|
616
+ | `pass` | graded — at least one check actually ran, and every check passed |
617
+ | `fail` | graded — a check ran and failed |
618
+ | `ungraded` | **no check ran** — no rubric declared, tooling absent, or the checker itself errored |
619
+
620
+ - `ungraded` **MUST NOT** be coerced to `pass` anywhere: API, UI, ledger (§24), digest, or gate.
621
+ - A UI **MUST** render `ungraded` distinctly from `pass` — a neutral marker, never a check-mark.
622
+ - A `must-approve` gate (§21) treats `ungraded` as `fail` (fail-closed).
623
+ - Ledger `status` accepts `ungraded`; a digest (§18) **MUST** count it separately. "3 done" where two were never graded is a false report.
624
+ - When a checker cannot run (missing dependency, unavailable tool), its result is `ungraded` — **never** `pass`.
625
+
626
+ Rationale: a harness in which "not measured" and "measured and good" are indistinguishable renders every green number it emits meaningless — and makes §27 proof worthless.
627
+
628
+ ---
629
+
630
+ ## §30 — Fixture provenance (v1.6)
631
+
632
+ > Reference impl: `lib/eval.js` (`parseFixture`) prints provenance beside every verdict; `scroll audit` warns on a missing/invalid provenance and on a suite that is entirely `synthetic`. The shipped scaffold declares its own provenance.
633
+
634
+ §8 requires grading the end state rather than the execution path. It is silent on **where the precondition came from** — and that silence lets a green suite prove nothing.
635
+
636
+ If a case's precondition was created **by hand** rather than by the product's own path, the case says nothing about that path. Every gold case (§8) **MUST** declare its fixture's provenance:
637
+
638
+ ```yaml
639
+ ---
640
+ id: case-01-...
641
+ fixture:
642
+ provenance: product-path | recorded | synthetic # REQUIRED
643
+ setup: <command/path that creates the precondition> # REQUIRED when provenance = product-path
644
+ ---
645
+ ```
646
+
647
+ - `product-path` — the precondition is produced by the product's own path, the one an operator takes. **Default.**
648
+ - `recorded` — captured from a real environment; carries a hash and a source.
649
+ - `synthetic` — hand-constructed. **MUST** carry a `justification`, and **MUST NOT** count as evidence for the path that would otherwise have created that precondition.
650
+ - Any capability that carries state (a schedule, an account, a permission, a subscription) **MUST** have at least one `product-path` case covering its **arm/setup** path — not only its **execute** path. Exercising `execute` against a hand-made precondition leaves `arm` completely unverified while the suite stays green.
651
+ - `scroll eval` **MUST** print provenance beside every verdict; `scroll audit` **MUST** warn when a capability is covered only by `synthetic` cases.
652
+
653
+ **Never hand-mutate the state of the system you are grading.** If a fixture must be hand-patched before a case will run, the case has just found a defect — not an inconvenience.
654
+
655
+ ---
656
+
657
+ ## §31 — Subject memory (v1.7)
658
+
659
+ > Reference impl: `lib/memory.js` (`openStore`) · CLI `scroll memory …` (`lib/memory-cli.js`) · read path wired into `scroll run` (`task.subject`) · tests `test/v17.smoke.mjs`, including a mutation self-test.
660
+
661
+ §7 is the memory an **agent** keeps about its own work. §31 is the memory an agent keeps about the **subjects it serves**: a person, a group, a project, or another agent. The rule that governs everything below: **the agent proposes, the machine decides.** A model may suggest that something be remembered; only a gate written in code turns it into a durable fact.
662
+
663
+ ### 31.1 Store and identity
664
+
665
+ - Subject memory lives in a **data plane outside git and outside every workdir**. A store located inside a run's workdir **MUST** be refused (`store_inside_workdir`). Any raw tool path (shell, file read/write) that resolves into the store **MUST** be treated as tier `destructive` before normal tier resolution — the loader and the `memory.*` capabilities are the only legal way in.
666
+ - A subject id is opaque and immutable: `s_<region>_<16 hex>`, never derived from personal data. The region is part of the id, so routing is a path.
667
+ - Storage is sharded by the hex of the id: `subjects/<hh>/<hh>/<sid>/`. **One directory per subject; no file may hold the content of two subjects** (search indexes, ledgers and caches included).
668
+ - Channel identities (`telegram:<id>`, an email, a phone, `device:<id>`, `mcp:<client>`) are **aliases**: stored as `sha256(normalize(alias)) → sid`. An alias that already points at another subject is refused (`alias_conflict`); merging is an explicit operation.
669
+ - Raw sids never leave the data plane: events, digests and ledgers carry an HMAC pseudonym.
670
+
671
+ ### 31.2 Journal leads, projections follow
672
+
673
+ ```
674
+ <sid>/journal/CURRENT · seg-NNNN.jsonl · seg-NNNN.jsonl.sealed # source of truth for facts
675
+ <sid>/profile.json · index.md · days/ · sessions/*.card.md # projections — rebuildable
676
+ ```
677
+
678
+ - A write takes the subject lock, appends, fsyncs, and **confirms by reading back** (§28) before it counts. Projections are replaced by atomic rename.
679
+ - A checkpoint is a **structural** marker in journal order; the tail after it is ordered by `(ts, append order)`, so replaying a journal twice yields byte-identical projections, and an op appended after a checkpoint with an earlier clock still survives.
680
+ - Consolidation is bracketed (`consolidate_start` … `consolidate_end`), writes a checkpoint as the first line of a new segment, seals the old ones, and appends an **anchor** — a running hash over every journal line. `fsck` recomputes it; a line edited behind the store's back breaks every later anchor. A torn tail is skipped on read and truncated by `fsck --repair`.
681
+ - Invariant (machine-checked): at most **one active fact per `(key, about)`**; a new value supersedes the old one, which stays queryable with `superseded_by`.
682
+
683
+ ### 31.3 Fact schema
684
+
685
+ `id · key (namespace.key, registered in the taxonomy) · value · about (self | person:<slug> | group) · provenance · evidence · sensitivity · derived_from? · expires_at? · status`
686
+
687
+ Provenance is a closed vocabulary: `stated` (the subject said it) · `agent_observed` · `system_verified` · `user_edit` · `derived` (consolidated from cited facts). Evidence for `stated` / `agent_observed` is `{ ref: "<session>#<seq>", quote }` — a pointer to a stored turn and a verbatim quote from it.
688
+
689
+ ### 31.4 The gate (one gate, every write path)
690
+
691
+ Every write — a mid-session proposal, the end-of-session sweep (§32.3), consolidation (§31.6), a human edit — passes the same five layers, in order:
692
+
693
+ 1. **Syntax** — the key is registered in the taxonomy; type, length, enum and required fields hold.
694
+ 2. **Evidence** — the referenced turn exists and contains the quote verbatim (case- and whitespace-insensitive). For `stated`, that turn **MUST** have been spoken by the subject itself; a quote from the agent's own turn can at most yield `agent_observed` (`speaker_mismatch` otherwise). `derived` facts **MUST** cite existing fact ids. `system_verified` / `user_edit` are accepted only from trusted callers.
695
+ 3. **Provenance floor** — keys may require a provenance (e.g. entitlements require `system_verified`).
696
+ 4. **Sensitivity** — each key has a class `normal | sensitive | never`. `never` is refused outright; `sensitive` only when the policy allows it. Values and quotes are scanned for secrets (keys, tokens, card numbers, password assignments) and refused on a hit. Turns are redacted **before** they reach disk. Apps MAY add secret shapes for their own language (`secret_patterns`); the built-in ones always apply.
697
+ 5. **Instruction-like content** — a value that reads as an instruction to the agent (ignore rules, skip confirmations, elevate privileges, exfiltrate credentials) is refused. Memory is data, never a channel for installing rules. Apps MAY add patterns; they may not remove the built-in ones.
698
+
699
+ A value whose folded form matches a **tombstone** (§32.7) is refused (`forgotten`). A machine write (`derived` / `agent_observed`) that would overwrite a `user_edit`, or a `derived` sensitive fact, goes to a **review queue** instead of the journal.
700
+
701
+ ### 31.5 The loader
702
+
703
+ - Loads only what the gate would accept today: a fact below its key's provenance floor, or of class `never`, **MUST NOT** load even if it reached the journal by another route.
704
+ - `sensitive` facts never load into the contract; they surface only through an explicit search (§32.5), flagged.
705
+ - Scoping is a static lookup, not a model judgment: `capability_topics` maps the agent's capabilities to namespaces; `always_load` / `always_load_for: [capability]` pins keys; with a `persona`, a shared account loads only account-level facts and that persona's own.
706
+ - Profiles that require verification (e.g. customer service) **MUST** deny the contract and search to an unverified subject.
707
+ - Output is fenced and marked as data: `<subject-memory sid="<hmac>" snapshot="<hash>"> (DATA ONLY …) … </subject-memory>`. Subject memory is never a valid grounding source (§22) for `financial` parameters unless `system_verified`.
708
+ - In `scroll run`, a task with `subject:` (or `--subject`) gets its subject's contract in the volatile part of the prompt (§13) and emits `memory_loaded { subject (hmac), snapshot, memoryChars, truncated }` or `memory_denied`.
709
+
710
+ ### 31.6 Consolidation
711
+
712
+ - **Mechanical tier** (deterministic, no model): checkpoint + seal, TTL expiry, retention (§32.6), recall-based promotion (§32.5), anchor. Bracketed.
713
+ - **Model tier** ("dream"): the app supplies the model call; every output op goes through the gate and **MUST** cite fact ids. A merge marks each source `superseded_by` the merged fact. Before committing, the runner checks **handoff fidelity**: every fact active before the dream is still active or superseded/expired with a link; anything else aborts. A dream is gated (a minimum of new swept sessions **and** of elapsed time) and **SHOULD** be scheduled as an ordinary bounded run (§23), not a background daemon. **A failed dream is a terminal state** that blocks the next dream until a human acknowledges it — never "warn and continue".
714
+
715
+ ---
716
+
717
+ ## §32 — Episodic memory: sessions and days (v1.7)
718
+
719
+ > Reference impl: `lib/memory.js` (`openSession` · `appendTurn` · `closeSession` · `sweep` · `snapshot` · `search` · `forget`).
720
+
721
+ ### 32.1 Layers
722
+
723
+ | Layer | Unit | Written by | In the load contract |
724
+ |---|---|---|---|
725
+ | L1 session | every turn: `seq, ts, surface, speaker, role, text` | the runtime, append-only | never wholesale; only the capsule (§32.4) |
726
+ | L2 card | a summary of one session; every line cites turn `seq`s | the sweep (model, gated) | via day notes |
727
+ | L3 day | `days/YYYY-MM-DD.md`, rebuilt **deterministically** from cards + facts of that day | the machine | today and yesterday |
728
+ | L4 facts | §31 | the gate | by topic/capability |
729
+ | L5 procedure | the agent's own lessons (§7) | the agent | stable prefix |
730
+ | index | "what is in memory": namespaces, counts, date ranges | the machine | always |
731
+
732
+ ### 32.2 Sessions on conversational surfaces
733
+
734
+ §14 runs end at a machine-defined point. A conversation does not, so the boundary is part of the contract: a session closes on `idle | closed | daily | compaction | explicit | reset`. The app decides the thresholds; closing before a context compaction is the **pre-compaction flush**. A subject MAY have several sessions open at once (one per surface); each has its own file, so they never contend.
735
+
736
+ ### 32.3 Sweep
737
+
738
+ On close, `sweep(session, summarize)` runs the app's summarizer over the session and is **idempotent**: a watermark records the last swept `seq`; a crash means it re-runs, and duplicate facts are no-ops.
739
+ - Card lines without a valid citation, or that read as instructions, are dropped. A line citing a turn that produced a `sensitive` fact is kept out of the card (cards feed day notes, which load every session).
740
+ - Proposed facts carry `{ seq, quote }` and pass the §31.4 gate.
741
+
742
+ ### 32.4 The load contract
743
+
744
+ Built by code, in a fixed order: index → facts → group facts (§33) → day notes (today, yesterday) → **capsule** (the last K turns across every surface, excluding the running session; turns that produced a sensitive fact are masked) → open items. Over budget, sections are cut from the bottom **with a marker**, never silently.
745
+
746
+ - The contract is **frozen for the session**: writes made during the session do not change it (the agent sees them through tool results and search). This keeps the prompt prefix cacheable.
747
+ - It is **hashed**; the session's first line records the hash, so "what did the agent know at that moment" can be replayed.
748
+ - Open items are context, not an agenda: an agent does not raise them unprompted.
749
+
750
+ ### 32.5 Search
751
+
752
+ `search(query, scope, since, limit)` is deterministic: diacritic-insensitive prefix matching over the subject's own files (facts including superseded and expired ones, turns, cards, days), ranked by `(matched terms desc, ts desc, ref asc)`. It returns bounded, labelled hits. **Every read is recorded** in the subject's access ledger (`reader`, `session`, `query`, `refs`). Facts recalled in at least `min_recalls` reads across at least `min_sessions` sessions are pinned by the mechanical tier — counts decide, not a model. An index (for example SQLite FTS) MAY be added as a projection, provided it is rebuildable, per-subject, and returns the same ranked results as the scan.
753
+
754
+ ### 32.6 Retention
755
+
756
+ Raw turns older than `retention_days` are removed by the mechanical tier; cards, day notes and facts remain. Facts keep their own quote, so evidence survives the turn it came from.
757
+
758
+ ### 32.7 Forget
759
+
760
+ `forget(fact)` writes a tombstone (a hash of the folded value) and **cascades**: a `derived` fact whose every source is forgotten is forgotten too. The content is then removed **everywhere it lives** — journal lines (including checkpoints in sealed segments) become stubs, the quote and value are scrubbed from stored turns (policy `forget_purges_turn`, default on), card lines carrying them are dropped, access-ledger entries and review items quoting them are removed, and projections are rebuilt. A `redact` op is appended so `fsck` knows anchors before it were rewritten on purpose. Conformance test: after a forget, a grep of the whole store for the content finds nothing, and re-proposing it — even from a new session — is refused.
761
+
762
+ `edit(fact)` supersedes with provenance `user_edit`; machines cannot overwrite it except through the review queue (§31.4). Erasing a whole subject is `destructive` and requires approval; it removes the directory and every alias, and the erase ledger keeps only the pseudonym.
763
+
764
+ ---
765
+
766
+ ## §33 — Groups, shared accounts and many surfaces (v1.7)
767
+
768
+ > Reference impl: `lib/memory.js` (`addMember` · `removeMember` · `proposeToGroup`) and `lib/memory-tracker.js` (`createScopedMemoryTracker` — channel-agnostic 3-axis `user` / `group` / `member` tracker + L5 lessons + sweep/dream orchestration for any surface).
769
+
770
+ - Subject kinds: `person | group | agent | project`. A **group** (a household, a team, a company) is a subject with its own store.
771
+ - Membership is a `system_verified` op written to both journals: `member_of { group, role, read: [namespaces], write: [namespaces] }`. Only trusted callers create it.
772
+ - A person's contract includes the group facts in the namespaces they may read. **It never includes another person's facts, even within the same group** (conformance: a canary planted in one member's memory never appears in another member's contract or search).
773
+ - A member may propose a group fact only in a namespace they may write, with evidence from **their own** turn.
774
+ - What a person says about a third party is stored in the speaker's memory under the speaker's subject (`about: person:<slug>`) — relationship context, never a profile of the other person.
775
+ - Session scope across surfaces is policy: `main` (one owner, every surface continues one conversation), `per-surface`, or `per-peer`. Whatever the scope, every surface writes to the same subject.
776
+ - Another agent acting for the subject (e.g. through MCP) is a different speaker: its turns can yield `agent_observed`, never `stated`. Its reads are recorded like any other (§32.5).
777
+
778
+ ### SPEC / APP boundary
779
+
780
+ | SPEC fixes (conformance) | APP decides (policy) |
781
+ |---|---|
782
+ | layout and isolation · journal + projections + anchors · the five-layer gate · tombstones and forget cascade · loader laws (provenance floor, sensitive out, persona, verification) · frozen, hashed, fenced contract · deterministic search + access ledger · bracketed consolidation and dream rules · group read/write by namespace | store location and region · taxonomy, sensitivity classes and extra instruction patterns · budgets, capsule size, retention, TTLs · session boundaries and scope · promotion and dream thresholds · who reviews · labels and language of the contract |
783
+
784
+ A memory need the mechanism does not cover is a proposal to change this spec — not a workaround inside the app.
785
+
786
+ ---
787
+
788
+ ## §34 — Loading skills (v1.8)
789
+
790
+ > Reference impl: `lib/skills.js` (`openSkills` · `resolveSources` · `findSkillDirs` · `registerSourceLayout`). CLI: `scroll skill list | view | index | sources`.
791
+
792
+ Skills written for one agent runtime are folders in an open format, so an agent built on SCROLL can use them as they are. The loader decides, in code, which skills an agent may see; the model only ever sees what passed.
793
+
794
+ ### 34.1 Format
795
+ A skill is a folder holding `SKILL.md` in the open Agent Skills format (§19.3). `name` is 1–64 characters of lowercase letters, digits and single hyphens; `description` is at most 1024 characters and says what the skill does and when to use it. SCROLL-specific fields live under `metadata.scroll`: `requires`, `fallback_for`, `platforms` (§34.5). Fields other runtimes define (for example `metadata.hermes.requires_tools`, `disable-model-invocation`) **SHOULD** be honored when their meaning is clear. A loader **MUST** read block scalars, quoted strings and wrapped lines in the frontmatter; a description must never be lost to a YAML subset.
796
+
797
+ ### 34.2 Sources and precedence
798
+ Sources are read in this order; for a given name the first source wins and the others are reported as shadowed:
799
+
800
+ 1. `agents/<name>/skills/` (trust `trusted`)
801
+ 2. repo `skills/` (trust `trusted`)
802
+ 3. `skills.external_dirs` in `scroll.config.*`, in the order listed, then `SCROLL_SKILLS_DIRS` (path-delimited). Each entry is a path or `{ path, trust, layout, max_depth }`; `~` and `${VAR}` expand. Default trust: `community`.
803
+
804
+ - External sources are **read-only**: a loader **MUST NOT** write to them.
805
+ - Inside one source, when several folders declare the same name (a plugin cache keeping old versions), the copy with the newest `SKILL.md` wins.
806
+ - A `layout` says how to find skill folders in a source. `dir` (default): every directory holding a `SKILL.md`, at any depth up to `max_depth` (default 6), following directory symlinks once. `claude-code-plugins`: only the plugin versions its `installed_plugins.json` lists as installed. Layouts are extensible.
807
+ - An agent with `skills_external: false` sees only sources 1–2.
808
+ - Nothing outside the configured sources is read. A tool **MAY** report well-known skill folders of other tools that exist on the machine (`scroll skill sources --detect`), but adding one is the operator's decision.
809
+
810
+ ### 34.3 The index
811
+ - The index is one block in the stable prefix (§13), after hard-rules:
812
+ ```
813
+ <available_skills>
814
+ <one fixed line telling the model to read a skill with skill_view before using it>
815
+ - <name>: <description>
816
+ </available_skills>
817
+ ```
818
+ - It **MUST** be a deterministic function of the visible skill set, the pinned list and the limits: lines sorted by name, whitespace collapsed, angle brackets removed (a description cannot close the block). Two builds over the same set **MUST** be byte-identical.
819
+ - The index is **frozen** when a session or run opens it. Skills added, removed or changed later are announced in the volatile suffix on the next turn (`refresh` returns the notice); the prefix is rebuilt only when asked.
820
+
821
+ ### 34.4 Read tools
822
+ Two tools, gated by the capability `skills.read`. Their names are data (default `skill_list`, `skill_view`).
823
+ - `skill_list(query?, limit?, offset?)` — name and short description of visible skills; with a query, a deterministic search over name and description, folded for diacritics.
824
+ - `skill_view(name, path?)` — without `path`: the `SKILL.md` body, preceded by the tool-name map for this runtime (§35.2) and the list of files in the skill. With `path`: one text file inside the skill folder.
825
+ - `skill_view` **MUST** refuse absolute paths, `..`, any path whose real location (after symlinks) is outside the skill folder, binary files and files above the size cap.
826
+ - Before serving, the loader **MUST** compare the skill's files with what it scanned. A changed skill is validated, scanned and gated again; one that no longer passes is refused for the rest of the session.
827
+ - Every view is an event (`skill_viewed`, `skill_denied`) with the skill's content hash.
828
+
829
+ ### 34.5 Visibility
830
+ A skill reaches the index and the tools only if all of these hold:
831
+ - it is valid (§36.1) and passed the security scan (§36.2);
832
+ - `disable-model-invocation` is not `true` (a skill meant to be started by a person only);
833
+ - the current platform is in `platforms`, when declared (`macos | linux | windows`);
834
+ - none of its `fallback_for` tools or capabilities is available (a fallback appears only when the primary tool is missing);
835
+ - its compatibility status is not `hidden` (§35), unless the operator overrides it.
836
+
837
+ ### 34.6 Caps
838
+ The index holds at most `skills.max_index` skills (default 150) and `skills.max_index_tokens` tokens (default 6000). Descriptions are shortened first; then skills are dropped lowest-ranked first. Rank: pinned (`IDENTITY.skills`, in order) → usage counts supplied by the application → source order → name. A skill left out of the index stays reachable through `skill_list`.
839
+
840
+ ### 34.7 Steps that name skills
841
+ A `WORK.md` task (or `scroll run --skill a,b`) MAY list `skills: [...]`. The runner loads each in full into that step's volatile suffix. If any of them is not visible, the step **MUST NOT** run: it is blocked (`gate_blocked`, reason `skill`) and no model is called.
842
+
843
+ ---
844
+
845
+ ## §35 — One skill, many runtimes (v1.8)
846
+
847
+ > Reference impl: `lib/skills.js` (`TOOL_ALIASES` · `skillRequirements` · `compatStatus` · `writeCompatFile`). CLI: `scroll skill scan`.
848
+
849
+ ### 35.1 What a skill needs
850
+ A loader derives a skill's requirements from:
851
+ - **declared** (hard): `allowed-tools`, `metadata.scroll.requires`, `metadata.hermes.requires_tools`, operator overrides;
852
+ - **named in the text** (soft): MCP tool names (`mcp__server__tool`, `Server:tool`) and known tool names of other runtimes. Ordinary words (`Read`, `Task`, `patch`) count only as `` `Name` `` or "Name tool".
853
+
854
+ Foreign tool names map to SCROLL capabilities through a table that is **data** (`TOOL_ALIASES`, extended by `skills.tool_aliases` in config). A name with no portable equivalent maps to nothing and is satisfied only by a tool of exactly that name. A missing planning tool (`tasks.track`) never counts against a skill.
855
+
856
+ ### 35.2 Status
857
+ Against what the agent has (capabilities, tool names, MCP servers):
858
+ - `ok` — everything is available.
859
+ - `partial` — some tools named in the text are missing; the skill is shown, and `skill_view` says which ones are not available here.
860
+ - `hidden` — a declared requirement is missing, or most of the tools its text names are missing (at least two, and more missing than present): a skill built around another runtime's tools.
861
+
862
+ `skill_view` prepends a map from the names the skill uses to this runtime's tools (from `TOOLS.md` bindings, §5.2), e.g. `AskUserQuestion → ask_owner`. The skill's own text is never rewritten.
863
+
864
+ ### 35.3 The sidecar
865
+ `scroll skill scan` writes `skills-compat.json` (per agent: `agents/<name>/skills-compat.json`): per skill its source, trust, content hash, state, status and missing tools. The operator corrects the machine under `overrides`: `{ "<skill>": { "status": "ok" | "hidden", "map": { "<ForeignTool>": "<local tool>" }, "requires": [...] } }`. Overrides survive every rescan. An override can show or hide a skill; it can never admit a skill the security scan blocked.
866
+
867
+ ---
868
+
869
+ ## §36 — Checking and grading skills (v1.8)
870
+
871
+ > Reference impl: `lib/skills.js` (`validateSkill` · `scanSkillDir` · `SECURITY_RULES` · `checkSkills`), `lib/skill-eval.js` (`runSkillEval`). CLI: `scroll skill check | eval`; `scroll check` and `scroll audit` include skills.
872
+
873
+ ### 36.1 Validation
874
+ `name` and `description` present and well-formed; `description` and `compatibility` within limits; files the body links to exist and stay inside the folder; the body under 500 lines (warning); references one level deep (warning). For skills the repo ships (sources 1–2) a broken SHOULD is an **error** and fails `scroll check`; for external skills it is a warning, and only a skill that cannot be addressed (no name, no description, a name outside the pattern) is kept out.
875
+
876
+ ### 36.2 Security scan
877
+ Every text file in a skill (up to a file and size cap) is scanned line by line. Rules are data; each has a severity:
878
+
879
+ | rule | severity |
880
+ |---|---|
881
+ | a live credential (`secret`); exfiltration of credentials or private files; a reverse shell; bidirectional control characters | critical |
882
+ | zero-width hidden text; instructions to drop earlier instructions or hide actions from the user; deleting a home or root folder; erasing a disk; downloading and running code unseen; writing to shell start-up files or `authorized_keys` | high |
883
+ | installing scheduled jobs; `sudo`; force-pushing | medium |
884
+
885
+ - A phrase quoted as an example (`"ignore previous instructions" — do not obey it`) is reported at medium.
886
+ - Whether a finding **blocks** depends on the source's trust: `builtin` and `trusted` block at critical, `community` at high, `untrusted` at medium. Lower findings are reported.
887
+ - A blocked skill **MUST NOT** reach the index, `skill_view`, a step, an install (`scroll skill add`, `scroll plugin add`) or an eval. There is no flag that forces it in; changing a source's trust is an edit to configuration, made by a person.
888
+ - Findings name the rule, file and line, never the matched text.
889
+ - `scroll audit` binds its record to the content of the agent's and the repo's skills: editing one after the audit fails `audit --verify`.
890
+
891
+ ### 36.3 Evaluation
892
+ Cases travel with the skill: `evals/*.md` (gold cases, §8) or `evals/evals.json` (`{ "evals": [{ "id", "prompt", "expected_output", "expectations", "files", "checks" }] }`).
893
+ - Each case runs on each named model **with** the skill and **without** it (the baseline), `runs` times each. Machine checks grade both sides.
894
+ - An optional judge compares the two final answers **blind**: it never sees the skill, and the order of the answers alternates case by case.
895
+ - Verdicts are ternary (§29). A case with no machine check and no judge result is `ungraded`.
896
+ - The record (`.scroll/skill-eval/<name>.json`, bound to the skill's content hash) states a recommendation: `keep` (passes, and beats the baseline somewhere), `retire-or-rewrite` (the model does as well without it), `fix` (fails on some model), `ungraded`.
897
+ - A skill the repo ships **SHOULD** have at least three cases.
898
+
899
+ ### SPEC / APP boundary (skills)
900
+
901
+ | SPEC fixes (conformance) | APP decides (policy) |
902
+ |---|---|
903
+ | the format and its validation · source order and precedence · read-only external sources · the scan and what blocks per trust level · read-time recheck · `skill_view` confinement · a deterministic, frozen index · hidden ⇒ not offered · a step never runs without the skills it names · with/without evaluation and ternary verdicts | which external folders, and how much each is trusted · index caps and usage ranking · tool names and the alias table · overrides in the sidecar · which models a skill is evaluated on |
904
+
905
+ ---
906
+
907
+ ## §38 — Deployment `USER.md` (v1.9)
908
+
909
+ > Reference impl: `lib/user.js` (`openUser` · `parseUserMd` · `validateUserMd` · `importWorkspaceUserMd` · `guard` · `checkHashChange`) wrapping `lib/people.js` (`validateCard` · `canApprove`) · CLI `scroll user check|new|show|import` and `scroll check user`.
910
+
911
+ An agent folder describes a reusable role (`IDENTITY.md`, `SOUL.md`, `TOOLS.md`, `hard-rules.md`, `evals/`). It stays free of real people and deployment secrets. Each deployment adds **one `USER.md`** at the deployment root stating whom the agents work for and which internal people may assign or approve work. Customers and external contacts never go into `USER.md` — they live in subject memory (§31).
912
+
913
+ ### 38.1 Location
914
+ One file per deployment: `--user <path>`, then `SCROLL_USER_FILE`, then `user.file` in `scroll.config.*`, then `<repo>/USER.md`. `USER.md` **MUST NOT** live inside `agents/` (§41). Legacy per-person cards under `people/<slug>.md` remain supported when no `USER.md` is present.
915
+
916
+ ### 38.2 Frontmatter (machine-only)
917
+ Frontmatter is read only by code and **NEVER** serialized into the model prompt:
918
+
919
+ - `principal` (MUST, map): `kind: person | org`, `name` (<= 120 chars), optional `self`, `call_others` (<= 60 chars), `handoff` (role name, default `owner`).
920
+ - `people` (OPTIONAL, list of internal members only): `{ id, name, call, self?, role|roles, approve, max_amount, channels?, channel_ids? }`. `id` MUST match `^[a-z][a-z0-9-]*$` and MUST NOT look like a phone number, email, handle or URL; applications bind verified channel sender IDs to `id`. Each entry is validated through `validateCard()` from `lib/people.js`.
921
+
922
+ ### 38.3 Body & sections
923
+ The markdown body is capped by code (`user.max_body_chars`, default **3,000 characters**). An over-cap body is an error and `USER.md` does not load. Body and frontmatter are scanned for secrets and prompt-injection instructions (§31.4). Sections split cleanly into:
924
+ - `# About <principal>` — internal-only context, loaded only for internal turns.
925
+ - `## May say on behalf` — public facts loaded for external turns as well, and accepted as a valid grounding source.
926
+ - `## Must not say` — topic-level boundaries loaded for external turns as well (state the topic, never the secret itself).
927
+
928
+ ### 38.4 Ownership, hash audit, and external workspace import
929
+ - Agents never write `USER.md`; applications call `guard(path)` at tool boundaries (raw writes return `allowed: false, tier: 'destructive'`).
930
+ - Every run hashes `USER.md` (`checkHashChange`); an out-of-band edit emits `user_md_changed` and writes a hash-chained record to `audit.jsonl`.
931
+ - `importWorkspaceUserMd()` imports plain external workspace `USER.md` files: human-written prose becomes the `USER.md` body, while agent-authored sections/lines (`## Notes`, `## Learned`, `## Observations`, `[agent]`) are separated and routed to the gated subject-memory review queue instead of becoming principal prose.
932
+
933
+ ## §39 — Neutral prompt framing & role binding (v1.9)
934
+
935
+ > Reference impl: `lib/user.js` (`render`) · `lib/scroll.js` (`checkAgent`, `buildAgent`) · `lib/runtime.js` (`stablePrefix`, `context_loaded`).
936
+
937
+ ### 39.1 Agent roles stay portable
938
+ `IDENTITY.md` declares `serves: [owner]` (or `role:owner`) and `reports_to: role:<role>` or an agent name. A `person:<slug>` value in either is an error.
939
+
940
+ ### 39.2 Neutral prompt header (never "user")
941
+ When loading `USER.md` into the stable prefix (both compact and full paths, alongside `hard-rules.md`), the loader wraps allowed body sections under a neutral header (**"The party this agent works for"** by default, configurable via `user.labels`), never using the word `"user"`, so models never mistake an external chat counterparty for the principal. Every run emits `context_loaded { files, chars }` listing the exact files and character counts that reached the model.
942
+
943
+ ## §40 — Internal authority at the gate & in `WORK.md` (v1.9)
944
+
945
+ > Reference impl: `lib/user.js` (`canApprove` · `approversFor`) · `lib/people.js` · `lib/runtime.js` (`personStep`, approval check, `audit.jsonl`, `notify`).
946
+
947
+ ### 40.1 A person owns a step
948
+ `owner: person:<slug>` (§9.1). The controller **MUST** be an agent. The runner emits `human_task_requested` + `notify`, pauses the dependent branch, and resumes only when that exact person writes `control/done/<task-id>.json`.
949
+
950
+ ### 40.2 Checked approvals
951
+ When `USER.md` (or legacy `people/`) is active, a `must-approve` gate checks `{ "by": "<id>" }` in code via `canApprove()` against the person's `approve` list (action classes `write|send|publish|pay|delete` or §21 tiers), `max_amount`, and deployment `authority_ceiling`. Decisions (`accepted`, `rejected`, `auto-approved`) append to hash-chained `runs/<id>/audit.jsonl`.
952
+
953
+ ## §41 — Privacy, package boundaries, and canary audit (v1.9)
954
+
955
+ > Reference impl: `lib/people.js` (`scanForPeople` · `zipEntries`) · `lib/audit.js` (`auditRepo` · `auditPrivacy` · `scanCanaries`) · `lib/installers.js`.
956
+
957
+ - **Outside every agent folder.** `USER.md` and `knowledge/` live at the deployment root, outside `agents/`, and are warned about when missing from `.gitignore` unless `user.tracked: true`.
958
+ - **Never in a shared package.** `scroll audit` fails when a `USER.md`, a `knowledge/` folder, a `people/` folder, or a card-shaped file is found inside `agents/<name>/`, `skills/`, or a plugin bundle / `.plugin` / `.zip` archive. `scroll skill add` and `scroll plugin add` refuse or skip them.
959
+ - **Canary content-leak scan.** Private canary markers (`<!-- canary: TOKEN -->` in `USER.md` or `user.canaries` in `scroll.config.*`) are scanned across the contents of `agents/`, `skills/`, and plugin bundles so leaks inside `SOUL.md`, `evals/`, or `lessons.md` fail `scroll audit` and break `audit --verify` (`privacyHash`).
960
+
961
+ ### SPEC / APP boundary (deployment principal)
962
+
963
+ | SPEC fixes (conformance) | APP decides (policy) |
964
+ |---|---|
965
+ | `USER.md` schema & validation via `validateCard` · 3,000-char body cap · frontmatter never enters prompt · neutral prompt header (no "user") · `hard-rules.md` loaded on every runtime & build path · `guard()` blocks raw writes · hash-change audit · `canApprove()` checked in code · `USER.md`, `knowledge/`, and canaries blocked from shared packages | where `USER.md` lives · role table & authority ceilings · labels & locale · channel-id to person-id mapping · notification delivery |
966
+
967
+ ## §42 — Per-turn internal vs external boundary & group wall (v1.9)
968
+
969
+ > Reference impl: `lib/user.js` (`classifyTurn` · `isIdentityQuestion` · `checkAiDisclosure` · `applyAiLabel`) · `lib/runtime.js` (per-turn enforcement) · tests `test/v19-boundary.smoke.mjs`.
970
+
971
+ Whether a turn is **internal** or **external** is computed by code on **every turn** — never by a static deployment mode or by matching a sender's display name:
972
+
973
+ - **Verified identity only:** a sender is `internal` only when their verified channel ID (resolved via `channelMap` or `channel_ids` on `USER.md`) or verified internal ID matches a valid person in `USER.md`. Missing sender IDs fail closed to `external`.
974
+ - **Group lowest-trust content wall:** in a group chat, speaker authority tracks the speaker, while loaded content and output rules track the **least-trusted participant present**. If any participant is `external`, `contentAudience` is `external` — `# About` private notes never load, write tools are stripped (`toolPolicy = 'none'`), and subject memory is restricted to the chat's own subject (`chat_only`).
975
+ - **External output gate:** external turns cannot invoke `reversible_write`, `financial`, or `destructive` tools; replies stay drafts (`decision: 'hold'`) awaiting human approval by default; unreviewed replies for `self`/`org` carry a machine-attached AI label from config/locale; identity questions escalate to handoff for `speaks_as: owner` and require explicit AI acknowledgement for `self`/`org`.
976
+
977
+ ## §43 — `speaks_as`, machine-enforced `style:`, Voice hooks, presets, and reply grounding (v1.9)
978
+
979
+ > Reference impl: `lib/style.js` (`ENFORCED_STYLE_KEYS` · `validateStyle` · `enforceStyle` · `hasBareNumericSlider`) · `lib/grounding.js` (`collectPrincipalSources` · `groundReply` · `verifyClaimsInvariant`) · `lib/scroll.js` (`AGENT_PRESETS` · `scaffold`) · `lib/runtime.js` (2 official voice hooks) · tests `test/v19-style-grounding.smoke.mjs`.
980
+
981
+ ### 43.1 `speaks_as` & role setup presets
982
+ `IDENTITY.md` declares `speaks_as: self | owner | org` (default `self`). `scroll new <name> --preset <preset>` scaffolds standardized English blueprints for the four canonical roles: `assistant` (`self`), `service` (`org`), `proxy` (`owner`), and `teammate` (`self`).
983
+
984
+ ### 43.2 Machine-enforced `style:` block
985
+ `IDENTITY.style` accepts **only** keys with deterministic code enforcement: `bubbles` (`>= 1`), `max_chars` (`>= 20`), `emoji` (`>= 0`), `follow_up` (`>= 0`). Any unenforced qualitative key (`warmth`, `humor`, `tone`) fails `scroll check`. `enforceStyle()` strips redundant markdown, enforces emoji/follow-up/bubble ceilings, regenerates at most once on `max_chars` breach (else holds for review), and **never alters numbers, amounts, product codes, dates, or links**.
986
+
987
+ ### 43.3 Two official Voice plugin hooks & safety ordering
988
+ Conversational voice modules (persona, affective control, human-like delivery) remain at the plugin/app layer and plug into SCROLL via two hooks:
989
+ 1. **`beforeTurn()`**: returns volatile turn guidance (`<= 650` chars) appended at the **end** of the prompt after history/deliverable so the stable prefix stays cache-stable. Bare numeric sliders (`warmth: 4/5`) are rejected — plugins must translate levels into concrete behavioral wording.
990
+ 2. **`shapeOutgoing()`**: runs **after** `groundReply()` on the raw model text. `verifyClaimsInvariant(rawText, shapedText)` verifies the multiset of `(amount, code, date, link)` claims is unchanged; any perturbation reverts and holds the reply. Outbox approvals bind to `shapedHash`.
991
+
992
+ ### 43.4 Reply grounding (principal sources only)
993
+ `groundReply()` checks every amount, product code, date, and link in an external reply against **principal-authored sources only** (`collectPrincipalSources`: retrieved `knowledge/` chunks, `USER.md` `May say on behalf`, tool outputs — never customer messages). It also verifies same-line `code <-> amount` pairs (`pair_mismatch`) and holds unverified high-risk claim classes (`percent`, `time`, `relative_date`, `inventory`, `written_number`) for human review.
994
+
995
+ ## §44 — Large deployment knowledge retrieval, conversational mode & source-aware grounding (v1.10)
996
+
997
+ > Reference impl: `lib/knowledge.js` (`indexKnowledge` · `retrieveKnowledge` · `formatKnowledgeBlock` · `openKnowledge`) · `lib/runtime.js` (`knowledge_retrieved` · conversational deliverable · `<verified-caller>`) · `lib/grounding.js` · `lib/audit.js` · tests `test/v110-knowledge.smoke.mjs`.
998
+
999
+ - **Deterministic zero-dep `knowledge/` chunking & retrieval:** `openKnowledge()` indexes deployment-root `knowledge/` (outside `agents/`, per §41), splits Markdown by `##`/`###` headings with a bounded per-chunk cap (`maxChunkChars = 1600`, preserving Markdown table headers when sub-splitting), and retrieves top-K chunks via Unicode-folded BM25 + heading + bigram + exact SKU/alpha-code matching.
1000
+ - **Prompt injection + cache safety:** `runWork()` automatically retrieves relevant chunks from `knowledge/` (or accepts explicit `opts.knowledgeChunks`), injects `<retrieved-knowledge>` into the **volatile** suffix after `stablePrefix` so prompt-prefix caching stays intact, emits `knowledge_retrieved`, and passes the exact same chunks to `groundReply()`.
1001
+ - **Conversational deliverable mode:** When a turn is external, declares `style:`, uses `voiceHooks`, or sets `speaks_as: org|owner` (or `opts.conversational: true`), `runtime.js` omits the research-report `Verdict / Evidence / Assumptions / Next actions` template so `SOUL.md` and `style:` control natural chat output, and `verify()` validates conversational replies without requiring report headings.
1002
+ - **Source-aware large-KB grounding:** `grounding.js` recognizes both alphanumeric and uppercase hyphenated alpha codes (`AUR-DLX`, `FDP-STD`), strips trailing backticks on Markdown inline-code URLs, excludes explicitly marked expired/invalid/trap lines from authorized pricing pools, covers hospitality/booking inventory claims, and skips false-positive holds on clock times or percentages that appear verbatim in `principalSources` (or inside explicit refusals).
1003
+ - **Verified internal caller & clean `USER.md` audit:** Verified internal turns receive a machine-generated `<verified-caller audience="internal" ...>` header; `auditPeople()` skips redundant legacy `people/` `serves`-role warnings when deployment `USER.md` is active.
1004
+
1005
+ ## §45 — Interactive multi-turn chat session runtime (v2.0)
1006
+
1007
+ > Reference impl: `lib/chat-session.js` (`createChatSessionRuntime`) · `lib/scroll.js` (`scroll chat`) · tests `test/v20-chat-tools-mcp.smoke.mjs`.
1008
+
1009
+ SCROLL 2.0 extends the batch `WORK.md` runner with an interactive, streaming, per-conversation **Chat Session Runtime** that enforces every SCROLL safety primitive on every live chat turn:
1010
+
1011
+ - **Per-conversation durable transcripts & auto-compaction:** each conversation persists turns to an append-only JSONL transcript outside the agent folder (`0600`) and automatically compacts older turns into a deterministic (or caller-summarized) summary record when context crosses `compactAtChars`.
1012
+ - **Per-turn SCROLL enforcement:** every turn runs `classifyTurn` (§42 boundary & group lowest-trust wall), subject memory snapshot (§31–§33, gated to `principal_and_team`), `retrieveKnowledge` (§44), Voice Hook 1 (`beforeTurn`, rejecting bare numeric sliders per §43), live multi-round tool calls (§47), `groundReply` (§43–§44), `enforceStyle` (§43), and Voice Hook 2 (`shapeOutgoing`, verified by `verifyClaimsInvariant` so voice shaping can never mutate amounts, codes, dates, or links).
1013
+ - **Hot-reload & interrupt:** `reload()` refreshes `IDENTITY.md`, `SOUL.md`, `hard-rules.md`, `USER.md`, and `knowledge/` live without restarting the host process; `abortTurn(conversationId)` interrupts an in-flight turn cleanly via `AbortController`.
1014
+
1015
+ ## §46 — Unified AuthProvider & persistent Codex App-Server client (v2.0)
1016
+
1017
+ > Reference impl: `lib/auth.js` (`createPkceChallenge` · `buildAuthorizationUrl` · `exchangeAuthCode` · `startDeviceAuth` · `pollDeviceToken` · `createAuthStore`) · `lib/codex-app-server.js` (`findCodexBinary` · `createCodexAppServerClient`) · `lib/providers.js` (`codex-app-server` · `openai-compatible`) · `lib/scroll.js` (`scroll auth`) · tests `test/v20-auth-provider.smoke.mjs`.
1018
+
1019
+ - **Unified credential store (`0600`, atomic writes):** supports `oauth`, `api_key`, `proxy`, and `codex_app_server` profiles in one redacted store with automatic OAuth token refresh (`skewMs`), multi-account priority ordering, and automatic 429/401 circuit-breaker cooldown failover (`withFailover`).
1020
+ - **Standard OAuth 2.0 flows:** ships zero-dep RFC 7636 PKCE (`S256`) and RFC 8628 Device Authorization Grant helpers so web apps and headless chat bots can authenticate users without external SDKs.
1021
+ - **Persistent Codex App-Server JSON-RPC client:** keeps a single stdio `codex app-server --listen stdio://` subprocess alive for ChatGPT OAuth (`account/read`, `account/login/start`, `account/rateLimits/read`), automatic explicit model resolution via `model/list`, streaming `item/agentMessage/delta` notifications, and `turn/interrupt` on abort.
1022
+ - **OpenAI-compatible streaming provider:** supports custom `baseUrl`, `AuthStore` failover, native function calling (`tools`), vision image inputs, and SSE delta streaming.
1023
+
1024
+ ## §47 — Live multi-round tool executor & zero-dep MCP stdio client (v2.0)
1025
+
1026
+ > Reference impl: `lib/mcp-client.js` (`loadMcpConfig` · `createMcpStdioClient` · `createMcpManager`) · `lib/tools.js` (`createToolRegistry` · `isSafePublicUrl`) · tests `test/v20-chat-tools-mcp.smoke.mjs`.
1027
+
1028
+ - **One deterministic safety gate for all tools:** built-in tools (`read_file`, `list_dir`, `web_fetch`, `web_search`, `knowledge_search`, `memory_search`, `memory_remember`, `memory_forget`, `automations`, `spawn_worker`, `exec`) and dynamically discovered MCP stdio tools all pass through §42 boundary filtering (external/mixed-group turns are strictly `read_only`), §21 risk tier + policy matrix, §22 parameter grounding, interactive HITL approval (`requestApproval`), and §28 post-write read-back confirmation (`confirmEffect`).
1029
+ - **Hardened built-ins:** `read_file` and `list_dir` enforce workspace containment and block memory-store direct access (§31.7 I-01); `web_fetch` blocks localhost, RFC1918, link-local, CGNAT, and cloud metadata IPs before and after redirects.
1030
+ - **Zero-dep MCP stdio client:** reads `.mcp.json`, resolves `${vault:KEY}` from environment variables at runtime only, handshakes via JSON-RPC 2.0 `initialize` + `tools/list`, and registers discovered tools alongside SCROLL `risk`/`ground`/`confirm` metadata.
1031
+
1032
+ ## §47.2 — Portable Tool Retriever, Room-Sticky Group Caching & ASI04 Pinning (v2.5)
1033
+
1034
+ > Reference impl: `lib/tool-retriever.js` (`buildToolRetriever` · `buildAvailableToolsIndex` · `validateToolArgs` · `computeSchemaHash`) · `lib/tools.js` (`getPromptSurface` · `searchTools` · `executeTool` Transparent Unwrap) · `lib/mcp-client.js` (`createMcpHttpClient` · `verifyAndPinTools` · `approveMcpLock`) · `lib/scroll.js` (`checkMcpConfigPinning` · `scroll mcp diff|approve`) · tests `test/v25-tool-retriever.smoke.mjs`.
1035
+
1036
+ - **3-Set Architecture (`C / V / E`):**
1037
+ 1. **Catalog `C` (deployment-frozen, Region A):** When registered tools exceed `defer_threshold` (default `15`) or `max_schema_bytes` (`8 KB`), only core always-loaded tools plus `tool_search` and `tool_invoke` enter provider tool schemas. Remaining tools appear in a frozen `<available_tools>` catalog capped at `<= 1,500` tokens across three adaptive density tiers (full summaries, compact groups, namespace counts).
1038
+ 2. **Visible `V` (per-turn volatile, Region C):** `tool_search` accepts single `query` or batch `queries[]`, filters strictly by the turn's speaker trust (`allowWriteTools`, `delegatedTools`, `tools_allow`), ranks via deterministic multi-field BM25F + bigrams + bilingual synonyms (+ optional `embedFn`), and records each returned tool's `schemaHash` in the session's `hydratedTools` map.
1039
+ 3. **Executable `E` (per-call Transparent Unwrap):** `tool_invoke({ name, arguments })` rejects recursion (`tool_invoke`/`tool_search`), requires prior `tool_search` hydration for deferred tools, verifies `schemaHash` against mid-session drift (ASI04), validates `arguments` against JSON Schema on the host (`validateToolArgs`), and unwraps directly into the single unified `executeTool(targetName, targetArgs, ctx)` gate (enforcing §42, §21, §22, §28, budget/loop breakers, and `audit.jsonl` under the real target tool name).
1040
+ - **Room-Sticky Group Cache Invariance:** In multi-speaker group rooms, Region A (`USER.md` rendered for room audience, safety contract, `<available_skills>`, `<available_tools>`, and tool schemas) stays byte-identical across alternating Owner, Teammate, and Guest turns (`prefixHash` variance = 0), while per-turn `<turn_speaker ... />` sanitized metadata attaches in Region C and per-speaker RBAC enforces strictly on `V` and `E`.
1041
+ - **Supply-Chain & Rug-Pull Protection (ASI04):** MCP tool descriptions are scanned via `scanText()` and quarantined on prompt injection or hidden Unicode; `.scroll/mcp.lock.json` pins `(cmdHash, schemaHash, descHash)` on first use (TOFU) and quarantines unexpected descriptor drift until explicitly approved via `scroll mcp approve`; `scroll check` and `scroll audit` ban unpinned `npx …@latest` / unversioned packages in `.mcp.json`.
1042
+
1043
+ ## §48 — Multimodal attachments in chat sessions (v2.0 / v2.5)
1044
+
1045
+ > Reference impl: `lib/chat-session.js` (`processAttachments`) · `lib/providers.js` · tests `test/v20-chat-tools-mcp.smoke.mjs`.
1046
+
1047
+ - Chat turns accept structured `attachments` (`image`, `audio`/`voice`, `document`/`file`).
1048
+ - Images are forwarded directly to multimodal providers (URL, base64 data URI, or local image path); audio/voice notes pass through pluggable `multimodalHooks.transcribeAudio`; documents pass through `multimodalHooks.extractDocument` or bounded UTF-8 extraction.
1049
+
1050
+ ## §49 — Timezone-aware cron, heartbeat & reminder scheduler (v2.0)
1051
+
1052
+ > Reference impl: `lib/scheduler.js` (`parseCron` · `zonedParts` · `matchesCron` · `canManageJob` · `createScheduler`) · `lib/scroll.js` (`scroll cron`) · tests `test/v20-scheduler-workers.smoke.mjs`.
1053
+
1054
+ - Pure Node `Intl.DateTimeFormat` 5-field cron evaluation in any IANA timezone (e.g. `Asia/Ho_Chi_Minh`), plus interval (`everyMs`) and one-shot (`at`) reminders, persisted atomically (`0600`).
1055
+ - Enforces single-fire-per-minute deduplication, exponential retry backoff on transient/429 errors, per-job `maxDailyRuns` budget caps, and a global `paused` kill-switch.
1056
+ - **Owner DM authority (`canManageJob`):** a verified internal `owner`/`admin` in a direct message is authorized to inspect, toggle, edit, or delete scheduled jobs targeting any group chat.
1057
+
1058
+ ## §50 — Async background workers & hybrid memory search (v2.0)
1059
+
1060
+ > Reference impl: `lib/chat-session.js` (`createWorkerPool`) · `lib/memory.js` (`searchHybrid` · `consolidateDigest`) · tests `test/v20-scheduler-workers.smoke.mjs`.
1061
+
1062
+ - **Non-blocking worker pool:** `createWorkerPool` bounds concurrent background jobs (`maxConcurrent`), supports cancellation via `AbortController`, and invokes `onComplete` so long-running tasks never block live chat turns.
1063
+ - **Hybrid semantic + lexical memory search:** `memoryStore.searchHybrid(sid, { query, embed, semanticWeight })` combines optional caller-supplied vector embeddings (cosine similarity) with SCROLL's deterministic lexical scan while preserving every §31–§33 access-ledger and isolation guarantee; `consolidateDigest()` yields a bounded deterministic fact digest.
1064
+
1065
+ ---
1066
+
1067
+ ## Design note — §28–30 and the failure they answer
1068
+
1069
+ §21 (risk), §22 (grounding) and §1.4 (enforce at the tool boundary) compensate for weaknesses of the *model*: it does not understand consequences, it hallucinates identifiers, it will not stop on its own.
1070
+
1071
+ §28–30 compensate for weaknesses of the *engineers and operators*:
1072
+
1073
+ | mechanism | compensates for |
1074
+ |---|---|
1075
+ | §28 effect confirmation | a system that reports success for work it never performed — which an agent then relays in good faith |
1076
+ | §29 ungraded ≠ pass | "no yardstick" being indistinguishable from "measured and good" |
1077
+ | §30 fixture provenance | hand-patching a precondition and calling the result acceptance |
1078
+
1079
+ A harness that only guards against the model is half a harness.