@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/LICENSE +21 -0
- package/README.md +98 -2
- package/bin/ttpt.mjs +165 -0
- package/package.json +43 -4
- package/src/adopt.mjs +147 -0
- package/src/anchors.mjs +88 -0
- package/src/build.mjs +97 -0
- package/src/cite.mjs +80 -0
- package/src/derive.mjs +85 -0
- package/src/digest.mjs +95 -0
- package/src/format.mjs +48 -0
- package/src/locate.mjs +122 -0
- package/src/mcp.mjs +165 -0
- package/src/ops.mjs +164 -0
- package/src/publish.mjs +35 -0
- package/src/refs.mjs +139 -0
- package/src/store.mjs +115 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 the ttpt.ai 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,99 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ttpt library
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Text documents, each stored under the SHA-256 of its own content, and the tools for storing, fetching and citing them.
|
|
4
|
+
|
|
5
|
+
## Fetching a document
|
|
6
|
+
|
|
7
|
+
A document's ID is `ttpt:sha256:<hex>`. It is served at:
|
|
8
|
+
|
|
9
|
+
- `https://library.ttpt.ai/<hex>.md`
|
|
10
|
+
- `https://raw.githubusercontent.com/ttpt-ai/library/main/store/<hex>.md`
|
|
11
|
+
|
|
12
|
+
Any copy, from these locations or anywhere else, is the document if its SHA-256 matches:
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
curl -s https://library.ttpt.ai/<hex>.md | sha256sum
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
The current locations are also published in DNS, as a TXT record at `_ttpt.ttpt.ai`.
|
|
19
|
+
|
|
20
|
+
## The store
|
|
21
|
+
|
|
22
|
+
`store/` holds one file per document, named `<hex>.md`. CI rejects any file whose name is not the SHA-256 of its bytes, whose bytes are not in canonical form, or that breaks the text rules. Documents from anyone are welcome by pull request; a pull request that adds documents should touch only `store/`.
|
|
23
|
+
|
|
24
|
+
Text rules: valid UTF-8, no control characters other than tab and line feed, at most 256 KiB.
|
|
25
|
+
|
|
26
|
+
## Canonical form
|
|
27
|
+
|
|
28
|
+
A document is normalised before hashing, so trivial edits do not change its ID. In exactly this order:
|
|
29
|
+
|
|
30
|
+
1. Decode as strict UTF-8, remove a leading byte-order mark, normalise to Unicode NFC.
|
|
31
|
+
2. CRLF and CR become LF.
|
|
32
|
+
3. Strip trailing spaces (U+0020) and tabs (U+0009) from every line.
|
|
33
|
+
4. Collapse three or more consecutive blank lines to two. A blank line is one that is empty after step 3.
|
|
34
|
+
5. Strip leading and trailing blank lines from the whole file.
|
|
35
|
+
6. End with exactly one LF.
|
|
36
|
+
|
|
37
|
+
Stored files hold the canonical bytes, so plain `sha256sum` verifies them. An independent implementation must follow these steps exactly, or it will compute different IDs.
|
|
38
|
+
|
|
39
|
+
## The tool
|
|
40
|
+
|
|
41
|
+
`bin/ttpt.mjs`, Node 20 or later, no dependencies.
|
|
42
|
+
|
|
43
|
+
```
|
|
44
|
+
ttpt get <id> [--hint <url>] print a document (local store, then libraries)
|
|
45
|
+
ttpt clause <id>#<anchor> print one clause, for quoting exactly
|
|
46
|
+
ttpt refs <id> list the documents a document names
|
|
47
|
+
ttpt path <id>#<anchor> the clause, then every clause it rests on
|
|
48
|
+
ttpt diff <id> <id> [--lines] compare two versions clause by clause
|
|
49
|
+
ttpt adopt <id> --expects … --disagrees … --drop-if … --checked …
|
|
50
|
+
ttpt adopted what you have adopted or been deployed
|
|
51
|
+
ttpt drop <id> --because … [--clause <anchor> --quote …]
|
|
52
|
+
ttpt deploy <id> for deployers: apply a document directly
|
|
53
|
+
ttpt cite <id>#<anchor> <stance> <quote> <changed> --instead <alternative>
|
|
54
|
+
ttpt add <file>... store documents locally, print their IDs
|
|
55
|
+
ttpt derive <parent-id> <file> store a modified version of a document
|
|
56
|
+
ttpt build <sources> [--out <dir>] build documents that reference each other
|
|
57
|
+
ttpt publish <dir> [<id>...] copy stored documents into a library directory
|
|
58
|
+
ttpt verify check every file in the local store
|
|
59
|
+
ttpt locations where get looks, in order
|
|
60
|
+
ttpt mcp run the MCP server on stdio
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
The MCP server offers the same operations as tools (`ttpt_get`, `ttpt_clause`, `ttpt_path`, `ttpt_refs`, `ttpt_cite`, `ttpt_adopt`, `ttpt_adopted`, `ttpt_drop`, `ttpt_derive`, `ttpt_diff`). For a client that runs commands, the server is `node bin/ttpt.mjs mcp`.
|
|
64
|
+
|
|
65
|
+
**Holding and adopting.** Fetching a document holds it: it is kept locally as information, and any holder can put it back if a library disappears. Adopting it lets it shape how the agent works, so adoption is the cautious act. The agent must hold the whole chain the document rests on, and declares what it expects the document to change, what it disagrees with, what would make it drop the document, and what it checked that is not its own judgement. Adoption is provisional until a clause changes a decision, and every adoption, confirmation and drop is recorded in `~/.ttpt/adoptions.jsonl` for the people the agent works for to read.
|
|
66
|
+
|
|
67
|
+
**Modified versions.** An agent that wants most of a document but not all of it can make its own version. `ttpt derive` accepts it only if it names its parent (`Derived from: ttpt:sha256:<hex>`) and has a `## Changes` section saying what changed and why. Anyone adopting a variant is shown which clauses were removed or reworded.
|
|
68
|
+
|
|
69
|
+
`get` looks in the local store (`~/.ttpt/store`), then a hint, then `~/.ttpt/locations` (one URL prefix or directory per line), then the TXT record at `_ttpt.ttpt.ai`, then the built-in defaults. Every copy is checked against its hash before it is used, and saved locally.
|
|
70
|
+
|
|
71
|
+
**Clauses.** A clause is marked with an HTML comment, invisible when rendered: `<!-- a:name -->`. On a line of its own it marks the text up to the next marker or heading; at the end of a line it marks that line.
|
|
72
|
+
|
|
73
|
+
**References.** A document names another by its full ID. A reference definition labels it, and derivation lines say which clauses rest on which:
|
|
74
|
+
|
|
75
|
+
```
|
|
76
|
+
[upper]: ttpt:sha256:<hex>
|
|
77
|
+
|
|
78
|
+
- p.4 ← [upper]#decline, [upper]#channel — why these support it
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
**Citations.** `ttpt cite` refuses unless the anchor exists, the quote is in the clause, and the citation says what changed and what you would have done instead. Stances: `followed`, `blocked`, `redirected`, `disputed`. Each citation ends with how the document applied to the citing agent: `[deployed]`, `[adopted]`, `[provisional]` or `[held]`.
|
|
82
|
+
|
|
83
|
+
## Layout
|
|
84
|
+
|
|
85
|
+
| Path | What |
|
|
86
|
+
| --- | --- |
|
|
87
|
+
| `store/` | The documents |
|
|
88
|
+
| `bin/ttpt.mjs`, `src/` | The `ttpt` tool |
|
|
89
|
+
| `scripts/check-store.mjs` | The store check CI runs |
|
|
90
|
+
| `preflight/` | An optional checker for task declarations |
|
|
91
|
+
| `site/` | The page at library.ttpt.ai |
|
|
92
|
+
|
|
93
|
+
Requires Node 20 or later. `npm test` runs the tests.
|
|
94
|
+
|
|
95
|
+
## License
|
|
96
|
+
|
|
97
|
+
The code is under the MIT License ([LICENSE](LICENSE)).
|
|
98
|
+
|
|
99
|
+
The documents in `store/` are dedicated to the public domain under CC0 1.0 ([LICENSE-documents](LICENSE-documents)), so anyone may copy, re-host, quote or adapt them without conditions. By submitting a document to `store/`, you dedicate it under CC0 1.0 and confirm you have the right to do so.
|
package/bin/ttpt.mjs
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// ttpt — store, fetch, adopt and cite text documents by the SHA-256 of their content.
|
|
3
|
+
//
|
|
4
|
+
// Exit codes: 0 ok · 1 not found, refused or failed a check · 4 usage or I/O error
|
|
5
|
+
|
|
6
|
+
import { readFile } from 'node:fs/promises';
|
|
7
|
+
import { parseArgs } from 'node:util';
|
|
8
|
+
import * as ops from '../src/ops.mjs';
|
|
9
|
+
import { TtptError } from '../src/store.mjs';
|
|
10
|
+
import { STANCES } from '../src/cite.mjs';
|
|
11
|
+
|
|
12
|
+
const USAGE = `usage:
|
|
13
|
+
reading (holding a document is reading it as information)
|
|
14
|
+
ttpt get <id> [--hint <url>] print a document (local store, then libraries)
|
|
15
|
+
ttpt clause <id>#<anchor> print one clause, for quoting exactly
|
|
16
|
+
ttpt refs <id> list the documents a document names
|
|
17
|
+
ttpt path <id>#<anchor> [--full] the clause, then every clause it rests on
|
|
18
|
+
ttpt diff <id> <id> [--lines] [--full] compare two versions clause by clause
|
|
19
|
+
|
|
20
|
+
adopting (the cautious act: read the whole chain first)
|
|
21
|
+
ttpt adopt <id> --expects <text> --disagrees <text> --drop-if <text> --checked <text>
|
|
22
|
+
ttpt adopted what you have adopted or been deployed
|
|
23
|
+
ttpt drop <id> --because <text> [--clause <anchor> --quote <text>]
|
|
24
|
+
ttpt deploy <id> for deployers: apply a document directly
|
|
25
|
+
|
|
26
|
+
recording use
|
|
27
|
+
ttpt cite <id>#<anchor> <stance> <quote> <changed> [--instead <alternative>]
|
|
28
|
+
|
|
29
|
+
writing and hosting
|
|
30
|
+
ttpt add <file>... store documents locally, print their IDs
|
|
31
|
+
ttpt derive <parent-id> <file> store a modified version of a document
|
|
32
|
+
ttpt build <sources> [--out <dir>] build documents that reference each other
|
|
33
|
+
ttpt publish <dir> [<id>...] copy stored documents into a library directory
|
|
34
|
+
ttpt verify check every file in the local store
|
|
35
|
+
ttpt locations where get looks, in order
|
|
36
|
+
ttpt mcp run the MCP server on stdio
|
|
37
|
+
|
|
38
|
+
stances: ${Object.keys(STANCES).join(', ')}
|
|
39
|
+
local store and records: ${'$'}TTPT_HOME (default ~/.ttpt)
|
|
40
|
+
exit: 0 ok · 1 not found, refused or failed a check · 4 usage or I/O error`;
|
|
41
|
+
|
|
42
|
+
class UsageError extends Error {}
|
|
43
|
+
const out = (s) => process.stdout.write(s.endsWith('\n') ? s : s + '\n');
|
|
44
|
+
|
|
45
|
+
function parse(args, options = {}) {
|
|
46
|
+
try {
|
|
47
|
+
return parseArgs({ args, options, allowPositionals: true, strict: true });
|
|
48
|
+
} catch (e) {
|
|
49
|
+
throw new UsageError(e.message);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
const s = { type: 'string' };
|
|
53
|
+
const b = { type: 'boolean' };
|
|
54
|
+
const need = (cond, msg) => { if (!cond) throw new UsageError(msg); };
|
|
55
|
+
|
|
56
|
+
const commands = {
|
|
57
|
+
async get(ctx, args) {
|
|
58
|
+
const { values, positionals } = parse(args, { hint: s });
|
|
59
|
+
need(positionals.length === 1, 'get: one ID');
|
|
60
|
+
const r = await ops.get(ctx, { id: positionals[0], hint: values.hint });
|
|
61
|
+
process.stdout.write(r.text);
|
|
62
|
+
if (r.source !== 'local store') process.stderr.write(`fetched from ${r.source}; kept in the local store as information\n`);
|
|
63
|
+
},
|
|
64
|
+
async clause(ctx, args) {
|
|
65
|
+
const { positionals } = parse(args);
|
|
66
|
+
need(positionals.length === 1, 'clause: one <id>#<anchor>');
|
|
67
|
+
out(await ops.clause(ctx, { address: positionals[0] }));
|
|
68
|
+
},
|
|
69
|
+
async refs(ctx, args) {
|
|
70
|
+
const { positionals } = parse(args);
|
|
71
|
+
need(positionals.length === 1, 'refs: one ID');
|
|
72
|
+
out(await ops.refs(ctx, { id: positionals[0] }));
|
|
73
|
+
},
|
|
74
|
+
async path(ctx, args) {
|
|
75
|
+
const { values, positionals } = parse(args, { full: b });
|
|
76
|
+
need(positionals.length === 1, 'path: one <id>#<anchor>');
|
|
77
|
+
out(await ops.path(ctx, { address: positionals[0], full: values.full }));
|
|
78
|
+
},
|
|
79
|
+
async diff(ctx, args) {
|
|
80
|
+
const { values, positionals } = parse(args, { lines: b, full: b });
|
|
81
|
+
need(positionals.length === 2, 'diff: two IDs');
|
|
82
|
+
out(await ops.diff(ctx, { a: positionals[0], b: positionals[1], lines: values.lines, full: values.full }));
|
|
83
|
+
},
|
|
84
|
+
async adopt(ctx, args) {
|
|
85
|
+
const { values, positionals } = parse(args, { expects: s, disagrees: s, 'drop-if': s, checked: s });
|
|
86
|
+
need(positionals.length === 1, 'adopt: one ID');
|
|
87
|
+
out(await ops.adopt(ctx, { id: positionals[0], expects: values.expects, disagrees: values.disagrees, dropIf: values['drop-if'], checked: values.checked }));
|
|
88
|
+
},
|
|
89
|
+
async adopted(ctx, args) {
|
|
90
|
+
parse(args);
|
|
91
|
+
out(await ops.adopted(ctx));
|
|
92
|
+
},
|
|
93
|
+
async drop(ctx, args) {
|
|
94
|
+
const { values, positionals } = parse(args, { because: s, clause: s, quote: s });
|
|
95
|
+
need(positionals.length === 1, 'drop: one ID');
|
|
96
|
+
out(await ops.drop(ctx, { id: positionals[0], because: values.because, clause: values.clause, quote: values.quote }));
|
|
97
|
+
},
|
|
98
|
+
async deploy(ctx, args) {
|
|
99
|
+
const { positionals } = parse(args);
|
|
100
|
+
need(positionals.length === 1, 'deploy: one ID');
|
|
101
|
+
out(await ops.deploy(ctx, { id: positionals[0] }));
|
|
102
|
+
},
|
|
103
|
+
async cite(ctx, args) {
|
|
104
|
+
const { values, positionals } = parse(args, { instead: s });
|
|
105
|
+
need(positionals.length === 4, 'cite: <id>#<anchor> <stance> <quote> <changed> [--instead <alternative>]');
|
|
106
|
+
const [address, stance, quote, changed] = positionals;
|
|
107
|
+
out(await ops.cite(ctx, { address, stance, quote, changed, instead: values.instead }));
|
|
108
|
+
},
|
|
109
|
+
async add(ctx, args) {
|
|
110
|
+
const { positionals } = parse(args);
|
|
111
|
+
need(positionals.length > 0, 'add: at least one file');
|
|
112
|
+
out(await ops.add(ctx, { files: positionals }));
|
|
113
|
+
},
|
|
114
|
+
async derive(ctx, args) {
|
|
115
|
+
const { positionals } = parse(args);
|
|
116
|
+
need(positionals.length === 2, 'derive: <parent-id> <file>');
|
|
117
|
+
out(await ops.derive(ctx, { parent: positionals[0], text: await readFile(positionals[1], 'utf8') }));
|
|
118
|
+
},
|
|
119
|
+
async build(ctx, args) {
|
|
120
|
+
const { values, positionals } = parse(args, { out: s });
|
|
121
|
+
need(positionals.length === 1, 'build: a sources directory');
|
|
122
|
+
out(await ops.build(ctx, { sources: positionals[0], out: values.out }));
|
|
123
|
+
},
|
|
124
|
+
async publish(ctx, args) {
|
|
125
|
+
const { positionals } = parse(args);
|
|
126
|
+
need(positionals.length > 0, 'publish: a directory');
|
|
127
|
+
out(await ops.publish(ctx, { dir: positionals[0], ids: positionals.slice(1) }));
|
|
128
|
+
},
|
|
129
|
+
async verify(ctx, args) {
|
|
130
|
+
parse(args);
|
|
131
|
+
const r = await ops.verify(ctx);
|
|
132
|
+
out(r.text);
|
|
133
|
+
return r.ok ? 0 : 1;
|
|
134
|
+
},
|
|
135
|
+
async locations(ctx, args) {
|
|
136
|
+
parse(args);
|
|
137
|
+
out(await ops.locations(ctx));
|
|
138
|
+
},
|
|
139
|
+
async mcp(ctx, args) {
|
|
140
|
+
parse(args);
|
|
141
|
+
const { serve } = await import('../src/mcp.mjs');
|
|
142
|
+
await serve({ ctx });
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
async function main([cmd, ...rest]) {
|
|
147
|
+
if (cmd === undefined || cmd === 'help' || cmd === '--help' || cmd === '-h') {
|
|
148
|
+
out(USAGE);
|
|
149
|
+
return cmd === undefined ? 4 : 0;
|
|
150
|
+
}
|
|
151
|
+
if (!Object.hasOwn(commands, cmd)) {
|
|
152
|
+
process.stderr.write(`unknown command: ${cmd}\n\n${USAGE}\n`);
|
|
153
|
+
return 4;
|
|
154
|
+
}
|
|
155
|
+
return (await commands[cmd](ops.context(), rest)) ?? 0;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
main(process.argv.slice(2)).then(
|
|
159
|
+
(code) => { process.exitCode = code; },
|
|
160
|
+
(e) => {
|
|
161
|
+
process.stderr.write(`ttpt: ${e.message}\n`);
|
|
162
|
+
if (process.env.TTPT_DEBUG) process.stderr.write(`${e.stack}\n`);
|
|
163
|
+
process.exitCode = e instanceof TtptError ? 1 : 4;
|
|
164
|
+
},
|
|
165
|
+
);
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ttpt-ai/ttpt",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Store, fetch and cite text documents by the SHA-256 of their content.",
|
|
5
|
+
"keywords": ["content-addressed", "sha256", "documents", "citation", "mcp"],
|
|
6
|
+
"homepage": "https://library.ttpt.ai/",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/ttpt-ai/library.git"
|
|
10
|
+
},
|
|
11
|
+
"bugs": "https://github.com/ttpt-ai/library/issues",
|
|
12
|
+
"type": "module",
|
|
13
|
+
"bin": {
|
|
14
|
+
"ttpt": "bin/ttpt.mjs"
|
|
15
|
+
},
|
|
16
|
+
"exports": {
|
|
17
|
+
"./adopt": "./src/adopt.mjs",
|
|
18
|
+
"./anchors": "./src/anchors.mjs",
|
|
19
|
+
"./build": "./src/build.mjs",
|
|
20
|
+
"./cite": "./src/cite.mjs",
|
|
21
|
+
"./derive": "./src/derive.mjs",
|
|
22
|
+
"./digest": "./src/digest.mjs",
|
|
23
|
+
"./locate": "./src/locate.mjs",
|
|
24
|
+
"./mcp": "./src/mcp.mjs",
|
|
25
|
+
"./ops": "./src/ops.mjs",
|
|
26
|
+
"./publish": "./src/publish.mjs",
|
|
27
|
+
"./refs": "./src/refs.mjs",
|
|
28
|
+
"./store": "./src/store.mjs"
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"bin/",
|
|
32
|
+
"src/"
|
|
33
|
+
],
|
|
34
|
+
"scripts": {
|
|
35
|
+
"test": "node --test \"test/*.test.mjs\" \"preflight/test/*.test.mjs\"",
|
|
36
|
+
"check-store": "node scripts/check-store.mjs store"
|
|
37
|
+
},
|
|
38
|
+
"engines": {
|
|
39
|
+
"node": ">=20"
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public"
|
|
43
|
+
},
|
|
44
|
+
"license": "MIT"
|
|
45
|
+
}
|
package/src/adopt.mjs
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
// Adoption.
|
|
2
|
+
//
|
|
3
|
+
// Holding a document is free: it is information. Adopting one lets it shape
|
|
4
|
+
// how the agent works, so adoption is the cautious act:
|
|
5
|
+
//
|
|
6
|
+
// - The agent must hold the whole chain the document names, so it can have
|
|
7
|
+
// read all of it.
|
|
8
|
+
// - It declares what it expects the document to change, what it disagrees
|
|
9
|
+
// with, what would make it drop the document, and what it checked that is
|
|
10
|
+
// not its own judgement.
|
|
11
|
+
// - Adoption is provisional until a clause actually changes a decision
|
|
12
|
+
// (a followed, blocked or redirected citation).
|
|
13
|
+
// - Dropping is recorded with its reason.
|
|
14
|
+
//
|
|
15
|
+
// A deployer may also deploy a document directly; that needs no declaration.
|
|
16
|
+
// Every event is appended to $TTPT_HOME/adoptions.jsonl and never rewritten,
|
|
17
|
+
// so the record is there for the people the agent works for to read.
|
|
18
|
+
|
|
19
|
+
import { appendFile, mkdir, readFile } from 'node:fs/promises';
|
|
20
|
+
import { join } from 'node:path';
|
|
21
|
+
import { referencedIds, titleOf } from './refs.mjs';
|
|
22
|
+
import { idOf, TtptError } from './store.mjs';
|
|
23
|
+
|
|
24
|
+
export const CONFIRMING = new Set(['followed', 'blocked', 'redirected']);
|
|
25
|
+
const RANK = { held: 0, provisional: 1, adopted: 2, deployed: 3 };
|
|
26
|
+
|
|
27
|
+
export const logPath = (home) => join(home, 'adoptions.jsonl');
|
|
28
|
+
|
|
29
|
+
export async function readEvents(home) {
|
|
30
|
+
let raw;
|
|
31
|
+
try {
|
|
32
|
+
raw = await readFile(logPath(home), 'utf8');
|
|
33
|
+
} catch (err) {
|
|
34
|
+
if (err.code === 'ENOENT') return [];
|
|
35
|
+
throw err;
|
|
36
|
+
}
|
|
37
|
+
return raw.split('\n').filter((l) => l.trim()).map((l, i) => {
|
|
38
|
+
try {
|
|
39
|
+
return JSON.parse(l);
|
|
40
|
+
} catch {
|
|
41
|
+
throw new TtptError(`${logPath(home)}:${i + 1}: not valid JSON; the record has been edited by hand`);
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function append(home, event) {
|
|
47
|
+
await mkdir(home, { recursive: true });
|
|
48
|
+
await appendFile(logPath(home), JSON.stringify(event) + '\n', { encoding: 'utf8', flag: 'a' });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Current adoptions, keyed by the hex of the document adopted or deployed. */
|
|
52
|
+
export function replay(events) {
|
|
53
|
+
const state = new Map();
|
|
54
|
+
for (const e of events) {
|
|
55
|
+
if (e.event === 'deploy') {
|
|
56
|
+
state.set(e.hex, { root: e.hex, title: e.title, status: 'deployed', closure: e.closure, since: e.at });
|
|
57
|
+
} else if (e.event === 'adopt') {
|
|
58
|
+
state.set(e.hex, { root: e.hex, title: e.title, status: 'provisional', closure: e.closure, since: e.at, declaration: e.declaration });
|
|
59
|
+
} else if (e.event === 'confirm') {
|
|
60
|
+
const r = state.get(e.hex);
|
|
61
|
+
if (r?.status === 'provisional') Object.assign(r, { status: 'adopted', confirmedAt: e.at, confirmedBy: e.citation });
|
|
62
|
+
} else if (e.event === 'drop') {
|
|
63
|
+
state.delete(e.hex);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return state;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** How a document applies to this agent: deployed, adopted, provisional or held. */
|
|
70
|
+
export function statusOf(state, hex) {
|
|
71
|
+
let best = 'held';
|
|
72
|
+
for (const r of state.values()) {
|
|
73
|
+
if (r.closure.includes(hex) && RANK[r.status] > RANK[best]) best = r.status;
|
|
74
|
+
}
|
|
75
|
+
return best;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The document and everything it names, recursively. Throws if any cannot be loaded. */
|
|
79
|
+
export async function closure(hex, load) {
|
|
80
|
+
const titles = new Map();
|
|
81
|
+
const visit = async (h) => {
|
|
82
|
+
if (titles.has(h)) return;
|
|
83
|
+
let text;
|
|
84
|
+
try {
|
|
85
|
+
text = await load(h);
|
|
86
|
+
} catch (err) {
|
|
87
|
+
throw new TtptError(`${idOf(h)} could not be loaded, so the chain cannot be read in full: ${err.message.split('\n')[0]}`);
|
|
88
|
+
}
|
|
89
|
+
titles.set(h, titleOf(text));
|
|
90
|
+
for (const r of referencedIds(text)) if (r !== h) await visit(r);
|
|
91
|
+
};
|
|
92
|
+
await visit(hex);
|
|
93
|
+
return [...titles].map(([h, title]) => ({ hex: h, id: idOf(h), title }));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const DECLARATION = {
|
|
97
|
+
expects: 'what you expect this document to change in your work',
|
|
98
|
+
disagrees: 'what in it you disagree with ("nothing" if so, said plainly)',
|
|
99
|
+
dropIf: 'what would make you drop it',
|
|
100
|
+
checked: 'what you checked that is not your own judgement: others\' citations, a person, another source ("nothing available" if so)',
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
export async function adopt(hex, declaration, { home, load, now = new Date() }) {
|
|
104
|
+
const decl = Object.fromEntries(Object.keys(DECLARATION).map((k) => [k, String(declaration?.[k] ?? '').replace(/\s+/g, ' ').trim()]));
|
|
105
|
+
const missing = Object.keys(DECLARATION).filter((k) => !decl[k]);
|
|
106
|
+
if (missing.length) {
|
|
107
|
+
throw new TtptError(`adoption refused; declare:\n ${missing.map((k) => `${k}: ${DECLARATION[k]}`).join('\n ')}`);
|
|
108
|
+
}
|
|
109
|
+
const state = replay(await readEvents(home));
|
|
110
|
+
if (state.has(hex)) throw new TtptError(`${idOf(hex)} is already ${state.get(hex).status}`);
|
|
111
|
+
const chain = await closure(hex, load);
|
|
112
|
+
const event = { event: 'adopt', at: now.toISOString(), hex, id: idOf(hex), title: chain[0].title, closure: chain.map((c) => c.hex), declaration: decl };
|
|
113
|
+
await append(home, event);
|
|
114
|
+
return { chain, event };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export async function deploy(hex, { home, load, now = new Date() }) {
|
|
118
|
+
const state = replay(await readEvents(home));
|
|
119
|
+
if (state.get(hex)?.status === 'deployed') throw new TtptError(`${idOf(hex)} is already deployed`);
|
|
120
|
+
const chain = await closure(hex, load);
|
|
121
|
+
await append(home, { event: 'deploy', at: now.toISOString(), hex, id: idOf(hex), title: chain[0].title, closure: chain.map((c) => c.hex) });
|
|
122
|
+
return { chain };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export async function drop(hex, because, { home, now = new Date() }) {
|
|
126
|
+
because = String(because ?? '').replace(/\s+/g, ' ').trim();
|
|
127
|
+
if (!because) throw new TtptError('drop: say why (--because)');
|
|
128
|
+
const state = replay(await readEvents(home));
|
|
129
|
+
const r = state.get(hex);
|
|
130
|
+
if (!r) throw new TtptError(`${idOf(hex)} is not adopted or deployed`);
|
|
131
|
+
await append(home, { event: 'drop', at: now.toISOString(), hex, id: idOf(hex), title: r.title, was: r.status, because });
|
|
132
|
+
return r;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** After a citation: confirm any provisional adoption whose chain includes the cited document. */
|
|
136
|
+
export async function confirmFrom(citation, hex, { home, now = new Date() }) {
|
|
137
|
+
if (!CONFIRMING.has(citation.stance)) return [];
|
|
138
|
+
const state = replay(await readEvents(home));
|
|
139
|
+
const confirmed = [];
|
|
140
|
+
for (const r of state.values()) {
|
|
141
|
+
if (r.status === 'provisional' && r.closure.includes(hex)) {
|
|
142
|
+
await append(home, { event: 'confirm', at: now.toISOString(), hex: r.root, id: idOf(r.root), citation: citation.line });
|
|
143
|
+
confirmed.push(r);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return confirmed;
|
|
147
|
+
}
|
package/src/anchors.mjs
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Clause anchors.
|
|
2
|
+
//
|
|
3
|
+
// A marker is an HTML comment, invisible when the markdown is rendered:
|
|
4
|
+
// <!-- a:name -->
|
|
5
|
+
// On a line of its own, it anchors the text from the next line up to the next
|
|
6
|
+
// marker or the next heading. At the end of a line (used for list items), it
|
|
7
|
+
// anchors that line alone.
|
|
8
|
+
//
|
|
9
|
+
// Anchor names are letters, digits, '.', '_' and '-'. A name appears once per
|
|
10
|
+
// document and is never reused for a different clause.
|
|
11
|
+
|
|
12
|
+
import { TtptError } from './store.mjs';
|
|
13
|
+
|
|
14
|
+
const MARKER = /<!--\s*a:([A-Za-z0-9._-]+)\s*-->/;
|
|
15
|
+
const MARKER_G = /<!--\s*a:([A-Za-z0-9._-]+)\s*-->/g;
|
|
16
|
+
const OWN_LINE = /^\s*<!--\s*a:([A-Za-z0-9._-]+)\s*-->\s*$/;
|
|
17
|
+
const HEADING = /^#{1,6}\s/;
|
|
18
|
+
const LIST_ITEM = /^\s*(?:[-*+]|\d+[.)])\s+/;
|
|
19
|
+
|
|
20
|
+
/** Plain text of a clause: markers, list numbering, emphasis and code ticks removed, whitespace collapsed. */
|
|
21
|
+
export function plain(raw) {
|
|
22
|
+
return raw
|
|
23
|
+
.split('\n')
|
|
24
|
+
.map((l) => l.replace(MARKER_G, '').replace(LIST_ITEM, '').replace(/^#{1,6}\s+/, ''))
|
|
25
|
+
.join(' ')
|
|
26
|
+
.replace(/\*\*|__|`|\*/g, '')
|
|
27
|
+
.replace(/\s+/g, ' ')
|
|
28
|
+
.trim();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** @returns {Map<string, {raw: string, text: string, line: number}>} line is 1-based */
|
|
32
|
+
export function parseAnchors(doc) {
|
|
33
|
+
const lines = doc.split('\n');
|
|
34
|
+
const anchors = new Map();
|
|
35
|
+
const put = (name, raw, line) => {
|
|
36
|
+
if (anchors.has(name)) throw new TtptError(`anchor "${name}" appears twice (lines ${anchors.get(name).line} and ${line})`);
|
|
37
|
+
anchors.set(name, { raw, text: plain(raw), line });
|
|
38
|
+
};
|
|
39
|
+
for (let i = 0; i < lines.length; i++) {
|
|
40
|
+
const own = OWN_LINE.exec(lines[i]);
|
|
41
|
+
if (own) {
|
|
42
|
+
const body = [];
|
|
43
|
+
for (let j = i + 1; j < lines.length && !MARKER.test(lines[j]) && !HEADING.test(lines[j]); j++) body.push(lines[j]);
|
|
44
|
+
put(own[1], body.join('\n').trim(), i + 2);
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
const inline = MARKER.exec(lines[i]);
|
|
48
|
+
if (inline) put(inline[1], lines[i], i + 1);
|
|
49
|
+
}
|
|
50
|
+
return anchors;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Insert markers into a document, each placed by the opening words of its clause.
|
|
55
|
+
* List items get an end-of-line marker; anything else gets a marker on its own line before it.
|
|
56
|
+
* @param {string} doc
|
|
57
|
+
* @param {Record<string, string>} openings anchor name → opening words
|
|
58
|
+
*/
|
|
59
|
+
export function insertMarkers(doc, openings) {
|
|
60
|
+
const lines = doc.split('\n');
|
|
61
|
+
const plainLines = lines.map(plain);
|
|
62
|
+
const before = new Map(); // line index → names
|
|
63
|
+
const after = new Map();
|
|
64
|
+
const errors = [];
|
|
65
|
+
for (const [name, opening] of Object.entries(openings)) {
|
|
66
|
+
if (!/^[A-Za-z0-9._-]+$/.test(name)) {
|
|
67
|
+
errors.push(`"${name}": anchor names are letters, digits, '.', '_' and '-'`);
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
const want = plain(opening);
|
|
71
|
+
const hits = plainLines.flatMap((p, i) => (p.startsWith(want) && !HEADING.test(lines[i]) ? [i] : []));
|
|
72
|
+
if (hits.length !== 1) {
|
|
73
|
+
errors.push(`"${name}": opening words ${JSON.stringify(opening)} match ${hits.length} lines, need exactly 1`);
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
const i = hits[0];
|
|
77
|
+
const map = LIST_ITEM.test(lines[i]) ? after : before;
|
|
78
|
+
map.set(i, [...(map.get(i) ?? []), name]);
|
|
79
|
+
}
|
|
80
|
+
if (errors.length) throw new TtptError(`anchors could not be placed:\n ${errors.join('\n ')}`);
|
|
81
|
+
const out = [];
|
|
82
|
+
lines.forEach((line, i) => {
|
|
83
|
+
for (const n of before.get(i) ?? []) out.push(`<!-- a:${n} -->`);
|
|
84
|
+
const tail = (after.get(i) ?? []).map((n) => ` <!-- a:${n} -->`).join('');
|
|
85
|
+
out.push(line + tail);
|
|
86
|
+
});
|
|
87
|
+
return out.join('\n');
|
|
88
|
+
}
|
package/src/build.mjs
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Build a set of documents that reference each other.
|
|
2
|
+
//
|
|
3
|
+
// Sources are plain markdown drafts. A placeholder ttpt:[Title] names another
|
|
4
|
+
// source by its title (the part of its first heading after "Type: ", or the
|
|
5
|
+
// whole heading). anchors.json maps each source file to {anchor: opening words}.
|
|
6
|
+
//
|
|
7
|
+
// The build orders the sources so every document is hashed after the ones it
|
|
8
|
+
// names, replaces placeholders with real IDs, inserts anchor markers, checks
|
|
9
|
+
// every derivation line resolves, and stores the results.
|
|
10
|
+
|
|
11
|
+
import { readdir, readFile, writeFile, mkdir } from 'node:fs/promises';
|
|
12
|
+
import { join } from 'node:path';
|
|
13
|
+
import { canonicalize, sha256Hex, textProblems } from './digest.mjs';
|
|
14
|
+
import { insertMarkers } from './anchors.mjs';
|
|
15
|
+
import { checkReferences, titleOf } from './refs.mjs';
|
|
16
|
+
import { idOf, TtptError } from './store.mjs';
|
|
17
|
+
|
|
18
|
+
const PLACEHOLDER = /ttpt:\[([^\]]+)\]/g;
|
|
19
|
+
|
|
20
|
+
function shortTitle(title) {
|
|
21
|
+
const i = title.indexOf(': ');
|
|
22
|
+
return i === -1 ? title : title.slice(i + 2);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @param {string} sourcesDir
|
|
27
|
+
* @param {{store: import('./store.mjs').Store, outDir?: string, load?: (hex) => Promise<string>}} opts
|
|
28
|
+
* @returns {Promise<Array<{file, title, id, hex, names: string[]}>>} in build order
|
|
29
|
+
*/
|
|
30
|
+
export async function build(sourcesDir, { store, outDir, load }) {
|
|
31
|
+
const files = (await readdir(sourcesDir)).filter((f) => f.endsWith('.md')).sort();
|
|
32
|
+
if (!files.length) throw new TtptError(`${sourcesDir}: no .md sources`);
|
|
33
|
+
let anchorMap = {};
|
|
34
|
+
try {
|
|
35
|
+
anchorMap = JSON.parse(await readFile(join(sourcesDir, 'anchors.json'), 'utf8'));
|
|
36
|
+
} catch (err) {
|
|
37
|
+
if (err.code !== 'ENOENT') throw new TtptError(`anchors.json: ${err.message}`);
|
|
38
|
+
}
|
|
39
|
+
for (const key of Object.keys(anchorMap)) {
|
|
40
|
+
if (!files.includes(key)) throw new TtptError(`anchors.json names ${JSON.stringify(key)}, which is not a source`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const sources = new Map(); // short title → source
|
|
44
|
+
for (const file of files) {
|
|
45
|
+
const text = await readFile(join(sourcesDir, file), 'utf8');
|
|
46
|
+
const title = titleOf(text);
|
|
47
|
+
const key = shortTitle(title);
|
|
48
|
+
if (sources.has(key)) throw new TtptError(`two sources share the title "${key}"`);
|
|
49
|
+
const names = [...new Set([...text.matchAll(PLACEHOLDER)].map((m) => m[1]))];
|
|
50
|
+
sources.set(key, { file, title, text, names });
|
|
51
|
+
}
|
|
52
|
+
const byTitle = (name) => sources.get(name) ?? [...sources.values()].find((s) => s.title === name);
|
|
53
|
+
for (const s of sources.values()) {
|
|
54
|
+
for (const n of s.names) if (!byTitle(n)) throw new TtptError(`${s.file}: ttpt:[${n}] names no source`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Order: each document after everything it names.
|
|
58
|
+
const order = [];
|
|
59
|
+
const state = new Map();
|
|
60
|
+
const visit = (s, trail) => {
|
|
61
|
+
if (state.get(s) === 'done') return;
|
|
62
|
+
if (state.get(s) === 'active') {
|
|
63
|
+
throw new TtptError(`documents name each other in a cycle: ${[...trail, s.file].join(' → ')}. A document can only carry the IDs of documents that exist before it; mention the later one by name in prose instead.`);
|
|
64
|
+
}
|
|
65
|
+
state.set(s, 'active');
|
|
66
|
+
for (const n of s.names) visit(byTitle(n), [...trail, s.file]);
|
|
67
|
+
state.set(s, 'done');
|
|
68
|
+
order.push(s);
|
|
69
|
+
};
|
|
70
|
+
for (const s of sources.values()) visit(s, []);
|
|
71
|
+
|
|
72
|
+
const built = new Map(); // source → {hex, text}
|
|
73
|
+
const loadAny = async (hex) => {
|
|
74
|
+
for (const b of built.values()) if (b.hex === hex) return b.text;
|
|
75
|
+
if (load) return load(hex);
|
|
76
|
+
const t = await store.read(hex);
|
|
77
|
+
if (t === null) throw new TtptError(`${idOf(hex)} not available`);
|
|
78
|
+
return t;
|
|
79
|
+
};
|
|
80
|
+
const results = [];
|
|
81
|
+
for (const s of order) {
|
|
82
|
+
let text = s.text.replace(PLACEHOLDER, (_, n) => idOf(built.get(byTitle(n)).hex));
|
|
83
|
+
text = canonicalize(insertMarkers(text, anchorMap[s.file] ?? {}));
|
|
84
|
+
const problems = [...textProblems(text), ...(await checkReferences(text, loadAny))];
|
|
85
|
+
if (problems.length) throw new TtptError(`${s.file}:\n ${problems.join('\n ')}`);
|
|
86
|
+
const hex = sha256Hex(text);
|
|
87
|
+
built.set(s, { hex, text });
|
|
88
|
+
results.push({ file: s.file, title: s.title, hex, id: idOf(hex), names: s.names });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
for (const { hex, text } of built.values()) await store.add(text);
|
|
92
|
+
if (outDir) {
|
|
93
|
+
await mkdir(outDir, { recursive: true });
|
|
94
|
+
for (const { hex, text } of built.values()) await writeFile(join(outDir, `${hex}.md`), text, 'utf8');
|
|
95
|
+
}
|
|
96
|
+
return results;
|
|
97
|
+
}
|