@volter/supercode-interchange 0.0.0-stage → 0.1.1

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/LICENSE-APACHE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 supercode contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,32 @@
1
- # Temporary Holding Version
1
+ # Supercode interchange
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Read-only metadata and discovery projection for the daemon-owned session index in
4
+ [TypeScript architecture step 4](../../docs/plans/typescript-architecture.md#order).
5
+ The port branch routes discovery and index windows through this library and the Teams owner.
6
+ [Dated private Mac/Windows observations](../../docs/evidence/session-index-owner-2026-10-08.md)
7
+ cover selected small homes; publication, all-format and large-home qualification remain open.
8
+ Full session translation codecs remain at their later boundary.
9
+
10
+ `resolveHarnessHomes` follows native HOME-first defaults and preserves explicitly empty harness-specific
11
+ home values. `projectMetadata` applies workspace scope, native lineage, repository-family, profile, time and
12
+ metadata-search filters with stable newest-first ordering. It clones raw rows before descendant roll-up.
13
+ `projectMetadataPage` returns the existing hex JSON tuple pagination cursor and coverage receipt; a cursor
14
+ whose row no longer matches is refused. These helpers neither read conversation previews nor imply that a
15
+ metadata page is an enriched public discovery response.
16
+
17
+ Workspace matching follows path components, includes directories linked directly into a subtree without
18
+ widening it to an ancestor, and preserves Hermes/OpenClaw's literal exact-directory matching. Repository
19
+ family matching reads Git common-directory and origin files without spawning Git.
20
+
21
+ Internal readers cover the seven file-backed formats and the four native stores. File results keep verified
22
+ fingerprints with their append offsets; compound rows also check auxiliary identities. Store snapshots are
23
+ read-only and observe DB/WAL changes. OpenCode and Goose compare native row marks; Hermes retains mirror
24
+ facts for query-time selection; orchestrator rows keep routing keys and the source change cursor. Codex names
25
+ and history topics, and late Claude rename aliases, have separate append-aware ledgers.
26
+
27
+ Bounded preview readers preserve source roles, provenance, native message cursors and Codex's adjacent
28
+ event/response pairing. Preview search enriches eligible rows before pagination. These readers and discovery
29
+ projection are connected to the owner; their presence is not a runtime or Windows qualification.
30
+
31
+ This package requires Node 22.15 or newer. It does not start a native harness, change a vendor home or own
32
+ a database. The machine daemon owns index state and subscriptions.
package/compressed.mjs ADDED
@@ -0,0 +1,58 @@
1
+ import { Readable } from 'node:stream';
2
+ import { pipeline } from 'node:stream/promises';
3
+ import * as zlib from 'node:zlib';
4
+ import { parseJsonLine } from './file-io.mjs';
5
+ import { headerFacts, headerComplete } from './metadata.mjs';
6
+
7
+ /** Decode only the native header budget, never a complete archived rollout.
8
+ * The compressed producer reads through the same verified handle as the row
9
+ * facts. Cancellation ends both streams before that handle can be released. */
10
+ export async function readCompressedCodexHeader(reader) {
11
+ if (typeof zlib.createZstdDecompress !== 'function') throw new Error('compressed Codex metadata requires Node with createZstdDecompress (Node 22.15 or later)');
12
+ const source = Readable.from((async function* () {
13
+ for (let offset = 0; offset < reader.size;) {
14
+ const chunk = await reader.read(offset, Math.min(16 * 1024, reader.size - offset));
15
+ offset += chunk.length;
16
+ yield chunk;
17
+ }
18
+ })(), { objectMode: false });
19
+ const decoder = zlib.createZstdDecompress({ chunkSize: 16 * 1024 });
20
+ const abort = new AbortController();
21
+ // Install the rejection handler before consuming output; neither a failed
22
+ // producer nor an intentional prefix cancellation is an unhandled promise.
23
+ const completion = pipeline(source, decoder, { signal: abort.signal }).then(() => null, (error) => error);
24
+ const records = [];
25
+ let trailing = Buffer.alloc(0), consumed = 0, lines = 0, stopped = false;
26
+ const accept = (input) => {
27
+ const line = input.at(-1) === 13 ? input.subarray(0, -1) : input;
28
+ consumed += line.length; lines++;
29
+ if (consumed > 256 * 1024) return true;
30
+ const value = parseJsonLine(line, { strictUtf8: true });
31
+ if (value != null) records.push(value);
32
+ const recognizable = records.some((record) => (record?.type === 'session_meta'
33
+ && (typeof record.payload?.id === 'string' || typeof record.payload?.cwd === 'string'))
34
+ || (record?.type === 'turn_context' && typeof record.payload?.cwd === 'string'));
35
+ return lines >= 32 || (recognizable && headerComplete(headerFacts(records, 'codex'), 'codex'));
36
+ };
37
+ try {
38
+ for await (const chunk of decoder) {
39
+ const bytes = trailing.length ? Buffer.concat([trailing, chunk]) : chunk;
40
+ let from = 0, end;
41
+ while ((end = bytes.indexOf(10, from)) >= 0) {
42
+ if (accept(bytes.subarray(from, end))) { stopped = true; break; }
43
+ from = end + 1;
44
+ }
45
+ if (stopped) break;
46
+ trailing = bytes.subarray(from);
47
+ if (consumed + trailing.length > 256 * 1024 + 1) { stopped = true; break; }
48
+ }
49
+ if (!stopped && trailing.length) accept(trailing);
50
+ return headerFacts(records, 'codex');
51
+ } finally {
52
+ // Returning from for-await destroys its decoder. Abort also releases the
53
+ // upstream iterator, including any outstanding read of compressed bytes.
54
+ abort.abort();
55
+ const failure = await completion;
56
+ if (failure && !stopped && failure.code !== 'ABORT_ERR') throw failure;
57
+ }
58
+ }
package/discovery.mjs ADDED
@@ -0,0 +1,110 @@
1
+ import { descriptorMatches, projectMetadata, projectMetadataPage, decodeDiscoveryCursor, encodeDiscoveryCursor, discoveryReceipt } from './query.mjs';
2
+ import { readLatestCandidates, readFileTopics } from './previews.mjs';
3
+ import { nativeTrim } from './text.mjs';
4
+
5
+ /** Preview refusal preserves the native metadata row. The owner can retain
6
+ * the exact failed source in diagnostics; it never invents message content. */
7
+ export async function enrichDescriptor(query, descriptor, { codexTopics, metrics, previewFailure } = {}) {
8
+ const row = { ...descriptor };
9
+ const take = async (read) => {
10
+ try { return await read(); }
11
+ catch (error) { previewFailure?.(row.locator, error); return []; }
12
+ };
13
+ if (query.include_topic_candidates) {
14
+ const history = row.locator.harness === 'codex' ? codexTopics?.get(row.locator.session_id) : null;
15
+ const topics = history != null ? (Array.isArray(history) ? history : [history])
16
+ : row.locator.storage.kind === 'file' ? await take(() => readFileTopics(row.locator.storage.path, row.locator.harness, metrics)) : [];
17
+ if (topics.length) row.preview_candidates = topics;
18
+ else delete row.preview_candidates;
19
+ }
20
+ const latest = await take(() => readLatestCandidates(row.locator, metrics));
21
+ if (latest.length) row.latest_message_candidates = latest;
22
+ else delete row.latest_message_candidates;
23
+ return row;
24
+ }
25
+
26
+ /** Bounded enrichment belongs to returned/current-window rows. Metadata
27
+ * maintenance never invokes this function, including unchanged warm queries. */
28
+ export async function enrichIndexPage(query, rows, options) {
29
+ const result = [];
30
+ for (const row of rows) result.push(await enrichDescriptor(query, row, options));
31
+ return result;
32
+ }
33
+
34
+ function queryName(query) { return query.query == null ? null : nativeTrim(query.query); }
35
+
36
+ export function namesWholeSessionId(query) {
37
+ const id = queryName(query);
38
+ return query.cursor == null && id?.length >= 8 && id.includes('-') && /^[0-9a-f-]+$/i.test(id);
39
+ }
40
+
41
+ /** Name suppliers use the owner's watched registry/rename ledgers. The late
42
+ * title supplier chooses one id by source mtime, before applying the other
43
+ * query filters, as native claude_session_named does. Neither is caller proof. */
44
+ export async function discoverFromIndex(query, descriptors, options = {}) {
45
+ const raw = [...descriptors];
46
+ if (query.search_previews) return previewPage(query, raw, options);
47
+ const page = projectMetadataPage(query, raw, options);
48
+ const name = queryName(query);
49
+ if (query.cursor == null && name) {
50
+ const selected = query.harnesses;
51
+ const canNameClaude = !selected?.length || selected.includes('claude-code');
52
+ const live = canNameClaude ? await options.liveClaudeName?.(name) : null;
53
+ if (live != null) {
54
+ const found = page.sessions.find((row) => row.locator.session_id === live.id);
55
+ if (found) {
56
+ if (found.title == null) found.title = live.name;
57
+ page.sessions = [found]; page.next_cursor = null;
58
+ }
59
+ }
60
+ }
61
+ // Native finish_discover_page restricts any exact returned id, rather than
62
+ // just the UUID-shaped optimization used before its cold scan.
63
+ if (name != null && page.sessions.some((row) => row.locator.session_id === name)) {
64
+ page.sessions = page.sessions.filter((row) => row.locator.session_id === name);
65
+ page.next_cursor = null;
66
+ }
67
+ if (!page.sessions.length && query.cursor == null && name && (!query.harnesses?.length || query.harnesses.includes('claude-code'))) {
68
+ const id = await options.lateClaudeName?.(name);
69
+ if (id != null) {
70
+ const rows = projectMetadata({ ...query, query: null, harnesses: ['claude-code'], limit: null }, raw, options);
71
+ const found = rows.find((row) => row.locator.session_id === id);
72
+ if (found) page.sessions.push({ ...found, title: name });
73
+ }
74
+ }
75
+ // Keep the native receipt from projection: its counts precede the exact-name
76
+ // post-filter and late-name fallback. Do not silently rewrite that contract.
77
+ page.sessions = await enrichIndexPage(query, page.sessions, options);
78
+ return page;
79
+ }
80
+
81
+ async function previewPage(query, raw, options) {
82
+ const search = queryName(query)?.toLowerCase();
83
+ if (!search) throw new Error('search_previews requires a nonempty query');
84
+ if (query.limit === 0) throw new Error('preview search limit must be positive');
85
+ if (query.limit != null && (!Number.isSafeInteger(query.limit) || query.limit < 0)) throw new Error('discovery limit must be a nonnegative integer');
86
+ const cursor = query.cursor == null ? null : JSON.stringify(decodeDiscoveryCursor(query.cursor));
87
+ const eligibleQuery = { ...query, query: null, search_previews: false, include_topic_candidates: true };
88
+ const eligible = projectMetadata(eligibleQuery, raw, options);
89
+ let cursorSeen = cursor == null, total = 0, more = false;
90
+ const sessions = [];
91
+ for (let row of eligible) {
92
+ const metadataMatch = descriptorMatches(row, search);
93
+ if (!metadataMatch) {
94
+ row = await enrichDescriptor(eligibleQuery, row, options);
95
+ if (![...(row.preview_candidates ?? []), ...(row.latest_message_candidates ?? [])].some((candidate) => candidate.content.toLowerCase().includes(search))) continue;
96
+ }
97
+ total++;
98
+ if (!cursorSeen) {
99
+ cursorSeen = cursor === JSON.stringify([row.updated_at_ms ?? null, row.locator.harness, row.locator.session_id]);
100
+ continue;
101
+ }
102
+ if (sessions.length < (query.limit ?? Infinity)) {
103
+ if (metadataMatch) row = await enrichDescriptor(eligibleQuery, row, options);
104
+ sessions.push(row);
105
+ } else more = true;
106
+ }
107
+ if (!cursorSeen) throw new Error('discovery cursor is stale or invalid');
108
+ return { sessions, next_cursor: more && sessions.length ? encodeDiscoveryCursor(sessions.at(-1)) : null,
109
+ receipt: discoveryReceipt(query, sessions, total, more, true) };
110
+ }
package/file-io.mjs ADDED
@@ -0,0 +1,151 @@
1
+ import { open, stat } from 'node:fs/promises';
2
+ import { parseNativeJson } from './native-json.mjs';
3
+
4
+ const stale = (path) => Object.assign(new Error(`${path} changed during its metadata read; previous index rows are retained`), { code: 'ESTALE' });
5
+ const same = (a, b) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs;
6
+
7
+ export function fileFingerprint(info) {
8
+ return { device: String(info.dev), inode: String(info.ino), size: String(info.size), mtime_ns: String(info.mtimeNs) };
9
+ }
10
+
11
+ export function sameFingerprint(left, right) {
12
+ return left != null && right != null && ['device', 'inode', 'size', 'mtime_ns'].every((key) => left[key] === right[key]);
13
+ }
14
+
15
+ export function appendableFingerprint(previous, current) {
16
+ return previous != null && current != null && previous.device === current.device && previous.inode === current.inode
17
+ && BigInt(current.size) > BigInt(previous.size);
18
+ }
19
+
20
+ /** Read one open identity; verify both the handle and its current path before
21
+ * returning facts for a transaction. A changed path never commits new offsets
22
+ * beside facts read from its predecessor. The caller owns failure retry. */
23
+ export async function withSessionFile(path, work, metrics = {}) {
24
+ const handle = await open(path, 'r');
25
+ metrics.files_opened = (metrics.files_opened ?? 0) + 1;
26
+ let countedRead = false;
27
+ try {
28
+ const before = await handle.stat({ bigint: true });
29
+ if (!before.isFile()) throw Object.assign(new Error(`${path} is not a session file`), { code: 'EINVAL' });
30
+ if (before.size > BigInt(Number.MAX_SAFE_INTEGER)) throw Object.assign(new Error(`${path} exceeds Node's exact file-offset range`), { code: 'EFBIG' });
31
+ const size = Number(before.size);
32
+ const reader = {
33
+ path, size, fingerprint: fileFingerprint(before), modified_ms: before.mtimeNs < 0n ? null : Number(before.mtimeNs / 1_000_000n),
34
+ async read(position, length, { appended = false } = {}) {
35
+ if (!Number.isSafeInteger(position) || position < 0 || !Number.isSafeInteger(length) || length < 0) throw new Error('invalid session-file range');
36
+ length = Math.min(length, Math.max(0, size - position));
37
+ const buffer = Buffer.alloc(length);
38
+ let received = 0;
39
+ while (received < length) {
40
+ const { bytesRead } = await handle.read(buffer, received, length - received, position + received);
41
+ if (!bytesRead) throw stale(path);
42
+ if (!countedRead) { metrics.files_read = (metrics.files_read ?? 0) + 1; countedRead = true; }
43
+ received += bytesRead;
44
+ metrics.bytes_read = (metrics.bytes_read ?? 0) + bytesRead;
45
+ if (appended) metrics.appended_bytes = (metrics.appended_bytes ?? 0) + bytesRead;
46
+ }
47
+ return buffer;
48
+ },
49
+ };
50
+ const result = await work(reader);
51
+ const after = await handle.stat({ bigint: true });
52
+ let current;
53
+ try { current = await stat(path, { bigint: true }); } catch { throw stale(path); }
54
+ if (!same(before, after) || !same(after, current)) throw stale(path);
55
+ return { result, fingerprint: reader.fingerprint, size, modified_ms: reader.modified_ms };
56
+ } finally { await handle.close(); }
57
+ }
58
+
59
+ export function parseJsonLine(buffer, { strictUtf8 = false } = {}) {
60
+ let text;
61
+ try { text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(buffer); }
62
+ catch (error) { if (strictUtf8) throw error; return null; }
63
+ try { return parseNativeJson(text); } catch { return null; }
64
+ }
65
+
66
+ /** A bounded head, with the native budget counted before parsing each line.
67
+ * A file's final unterminated line is visible to the cold header reader. */
68
+ export async function readHeaderRecords(reader, { bytes = 256 * 1024, lines = 32 } = {}) {
69
+ const buffer = await reader.read(0, bytes + lines * 2);
70
+ const scan = { lines: 0, bytes: 0, terminated: true, exhausted: false };
71
+ // Decode lazily: once the format reader has its complete header, malformed
72
+ // bytes in an unused later body line cannot turn that header into a failure.
73
+ const records = (function* () {
74
+ let from = 0;
75
+ while (from < buffer.length && scan.lines < lines) {
76
+ let end = buffer.indexOf(10, from);
77
+ scan.terminated = end >= 0;
78
+ if (end < 0) {
79
+ if (buffer.length < reader.size) { scan.exhausted = true; break; }
80
+ end = buffer.length;
81
+ }
82
+ const line = buffer.subarray(from, end > from && buffer[end - 1] === 13 ? end - 1 : end);
83
+ scan.bytes += line.length; scan.lines++;
84
+ if (scan.bytes > bytes) { scan.exhausted = true; break; }
85
+ const value = parseJsonLine(line, { strictUtf8: true });
86
+ if (value != null) yield value;
87
+ from = end + 1;
88
+ }
89
+ if (scan.lines >= lines) scan.exhausted = true;
90
+ })();
91
+ records.scan = scan;
92
+ return records;
93
+ }
94
+
95
+ /** Visit newly appended complete lines without reading the old prefix. The
96
+ * returned trailing bytes are committed with the offset, not discarded. A
97
+ * format reader can inspect the unfinished tail separately without counting
98
+ * it twice as a complete stored message. */
99
+ export async function visitAppendedLines(reader, previous, visit, { maxLineBytes = Infinity } = {}) {
100
+ let offset = previous?.offset ?? 0;
101
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > reader.size) throw stale(reader.path);
102
+ let pieces = previous?.trailing ? [Buffer.from(previous.trailing, 'base64')] : [];
103
+ let pendingBytes = pieces[0]?.length ?? 0;
104
+ let oversized = pendingBytes > maxLineBytes;
105
+ if (oversized) pieces = [];
106
+ let lineStart = offset - pendingBytes;
107
+ if (lineStart < 0) throw stale(reader.path);
108
+ while (offset < reader.size) {
109
+ const chunkStart = offset;
110
+ const chunk = await reader.read(offset, Math.min(64 * 1024, reader.size - offset), { appended: true });
111
+ offset += chunk.length;
112
+ let from = 0, end;
113
+ while ((end = chunk.indexOf(10, from)) >= 0) {
114
+ pendingBytes += end - from;
115
+ oversized ||= pendingBytes > maxLineBytes;
116
+ if (!oversized) pieces.push(chunk.subarray(from, end));
117
+ const input = oversized ? null : pieces.length === 1 ? pieces[0] : Buffer.concat(pieces, pendingBytes);
118
+ const line = input?.length && input.at(-1) === 13 ? input.subarray(0, -1) : input;
119
+ const lineEnd = chunkStart + end + 1;
120
+ await visit(line, { start: lineStart, end: lineEnd, oversized });
121
+ lineStart = lineEnd;
122
+ pieces = []; pendingBytes = 0; oversized = false;
123
+ from = end + 1;
124
+ }
125
+ if (from < chunk.length) {
126
+ pendingBytes += chunk.length - from;
127
+ oversized ||= pendingBytes > maxLineBytes;
128
+ if (oversized) pieces = [];
129
+ else pieces.push(chunk.subarray(from));
130
+ }
131
+ }
132
+ const trailing = oversized ? '' : Buffer.concat(pieces, pendingBytes).toString('base64');
133
+ return { offset, trailing, appendable: !oversized };
134
+ }
135
+
136
+ /** Visit complete tail boundaries newest-first; a partial first boundary is
137
+ * excluded when the range starts mid-file. The final boundary can lack LF. */
138
+ export function* tailRecords(buffer, fromMidFile = false) {
139
+ const floor = fromMidFile ? buffer.indexOf(10) + 1 : 0;
140
+ if (fromMidFile && floor === 0) return;
141
+ let end = buffer.length;
142
+ while (end > floor) {
143
+ const newline = buffer.lastIndexOf(10, end - 1);
144
+ const start = newline >= floor ? newline + 1 : floor;
145
+ if (start < end) {
146
+ const value = parseJsonLine(buffer.subarray(start, end));
147
+ if (value != null) yield { value, start, end };
148
+ }
149
+ end = start - 1;
150
+ }
151
+ }
@@ -0,0 +1,50 @@
1
+ import { finalizeNouns, catalogTimestamp } from './metadata.mjs';
2
+ import { readStore, statement, tableColumns, text, integer, unsigned, jsonColumn } from './sqlite-reader.mjs';
3
+ import { nativeTrim } from './text.mjs';
4
+
5
+ const MARKS = {
6
+ opencode: "SELECT id, title || char(31) || time_updated || char(31) || directory AS mark FROM session",
7
+ goose: "SELECT id, name || char(31) || updated_at || char(31) || working_dir AS mark FROM sessions WHERE archived_at IS NULL",
8
+ };
9
+
10
+ function marks(db, harness) {
11
+ return new Map(statement(db, MARKS[harness]).all().map((row) => [text(row.id), row.mark == null ? '' : text(row.mark)]));
12
+ }
13
+
14
+ function rows(db, path, harness, ids) {
15
+ if (ids?.size === 0) return [];
16
+ const params = ids == null ? [] : [JSON.stringify([...ids])];
17
+ const selected = ids == null ? '' : ' AND s.id IN (SELECT value FROM json_each(?))';
18
+ const sql = harness === 'opencode'
19
+ ? `SELECT s.id, s.directory AS cwd, s.title, s.time_updated AS updated, ${tableColumns(db, 'session').has('model') ? 's.model' : 'NULL'} AS model,
20
+ COUNT(m.id) AS message_count FROM session s LEFT JOIN message m ON m.session_id = s.id
21
+ WHERE 1=1${selected} GROUP BY s.id ORDER BY s.time_updated DESC`
22
+ : `SELECT s.id, s.working_dir AS cwd, s.name AS title, s.updated_at AS updated, s.model_config_json AS config,
23
+ COUNT(m.id) AS message_count FROM sessions s LEFT JOIN messages m ON m.session_id = s.id
24
+ WHERE s.archived_at IS NULL${selected} GROUP BY s.id ORDER BY s.updated_at DESC`;
25
+ return statement(db, sql).all(...params).map((row) => {
26
+ const id = text(row.id), title = text(row.title);
27
+ const config = harness === 'goose' ? jsonColumn(text(row.config, true)) : null;
28
+ const model = harness === 'opencode' ? text(row.model, true)
29
+ : config != null ? (Object.hasOwn(config, 'model_name') ? config.model_name : config.modelName) : null;
30
+ const updated = harness === 'opencode' ? unsigned(integer(row.updated))
31
+ : catalogTimestamp(text(row.updated)) ?? catalogTimestamp(`${row.updated.replaceAll(' ', 'T')}Z`);
32
+ return finalizeNouns({ locator: { harness, session_id: id, storage: { kind: 'sqlite', path, selector: id } },
33
+ cwd: text(row.cwd), title: (harness === 'opencode' ? title.length : nativeTrim(title).length) ? title : null,
34
+ updated_at_ms: updated, model: typeof model === 'string' ? model : null, message_count: unsigned(integer(row.message_count)) });
35
+ });
36
+ }
37
+
38
+ /** Marks and selected descriptors share a snapshot, so a changed/deleted id
39
+ * cannot be committed beside a mark read from a different store generation. */
40
+ export async function readForeignStore(harness, path, { previousMarks, metrics = {} } = {}) {
41
+ if (!Object.hasOwn(MARKS, harness)) throw new Error(`no foreign row marks for ${harness}`);
42
+ return readStore(path, (db) => {
43
+ const current = marks(db, harness);
44
+ const ids = previousMarks == null ? null : new Set([...current].filter(([id, mark]) => previousMarks.get(id) !== mark).map(([id]) => id));
45
+ const removed = previousMarks == null ? [] : [...previousMarks.keys()].filter((id) => !current.has(id));
46
+ const changed = rows(db, path, harness, ids);
47
+ metrics.store_sessions_read = (metrics.store_sessions_read ?? 0) + changed.length;
48
+ return { marks: current, rows: changed, removed };
49
+ }, metrics);
50
+ }
@@ -0,0 +1,9 @@
1
+ export const hermesMirrorKey = (row) => JSON.stringify([row.locator.storage.path, row.locator.session_id]);
2
+
3
+ /** The source retains all mirrors. Each query hides only the conversations
4
+ * represented by a selected worker, or explicitly carried to continued_as. */
5
+ export function includeHermesMirror(mirror, selected) {
6
+ if (mirror == null) return true;
7
+ const unchanged = mirror.messages == null || mirror.count <= mirror.messages;
8
+ return !((selected.has(mirror.harness) || mirror.continued) && unchanged);
9
+ }