@tomflow/chatloop-context 0.1.4 → 0.6.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 (46) hide show
  1. package/README.md +240 -271
  2. package/bin/cli.mjs +25 -250
  3. package/capabilities/approval.mjs +151 -0
  4. package/capabilities/context.mjs +376 -0
  5. package/capabilities/document.mjs +266 -0
  6. package/capabilities/evidence.mjs +134 -0
  7. package/capabilities/presentation.mjs +82 -0
  8. package/capabilities/project.mjs +349 -0
  9. package/capabilities/sdk.mjs +72 -0
  10. package/capabilities/start.mjs +73 -0
  11. package/capabilities/task.mjs +507 -0
  12. package/capabilities.generated.mjs +11 -0
  13. package/docs/interfaces.md +182 -0
  14. package/docs/operator-and-migration.md +277 -0
  15. package/index.mjs +236 -0
  16. package/lib/api-aspect.mjs +190 -0
  17. package/lib/api-log.mjs +161 -0
  18. package/lib/approval-policy.mjs +24 -0
  19. package/lib/capability-catalog.generated.json +1989 -0
  20. package/lib/capability-router.mjs +67 -0
  21. package/lib/cli-commands.mjs +280 -0
  22. package/lib/context-cli.mjs +16 -19
  23. package/lib/context-migration.mjs +17 -9
  24. package/lib/core/context.mjs +115 -0
  25. package/lib/core/evidence.mjs +51 -0
  26. package/lib/core/health.mjs +55 -0
  27. package/lib/core/migration.mjs +262 -0
  28. package/lib/core/project.mjs +246 -0
  29. package/lib/core/review.mjs +147 -0
  30. package/lib/core/run.mjs +343 -0
  31. package/lib/core/store.mjs +391 -0
  32. package/lib/core/task.mjs +166 -0
  33. package/lib/line-review.mjs +13 -0
  34. package/lib/methods.mjs +49 -202
  35. package/lib/operations.mjs +33 -145
  36. package/lib/orphan-operator.mjs +117 -0
  37. package/lib/process-inventory.mjs +20 -0
  38. package/lib/project-branch.mjs +312 -0
  39. package/lib/project-diagnostic.mjs +26 -328
  40. package/lib/project-guards.mjs +19 -0
  41. package/lib/project-store.mjs +115 -0
  42. package/lib/trusted-run.mjs +86 -0
  43. package/lib/workspace-operator.mjs +12 -2
  44. package/package.json +32 -14
  45. package/scripts/build-capabilities.mjs +114 -0
  46. package/lib/context-protocol.mjs +0 -1617
