@ttpt-ai/ttpt 0.0.0-stage → 0.1.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/src/cite.mjs ADDED
@@ -0,0 +1,80 @@
1
+ // Citations: one line of plain text recording that a clause changed what an agent did.
2
+ //
3
+ // ttpt:sha256:<hex>#<anchor> <stance> "<quote>" — <what changed> (instead: <alternative>) [<status>]
4
+ //
5
+ // status is how the document applied to the citing agent: deployed, adopted,
6
+ // provisional (adopted, not yet confirmed by use) or held (read as information).
7
+ //
8
+ // Refused unless the anchor exists, the quote is in the clause, the stance is
9
+ // known, "what changed" is given, and (except for disputed) so is "instead".
10
+
11
+ import { appendFile, mkdir, readFile } from 'node:fs/promises';
12
+ import { join, resolve } from 'node:path';
13
+ import { parseAnchors, plain } from './anchors.mjs';
14
+ import { parseAddress } from './refs.mjs';
15
+ import { idOf, TtptError } from './store.mjs';
16
+
17
+ export const STANCES = Object.freeze({
18
+ followed: 'the clause made you take an action you otherwise would not have',
19
+ blocked: 'an action considered and not taken',
20
+ redirected: 'an objective rewritten before work began',
21
+ disputed: 'the clause is wrong; "what changed" carries the argument',
22
+ });
23
+
24
+ const oneLine = (s) => String(s ?? '').replace(/\s+/g, ' ').trim();
25
+
26
+ /**
27
+ * Check a citation and build its line.
28
+ * @param {(hex: string) => Promise<string>} load
29
+ */
30
+ export const STATUSES = Object.freeze(['deployed', 'adopted', 'provisional', 'held']);
31
+
32
+ export async function makeCitation({ address, stance, quote, changed, instead }, load, status = 'held') {
33
+ if (!STATUSES.includes(status)) throw new TtptError(`unknown status ${status}`);
34
+ const problems = [];
35
+ const { hex, anchor } = parseAddress(address);
36
+ if (!Object.hasOwn(STANCES, stance)) problems.push(`stance must be one of ${Object.keys(STANCES).join(', ')}`);
37
+ quote = oneLine(quote);
38
+ changed = oneLine(changed);
39
+ instead = oneLine(instead);
40
+ if (!quote) problems.push('a quote from the clause is required');
41
+ if (quote.includes('"')) problems.push('the quote may not contain double quotes');
42
+ if (!changed) problems.push('"what changed" is required');
43
+ if (!instead && stance !== 'disputed') problems.push('"instead" is required: what would you have done without the clause?');
44
+
45
+ const doc = await load(hex);
46
+ const clause = parseAnchors(doc).get(anchor);
47
+ if (!clause) problems.push(`${idOf(hex)} has no anchor "${anchor}"`);
48
+ else if (quote && !clause.text.includes(plain(quote))) problems.push(`the quote is not in ${anchor}; fetch the clause and quote it exactly`);
49
+
50
+ if (problems.length) throw new TtptError(`citation refused:\n ${problems.join('\n ')}`);
51
+ const line = `${idOf(hex)}#${anchor} ${stance} "${quote}" — ${changed}${instead ? ` (instead: ${instead})` : ''} [${status}]`;
52
+ return { line, id: idOf(hex), anchor, stance, quote, changed, instead: instead || null, status };
53
+ }
54
+
55
+ /** Citations recorded in a log, oldest first. */
56
+ export async function readCitations(path) {
57
+ let raw;
58
+ try {
59
+ raw = await readFile(path, 'utf8');
60
+ } catch (err) {
61
+ if (err.code === 'ENOENT') return [];
62
+ throw err;
63
+ }
64
+ return raw.split('\n').filter((l) => l.trim()).flatMap((l) => {
65
+ try {
66
+ return [JSON.parse(l)];
67
+ } catch {
68
+ return [];
69
+ }
70
+ });
71
+ }
72
+
73
+ export function citationLogPath(env = process.env, cwd = process.cwd()) {
74
+ return env.TTPT_CITATIONS ? resolve(cwd, env.TTPT_CITATIONS) : join(cwd, '.ttpt', 'citations.jsonl');
75
+ }
76
+
77
+ export async function logCitation(citation, path = citationLogPath(), now = new Date()) {
78
+ await mkdir(resolve(path, '..'), { recursive: true });
79
+ await appendFile(path, JSON.stringify({ at: now.toISOString(), ...citation }) + '\n', { encoding: 'utf8', flag: 'a' });
80
+ }
package/src/derive.mjs ADDED
@@ -0,0 +1,85 @@
1
+ // Modified versions, and comparing versions.
2
+ //
3
+ // A document derived from another names its parent and says what it changed:
4
+ //
5
+ // Derived from: ttpt:sha256:<parent hex>
6
+ // ...
7
+ // ## Changes
8
+ // - Dropped the third step: ...
9
+ //
10
+ // The comparison is clause by clause, so anyone adopting a variant can see
11
+ // exactly which clauses were removed or reworded, including the cautious ones.
12
+
13
+ import { parseAnchors } from './anchors.mjs';
14
+
15
+ const DERIVED = /^Derived from:\s*ttpt:sha256:([0-9a-f]{64})\s*$/m;
16
+
17
+ export function lineageOf(text) {
18
+ const m = DERIVED.exec(text);
19
+ return m ? m[1] : null;
20
+ }
21
+
22
+ /** The body of the "## Changes" section, or null. */
23
+ export function changesSection(text) {
24
+ const lines = text.split('\n');
25
+ const start = lines.findIndex((l) => /^##\s+Changes\s*$/.test(l));
26
+ if (start === -1) return null;
27
+ const body = [];
28
+ for (let i = start + 1; i < lines.length && !/^#{1,2}\s/.test(lines[i]); i++) body.push(lines[i]);
29
+ return body.join('\n').trim();
30
+ }
31
+
32
+ export function checkDerived(text, parentHex, parentText) {
33
+ const problems = [];
34
+ const named = lineageOf(text);
35
+ if (named !== parentHex) {
36
+ problems.push(named
37
+ ? `it names ttpt:sha256:${named} as its parent, not ttpt:sha256:${parentHex}`
38
+ : `add a line "Derived from: ttpt:sha256:${parentHex}"`);
39
+ }
40
+ if (!changesSection(text)) problems.push('add a "## Changes" section listing what you changed from the parent and why');
41
+ if (text.trim() === parentText.trim()) problems.push('it is the same as its parent');
42
+ return problems;
43
+ }
44
+
45
+ /** Clause-level and heading-level differences from a to b. */
46
+ export function clauseDiff(a, b) {
47
+ const A = parseAnchors(a);
48
+ const B = parseAnchors(b);
49
+ const headings = (t) => t.split('\n').filter((l) => /^#{1,6}\s/.test(l)).map((l) => l.trim());
50
+ const ha = headings(a);
51
+ const hb = headings(b);
52
+ return {
53
+ removed: [...A].filter(([k]) => !B.has(k)).map(([anchor, c]) => ({ anchor, text: c.text })),
54
+ added: [...B].filter(([k]) => !A.has(k)).map(([anchor, c]) => ({ anchor, text: c.text })),
55
+ changed: [...A].filter(([k, c]) => B.has(k) && B.get(k).text !== c.text)
56
+ .map(([anchor, c]) => ({ anchor, before: c.text, after: B.get(anchor).text })),
57
+ headingsRemoved: ha.filter((h) => !hb.includes(h)),
58
+ headingsAdded: hb.filter((h) => !ha.includes(h)),
59
+ };
60
+ }
61
+
62
+ /** Line diff by longest common subsequence: [{op: ' ' | '-' | '+', line}] */
63
+ export function lineDiff(a, b) {
64
+ const x = a.split('\n');
65
+ const y = b.split('\n');
66
+ const n = x.length;
67
+ const m = y.length;
68
+ const L = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
69
+ for (let i = n - 1; i >= 0; i--) {
70
+ for (let j = m - 1; j >= 0; j--) {
71
+ L[i][j] = x[i] === y[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]);
72
+ }
73
+ }
74
+ const out = [];
75
+ let i = 0;
76
+ let j = 0;
77
+ while (i < n && j < m) {
78
+ if (x[i] === y[j]) { out.push({ op: ' ', line: x[i] }); i++; j++; }
79
+ else if (L[i + 1][j] >= L[i][j + 1]) out.push({ op: '-', line: x[i++] });
80
+ else out.push({ op: '+', line: y[j++] });
81
+ }
82
+ while (i < n) out.push({ op: '-', line: x[i++] });
83
+ while (j < m) out.push({ op: '+', line: y[j++] });
84
+ return out;
85
+ }
package/src/digest.mjs ADDED
@@ -0,0 +1,95 @@
1
+ // Canonical form, IDs, and the text-only rules for documents.
2
+ //
3
+ // The canonicalisation steps are a public contract: an independent
4
+ // implementation that disagrees about any of them produces different IDs for
5
+ // the same document. Changing them is a breaking change to every ID.
6
+ //
7
+ // 1. decode as strict UTF-8, remove a leading byte-order mark, normalise to NFC
8
+ // 2. CRLF and CR -> LF
9
+ // 3. strip trailing spaces and tabs from every line
10
+ // 4. collapse three or more consecutive blank lines to two
11
+ // 5. strip leading and trailing blank lines from the whole file
12
+ // 6. end with exactly one LF
13
+ //
14
+ // A document's ID is ttpt:sha256:<hex>, the SHA-256 of its canonical bytes.
15
+ // Stored files hold the canonical bytes, so plain `sha256sum` verifies them.
16
+
17
+ import { createHash } from 'node:crypto';
18
+ import { readFile } from 'node:fs/promises';
19
+
20
+ const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
21
+
22
+ export const MAX_BYTES = 256 * 1024;
23
+ export const HEX_PATTERN = /^[0-9a-f]{64}$/;
24
+ export const ID_PATTERN = /^ttpt:sha256:([0-9a-f]{64})$/;
25
+ export const DIGEST_PATTERN = /^sha256:[0-9a-f]{64}$/;
26
+ // Control characters other than tab and LF: C0, DEL and C1.
27
+ const CONTROL = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/;
28
+
29
+ export function decode(input) {
30
+ return typeof input === 'string' ? input : decoder.decode(input);
31
+ }
32
+
33
+ export function canonicalize(input) {
34
+ let text = decode(input);
35
+ text = text.replace(/^/, '').normalize('NFC'); // 1
36
+ text = text.replace(/\r\n?/g, '\n'); // 2
37
+ text = text.replace(/[ \t]+$/gm, ''); // 3
38
+ text = text.replace(/\n{4,}/g, '\n\n\n'); // 4: 3+ blank lines = 4+ LFs in a row
39
+ text = text.replace(/^\n+/, '').replace(/\n+$/, ''); // 5
40
+ return text + '\n'; // 6
41
+ }
42
+
43
+ export function sha256Hex(text) {
44
+ return createHash('sha256').update(text, 'utf8').digest('hex');
45
+ }
46
+
47
+ /** sha256:<hex> of the canonical form. */
48
+ export function digest(input) {
49
+ return `sha256:${sha256Hex(canonicalize(input))}`;
50
+ }
51
+
52
+ /** ttpt:sha256:<hex> of the canonical form. */
53
+ export function idFor(input) {
54
+ return `ttpt:sha256:${sha256Hex(canonicalize(input))}`;
55
+ }
56
+
57
+ export async function digestFile(path) {
58
+ return digest(await readFile(path));
59
+ }
60
+
61
+ /** Problems with canonical text as a document, or [] if it is acceptable. */
62
+ export function textProblems(canonical) {
63
+ const problems = [];
64
+ const bytes = Buffer.byteLength(canonical, 'utf8');
65
+ if (bytes > MAX_BYTES) problems.push(`${bytes} bytes; the limit is ${MAX_BYTES}`);
66
+ const m = CONTROL.exec(canonical);
67
+ if (m) {
68
+ const code = m[0].codePointAt(0).toString(16).toUpperCase().padStart(4, '0');
69
+ problems.push(`contains control character U+${code}; only tab and line feed are allowed`);
70
+ }
71
+ if (canonical.trim() === '') problems.push('is empty');
72
+ return problems;
73
+ }
74
+
75
+ /**
76
+ * Check a stored file: its name is <hex>.md, its bytes are valid canonical
77
+ * text within the rules, and the SHA-256 of its bytes is the name.
78
+ * @returns {string[]} problems, empty if the file is good
79
+ */
80
+ export function storedFileProblems(name, bytes) {
81
+ const m = /^([0-9a-f]{64})\.md$/.exec(name);
82
+ if (!m) return [`name must be <64 lowercase hex>.md`];
83
+ let text;
84
+ try {
85
+ text = decode(bytes);
86
+ } catch {
87
+ return ['is not valid UTF-8'];
88
+ }
89
+ const problems = [];
90
+ if (canonicalize(text) !== text) problems.push('is not in canonical form (run it through `ttpt add`)');
91
+ problems.push(...textProblems(text));
92
+ const actual = createHash('sha256').update(bytes).digest('hex');
93
+ if (actual !== m[1]) problems.push(`SHA-256 of its bytes is ${actual}, not its name`);
94
+ return problems;
95
+ }
package/src/format.mjs ADDED
@@ -0,0 +1,48 @@
1
+ // Text output shared by the CLI and the MCP server.
2
+
3
+ const clip = (s, full, n = 160) => (full || s.length <= n ? s : s.slice(0, n - 3) + '…');
4
+
5
+ export function formatPath(tree, { full = false } = {}) {
6
+ const lines = [];
7
+ const walk = (node, depth) => {
8
+ const pad = ' '.repeat(depth);
9
+ lines.push(`${pad}${depth ? '← ' : ''}${node.id}#${node.anchor} ${node.title}${node.seen ? ' (shown above)' : ''}`);
10
+ if (node.seen) return;
11
+ lines.push(`${pad} "${clip(node.text, full)}"`);
12
+ if (node.how) lines.push(`${pad} rests on these because: ${node.how}`);
13
+ for (const f of node.from) walk(f, depth + 1);
14
+ };
15
+ walk(tree, 0);
16
+ return lines.join('\n');
17
+ }
18
+
19
+ export function formatClauseDiff(d, { full = false } = {}) {
20
+ const lines = [];
21
+ const none = !d.removed.length && !d.added.length && !d.changed.length && !d.headingsRemoved.length && !d.headingsAdded.length;
22
+ if (none) return 'No clause or heading differs.';
23
+ for (const h of d.headingsRemoved) lines.push(`heading removed: ${h}`);
24
+ for (const h of d.headingsAdded) lines.push(`heading added: ${h}`);
25
+ for (const c of d.removed) lines.push(`REMOVED #${c.anchor}: "${clip(c.text, full)}"`);
26
+ for (const c of d.changed) lines.push(`changed #${c.anchor}:\n was: "${clip(c.before, full)}"\n now: "${clip(c.after, full)}"`);
27
+ for (const c of d.added) lines.push(`added #${c.anchor}: "${clip(c.text, full)}"`);
28
+ return lines.join('\n');
29
+ }
30
+
31
+ export function formatLineDiff(ops) {
32
+ return ops.filter((o) => o.op !== ' ').map((o) => `${o.op} ${o.line}`).join('\n') || 'No line differs.';
33
+ }
34
+
35
+ export function formatAdoptions(state) {
36
+ if (!state.size) return 'Nothing adopted or deployed. Documents you have fetched are held as information only.';
37
+ const out = [];
38
+ for (const r of state.values()) {
39
+ out.push(`${r.status.padEnd(11)} ${r.title} ttpt:sha256:${r.root}`);
40
+ out.push(` since ${r.since}; covers ${r.closure.length} document(s)`);
41
+ if (r.declaration) {
42
+ out.push(` expects: ${r.declaration.expects}`);
43
+ out.push(` drop if: ${r.declaration.dropIf}`);
44
+ }
45
+ if (r.confirmedBy) out.push(` confirmed: ${r.confirmedBy}`);
46
+ }
47
+ return out.join('\n');
48
+ }
package/src/locate.mjs ADDED
@@ -0,0 +1,122 @@
1
+ // Finding a document by ID.
2
+ //
3
+ // Order: the local store; a location hint carried with the reference; the
4
+ // agent's own list (~/.ttpt/locations); the DNS pointer (_ttpt.ttpt.ai); the
5
+ // built-in defaults. Every candidate is hashed before it is accepted, and an
6
+ // accepted copy is saved to the local store.
7
+ //
8
+ // A location is a URL prefix (https://host/path/) or a local directory; the
9
+ // document is at <prefix><hex>.md.
10
+
11
+ import { readFile } from 'node:fs/promises';
12
+ import { join } from 'node:path';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { resolveTxt as dnsResolveTxt } from 'node:dns/promises';
15
+ import { storedFileProblems } from './digest.mjs';
16
+ import { idOf, parseId, TtptError } from './store.mjs';
17
+
18
+ export const POINTER = '_ttpt.ttpt.ai';
19
+ export const DEFAULT_LOCATIONS = Object.freeze([
20
+ 'https://library.ttpt.ai/',
21
+ 'https://raw.githubusercontent.com/ttpt-ai/library/main/store/',
22
+ ]);
23
+ const TIMEOUT_MS = 15000;
24
+
25
+ export async function configuredLocations(home) {
26
+ let raw;
27
+ try {
28
+ raw = await readFile(join(home, 'locations'), 'utf8');
29
+ } catch (err) {
30
+ if (err.code === 'ENOENT') return [];
31
+ throw err;
32
+ }
33
+ return raw
34
+ .split(/\r?\n/)
35
+ .map((l) => l.replace(/#.*/, '').trim())
36
+ .filter(Boolean);
37
+ }
38
+
39
+ /** Locations from the DNS pointer: TXT "v=ttpt1 <prefix> <prefix> …". Never throws. */
40
+ export async function pointerLocations(resolveTxt = dnsResolveTxt) {
41
+ try {
42
+ const records = await resolveTxt(POINTER);
43
+ const out = [];
44
+ for (const chunks of records) {
45
+ const parts = chunks.join('').trim().split(/\s+/);
46
+ if (parts[0] === 'v=ttpt1') out.push(...parts.slice(1));
47
+ }
48
+ return out;
49
+ } catch {
50
+ return [];
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Where get() will look, in order, without duplicates.
56
+ * @returns {Promise<Array<{location: string, from: string}>>}
57
+ */
58
+ export async function locations({ home, hint, env = process.env, resolveTxt } = {}) {
59
+ const list = [];
60
+ if (hint) list.push({ location: hint, from: 'hint' });
61
+ for (const l of await configuredLocations(home)) list.push({ location: l, from: 'config' });
62
+ if (!env.TTPT_NO_DNS) for (const l of await pointerLocations(resolveTxt)) list.push({ location: l, from: 'dns' });
63
+ if (!env.TTPT_NO_DEFAULTS) for (const l of DEFAULT_LOCATIONS) list.push({ location: l, from: 'default' });
64
+ const seen = new Set();
65
+ return list.filter(({ location }) => (seen.has(location) ? false : (seen.add(location), true)));
66
+ }
67
+
68
+ function urlFor(location, hex) {
69
+ // A hint may be the full URL of the file rather than a prefix.
70
+ if (location.endsWith(`${hex}.md`)) return location;
71
+ return location.endsWith('/') ? `${location}${hex}.md` : `${location}/${hex}.md`;
72
+ }
73
+
74
+ /** Raw bytes from one location, or null if it does not have the document. */
75
+ export async function fetchFrom(location, hex, { fetchImpl = globalThis.fetch } = {}) {
76
+ if (/^https?:\/\//i.test(location)) {
77
+ const res = await fetchImpl(urlFor(location, hex), { signal: AbortSignal.timeout(TIMEOUT_MS), redirect: 'follow' });
78
+ if (res.status === 404) return null;
79
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
80
+ return Buffer.from(await res.arrayBuffer());
81
+ }
82
+ const dir = location.startsWith('file:') ? fileURLToPath(location) : location;
83
+ try {
84
+ return await readFile(location.endsWith(`${hex}.md`) ? dir : join(dir, `${hex}.md`));
85
+ } catch (err) {
86
+ if (err.code === 'ENOENT') return null;
87
+ throw err;
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Get a document by ID.
93
+ * @returns {Promise<{hex, id, text, source: string}>}
94
+ */
95
+ export async function get(idOrHex, { store, hint, env = process.env, resolveTxt, fetchImpl } = {}) {
96
+ const hex = parseId(idOrHex);
97
+ const local = await store.read(hex);
98
+ if (local !== null) return { hex, id: idOf(hex), text: local, source: 'local store' };
99
+
100
+ const tried = [];
101
+ for (const { location } of await locations({ home: store.home, hint, env, resolveTxt })) {
102
+ let bytes;
103
+ try {
104
+ bytes = await fetchFrom(location, hex, { fetchImpl });
105
+ } catch (err) {
106
+ tried.push(`${location}: ${err.message}`);
107
+ continue;
108
+ }
109
+ if (bytes === null) {
110
+ tried.push(`${location}: not there`);
111
+ continue;
112
+ }
113
+ const problems = storedFileProblems(`${hex}.md`, bytes);
114
+ if (problems.length) {
115
+ tried.push(`${location}: rejected (${problems[0]})`);
116
+ continue;
117
+ }
118
+ const { text } = await store.add(bytes);
119
+ return { hex, id: idOf(hex), text, source: location };
120
+ }
121
+ throw new TtptError(`${idOf(hex)} not found.\n ${tried.join('\n ') || 'no locations to try'}`);
122
+ }
package/src/mcp.mjs ADDED
@@ -0,0 +1,165 @@
1
+ // MCP server over stdio: newline-delimited JSON-RPC 2.0. No dependencies.
2
+ // Every tool calls the same operation as the CLI command of the same name.
3
+ // Nothing is written to stdout except protocol messages.
4
+
5
+ import { createInterface } from 'node:readline';
6
+ import * as ops from './ops.mjs';
7
+ import { TtptError } from './store.mjs';
8
+
9
+ const SUPPORTED = ['2025-06-18', '2025-03-26', '2024-11-05'];
10
+ const VERSION = '0.1.0';
11
+
12
+ const str = (description) => ({ type: 'string', description });
13
+ const ID = str('Document ID: ttpt:sha256:<64 hex>');
14
+ const ADDRESS = str('Clause address: ttpt:sha256:<64 hex>#<anchor>');
15
+
16
+ export const TOOLS = [
17
+ {
18
+ name: 'ttpt_get',
19
+ description: 'Fetch a document by ID: from the local store, else from library locations. Every copy is checked against its hash and kept in the local store. Holding a document is reading it as information; it does not adopt it.',
20
+ inputSchema: { type: 'object', properties: { id: ID, hint: str('Optional location to try first: a URL prefix or the full URL of the file') }, required: ['id'] },
21
+ run: async (ctx, a) => {
22
+ const r = await ops.get(ctx, a);
23
+ return `${r.text}${r.source === 'local store' ? '' : `\n[fetched from ${r.source}]`}`;
24
+ },
25
+ },
26
+ {
27
+ name: 'ttpt_clause',
28
+ description: 'Return the exact text of one clause, for quoting in a citation.',
29
+ inputSchema: { type: 'object', properties: { address: ADDRESS }, required: ['address'] },
30
+ run: (ctx, a) => ops.clause(ctx, a),
31
+ },
32
+ {
33
+ name: 'ttpt_path',
34
+ description: 'Show a clause and, recursively, every clause it rests on across documents, with the stated reason at each step.',
35
+ inputSchema: { type: 'object', properties: { address: ADDRESS, full: { type: 'boolean', description: 'Print clauses in full' } }, required: ['address'] },
36
+ run: (ctx, a) => ops.path(ctx, a),
37
+ },
38
+ {
39
+ name: 'ttpt_refs',
40
+ description: 'List the documents a document names, including its parent if it is a derived version.',
41
+ inputSchema: { type: 'object', properties: { id: ID }, required: ['id'] },
42
+ run: (ctx, a) => ops.refs(ctx, a),
43
+ },
44
+ {
45
+ name: 'ttpt_cite',
46
+ description: 'Record that a clause changed what you did. Cite only when you can name what you would have done without it. Stances: followed (it made you take an action you otherwise would not have), blocked (an action considered and not taken), redirected (an objective rewritten before work began), disputed (the clause is wrong; give the argument as "changed"). There is no stance for agreement. Refused if the quote is not in the clause.',
47
+ inputSchema: {
48
+ type: 'object',
49
+ properties: {
50
+ address: ADDRESS,
51
+ stance: { type: 'string', enum: ['followed', 'blocked', 'redirected', 'disputed'] },
52
+ quote: str('Words quoted exactly from the clause'),
53
+ changed: str('What you did because of it (for disputed: why the clause is wrong)'),
54
+ instead: str('What you would have done without it (required except for disputed)'),
55
+ },
56
+ required: ['address', 'stance', 'quote', 'changed'],
57
+ },
58
+ run: (ctx, a) => ops.cite(ctx, a),
59
+ },
60
+ {
61
+ name: 'ttpt_adopt',
62
+ description: 'Adopt a document, letting it shape how you work. Adoption is the cautious act: do it only after reading the document and every document it rests on in full (ttpt_get, ttpt_refs, ttpt_path), looking for records of others\' use and disputes, and judging that it would benefit your everyday work. You must hold the whole chain. Adoption is provisional until a clause changes a decision, and is recorded where the people you work for can see it; tell them.',
63
+ inputSchema: {
64
+ type: 'object',
65
+ properties: {
66
+ id: ID,
67
+ expects: str('What you expect it to change in your work'),
68
+ disagrees: str('What in it you disagree with ("nothing" if so)'),
69
+ dropIf: str('What would make you drop it'),
70
+ checked: str('What you checked that is not your own judgement: others\' citations, a person, another source ("nothing available" if so)'),
71
+ },
72
+ required: ['id', 'expects', 'disagrees', 'dropIf', 'checked'],
73
+ },
74
+ run: (ctx, a) => ops.adopt(ctx, a),
75
+ },
76
+ {
77
+ name: 'ttpt_adopted',
78
+ description: 'List the documents you have adopted or that were deployed to you, with their status and declarations.',
79
+ inputSchema: { type: 'object', properties: {} },
80
+ run: (ctx) => ops.adopted(ctx),
81
+ },
82
+ {
83
+ name: 'ttpt_drop',
84
+ description: 'Drop an adopted or deployed document, recording why. Give a clause and quote to also record a disputed citation against the clause that failed.',
85
+ inputSchema: {
86
+ type: 'object',
87
+ properties: { id: ID, because: str('Why you are dropping it'), clause: str('Optional anchor of the clause that failed'), quote: str('Words quoted from that clause') },
88
+ required: ['id', 'because'],
89
+ },
90
+ run: (ctx, a) => ops.drop(ctx, a),
91
+ },
92
+ {
93
+ name: 'ttpt_derive',
94
+ description: 'Store a modified version of a document. The text must contain a line "Derived from: ttpt:sha256:<parent>" and a "## Changes" section saying what changed and why. Returns the new ID and the clause-by-clause differences from the parent.',
95
+ inputSchema: { type: 'object', properties: { parent: ID, text: str('The full text of the modified version') }, required: ['parent', 'text'] },
96
+ run: (ctx, a) => ops.derive(ctx, a),
97
+ },
98
+ {
99
+ name: 'ttpt_diff',
100
+ description: 'Compare two documents clause by clause (removed, changed, added clauses and headings), or line by line.',
101
+ inputSchema: { type: 'object', properties: { a: ID, b: ID, lines: { type: 'boolean', description: 'Line-by-line instead of clause-by-clause' } }, required: ['a', 'b'] },
102
+ run: (ctx, a) => ops.diff(ctx, a),
103
+ },
104
+ ];
105
+
106
+ export function serve({ ctx = ops.context(), input = process.stdin, output = process.stdout } = {}) {
107
+ const send = (msg) => output.write(JSON.stringify(msg) + '\n');
108
+ const byName = new Map(TOOLS.map((t) => [t.name, t]));
109
+
110
+ const handle = async (msg) => {
111
+ const { id, method, params } = msg ?? {};
112
+ const isRequest = id !== undefined && id !== null;
113
+ const reply = (result) => isRequest && send({ jsonrpc: '2.0', id, result });
114
+ const fail = (code, message) => isRequest && send({ jsonrpc: '2.0', id, error: { code, message } });
115
+ if (msg?.jsonrpc !== '2.0' || typeof method !== 'string') {
116
+ if (isRequest) fail(-32600, 'invalid request');
117
+ return;
118
+ }
119
+ switch (method) {
120
+ case 'initialize': {
121
+ const asked = params?.protocolVersion;
122
+ return reply({
123
+ protocolVersion: SUPPORTED.includes(asked) ? asked : SUPPORTED[0],
124
+ capabilities: { tools: {} },
125
+ serverInfo: { name: 'ttpt', version: VERSION },
126
+ instructions: 'Documents identified by the SHA-256 of their text. Fetching one holds it as information. Adopting one is a separate, cautious act: read the whole chain first.',
127
+ });
128
+ }
129
+ case 'ping':
130
+ return reply({});
131
+ case 'tools/list':
132
+ return reply({ tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) });
133
+ case 'tools/call': {
134
+ const tool = byName.get(params?.name);
135
+ if (!tool) return fail(-32602, `unknown tool: ${params?.name}`);
136
+ try {
137
+ const text = await tool.run(ctx, params.arguments ?? {});
138
+ return reply({ content: [{ type: 'text', text: String(text) }], isError: false });
139
+ } catch (err) {
140
+ const known = err instanceof TtptError;
141
+ return reply({ content: [{ type: 'text', text: known ? err.message : `internal error: ${err.message}` }], isError: true });
142
+ }
143
+ }
144
+ default:
145
+ if (method.startsWith('notifications/')) return undefined;
146
+ return fail(-32601, `method not found: ${method}`);
147
+ }
148
+ };
149
+
150
+ const rl = createInterface({ input, crlfDelay: Infinity });
151
+ const pending = new Set();
152
+ rl.on('line', (line) => {
153
+ if (!line.trim()) return;
154
+ let msg;
155
+ try {
156
+ msg = JSON.parse(line);
157
+ } catch {
158
+ send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } });
159
+ return;
160
+ }
161
+ const p = (Array.isArray(msg) ? Promise.all(msg.map(handle)) : handle(msg)).finally(() => pending.delete(p));
162
+ pending.add(p);
163
+ });
164
+ return new Promise((resolve) => rl.on('close', () => Promise.all(pending).then(resolve)));
165
+ }