@atrib/trace 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or otherwise designated in writing by the copyright owner as
57
+ "Not a Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and subsequently
61
+ incorporated within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or a Contribution
81
+ incorporated within the Work constitutes direct or contributory patent
82
+ infringement, then any patent licenses granted to You under this License
83
+ for that Work shall terminate as of the date such litigation is filed.
84
+
85
+ 4. Redistribution. You may reproduce and distribute copies of the
86
+ Work or Derivative Works thereof in any medium, with or without
87
+ modifications, and in Source or Object form, provided that You
88
+ meet the following conditions:
89
+
90
+ (a) You must give any other recipients of the Work or Derivative Works
91
+ a copy of this License; and
92
+
93
+ (b) You must cause any modified files to carry prominent notices
94
+ stating that You changed the files; and
95
+
96
+ (c) You must retain, in the Source form of any Derivative Works
97
+ that You distribute, all copyright, patent, trademark, and
98
+ attribution notices from the Source form of the Work,
99
+ excluding those notices that do not pertain to any part of
100
+ the Derivative Works; and
101
+
102
+ (d) If the Work includes a "NOTICE" text file as part of its
103
+ distribution, You must include a readable copy of the attribution
104
+ notices contained within such NOTICE file, in at least one
105
+ of the following places: within a NOTICE text file distributed
106
+ as part of the Derivative Works; within the Source form or
107
+ documentation, if provided along with the Derivative Works; or,
108
+ within a display generated by the Derivative Works, if and
109
+ wherever such third-party notices normally appear. The contents
110
+ of the NOTICE file are for informational purposes only and
111
+ do not modify the License. You may add Your own attribution
112
+ notices within Derivative Works that You distribute, alongside
113
+ or as an addendum to the NOTICE text from the Work, provided
114
+ that such additional attribution notices cannot be construed
115
+ as modifying the License.
116
+
117
+ You may add Your own license statement for Your modifications and
118
+ may provide additional grant of rights to use, modify, or distribute
119
+ those modifications in accordance with this License.
120
+
121
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
122
+ any Contribution intentionally submitted for inclusion in the Work
123
+ by You to the Licensor shall be under the terms and conditions of
124
+ this License, without any additional terms or conditions.
125
+ Notwithstanding the above, nothing herein shall supersede or modify
126
+ the terms of any separate license agreement you may have executed
127
+ with Licensor regarding such Contributions.
128
+
129
+ 6. Trademarks. This License does not grant permission to use the trade
130
+ names, trademarks, service marks, or product names of the Licensor,
131
+ except as required for reasonable and customary use in describing the
132
+ origin of the Work and reproducing the content of the NOTICE file.
133
+
134
+ 7. Disclaimer of Warranty. Unless required by applicable law or
135
+ agreed to in writing, Licensor provides the Work (and each
136
+ Contributor provides its Contributions) on an "AS IS" BASIS,
137
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
138
+ implied, including, without limitation, any warranties or conditions
139
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
140
+ PARTICULAR PURPOSE. You are solely responsible for determining the
141
+ appropriateness of using or reproducing the Work and assume any
142
+ risks associated with Your exercise of permissions under this License.
143
+
144
+ 8. Limitation of Liability. In no event and under no legal theory,
145
+ whether in tort (including negligence), contract, or otherwise,
146
+ unless required by applicable law (such as deliberate and grossly
147
+ negligent acts) or agreed to in writing, shall any Contributor be
148
+ liable to You for damages, including any direct, indirect, special,
149
+ incidental, or exemplary damages of any character arising as a
150
+ result of this License or out of the use or inability to use the
151
+ Work (including but not limited to damages for loss of goodwill,
152
+ work stoppage, computer failure or malfunction, or all other
153
+ commercial damages or losses), even if such Contributor has been
154
+ advised of the possibility of such damages.
155
+
156
+ 9. Accepting Warranty or Additional Liability. While redistributing
157
+ the Work or Derivative Works thereof, You may choose to offer,
158
+ and charge a fee for, acceptance of support, warranty, indemnity,
159
+ or other liability obligations and/or rights consistent with this
160
+ License. However, in accepting such obligations, You may act only
161
+ on Your own behalf and on Your sole responsibility, not on behalf
162
+ of any other Contributor, and only if You agree to indemnify,
163
+ defend, and hold each Contributor harmless for any liability
164
+ incurred by, or claims asserted against, such Contributor by reason
165
+ of your accepting any such warranty or additional liability.
166
+
167
+ END OF TERMS AND CONDITIONS
168
+
169
+ APPENDIX: How to apply the Apache License to your work.
170
+
171
+ To apply the Apache License to your work, attach the following
172
+ boilerplate notice, with the fields enclosed by brackets "[]"
173
+ replaced with your own identifying information. (Don't include
174
+ the brackets!) The text should be enclosed in the appropriate
175
+ comment syntax for the file format in question. Also, an optional
176
+ "Statement of Purpose" appears after the copyright notice.
177
+
178
+ Copyright 2025-2026 Atrib contributors
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
189
+ implied. See the License for the specific language governing
190
+ permissions and limitations under the License.
package/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # @atrib/atrib-trace
2
+
3
+ MCP server exposing the `trace` tool — walks a record's `informed_by` chain backward to surface the reasoning chain that led to it.
4
+
5
+ Closes the consumer-side cognitive-loop primitive: recall returns raw records; trace returns the causal chain, so an agent asking "why did I do X?" can see "X was informed by Y, which was informed by Z" without manually walking `informed_by` hash-by-hash.
6
+
7
+ ## Tool
8
+
9
+ ```
10
+ mcp__atrib-trace__trace({
11
+ record_hash: "sha256:<64-hex>", // start
12
+ depth?: number, // hop cap (default 3, max 10)
13
+ max_nodes?: number, // safety cap (default 200, max 500)
14
+ compact?: boolean // omit signature/content_id bytes (default true)
15
+ })
16
+ → {
17
+ start_hash, direction: "backward",
18
+ depth_requested, depth_reached,
19
+ visited: [
20
+ {
21
+ depth, record_hash, parent_hashes, source,
22
+ event_type, context_id, creator_key, timestamp,
23
+ next_informed_by, next_resolved, next_dangling,
24
+ sidecar_summary?: { tool_name?, topics?, what?, importance?, producer? }
25
+ }
26
+ ],
27
+ dangling: string[],
28
+ truncated_by_depth, truncated_by_cap,
29
+ warnings
30
+ }
31
+ ```
32
+
33
+ ## Reads
34
+
35
+ Every `*.jsonl` mirror under `~/.atrib/records/` (override via `ATRIB_RECORDS_DIR`). Tolerates both producer envelope shapes:
36
+
37
+ - Bare `AtribRecord` per line (legacy / wrapper convention pre-sidecar)
38
+ - `{ record, _local?, written_at }` envelope (current shape)
39
+
40
+ When the envelope carries an optional `_local` sidecar (per the local-mirror sidecar pattern shipped in `@atrib/mcp` v0.2.x), trace surfaces a compact `sidecar_summary` per record: `tool_name`, `topics`, first ~200 chars of `what`/`summary`, and `importance` for annotations. Without the sidecar (legacy entries), the per-record output still includes the cryptographic evidence (event_type, hashes, creator_key, timestamp) — just without the semantic context.
41
+
42
+ ## Behaviors
43
+
44
+ - **Cycle-safe**: every record visited at most once, even with multiple parents referencing it.
45
+ - **Cap-safe**: hits `max_nodes` → returns partial result with `truncated_by_cap: true`.
46
+ - **Depth-safe**: hits `depth` → returns partial result with `truncated_by_depth: true`.
47
+ - **Dangling-aware**: `informed_by` entries pointing at records not in the local mirror surface in `dangling` and do NOT advance the walk.
48
+ - **Local-only (v1)**: reads only the local mirror. v2 will fall back to `log.atrib.dev/v1/lookup/<hash>` for hashes not in the local mirror.
49
+ - **Backward-only (v1)**: walks `informed_by` upstream. Forward-walk (records that reference THIS one) is a v2 concern via the graph service.
50
+
51
+ ## Wire-up
52
+
53
+ Add to your MCP host config (e.g. `~/.claude.json` `mcpServers`):
54
+
55
+ ```json
56
+ {
57
+ "atrib-trace": {
58
+ "command": "node",
59
+ "args": ["/path/to/atrib-trace/dist/main.js"]
60
+ }
61
+ }
62
+ ```
63
+
64
+ Or run as a one-off subprocess via `pnpm --filter @atrib/atrib-trace start`.
65
+
66
+ ## Status
67
+
68
+ Initial scaffold (v0.1.0). 8 tests covering: empty-mirror, single-record, one-hop walk, multi-hop chain, depth truncation, diamond fan-in, dangling references, max_nodes cap. Full workspace tests green.
69
+
70
+ The companion consumer-side primitive `atrib-summarize` (synthesizes narrative across N records) is the next ship.
@@ -0,0 +1,19 @@
1
+ /**
2
+ * atrib-trace MCP server: registers the `trace` tool that walks a record's
3
+ * informed_by chain backward to surface the reasoning chain that led to it.
4
+ *
5
+ * Closes the consumer-side cognitive-loop primitive: recall returns raw
6
+ * records; trace returns the causal chain, so an agent asking "why did
7
+ * I do X?" can see "X was informed by Y, which was informed by Z" without
8
+ * manually walking informed_by hash-by-hash.
9
+ *
10
+ * Reads only the local mirror (~/.atrib/records/*.jsonl) for v1 — same scope
11
+ * as recall. v2 will fall back to log.atrib.dev/v1/lookup/<hash> for hashes
12
+ * not in the local mirror. Forward-walk (records that reference THIS one)
13
+ * is also a v2 concern; v1 is backward-only.
14
+ */
15
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
16
+ export interface AtribTraceServer {
17
+ mcp: McpServer;
18
+ }
19
+ export declare function createAtribTraceServer(): Promise<AtribTraceServer>;
package/dist/index.js ADDED
@@ -0,0 +1,118 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ /**
3
+ * atrib-trace MCP server: registers the `trace` tool that walks a record's
4
+ * informed_by chain backward to surface the reasoning chain that led to it.
5
+ *
6
+ * Closes the consumer-side cognitive-loop primitive: recall returns raw
7
+ * records; trace returns the causal chain, so an agent asking "why did
8
+ * I do X?" can see "X was informed by Y, which was informed by Z" without
9
+ * manually walking informed_by hash-by-hash.
10
+ *
11
+ * Reads only the local mirror (~/.atrib/records/*.jsonl) for v1 — same scope
12
+ * as recall. v2 will fall back to log.atrib.dev/v1/lookup/<hash> for hashes
13
+ * not in the local mirror. Forward-walk (records that reference THIS one)
14
+ * is also a v2 concern; v1 is backward-only.
15
+ */
16
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
17
+ import { z } from 'zod';
18
+ import { loadAllRecords } from './storage.js';
19
+ import { traceBackward } from './trace.js';
20
+ const SHA256_REF_PATTERN = /^sha256:[0-9a-f]{64}$/;
21
+ const TraceInput = z.object({
22
+ record_hash: z.string().regex(SHA256_REF_PATTERN).describe("The 'sha256:<64-hex>' record_hash to start from. Walks backward via " +
23
+ 'informed_by edges from this record.'),
24
+ depth: z.number().int().min(1).max(10).optional().describe('Maximum hop count from the starting record. Defaults to 3. Bounded ' +
25
+ 'at 10 to keep responses tractable; deeper chains should be walked ' +
26
+ 'in pieces by re-rooting at a returned upstream hash.'),
27
+ max_nodes: z.number().int().min(1).max(500).optional().describe('Hard cap on total visited records. Defaults to 200. Prevents pathological ' +
28
+ 'fan-out (a record with hundreds of informed_by entries) from exploding ' +
29
+ 'the response.'),
30
+ compact: z.boolean().optional().describe('When true (the default), per-record output omits signature/content_id/' +
31
+ 'spec_version/chain_root to keep the response small. Set false for full ' +
32
+ 'record bytes (useful for re-verification).'),
33
+ });
34
+ /** Pull a compact summary from the sidecar's content payload. */
35
+ function summarizeSidecar(loadedRecord) {
36
+ if (!loadedRecord?.local)
37
+ return undefined;
38
+ const sc = loadedRecord.local;
39
+ const out = {};
40
+ if (sc.toolName)
41
+ out.tool_name = sc.toolName;
42
+ if (sc.producer)
43
+ out.producer = sc.producer;
44
+ const c = sc.content;
45
+ if (c && Array.isArray(c['topics'])) {
46
+ out.topics = c['topics'].filter((t) => typeof t === 'string').slice(0, 6);
47
+ }
48
+ if (c && typeof c['what'] === 'string') {
49
+ const w = c['what'];
50
+ out.what = w.length > 200 ? w.slice(0, 197) + '…' : w;
51
+ }
52
+ else if (c && typeof c['summary'] === 'string') {
53
+ const s = c['summary'];
54
+ out.what = s.length > 200 ? s.slice(0, 197) + '…' : s;
55
+ }
56
+ if (c && typeof c['importance'] === 'string')
57
+ out.importance = c['importance'];
58
+ return Object.keys(out).length === 0 ? undefined : out;
59
+ }
60
+ function compactVisited(v, danglingSet, byHash) {
61
+ const indexed = byHash.get(v.record_hash);
62
+ return {
63
+ depth: v.depth,
64
+ record_hash: v.record_hash,
65
+ parent_hashes: v.parent_hashes,
66
+ source: v.source,
67
+ event_type: v.record?.event_type ?? null,
68
+ context_id: v.record?.context_id ?? null,
69
+ creator_key: v.record?.creator_key ?? null,
70
+ timestamp: v.record?.timestamp ?? null,
71
+ next_informed_by: v.next_informed_by,
72
+ next_resolved: v.next_informed_by.filter((h) => !danglingSet.has(h)),
73
+ next_dangling: v.next_informed_by.filter((h) => danglingSet.has(h)),
74
+ ...(summarizeSidecar(indexed) ? { sidecar_summary: summarizeSidecar(indexed) } : {}),
75
+ };
76
+ }
77
+ export async function createAtribTraceServer() {
78
+ const mcp = new McpServer({
79
+ name: 'atrib-trace',
80
+ version: '0.1.0',
81
+ });
82
+ mcp.registerTool('trace', {
83
+ title: 'trace informed_by chain backward',
84
+ description: 'Walk a record\'s informed_by chain backward to surface the reasoning ' +
85
+ 'chain that led to it. Reads from the local signed-record mirror ' +
86
+ '(~/.atrib/records/*.jsonl). Returns the records visited, parent links ' +
87
+ 'so the caller can reconstruct the tree, and dangling hashes (records ' +
88
+ 'referenced via informed_by but not present in the local mirror).',
89
+ inputSchema: TraceInput.shape,
90
+ }, async (args) => {
91
+ const depth = args.depth ?? 3;
92
+ const maxNodes = args.max_nodes ?? 200;
93
+ const compact = args.compact ?? true;
94
+ const { byHash } = loadAllRecords();
95
+ const result = traceBackward(args.record_hash, depth, byHash, { maxNodes });
96
+ const danglingSet = new Set(result.dangling);
97
+ const payload = compact
98
+ ? {
99
+ start_hash: result.start_hash,
100
+ direction: result.direction,
101
+ depth_requested: result.depth_requested,
102
+ depth_reached: result.depth_reached,
103
+ visited: result.visited.map((v) => compactVisited(v, danglingSet, byHash)),
104
+ dangling: result.dangling,
105
+ truncated_by_depth: result.truncated_by_depth,
106
+ truncated_by_cap: result.truncated_by_cap,
107
+ warnings: result.warnings,
108
+ }
109
+ : {
110
+ ...result,
111
+ // Full records included
112
+ };
113
+ return {
114
+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
115
+ };
116
+ });
117
+ return { mcp };
118
+ }
package/dist/main.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/main.js ADDED
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // atrib-trace standalone binary. Wires the McpServer to a stdio transport
4
+ // so it can be launched as a subprocess by an MCP host (Claude Code,
5
+ // Claude Desktop, etc.).
6
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
7
+ import { createAtribTraceServer } from './index.js';
8
+ async function main() {
9
+ const { mcp } = await createAtribTraceServer();
10
+ const transport = new StdioServerTransport();
11
+ await mcp.connect(transport);
12
+ // Stays alive on the stdio transport until the host closes it.
13
+ }
14
+ main().catch((e) => {
15
+ console.error('atrib-trace: fatal', e instanceof Error ? e.stack ?? e.message : String(e));
16
+ process.exit(1);
17
+ });
@@ -0,0 +1,36 @@
1
+ import { type AtribRecord, type OnRecordSidecar } from '@atrib/mcp';
2
+ export interface IndexedRecord {
3
+ record: AtribRecord;
4
+ /** sha256:<64-hex> form, matching informed_by entries. */
5
+ record_hash: string;
6
+ /** Source file the record was read from (for debugging). */
7
+ source: string;
8
+ /**
9
+ * Pre-sign payload context, when the producer wrote it to the local
10
+ * mirror as a `_local` sidecar on the envelope. Carries semantic content
11
+ * (toolName, args, result, content) the signed AtribRecord COMMITS TO
12
+ * via content_id / args_hash / result_hash but does not itself contain.
13
+ * Absent on legacy bare-record entries from older mirror writes.
14
+ */
15
+ local?: SidecarPayload;
16
+ }
17
+ /**
18
+ * Combined sidecar shape — superset of every producer's local payload
19
+ * (mcp-wrap writes toolName/args/result; atrib-emit writes content).
20
+ */
21
+ export interface SidecarPayload extends OnRecordSidecar {
22
+ content?: Record<string, unknown>;
23
+ producer?: string;
24
+ }
25
+ /**
26
+ * Read every *.jsonl mirror in ATRIB_RECORDS_DIR and return an index keyed
27
+ * by sha256:<64-hex> record_hash. Both shapes (bare AtribRecord and emit's
28
+ * { record, proof, written_at } envelope) are supported.
29
+ *
30
+ * Returns the indexed map AND a flat list (newest-first by timestamp) for
31
+ * callers that want recall-style enumeration without by-hash lookup.
32
+ */
33
+ export declare function loadAllRecords(dir?: string): {
34
+ byHash: Map<string, IndexedRecord>;
35
+ newestFirst: IndexedRecord[];
36
+ };
@@ -0,0 +1,84 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ /**
3
+ * Local mirror reader for atrib-trace.
4
+ *
5
+ * Reads every *.jsonl mirror under ~/.atrib/records/ and normalizes to bare
6
+ * AtribRecord shape regardless of producer (wrapper-signed or emit envelope).
7
+ *
8
+ * Builds an in-memory index by record_hash so trace can walk informed_by
9
+ * chains in O(1) per hop. The hash key is sha256:<64-hex> (the same form
10
+ * informed_by entries use), so no transformation needed at lookup time.
11
+ */
12
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
13
+ import { homedir } from 'node:os';
14
+ import { join } from 'node:path';
15
+ import { canonicalRecord, hexEncode, sha256 } from '@atrib/mcp';
16
+ const RECORDS_DIR = process.env.ATRIB_RECORDS_DIR ?? join(homedir(), '.atrib', 'records');
17
+ /**
18
+ * Read every *.jsonl mirror in ATRIB_RECORDS_DIR and return an index keyed
19
+ * by sha256:<64-hex> record_hash. Both shapes (bare AtribRecord and emit's
20
+ * { record, proof, written_at } envelope) are supported.
21
+ *
22
+ * Returns the indexed map AND a flat list (newest-first by timestamp) for
23
+ * callers that want recall-style enumeration without by-hash lookup.
24
+ */
25
+ export function loadAllRecords(dir = RECORDS_DIR) {
26
+ const byHash = new Map();
27
+ const all = [];
28
+ if (!existsSync(dir))
29
+ return { byHash, newestFirst: [] };
30
+ let files = [];
31
+ try {
32
+ files = readdirSync(dir).filter((f) => f.endsWith('.jsonl'));
33
+ }
34
+ catch {
35
+ return { byHash, newestFirst: [] };
36
+ }
37
+ for (const fname of files) {
38
+ const path = join(dir, fname);
39
+ try {
40
+ const raw = readFileSync(path, 'utf8');
41
+ for (const line of raw.split('\n')) {
42
+ const trimmed = line.trim();
43
+ if (!trimmed)
44
+ continue;
45
+ try {
46
+ const parsed = JSON.parse(trimmed);
47
+ // Normalize: envelope shape vs legacy bare record shape.
48
+ const isEnvelope = 'record' in parsed &&
49
+ parsed.record &&
50
+ parsed.record.context_id !== undefined;
51
+ const rec = isEnvelope
52
+ ? parsed.record
53
+ : parsed;
54
+ if (!rec.context_id || !rec.signature || !rec.timestamp)
55
+ continue;
56
+ const hashHex = hexEncode(sha256(canonicalRecord(rec)));
57
+ const indexed = {
58
+ record: rec,
59
+ record_hash: `sha256:${hashHex}`,
60
+ source: fname,
61
+ };
62
+ // Lift the `_local` sidecar onto the indexed record when present.
63
+ // Legacy bare-record entries have no sidecar; that's OK — consumers
64
+ // tolerate its absence.
65
+ if (isEnvelope) {
66
+ const sidecar = parsed._local;
67
+ if (sidecar)
68
+ indexed.local = sidecar;
69
+ }
70
+ byHash.set(indexed.record_hash, indexed);
71
+ all.push(indexed);
72
+ }
73
+ catch {
74
+ // Malformed line; skip.
75
+ }
76
+ }
77
+ }
78
+ catch {
79
+ // File read failure; skip this file.
80
+ }
81
+ }
82
+ all.sort((a, b) => b.record.timestamp - a.record.timestamp);
83
+ return { byHash, newestFirst: all };
84
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Bounded backward walk through informed_by chains.
3
+ *
4
+ * Given a starting record_hash and a depth bound, breadth-first walks every
5
+ * informed_by edge until either (a) depth bound reached, (b) no more
6
+ * unresolved hashes remain, or (c) safety cap on total visited nodes hit.
7
+ *
8
+ * Each visited record is annotated with:
9
+ * - depth — hop count from the starting record (0 = the start)
10
+ * - parent_hashes — which records in the previous level referenced this one
11
+ *
12
+ * Records referenced via informed_by but NOT present in the local mirror
13
+ * are surfaced as `dangling` entries: the verifier hasn't seen the upstream
14
+ * locally. This is informational, not a failure — the upstream may live on
15
+ * the public log but not in the agent's local mirror.
16
+ *
17
+ * Forward-walk (records that reference THIS record via informed_by) is
18
+ * out of scope for v1; it requires either a full-mirror scan per call
19
+ * (acceptable but slower) or the graph service. v1 is backward-only;
20
+ * forward-walk arrives in v2.
21
+ */
22
+ import type { IndexedRecord } from './storage.js';
23
+ import type { AtribRecord } from '@atrib/mcp';
24
+ export type TraceDirection = 'backward';
25
+ export interface TraceVisited {
26
+ depth: number;
27
+ record_hash: string;
28
+ parent_hashes: string[];
29
+ /** Empty when source mirror lacks this record (dangling). */
30
+ record: AtribRecord | null;
31
+ /** Source file the record was read from, or null if dangling. */
32
+ source: string | null;
33
+ /** Sub-set of informed_by entries that are themselves walkable next-hop. */
34
+ next_informed_by: string[];
35
+ }
36
+ export interface TraceResult {
37
+ start_hash: string;
38
+ direction: TraceDirection;
39
+ depth_requested: number;
40
+ depth_reached: number;
41
+ visited: TraceVisited[];
42
+ dangling: string[];
43
+ truncated_by_depth: boolean;
44
+ truncated_by_cap: boolean;
45
+ warnings: string[];
46
+ }
47
+ export interface TraceOptions {
48
+ /** Hard cap on total visited nodes regardless of depth. Defaults to 200. */
49
+ maxNodes?: number;
50
+ }
51
+ /**
52
+ * Walk informed_by edges backward from the starting record.
53
+ *
54
+ * Behaviors:
55
+ * - Cycle-safe: every record is visited at most once, even if multiple
56
+ * parents reference it.
57
+ * - Cap-safe: if maxNodes is hit mid-walk, returns partial result with
58
+ * truncated_by_cap=true. Callers can re-run with a smaller depth or
59
+ * start from a sub-tree if needed.
60
+ * - Dangling-aware: informed_by entries pointing at records not in the
61
+ * local mirror surface as `dangling`. Those entries do NOT advance the
62
+ * walk (we have nothing to walk from).
63
+ */
64
+ export declare function traceBackward(startHash: string, depth: number, index: Map<string, IndexedRecord>, options?: TraceOptions): TraceResult;
package/dist/trace.js ADDED
@@ -0,0 +1,95 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ /**
3
+ * Walk informed_by edges backward from the starting record.
4
+ *
5
+ * Behaviors:
6
+ * - Cycle-safe: every record is visited at most once, even if multiple
7
+ * parents reference it.
8
+ * - Cap-safe: if maxNodes is hit mid-walk, returns partial result with
9
+ * truncated_by_cap=true. Callers can re-run with a smaller depth or
10
+ * start from a sub-tree if needed.
11
+ * - Dangling-aware: informed_by entries pointing at records not in the
12
+ * local mirror surface as `dangling`. Those entries do NOT advance the
13
+ * walk (we have nothing to walk from).
14
+ */
15
+ export function traceBackward(startHash, depth, index, options = {}) {
16
+ const maxNodes = options.maxNodes ?? 200;
17
+ const warnings = [];
18
+ const visited = new Map();
19
+ const dangling = new Set();
20
+ let truncatedByCap = false;
21
+ let truncatedByDepth = false;
22
+ let depthReached = 0;
23
+ const startIdx = index.get(startHash);
24
+ if (!startIdx) {
25
+ return {
26
+ start_hash: startHash,
27
+ direction: 'backward',
28
+ depth_requested: depth,
29
+ depth_reached: 0,
30
+ visited: [],
31
+ dangling: [startHash],
32
+ truncated_by_depth: false,
33
+ truncated_by_cap: false,
34
+ warnings: [`start_hash ${startHash} not in local mirror`],
35
+ };
36
+ }
37
+ const frontier = [{ hash: startHash, depth: 0, parent: null }];
38
+ while (frontier.length > 0) {
39
+ if (visited.size >= maxNodes) {
40
+ truncatedByCap = true;
41
+ break;
42
+ }
43
+ const current = frontier.shift();
44
+ if (current.depth > depth) {
45
+ truncatedByDepth = true;
46
+ continue;
47
+ }
48
+ depthReached = Math.max(depthReached, current.depth);
49
+ const idx = index.get(current.hash);
50
+ if (!idx) {
51
+ dangling.add(current.hash);
52
+ // Tag the parent so caller can see which walkable record had a
53
+ // dangling reference, but we don't visit further.
54
+ continue;
55
+ }
56
+ let v = visited.get(current.hash);
57
+ if (!v) {
58
+ const informedByEntries = Array.isArray(idx.record.informed_by)
59
+ ? idx.record.informed_by
60
+ : [];
61
+ v = {
62
+ depth: current.depth,
63
+ record_hash: current.hash,
64
+ parent_hashes: [],
65
+ record: idx.record,
66
+ source: idx.source,
67
+ next_informed_by: informedByEntries,
68
+ };
69
+ visited.set(current.hash, v);
70
+ // Schedule informed_by entries for visit at depth+1.
71
+ if (current.depth < depth) {
72
+ for (const upstream of informedByEntries) {
73
+ frontier.push({ hash: upstream, depth: current.depth + 1, parent: current.hash });
74
+ }
75
+ }
76
+ else if (informedByEntries.length > 0) {
77
+ truncatedByDepth = true;
78
+ }
79
+ }
80
+ if (current.parent && !v.parent_hashes.includes(current.parent)) {
81
+ v.parent_hashes.push(current.parent);
82
+ }
83
+ }
84
+ return {
85
+ start_hash: startHash,
86
+ direction: 'backward',
87
+ depth_requested: depth,
88
+ depth_reached: depthReached,
89
+ visited: Array.from(visited.values()),
90
+ dangling: Array.from(dangling),
91
+ truncated_by_depth: truncatedByDepth,
92
+ truncated_by_cap: truncatedByCap,
93
+ warnings,
94
+ };
95
+ }
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@atrib/trace",
3
+ "version": "0.2.0",
4
+ "description": "MCP server for atrib. Walks informed_by chains backward from a record_hash to surface the reasoning chain that produced it.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "bin": {
9
+ "atrib-trace": "./dist/main.js"
10
+ },
11
+ "dependencies": {
12
+ "@modelcontextprotocol/sdk": "^1.29.0",
13
+ "zod": "^3.25.76",
14
+ "@atrib/mcp": "0.4.0"
15
+ },
16
+ "devDependencies": {
17
+ "@types/node": "^22.19.17",
18
+ "tsx": "^4.21.0",
19
+ "typescript": "^5.9.3",
20
+ "vitest": "^3.2.4"
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "scripts": {
29
+ "build": "rm -rf dist && tsc",
30
+ "start": "node dist/main.js",
31
+ "dev": "tsx src/main.ts",
32
+ "test": "vitest run"
33
+ }
34
+ }