package/README.md CHANGED
@@ -1,271 +1,240 @@
1
- # @tomflow/chatloop-context — Context SDK and CLI
2
-
3
- Independent Context SDK. Method Catalog supports Node >=20; CLI/Core require Node >=24. Chat Loop Tools and other explicitly
4
- authorized local adapters use the same versioned Method Catalog and SQLite Core.
5
- This package is not a Chrome controller, HTTP service or background process.
6
-
7
- ## Project data (target layout, not a production cutover)
8
-
9
- Each explicitly registered project has one SQLite source of truth:
10
- ~/.chat-loop/context/<projectId>/context.sqlite
11
-
12
- Optional artifacts/ and backups/ live beside it; no competing project.json,
13
- current.md, history.md or handoff.md. The user's source repository and AGENTS.md
14
- are NOT managed or modified by Context. A project may reference authorized
15
- Workspace roots via Project.sharedContext.workspaceRefs.
16
-
17
- ## SDK method disclosure
18
-
19
- Use:
20
- chatloop-context methods list --json
21
- chatloop-context methods describe project.open
22
-
23
- Both use lib/methods.mjs, the same catalog that generates ChatGPT MCP inputSchema.
24
- No hidden run.bind/fence/permit controls are exposed as ordinary SDK methods.
25
-
26
- Example after an approved pinned installation (future release, not yet published):
27
- npx --yes --offline --package=@tomflow/chatloop-context@0.1.0 chatloop-context methods list --json
28
-
29
- Requests take one bounded JSON object from stdin and emit one JSON object on
30
- stdout. Never place credentials or sensitive project bodies in CLI args or logs:
31
- echo '{"operation":"sdk.methods.list","group":"project"}' | chatloop-context request --json
32
-
33
- A trusted local adapter supplies CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS and, if
34
- needed, CHAT_LOOP_CONTEXT_ROOT (default ~/.chat-loop/context) or an explicit
35
- CHAT_LOOP_CONTEXT_DB solely for existing legacy Store compatibility.
36
- The comma-separated Project grant is parsed atomically: invalid, empty or
37
- duplicate IDs reject the whole grant, including in MCP and Native adapters.
38
- Use project.list/task.list with limit (1–100) and cursor for bounded pages;
39
- omitting both keeps the legacy array return. A page is not a cross-request
40
- snapshot; verify revisions when resuming after concurrent writes.
41
-
42
- ## Reviewed Project registration and Workspace ownership (local operator)
43
-
44
- The local operator must explicitly enable admin scope, choose the permitted
45
- Project IDs, and use an **interactive terminal**. The user-reviewed entry
46
- validates real canonical directories and prompts for an exact action+scope
47
- confirmation BEFORE creating a Store:
48
-
49
- CHAT_LOOP_CONTEXT_ADMIN_ENABLE=1 \
50
- CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS=demo \
51
- chatloop-context project register demo "Demo project" /confirmed/workspace
52
-
53
- Additional Workspace roots may be supplied to `register` (up to 16).
54
- Registration uses a global per-Context-root lock, rejects symlink roots,
55
- nested/overlapping roots and previously claimed roots, and atomically renames
56
- a newly staged per-Project SQLite. An existing Project is never overwritten.
57
-
58
- To replace the **whole** Workspace set on an existing Project, first call
59
- `project.open` and read its projectRevision and storeEpoch, then explicitly
60
- run the local operator command (with the same admin grant and TTY confirmation):
61
-
62
- chatloop-context project bind demo <revision> <storeEpoch> <writeRequestId> /root/a /root/b
63
- chatloop-context project bind demo <revision> <storeEpoch> <writeRequestId> --clear
64
-
65
- The second command explicitly clears every Workspace binding. A bind checks
66
- the original Project identity, CAS revision/epoch, global Project ownership,
67
- path stability, active execution/Handoff writer fences, then writes one durable
68
- Core receipt. If the CLI result is lost, use the **same** request ID for a
69
- read-only operator lookup, never repeat the mutation with a different ID:
70
-
71
- chatloop-context project receipt demo <storeEpoch> <writeRequestId>
72
-
73
- The older `project init` remains an explicit *local-admin* compatibility
74
- command for already approved automated setup; it does **not** itself collect
75
- a real user-review prompt and must not be offered as the normal first-use flow.
76
- None of these commands are exposed as ordinary model Context MCP mutations.
77
- A local TTY/OS-UID operator approval is not cryptographic ChatGPT user
78
- authentication. Without explicit user authorization, do not infer independent
79
- approval or claim a completed in-Chat self-service onboarding. For a user-
80
- delegated Agent migration, label the operator `USER_DELEGATED_AGENT` and retain
81
- the exact verified source/backup/revision evidence; never describe this as an
82
- independent human or platform-authenticated approval. None of these operations
83
- grant Chrome Owner or migrate an existing Legacy Store by themselves.
84
-
85
- ## Offline shared Store extraction (diagnostic ONLY, not a cutover)
86
-
87
- Before a cutover, use the **read-only** source integrity audit with an explicitly
88
- granted Project and a verified old Store epoch:
89
-
90
- CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS=demo \
91
- chatloop-context project audit-sources demo /private/old/shared.sqlite <sourceEpoch>
92
-
93
- To inspect a Registry task document that changed since shadow scan, point to
94
- a verified private Recovery Archive copy of the **original** document:
95
-
96
- chatloop-context project inspect-reference demo /private/old/shared.sqlite \
97
- <sourceEpoch> <sourceUnitId> <taskId> /private/archive/task-document.md
98
-
99
- This is a read-only two-version evidence check: exact Registry SHA and
100
- task identity, archived document SHA, current document SHA, and a bounded
101
- insertions-only vs changed-content comparison. It outputs a review-required
102
- receipt (not a stored approval); `canActivate` and `canExecute` remain false.
103
- Never rewrite the old Registry to suppress drift.
104
-
105
- **Reviewed local reconciliation (not SourceUnit activation):** after independently
106
- reviewing the exact original archive, current document, Project scope and old
107
- writers, a local terminal operator may run:
108
-
109
- CHAT_LOOP_CONTEXT_ADMIN_ENABLE=1 CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS=demo \
110
- chatloop-context project reconcile-reference demo /private/old/shared.sqlite \
111
- <epoch> <sourceUnitId> <migrationRevision> <taskId> <originalArchiveFile> \
112
- <currentDocSha256> <operatorReviewRef> <writeRequestId>
113
-
114
- A real TTY is required and the exact source/old/new hashes and review reference
115
- must be confirmed. Only insertions-only Task document drift is admitted; other
116
- content changes need separate review. The Core uses epoch, migration revision
117
- and durable request receipts, keeps original and current SHA plus original
118
- archive locator in the SourceUnit, leaves the Registry file unchanged and
119
- keeps the SourceUnit in SHADOW_RO. It cannot create R/P approvals or Browser
120
- Owner, or assert the independent old-writer / user-authentication gates.
121
- For an uncertain result, **query** with the same ID, never resubmit with a new ID:
122
-
123
- chatloop-context project reconcile-receipt demo /private/old/shared.sqlite \
124
- <epoch> <writeRequestId>
125
-
126
- This interface is a local-operator entry; a TTY under one OS UID is not
127
- proof of platform-authenticated ChatGPT user approval. By default an autonomous
128
- agent MUST NOT infer an independent operator decision. When the user expressly
129
- delegates the precise migration scope in the current conversation, the agent
130
- may operate the existing TTY path as a **disclosed user-delegated local agent**,
131
- with exact SourceUnit/hash/revision checks and an immutable private delegation
132
- audit record. Record `USER_DELEGATED_AGENT`, never `INDEPENDENT_HUMAN` or
133
- platform-authenticated consent. This delegation does not approve R/P or Owner.
134
- The audit reads source bytes and Registry-linked Task documents, checks exact
135
- Project Material hash/path coverage, and distinguishes a changed Registry
136
- file from drift in a linked task document. Its CLI receipt also includes
137
- `supportedWriterObservation: {status,pids}` from the same bounded process
138
- inventory used by `activate` (PID only; never argv). `MATCHED` reports a known
139
- writer still running; `NO_SUPPORTED_PROCESS_MATCH` is **not proof** that all
140
- legacy writers were independently fenced, and `UNVERIFIED` means the process
141
- scan itself failed. It reports mixed CURRENT items still requiring human
142
- classification, without revealing historical document bodies or treating a
143
- recovered user Turn as fresh approval. Its `BLOCKED` status intentionally
144
- includes independent old-writer fencing and release/E2E gates that a local
145
- file scan cannot prove. It never creates a Store or modifies SourceUnits,
146
- revisions, permissions, Owner or approvals.
147
-
148
- **Mixed CURRENT EvidenceOnly classification (local operator only):** when
149
- the complete, exact historical Markdown bytes are already stored as a
150
- `LEGACY_UNVERIFIED` Project Material under the canonical source path/hash,
151
- the operator may explicitly classify a mixed source as historical evidence
152
- without promoting ANY text to a current Project/Task/R/P fact:
153
-
154
- CHAT_LOOP_CONTEXT_ADMIN_ENABLE=1 CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS=demo \
155
- chatloop-context project classify-evidence demo /private/old/shared.sqlite \
156
- <epoch> <sourceUnitId> <migrationRevision> <sourceSha256> \
157
- <operatorReviewRef> <writeRequestId>
158
-
159
- The preflight verifies the physical SourceUnit and the complete stored body,
160
- and requires exact interactive terminal confirmation. Only the Core's
161
- `migrationClassify` mutates the SourceUnit manifest with
162
- `taskContexts=[]`, `projectSharedContext={}` and a reference to the
163
- entire original content as EvidenceOnly/UNKNOWN; the Unit stays SHADOW_RO.
164
- This is an intentional human-reviewed historical *disposition*, not a
165
- claim that the historical statements are current or approved. It does not
166
- activate a Store, release an old writer, or authorize Chrome Owner.
167
- For an unknown result use `project migration-receipt` with original epoch and
168
- writeRequestId. Local TTY is not ChatGPT platform user authentication.
169
-
170
- An older single SQLite may contain several Projects. Never copy or rename it
171
- directly into the active per-Project location: doing so leaks unrelated data,
172
- reuses the old epoch and risks reviving stale runs. The local operator can
173
- first inspect the legacy Store read-only to obtain the **exact** source
174
- `storeEpoch` and target `projectRevision`, then, on a separate private
175
- target root and with explicit real TTY confirmation, use:
176
-
177
- CHAT_LOOP_CONTEXT_ROOT=/private/review-target \\
178
- CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS=demo \\
179
- CHAT_LOOP_CONTEXT_ADMIN_ENABLE=1 \\
180
- chatloop-context project stage-diagnostic demo /private/old/shared.sqlite <sourceEpoch> <projectRevision>
181
-
182
- This action reads the source through a SQLite online snapshot, selects ONLY
183
- the named Project and its scoped rows, retains their exact Task/Material/
184
- SourceUnit history and old-epoch receipts, then strips runnable leases,
185
- permits and writer credentials. It vacuums foreign Project content from the
186
- new database and checks the physical row counts, integrity and ownership
187
- before atomically publishing the result. A private `migration-diagnostic.json`
188
- receipt names the old/new epochs and counts but is **not** a second active
189
- Context authority or a retained full-Store backup.
190
-
191
- The resulting Project is always `DIAGNOSTIC_ONLY`, with a new epoch,
192
- `canExecute=false` and `approvalsRevalidated=false`. Old receipts cannot
193
- replay under the new epoch. No SourceUnit becomes `MANAGED_RW`, and no
194
- Task/Run, browser Owner or previously observed R/P approval gains authority.
195
- The source is left untouched. An invalid SourceUnit, unexpected schema,
196
- stale revision, missing operator approval or existing target fails closed;
197
- incomplete staging is removed. This command is not exposed through MCP.
198
-
199
- ## Reviewed single-Project release (local operator, not MCP)
200
-
201
- A diagnostic branch is **never** promoted. A separate terminal-only release
202
- works exclusively with an already reviewed legacy SQLite containing **exactly
203
- one Project**. The existing `project audit-sources` must show source hashes,
204
- reference checks, mixed evidence and bodies reviewed, and every SourceUnit
205
- must already be `MANAGED_RW`. All known Gateway writers must be stopped, any
206
- unknown legacy clients independently fenced, and all running Task leases/
207
- permits/UNKNOWN effects reconciled before sealing. If any requirement fails,
208
- do not run these commands.
209
-
210
- With `CHAT_LOOP_CONTEXT_ADMIN_ENABLE=1` and a single explicit Project grant,
211
- and **without** `CHAT_LOOP_CONTEXT_DB`, the local operator first confirms
212
- the exact source Epoch/revision, backup path and output receipt in a real TTY:
213
-
214
- chatloop-context project seal-source <projectId> <sourceDb> <epoch> \
215
- <projectRevision> <privateBackup.sqlite> <privateSeal.json>
216
-
217
- Sealing makes a fresh private SQLite online backup, verifies the source again
218
- under an exclusive write transaction, and durably sets the single old Store
219
- to `CUTOVER_FENCED`. The old Store then rejects ordinary and internal writes
220
- even when the old Epoch is supplied. This is **not** SourceUnit approval and
221
- does not restore any Browser Owner. If the command reports UNKNOWN, inspect
222
- the old Store mode and original private receipt; never remove the fence or
223
- retry with a new Project/backup path.
224
-
225
- Only when the seal receipt and its SHA-256 are independently verified, the
226
- operator may separately confirm:
227
-
228
- chatloop-context project publish-managed <projectId> <sourceDb> <epoch> \
229
- <projectRevision> <privateSeal.json> <sealSha256>
230
-
231
- Publication accepts only a sealed, **single-Project** source, exact backup
232
- hash, unchanged logical source hash, all reviewed SourceUnits and no known
233
- live MCP writer. It creates a new-Epoch `ACTIVE` single-Project SQLite under
234
- the canonical Context root, with an atomic directory rename, zero foreign
235
- projects, zero runnable permits/leases and **zero inherited R/P approvals or
236
- run credentials**. The original old Store stays `CUTOVER_FENCED`; no dual
237
- write. The published Project can use Context business writes, but its old
238
- approvals are untrusted: Workspace binding and **fresh** R/P presentation,
239
- confirmation, Native Owner and Chrome E2E must each be validated separately.
240
- The response deliberately sets `canExecute:false`.
241
-
242
- If publication fails after sealing, preserve the sealed source, existing
243
- private backup and seal receipt for offline recovery; never copy/rename a
244
- `DIAGNOSTIC_ONLY` Store into production or flip `storeMode` directly.
245
- The CLI rejects non-TTY callers and the module is not exposed via ordinary
246
- MCP. Same-UID local terminal confirmation alone is **not** proof of an
247
- independent ChatGPT user authorization. Exception: a current explicit user
248
- instruction can delegate a specific Project cutover to an Agent, which may
249
- operate the local TTY as `USER_DELEGATED_AGENT` after recording the source
250
- identities, hashes, revisions, physical writer fence, backup and restoration
251
- evidence. The resulting review is delegated, **not independently human-verified**.
252
- Do not weaken the actual Core CAS, offline backup, old-writer check, Legacy
253
- fence, R/P approval, UNKNOWN-send or browser Owner guards.
254
-
255
- **Production remains BLOCKED** until the physical source hashes, mixed
256
- CURRENT ownership, old writers and true operator approval have been reviewed,
257
- old app/Native/Registry clients fenced, fresh backup plus recovery tested and
258
- the release/real Chrome E2E gates passed. See P0-02 in
259
- `docs/research/chat-loop-context-cli-architecture-20261109.md`.
260
-
261
- ## Safety
262
-
263
- Writes use expectedStoreEpoch, revision CAS and durable writeRequestId.
264
- Unknown results must be checked with the SAME request ID; never blindly
265
- resubmit with another ID. Active-run holder controls live outside ordinary
266
- MCP/CLI mutations in the restricted Worker→Native adapter. An SDK business
267
- checkpoint never grants Browser Owner. One OS UID is not per-Chat isolation.
268
-
269
- No serve, Socket, HTTP API, second Tunnel or per-project daemon. The real
270
- legacy Context and UNKNOWN Chrome Owner remain unchanged until explicit
271
- migration and recovery approval.
1
+ # @tomflow/chatloop-context
2
+
3
+ One authoritative per-Project SQLite Context Store for **Project / Task / R/P Review /
4
+ Run Permit / Checkpoint / CAS / Receipt**. This package does **not** own the
5
+ Chrome Session Owner, user-message evidence collection, Trace, MCP Supervisor,
6
+ execution workflow or external source discovery.
7
+
8
+ ## Exactly two npm access points
9
+
10
+ | Entry | npm declaration | Who uses it | Purpose |
11
+ | --- | --- | --- | --- |
12
+ | **Module entry** | `exports["."] = "./index.mjs"` | SDK clients, Tools MCP, Native/Operator adapters | All importable functions, clearly separated by role |
13
+ | **Executable entry** | `bin["chatloop-context"] = "./bin/cli.mjs"` | Pinned Tools CLI process or explicitly authorized local operator | Bounded `request --json`, method discovery and reviewed operator commands |
14
+
15
+ **No `./protocol`, `./methods`, `./operations`, `./migration`,
16
+ `./admin` or `./cli` npm subpath is exported.** Internal files in
17
+ `lib/` are implementation, not an integration contract. The installed CLI
18
+ comes from npm `bin`, not a second importable npm module.
19
+
20
+ **Implementation boundary:** No module in `lib/**` imports another `lib/**`
21
+ implementation. The sole SDK root `index.mjs` injects named API capabilities
22
+ through three lazy compositions: Business, Trusted Native and Local Operator.
23
+ `bin/cli.mjs` imports only `index.mjs` and invokes the reviewed operator
24
+ `runLocalCliCommand()` API; it does not import implementation files.
25
+
26
+ ```text
27
+ index.mjs (sole SDK entry and dependency assembler)
28
+ |-- Build manifest -> capability contracts and generic dispatcher
29
+ |-- Business API -> Core / Project / Task / Review / Context
30
+ |-- Trusted API -> Run / Permit (signed-IPC consumer)
31
+ +-- Operator API -> Workspace / Migration / CLI commands
32
+ bin/cli.mjs (sole executable entry) -> index.mjs -> Operator API
33
+ lib/** (private implementations) <- named capabilities injected by index.mjs
34
+ Core -> one SQLite handle, CAS transaction and durable receipt owner
35
+ ```
36
+
37
+ A module knows only its injected API contract, never the source file or internal
38
+ structure of the provider. Modules do not import `index.mjs` in reverse, so
39
+ no circular npm import is created. An import, `npx` invocation or module loader
40
+ alone **does not grant** Project ACL, Native Permit or operator permission.
41
+
42
+ ## Module exports: always import only from the package root
43
+
44
+ ```js
45
+ import {
46
+ CONTEXT_CONTRACT, CONTEXT_PACKAGE_VERSION,
47
+ requestContext, contextGateway, loadTrustedRuntime, loadLocalOperator,
48
+ subscribeContextApiLog
49
+ } from '@tomflow/chatloop-context';
50
+ ```
51
+
52
+ | Surface | Exact exported names | Trust boundary |
53
+ | --- | --- | --- |
54
+ | **Public SDK** | `CONTEXT_CONTRACT`, `CONTEXT_PACKAGE_VERSION`, `requestContext` | Strict Method Catalog; Project ACL; CAS / receipt |
55
+ | **Tools MCP adapter** | `contextGateway` namespace (`tools`, `validate`, `allowedProjects`, `cliPath`) | The pinned package owns its own CLI path; caller cannot select arbitrary executable |
56
+ | **Trusted Native adapter** | `loadTrustedRuntime()` → `execute(command,args,native)` | Only a signed IPC verified Native projection is accepted by its consumer; Context validates domain command, Native fields, Project grant and CAS |
57
+ | **Local operator** | `loadLocalOperator()` → only `runLocalCliCommand` (CLI consumer) | Explicit reviewed CLI/TTY and verified Project/SourceUnit / backups |
58
+ | **Observability** | `subscribeContextApiLog(listener)` → `unsubscribe()` | Tools routes non-authoritative events to the existing Supervisor Trace writer |
59
+
60
+ `loadTrustedRuntime` and `loadLocalOperator` do not themselves authorize any
61
+ action. They organize trusted integrators behind **the same root**; they are
62
+ not ordinary model/MCP operations.
63
+
64
+ See [provider / consumer / dependency matrix](docs/interfaces.md) for the
65
+ **complete** cross-module reference. For exact method IDs, schemas and
66
+ semantics, use `sdk.methods.list` / `sdk.methods.describe` on the connected SDK.
67
+
68
+ ## External API minimization (no compatibility surface)
69
+
70
+ The npm module exposes exactly seven names, and the ordinary Method Catalog
71
+ contains **34 current business operations** (no Legacy aliases). Public
72
+ JavaScript consumers must use `requestContext(args)`; discovery also uses
73
+ that same operation with `sdk.methods.list` / `sdk.methods.describe`.
74
+ There are no separately exported `listMethods` / `describeMethod` helpers.
75
+
76
+ The CLI is the *only* consumer of `loadLocalOperator()`, whose returned
77
+ namespace contains only `runLocalCliCommand`. Its migration, workspace,
78
+ SourceUnit and orphan-fence utilities stay private to the `index.mjs`
79
+ composition. `project.create`, `project.registryAuthority`, `project.get`,
80
+ `project.archive`, `task.get`, `task.archive`, and `evidence.detach` are **not**
81
+ public operations. For new projects use reviewed `chatloop-context project
82
+ register/init`; for Project/Task detail use `project.open` / `task.open`.
83
+ There is no version-1 forwarding or fallback. Clients must upgrade together
84
+ and verify the `chat-loop.context-sdk.v2` contract before use.
85
+ `project.list` and `task.list` always return a bounded page object,
86
+ respectively `{projects,incomplete,nextCursor,limit}` and
87
+ `{tasks,incomplete,nextCursor,limit}`, with `limit=30` by default. There is
88
+ no implicit full-array result when pagination arguments are omitted.
89
+
90
+ ## Capability-based build composition
91
+
92
+ The stable npm/CLI/MCP entrypoints now compose **34 existing methods from
93
+ nine independent capability descriptors** in `capabilities/<group>.mjs`.
94
+ Each descriptor owns its method IDs, Schema, mode, version, and dispatch route.
95
+ To add an independent capability, create one new descriptor with a unique
96
+ group name; no edits to existing capabilities or the central router are needed.
97
+
98
+ `npm run build:capabilities` produces the deterministic
99
+ `capabilities.generated.mjs` (static imports) and
100
+ `lib/capability-catalog.generated.json` (strict metadata). The generated
101
+ catalog drives `sdk.methods.list/describe`, SDK validation, both MCP tool
102
+ schemas and CLI discovery. Build/check/pack fail when outputs
103
+ are missing or stale; runtime never scans arbitrary directories.
104
+
105
+ Existing Core writes continue to require the original Project authority,
106
+ MANAGED_RW, CAS and durable receipts. The new `module` route is limited to
107
+ authorized **read-only** Project access with a restricted document/material
108
+ read port; it does not expose a raw database, writer credential or Owner.
109
+ The scoped Store remains open until an asynchronous capability Promise settles,
110
+ then closes on both success and failure.
111
+ A future independently writable capability requires a separately reviewed
112
+ transaction/receipt contract, not a security bypass. No RAG implementation
113
+ or new business feature is included in this refactor.
114
+
115
+ The isolated additive `probe` test builds and routes a 35th method, verifies
116
+ its Project boundary, then removes it to recover the original 34 methods.
117
+ The compiler rejects unsafe writes and conflicting capability declarations.
118
+
119
+ ## Context API logging — Proxy/AOP, no domain instrumentation
120
+
121
+ The exported `requestContext` intercepts **all 34 business operations**.
122
+ The same reusable `Proxy` intercepts `contextGateway.validate`,
123
+ `contextGateway.allowedProjects`, Trusted Native `execute`, and Local
124
+ Operator `runLocalCliCommand`. The package exports one consumed hook,
125
+ `subscribeContextApiLog(listener)`, for Tools to attach a best-effort sink.
126
+
127
+ Each call emits a sanitized
128
+ `{contract,callId,traceId,spanId,parentSpanId,api,surface,mode,projectRef,taskRef,phase,time,durationMs,errorCode}`
129
+ event with `BEGIN` followed by `OK` or `FAILED`. API calls
130
+ within one asynchronous chain inherit a soft `traceId`; every API gets its
131
+ own `spanId` and optional parent. The pinned child CLI inherits only an
132
+ opaque sanitized parent reference, never a permission or Owner credential.
133
+ Input bodies, credentials, paths and output values are never logged. Callbacks and CLI STDERR output
134
+ are deferred through a bounded best-effort queue (up to 4096 pending events),
135
+ so an observer cannot synchronously delay a business API. Log failures and
136
+ queue saturation cannot change the original result, Promise rejection,
137
+ CAS transaction or business receipt; they must not trigger retries.
138
+ Observations can be dropped when overloaded and are not durable evidence.
139
+
140
+ Context CLI emits structured STDERR log records without polluting its
141
+ single JSON stdout response. For a Context-authorized single Project, Tools
142
+ routes these observations into **one** existing Supervisor Trace v2
143
+ `events.jsonl` file even when the public Trace MCP is disabled. Reading via
144
+ `chat_loop_trace_diagnose` still requires independent Trace opt-in.
145
+ Records use fixed `event=context.api`, typed `api={name,surface,mode}`,
146
+ and correlated `traceId/spanId/parentSpanId` for nested API calls. For
147
+ root calls without an inherited parent, `traceId=callId`.
148
+ No second logging database or daemon is created. Without a connected Trace
149
+ sink, CLI STDERR remains observable but no permanent retention is claimed.
150
+ These are soft execution observations, never R/P approval, browser-send
151
+ proof or Native Owner evidence.
152
+
153
+ ## Minimal usage
154
+
155
+ Node **20+** may import the root and discover methods; SQLite access, runtime
156
+ and operator work require **Node 24+**. The package does not create a daemon.
157
+
158
+ ```js
159
+ import {requestContext} from '@tomflow/chatloop-context';
160
+
161
+ const capabilities=await requestContext({operation:'sdk.methods.list',view:'groups'});
162
+ const schema=(await requestContext({operation:'sdk.methods.describe',
163
+ methodId:'project.open'})).inputSchema;
164
+ const project=await requestContext({operation:'project.open',projectId:'demo'});
165
+ console.log(project.authority,project.storeEpoch);
166
+ ```
167
+
168
+ A public SDK call is accepted only for configured, explicitly authorized
169
+ Project IDs. A normal adapter uses `CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS` plus
170
+ **exactly one** of `CHAT_LOOP_CONTEXT_ROOT` (one SQLite per Project) or the
171
+ explicitly controlled legacy `CHAT_LOOP_CONTEXT_DB` migration mode. Never
172
+ set both roots.
173
+
174
+ Write operations require relevant `expectedStoreEpoch`, revision CAS,
175
+ `writeRequestId`, and for active-run updates the real RunRef/credential.
176
+ **UNKNOWN** result: check `context.request.status` using the **original**
177
+ request ID; never invent a second write attempt.
178
+
179
+ ## CLI lifecycle
180
+
181
+ The npm executable is `chatloop-context`, installed by a fixed dependency
182
+ or invoked separately through a **pinned, available** npm version:
183
+
184
+ ```sh
185
+ npm install --save-exact @tomflow/chatloop-context@0.6.0
186
+ chatloop-context methods groups
187
+ chatloop-context methods list project
188
+ chatloop-context methods describe project.open
189
+ printf '%s
190
+ ' '{"operation":"sdk.methods.list","view":"groups"}' | chatloop-context request --json
191
+ ```
192
+
193
+ The CLI emits a **single structured result**:
194
+ `{contract,packageVersion,ok,result}` or
195
+ `{contract,packageVersion,ok:false,error:{code}}`. The binary is an
196
+ independent one-shot process; Tools starts its **pinned** CLI with
197
+ `shell:false` and does not resolve a new `npx` release per request.
198
+
199
+ Operator-only commands (`project register/bind/receipt/init`, `admin <action>`, recovery,
200
+ source audit and sealing, orphan fence, etc.) enforce separate local
201
+ authorization, exact input/revision and where required real TTY review.
202
+ See [operator and migration procedures](docs/operator-and-migration.md).
203
+
204
+ ## Actual consumers and dependencies
205
+
206
+ - **Consumers:** Project/Delivery/Continuity → Tools MCP
207
+ `chat_loop_context_get/mutate` → pinned Context CLI; Tools Registry
208
+ adapter → Context authority/Task reads; Extension Worker → Native Host
209
+ → signed Tools Supervisor → Context trusted runtime; local reviewed
210
+ operator → CLI.
211
+ - **npm dependencies:** `@tomflow/chatloop-extension` (official verified
212
+ Owner evidence API) and `ps-list` (cross-platform process enumeration).
213
+ Both are declared, pinned, and consumed through named APIs; SQLite,
214
+ filesystem and crypto remain Node built-ins.
215
+ - **Owner boundary:** Context no longer constructs the Extension installation
216
+ path or reads the private Native Session file. Its `fence-orphan`
217
+ operator asks Extension to independently verify terminal IDLE and Owner
218
+ mismatch before and after review. The process observation API is not
219
+ itself a durable stop receipt.
220
+
221
+ Read [interfaces.md](docs/interfaces.md) for the exact source files, calls,
222
+ ownership boundaries and known coupling risks.
223
+
224
+ ## Deployment is separate from source
225
+
226
+ Local npm source version `0.6.0` does **not** establish the connected MCP
227
+ version. Verify the real `sdk.methods.list` response, Node runtime,
228
+ pinned Tools dependency, package bytes and Project authority before any
229
+ separately authorized installation. Source refactoring does **not** migrate
230
+ production SQLite, change Chrome Owner or approve R/P.
231
+
232
+ ```sh
233
+ npm run build:capabilities:check
234
+ npm test
235
+ ```
236
+
237
+ Each capability owns its API contract in `capabilities/<group>.mjs`;
238
+ there is no separate API inventory document. To discover exact available
239
+ methods and their schemas, use `sdk.methods.list` / `sdk.methods.describe`
240
+ from the installed SDK. Never substitute local source docs for deployed contracts.