@tomflow/chatloop-tools 0.4.34 → 0.9.4
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.
- package/README.md +120 -127
- package/bin/cli.mjs +48 -38
- package/bin/supervisor.mjs +4 -0
- package/index.mjs +269 -0
- package/lib/adapters/fixture.mjs +3 -2
- package/lib/adapters/index.mjs +14 -5
- package/lib/adapters/mcp-child.mjs +29 -7
- package/lib/adapters/tunnel.mjs +25 -7
- package/lib/api-aspect.mjs +190 -0
- package/lib/cli-command-router.mjs +34 -0
- package/lib/context-control-auth.mjs +12 -1
- package/lib/context-control-run.mjs +17 -79
- package/lib/context-gateway.mjs +108 -15
- package/lib/control.mjs +3 -2
- package/lib/extension-cli-contract.mjs +22 -0
- package/lib/extension-proxy.mjs +48 -19
- package/lib/gateway.mjs +46 -176
- package/lib/mcp-tool-router.mjs +60 -0
- package/lib/release-owner-preflight.mjs +41 -0
- package/lib/release.mjs +94 -49
- package/lib/{supervisor.mjs → supervisor-runtime.mjs} +143 -80
- package/lib/trace-gateway.mjs +25 -7
- package/lib/trace-observation.mjs +123 -0
- package/lib/tunnel.mjs +17 -29
- package/package.json +20 -14
- package/providers/context.mjs +20 -0
- package/providers/desktop.mjs +80 -0
- package/{lib/extension-contract.mjs → providers/extension.mjs} +36 -0
- package/providers/runtime.mjs +32 -0
- package/providers/trace.mjs +25 -0
- package/providers.generated.mjs +8 -0
- package/scripts/build-providers.mjs +69 -0
- package/lib/context-cli.mjs +0 -2
- package/lib/context-migration.mjs +0 -2
- package/lib/context-protocol.mjs +0 -2
- package/lib/task-registry-managed.mjs +0 -38
- package/lib/task-registry.mjs +0 -221
- package/node_modules/@tomflow/chatloop-context/README.md +0 -271
- package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +0 -273
- package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +0 -301
- package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +0 -272
- package/node_modules/@tomflow/chatloop-context/lib/context-protocol.mjs +0 -1617
- package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +0 -264
- package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +0 -219
- package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +0 -455
- package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +0 -159
- package/node_modules/@tomflow/chatloop-context/package.json +0 -21
- package/node_modules/@tomflow/chatloop-trace/README.md +0 -13
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +0 -259
- package/node_modules/@tomflow/chatloop-trace/package.json +0 -11
|
@@ -1,271 +0,0 @@
|
|
|
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,273 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// One invocation = one bounded Context SDK request; never a background server.
|
|
3
|
-
import {randomUUID,createHash} from 'node:crypto';
|
|
4
|
-
import {existsSync,mkdirSync,mkdtempSync,renameSync,rmSync} from 'node:fs';
|
|
5
|
-
import {join} from 'node:path';
|
|
6
|
-
let canonicalWorkspaceRefs,confirmWorkspaceOperator,assertWorkspaceUnclaimed,
|
|
7
|
-
withWorkspaceRegistryLock,rebindProjectWorkspaces,readOperatorWorkspaceReceipt;
|
|
8
|
-
import {CONTEXT_CONTRACT,CONTEXT_PACKAGE_VERSION,methodById,validateContextCall,listMethods,describeMethod} from '../lib/methods.mjs';
|
|
9
|
-
// Catalog is Node 20-compatible; SQLite operations load only after Node 24 preflight.
|
|
10
|
-
let openContextProtocol,dispatchContextCall,contextRoot,allowedProjects,
|
|
11
|
-
verifySourceUnit,
|
|
12
|
-
createProjectDiagnosticBranch,createManagedProjectBranch,fenceLegacyProjectStore,
|
|
13
|
-
auditLegacyProjectSources,inspectLegacyRegistryReference,activeLegacyWriters;
|
|
14
|
-
const fail=code=>Object.assign(new Error(code),{code});
|
|
15
|
-
const requestLimit=5*1024*1024;
|
|
16
|
-
const output=o=>process.stdout.write(JSON.stringify({
|
|
17
|
-
contract:CONTEXT_CONTRACT,packageVersion:CONTEXT_PACKAGE_VERSION,...o
|
|
18
|
-
})+'\n');
|
|
19
|
-
async function stdinJson(){
|
|
20
|
-
let bytes=0,parts=[];
|
|
21
|
-
for await(const chunk of process.stdin){
|
|
22
|
-
bytes+=chunk.length;
|
|
23
|
-
if(bytes>requestLimit)throw fail('REQUEST_TOO_LARGE');
|
|
24
|
-
parts.push(chunk);
|
|
25
|
-
}
|
|
26
|
-
if(!bytes)throw fail('REQUEST_REQUIRED');
|
|
27
|
-
try{return JSON.parse(Buffer.concat(parts).toString('utf8'))}
|
|
28
|
-
catch{throw fail('INVALID_JSON')}
|
|
29
|
-
}
|
|
30
|
-
async function registerProject(projectId,title,workspaces=[],reviewed=false){
|
|
31
|
-
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
|
32
|
-
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
33
|
-
if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(projectId))throw fail('INVALID_SCOPE');
|
|
34
|
-
if(typeof title!=='string'||!title.trim()||title.length>200)throw fail('INVALID_TITLE');
|
|
35
|
-
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
36
|
-
const refs=canonicalWorkspaceRefs(workspaces,{allowEmpty:!reviewed});
|
|
37
|
-
const root=contextRoot(),final=join(root,projectId);
|
|
38
|
-
if(existsSync(final))throw fail('PROJECT_EXISTS');
|
|
39
|
-
// The user-reviewed entry never creates a Store (or even a directory)
|
|
40
|
-
// before the local operator confirms the exact canonical roots.
|
|
41
|
-
if(reviewed)await confirmWorkspaceOperator('REGISTER',projectId,0,refs);
|
|
42
|
-
mkdirSync(root,{recursive:true,mode:0o700});
|
|
43
|
-
return withWorkspaceRegistryLock(root,()=>{
|
|
44
|
-
let tmp;
|
|
45
|
-
try{
|
|
46
|
-
if(existsSync(final))throw fail('PROJECT_EXISTS');
|
|
47
|
-
if(reviewed){
|
|
48
|
-
const current=canonicalWorkspaceRefs(workspaces);
|
|
49
|
-
if(JSON.stringify(current)!==JSON.stringify(refs))throw fail('WORKSPACE_CHANGED');
|
|
50
|
-
assertWorkspaceUnclaimed(root,projectId,refs);
|
|
51
|
-
}
|
|
52
|
-
tmp=mkdtempSync(join(root,'.register-'));
|
|
53
|
-
const db=openContextProtocol(join(tmp,'context.sqlite'),{
|
|
54
|
-
allowCreate:true,authorizeData:()=>true,principalId:'local-operator'});
|
|
55
|
-
let result;
|
|
56
|
-
try{
|
|
57
|
-
result=db.projectCreate({projectId,title,sharedContext:{workspaceRefs:refs},
|
|
58
|
-
expectedStoreEpoch:db.epoch,writeRequestId:randomUUID()});
|
|
59
|
-
}finally{db.close()}
|
|
60
|
-
renameSync(tmp,final);tmp=null;
|
|
61
|
-
return {...result,workspaceRefs:refs,projectDirectory:final};
|
|
62
|
-
}finally{
|
|
63
|
-
// Incomplete staging is diagnostic only, never silently promoted.
|
|
64
|
-
if(tmp)rmSync(tmp,{recursive:true,force:true});
|
|
65
|
-
}
|
|
66
|
-
});
|
|
67
|
-
}
|
|
68
|
-
const args=process.argv.slice(2);
|
|
69
|
-
try{
|
|
70
|
-
const node24=Number(process.versions.node.split('.')[0])>=24;
|
|
71
|
-
if(!node24&&args[0]!=='methods')throw fail('CONTEXT_RUNTIME_UNSUPPORTED');
|
|
72
|
-
if(node24){
|
|
73
|
-
({openContextProtocol}=await import('../lib/context-protocol.mjs'));
|
|
74
|
-
({verifySourceUnit}=await import('../lib/context-migration.mjs'));
|
|
75
|
-
({dispatchContextCall,contextRoot,allowedProjects}=await import('../lib/operations.mjs'));
|
|
76
|
-
({canonicalWorkspaceRefs,confirmWorkspaceOperator,assertWorkspaceUnclaimed,
|
|
77
|
-
withWorkspaceRegistryLock,rebindProjectWorkspaces,readOperatorWorkspaceReceipt}=
|
|
78
|
-
await import('../lib/workspace-operator.mjs'));
|
|
79
|
-
({createProjectDiagnosticBranch,createManagedProjectBranch,fenceLegacyProjectStore,
|
|
80
|
-
auditLegacyProjectSources,inspectLegacyRegistryReference}=
|
|
81
|
-
await import('../lib/project-diagnostic.mjs'));
|
|
82
|
-
({activeLegacyWriters}=await import('../lib/context-cli.mjs'));
|
|
83
|
-
}
|
|
84
|
-
const [command,sub,...rest]=args;
|
|
85
|
-
let value;
|
|
86
|
-
if(command==='methods'&&sub==='list'&&rest.length<=1)
|
|
87
|
-
value=listMethods(rest[0]==='--json'?undefined:rest[0]);
|
|
88
|
-
else if(command==='methods'&&sub==='describe'&&rest.length===1)
|
|
89
|
-
value=describeMethod(rest[0]);
|
|
90
|
-
else if(command==='request'&&sub==='--json'&&rest.length===0){
|
|
91
|
-
const payload=await stdinJson();
|
|
92
|
-
if(!payload||typeof payload!=='object'||Array.isArray(payload))throw fail('INVALID_ARGUMENT');
|
|
93
|
-
const method=validateContextCall(
|
|
94
|
-
payload.operation&&['sdk.methods.list','sdk.methods.describe'].includes(payload.operation)?
|
|
95
|
-
'chat_loop_context_get':
|
|
96
|
-
// A method is always assigned a fixed read/write mode by the SDK Catalog.
|
|
97
|
-
methodById.get(payload.operation)?.mode==='write'?
|
|
98
|
-
'chat_loop_context_mutate':'chat_loop_context_get',payload);
|
|
99
|
-
value=await dispatchContextCall(method.mode==='write'?
|
|
100
|
-
'chat_loop_context_mutate':'chat_loop_context_get',payload);
|
|
101
|
-
}else if(command==='project'&&sub==='init'&&(rest.length===2||rest.length===3))
|
|
102
|
-
value=await registerProject(rest[0],rest[1],rest.slice(2));
|
|
103
|
-
else if(command==='project'&&sub==='register'&&rest.length>=3&&rest.length<=18)
|
|
104
|
-
value=await registerProject(rest[0],rest[1],rest.slice(2),true);
|
|
105
|
-
else if(command==='project'&&sub==='bind'&&rest.length>=4&&rest.length<=20){
|
|
106
|
-
const [projectId,revision,epoch,requestId,...paths]=rest;
|
|
107
|
-
if(paths.length===1&&paths[0]==='--clear')paths.length=0;
|
|
108
|
-
value=await rebindProjectWorkspaces({projectId,
|
|
109
|
-
expectedProjectRevision:Number(revision),expectedStoreEpoch:epoch,
|
|
110
|
-
writeRequestId:requestId,workspaces:paths});
|
|
111
|
-
}else if(command==='project'&&sub==='receipt'&&rest.length===3)
|
|
112
|
-
value=await readOperatorWorkspaceReceipt({projectId:rest[0],
|
|
113
|
-
storeEpoch:rest[1],writeRequestId:rest[2]});
|
|
114
|
-
else if(command==='project'&&sub==='reconcile-reference'&&rest.length===10){
|
|
115
|
-
const [projectId,sourceDb,expectedStoreEpoch,sourceUnitId,revision,
|
|
116
|
-
taskId,originalArchivePath,expectedCurrentHash,reviewRef,writeRequestId]=rest;
|
|
117
|
-
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
|
118
|
-
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
119
|
-
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
120
|
-
const expectedMigrationRevision=Number(revision);
|
|
121
|
-
if(!Number.isSafeInteger(expectedMigrationRevision)||expectedMigrationRevision<1)
|
|
122
|
-
throw fail('MIGRATION_VERSION_CONFLICT');
|
|
123
|
-
// Fail closed before any writable handle exists. Review is NOT user R/P.
|
|
124
|
-
const evidence=inspectLegacyRegistryReference({sourceDb,projectId,
|
|
125
|
-
expectedStoreEpoch,sourceUnitId,taskId,archiveFile:originalArchivePath});
|
|
126
|
-
if(evidence.changeKind!=='INSERTIONS_ONLY'||
|
|
127
|
-
evidence.currentTaskHash!==expectedCurrentHash)
|
|
128
|
-
throw fail('REGISTRY_REFERENCE_VERSION_CONFLICT');
|
|
129
|
-
await confirmWorkspaceOperator('RECONCILE_REFERENCE',projectId,
|
|
130
|
-
expectedMigrationRevision,[sourceDb,sourceUnitId,taskId,
|
|
131
|
-
evidence.archivedTaskHash,expectedCurrentHash,reviewRef]);
|
|
132
|
-
const db=openContextProtocol(sourceDb,{principalId:'local-operator',
|
|
133
|
-
authorizeData:(_mode,p)=>p===projectId,
|
|
134
|
-
authorizeAdmin:(op,p)=>p===projectId&&[
|
|
135
|
-
'migration.reference.reconcile',
|
|
136
|
-
'migration.reference.reconcile.reviewed'].includes(op)});
|
|
137
|
-
try{
|
|
138
|
-
value=db.migrationReconcileReference({projectId,sourceUnitId,
|
|
139
|
-
expectedMigrationRevision,expectedStoreEpoch,writeRequestId,
|
|
140
|
-
taskId,originalArchivePath,expectedCurrentHash,
|
|
141
|
-
sourceHash:evidence.sourceHash,reviewRef});
|
|
142
|
-
}finally{db.close()}
|
|
143
|
-
}else if(command==='project'&&['reconcile-receipt','migration-receipt'].includes(sub)&&rest.length===4){
|
|
144
|
-
const [projectId,sourceDb,storeEpoch,writeRequestId]=rest;
|
|
145
|
-
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
146
|
-
const db=openContextProtocol(sourceDb,{readOnly:true,
|
|
147
|
-
principalId:'local-operator',
|
|
148
|
-
authorizeData:(_mode,p)=>p===projectId});
|
|
149
|
-
try{value=db.requestStatus({projectId,storeEpoch,writeRequestId})}
|
|
150
|
-
finally{db.close()}
|
|
151
|
-
}else if(command==='project'&&sub==='classify-evidence'&&rest.length===8){
|
|
152
|
-
const [projectId,sourceDb,expectedStoreEpoch,sourceUnitId,revision,
|
|
153
|
-
sourceHash,reviewRef,writeRequestId]=rest;
|
|
154
|
-
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
|
155
|
-
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
156
|
-
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
157
|
-
const expectedMigrationRevision=Number(revision);
|
|
158
|
-
if(!Number.isSafeInteger(expectedMigrationRevision)||expectedMigrationRevision<1)
|
|
159
|
-
throw fail('MIGRATION_VERSION_CONFLICT');
|
|
160
|
-
if(typeof reviewRef!=='string'||reviewRef.length<8||reviewRef.length>256)
|
|
161
|
-
throw fail('REVIEW_REFERENCE_REQUIRED');
|
|
162
|
-
// The historical body's original bytes must already be a matching
|
|
163
|
-
// LEGACY_UNVERIFIED Project Material, never a synthesized current Task.
|
|
164
|
-
const reader=openContextProtocol(sourceDb,{readOnly:true,
|
|
165
|
-
principalId:'local-operator',authorizeData:(_mode,p)=>p===projectId,
|
|
166
|
-
authorizeAdmin:(op,p)=>op==='migration.list'&&p===projectId});
|
|
167
|
-
let unit;
|
|
168
|
-
try{
|
|
169
|
-
if(reader.mode!=='ACTIVE')throw fail('STORE_DIAGNOSTIC_ONLY');
|
|
170
|
-
if(reader.epoch!==expectedStoreEpoch)throw fail('STALE_EPOCH');
|
|
171
|
-
unit=reader.migrationList(projectId).find(x=>x.sourceUnitId===sourceUnitId);
|
|
172
|
-
if(!unit||unit.status!=='SHADOW_RO'||
|
|
173
|
-
unit.manifest.sourceKind!=='MIXED_CONTEXT')
|
|
174
|
-
throw fail('MIXED_SOURCE_NOT_SHADOW');
|
|
175
|
-
if(unit.migrationRevision!==expectedMigrationRevision)
|
|
176
|
-
throw fail('MIGRATION_VERSION_CONFLICT');
|
|
177
|
-
if(unit.sourceHash!==sourceHash)throw fail('SOURCE_CHANGED');
|
|
178
|
-
verifySourceUnit(unit.manifest);
|
|
179
|
-
const material=reader.projectMaterialList(projectId).filter(m=>
|
|
180
|
-
m.sourcePath===unit.sourcePath&&m.contentHash===sourceHash&&
|
|
181
|
-
m.provenance==='LEGACY_UNVERIFIED');
|
|
182
|
-
if(!material.some(m=>createHash('sha256').update(
|
|
183
|
-
reader.projectMaterialGet(projectId,m.materialId,m.version).body
|
|
184
|
-
).digest('hex')===sourceHash))throw fail('MIGRATION_BODY_NOT_IMPORTED');
|
|
185
|
-
}finally{reader.close()}
|
|
186
|
-
// Human-reviewed disposition: preserve FULL mixed history as
|
|
187
|
-
// EvidenceOnly/UNKNOWN. Do not assert any current Task or R/P fact.
|
|
188
|
-
await confirmWorkspaceOperator('CLASSIFY_EVIDENCE_ONLY',projectId,
|
|
189
|
-
expectedMigrationRevision,[sourceDb,sourceUnitId,sourceHash,reviewRef]);
|
|
190
|
-
const db=openContextProtocol(sourceDb,{principalId:'local-operator',
|
|
191
|
-
authorizeData:(_mode,p)=>p===projectId,
|
|
192
|
-
authorizeAdmin:(op,p)=>p===projectId&&
|
|
193
|
-
['migration.classify','migration.classify.reviewed'].includes(op)});
|
|
194
|
-
try{
|
|
195
|
-
value=db.migrationClassify({projectId,sourceUnitId,sourceHash,
|
|
196
|
-
expectedStoreEpoch,expectedMigrationRevision,writeRequestId,
|
|
197
|
-
classification:{projectId,sourceUnitId,sourceHash,
|
|
198
|
-
currentFactsComplete:true,reviewRef,taskContexts:[],
|
|
199
|
-
projectSharedContext:{},
|
|
200
|
-
unknownHistoryRefs:[{locator:unit.sourcePath,sourceHash}]}});
|
|
201
|
-
}finally{db.close()}
|
|
202
|
-
}else if(command==='project'&&sub==='inspect-reference'&&rest.length===6){
|
|
203
|
-
const [projectId,sourceDb,expectedStoreEpoch,sourceUnitId,taskId,archiveFile]=rest;
|
|
204
|
-
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
205
|
-
value=inspectLegacyRegistryReference({projectId,sourceDb,
|
|
206
|
-
expectedStoreEpoch,sourceUnitId,taskId,archiveFile});
|
|
207
|
-
}else if(command==='project'&&sub==='audit-sources'&&rest.length===3){
|
|
208
|
-
const [projectId,sourceDb,expectedStoreEpoch]=rest;
|
|
209
|
-
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
210
|
-
value=auditLegacyProjectSources({projectId,sourceDb,expectedStoreEpoch});
|
|
211
|
-
// Observe known, supported MCP writers without claiming an independent
|
|
212
|
-
// old-writer fence. Only PIDs are returned, never process argv or secrets.
|
|
213
|
-
let writerObservation;
|
|
214
|
-
try{
|
|
215
|
-
const pids=activeLegacyWriters().map(line=>Number(line.match(/^\d+/)[0]));
|
|
216
|
-
writerObservation={status:pids.length?'MATCHED':'NO_SUPPORTED_PROCESS_MATCH',pids};
|
|
217
|
-
}catch{writerObservation={status:'UNVERIFIED',pids:[]}}
|
|
218
|
-
value={...value,supportedWriterObservation:writerObservation};
|
|
219
|
-
}else if(command==='project'&&sub==='seal-source'&&rest.length===6){
|
|
220
|
-
const [projectId,sourceDb,epoch,revision,backupPath,sealManifestPath]=rest;
|
|
221
|
-
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
|
222
|
-
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
223
|
-
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
224
|
-
const expectedProjectRevision=Number(revision);
|
|
225
|
-
if(!Number.isSafeInteger(expectedProjectRevision)||expectedProjectRevision<1)
|
|
226
|
-
throw fail('PROJECT_VERSION_CONFLICT');
|
|
227
|
-
await confirmWorkspaceOperator('SEAL_SOURCE',projectId,
|
|
228
|
-
expectedProjectRevision,[sourceDb,epoch,backupPath,sealManifestPath]);
|
|
229
|
-
value=await fenceLegacyProjectStore({sourceDb,projectId,
|
|
230
|
-
expectedStoreEpoch:epoch,expectedProjectRevision,backupPath,sealManifestPath});
|
|
231
|
-
}else if(command==='project'&&sub==='publish-managed'&&rest.length===6){
|
|
232
|
-
const [projectId,sourceDb,epoch,revision,sealManifest,expectedSealHash]=rest;
|
|
233
|
-
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
|
234
|
-
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
235
|
-
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
236
|
-
const expectedProjectRevision=Number(revision);
|
|
237
|
-
if(!Number.isSafeInteger(expectedProjectRevision)||expectedProjectRevision<1)
|
|
238
|
-
throw fail('PROJECT_VERSION_CONFLICT');
|
|
239
|
-
await confirmWorkspaceOperator('PUBLISH_MANAGED',projectId,
|
|
240
|
-
expectedProjectRevision,[sourceDb,epoch,sealManifest,expectedSealHash]);
|
|
241
|
-
const root=contextRoot();
|
|
242
|
-
mkdirSync(root,{recursive:true,mode:0o700});
|
|
243
|
-
value=await withWorkspaceRegistryLock(root,()=>createManagedProjectBranch({
|
|
244
|
-
sourceDb,targetRoot:root,projectId,expectedStoreEpoch:epoch,
|
|
245
|
-
expectedProjectRevision,sealManifest,expectedSealHash
|
|
246
|
-
}));
|
|
247
|
-
}else if(command==='project'&&sub==='stage-diagnostic'&&rest.length===4){
|
|
248
|
-
const [projectId,sourceDb,expectedStoreEpoch,revision]=rest;
|
|
249
|
-
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
|
250
|
-
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
251
|
-
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
252
|
-
const expectedProjectRevision=Number(revision);
|
|
253
|
-
if(!Number.isSafeInteger(expectedProjectRevision)||expectedProjectRevision<1)
|
|
254
|
-
throw fail('PROJECT_VERSION_CONFLICT');
|
|
255
|
-
// This is an offline diagnostic extract; NEVER a source cutover.
|
|
256
|
-
// The operator must review the exact source path and source CAS identity.
|
|
257
|
-
await confirmWorkspaceOperator('STAGE_DIAGNOSTIC',projectId,
|
|
258
|
-
expectedProjectRevision,[sourceDb,expectedStoreEpoch]);
|
|
259
|
-
const root=contextRoot();
|
|
260
|
-
mkdirSync(root,{recursive:true,mode:0o700});
|
|
261
|
-
value=await withWorkspaceRegistryLock(root,()=>createProjectDiagnosticBranch({
|
|
262
|
-
sourceDb,targetRoot:root,projectId,expectedStoreEpoch,expectedProjectRevision
|
|
263
|
-
}));
|
|
264
|
-
}else if(command==='doctor'&&sub==='--json'&&rest.length===0)
|
|
265
|
-
value={status:'READY',packageVersion:CONTEXT_PACKAGE_VERSION,projectRoot:contextRoot()};
|
|
266
|
-
else throw fail('UNKNOWN_COMMAND');
|
|
267
|
-
output({ok:true,result:value});
|
|
268
|
-
}catch(error){
|
|
269
|
-
// Never expose arbitrary OS/SQLite exception messages, paths or user data.
|
|
270
|
-
const code=error.code||'CONTEXT_FAILED';
|
|
271
|
-
output({ok:false,error:{code:/^[A-Z0-9_]+$/.test(code)?code:'CONTEXT_FAILED'}});
|
|
272
|
-
process.exitCode=1;
|
|
273
|
-
}
|