counterparts 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/CONSTITUTION.md +68 -0
- package/LICENSE +21 -0
- package/README.md +348 -0
- package/docs/ELI5.md +84 -0
- package/docs/QUICKSTART.md +1258 -0
- package/docs/module-map.md +81 -0
- package/package.json +63 -0
- package/src/adapters/claude-code/CONTRACT.md +606 -0
- package/src/adapters/claude-code/INTERFACE-GAPS.md +655 -0
- package/src/adapters/claude-code/NOTES.md +1055 -0
- package/src/adapters/claude-code/bin/hook.ts +820 -0
- package/src/adapters/claude-code/bin/runner.ts +522 -0
- package/src/adapters/claude-code/config.ts +778 -0
- package/src/adapters/claude-code/credentials.ts +199 -0
- package/src/adapters/claude-code/doctor.ts +2557 -0
- package/src/adapters/claude-code/embed-client.ts +617 -0
- package/src/adapters/claude-code/hooks.ts +2240 -0
- package/src/adapters/claude-code/index.ts +224 -0
- package/src/adapters/claude-code/interpret-client.ts +395 -0
- package/src/adapters/claude-code/page-writer.ts +462 -0
- package/src/adapters/claude-code/primacy.ts +162 -0
- package/src/adapters/claude-code/spawn.ts +241 -0
- package/src/adapters/claude-code/standdown.ts +536 -0
- package/src/adapters/claude-code/transcript.ts +661 -0
- package/src/adapters/claude-code/vectors.ts +415 -0
- package/src/adapters/cli/CONTRACT.md +255 -0
- package/src/adapters/cli/INTERFACE-GAPS.md +350 -0
- package/src/adapters/cli/NOTES.md +936 -0
- package/src/adapters/cli/bin/counterparts.ts +74 -0
- package/src/adapters/cli/commands.ts +6095 -0
- package/src/adapters/cli/export.ts +766 -0
- package/src/adapters/cli/index.ts +103 -0
- package/src/adapters/cli/install.ts +670 -0
- package/src/adapters/cli/removal.ts +1186 -0
- package/src/adapters/cli/repair-dates.ts +659 -0
- package/src/adapters/cli/self-page.ts +229 -0
- package/src/adapters/cli/snapshot.ts +279 -0
- package/src/adapters/cli/start-fresh.ts +1228 -0
- package/src/adapters/config-path.ts +342 -0
- package/src/adapters/dashboard/CONTRACT.md +67 -0
- package/src/adapters/dashboard/INTERFACE-GAPS.md +139 -0
- package/src/adapters/dashboard/NOTES.md +474 -0
- package/src/adapters/dashboard/activity.ts +121 -0
- package/src/adapters/dashboard/ansi.ts +82 -0
- package/src/adapters/dashboard/bin/dashboard.ts +479 -0
- package/src/adapters/dashboard/browse.ts +298 -0
- package/src/adapters/dashboard/identity.ts +182 -0
- package/src/adapters/dashboard/index.ts +183 -0
- package/src/adapters/dashboard/layout.ts +149 -0
- package/src/adapters/dashboard/registries.ts +291 -0
- package/src/adapters/dashboard/resolve.ts +206 -0
- package/src/adapters/dashboard/source.ts +48 -0
- package/src/adapters/dashboard/status.ts +327 -0
- package/src/adapters/dashboard/stories.ts +194 -0
- package/src/adapters/dashboard/web/app.html +1731 -0
- package/src/adapters/dashboard/web/brain.html +463 -0
- package/src/adapters/dashboard/web/fired.ts +31 -0
- package/src/adapters/dashboard/web/flow.ts +457 -0
- package/src/adapters/dashboard/web/narrate.ts +1042 -0
- package/src/adapters/dashboard/web/reveal.ts +135 -0
- package/src/adapters/dashboard/web/server.ts +287 -0
- package/src/adapters/dashboard/web/views.ts +1744 -0
- package/src/adapters/expansions.ts +569 -0
- package/src/adapters/fired.ts +1580 -0
- package/src/adapters/mcp/CONTRACT.md +240 -0
- package/src/adapters/mcp/INTERFACE-GAPS.md +271 -0
- package/src/adapters/mcp/NOTES.md +205 -0
- package/src/adapters/mcp/bin/serve.ts +349 -0
- package/src/adapters/mcp/deliberate.ts +619 -0
- package/src/adapters/mcp/index.ts +101 -0
- package/src/adapters/mcp/protocol.ts +170 -0
- package/src/adapters/mcp/server.ts +1740 -0
- package/src/adapters/mcp/stdio.ts +56 -0
- package/src/adapters/mcp/tools.ts +779 -0
- package/src/adapters/scopes.ts +657 -0
- package/src/adapters/sessions.ts +402 -0
- package/src/adapters/snapshots.ts +1069 -0
- package/src/adapters/stance-env.ts +137 -0
- package/src/core/associate/CONTRACT.md +118 -0
- package/src/core/associate/INTERFACE-GAPS.md +173 -0
- package/src/core/associate/NOTES.md +194 -0
- package/src/core/associate/buffer.ts +66 -0
- package/src/core/associate/edges.ts +188 -0
- package/src/core/associate/index.ts +570 -0
- package/src/core/associate/pending.ts +383 -0
- package/src/core/associate/spread.ts +149 -0
- package/src/core/associate/tunables.ts +123 -0
- package/src/core/bridge.ts +272 -0
- package/src/core/briefing.ts +67 -0
- package/src/core/counterpart.ts +3855 -0
- package/src/core/encode/CONTRACT.md +151 -0
- package/src/core/encode/INTERFACE-GAPS.md +135 -0
- package/src/core/encode/NOTES.md +146 -0
- package/src/core/encode/aliases.ts +71 -0
- package/src/core/encode/battery.ts +284 -0
- package/src/core/encode/chunk.ts +265 -0
- package/src/core/encode/emotion.ts +119 -0
- package/src/core/encode/floor.ts +76 -0
- package/src/core/encode/index.ts +100 -0
- package/src/core/encode/precision.ts +162 -0
- package/src/core/encode/preselect.ts +269 -0
- package/src/core/encode/salience.ts +108 -0
- package/src/core/encode/secrets.ts +265 -0
- package/src/core/encode/tunables.ts +99 -0
- package/src/core/encode/types.ts +286 -0
- package/src/core/encode/words.ts +75 -0
- package/src/core/handoff/CONTRACT.md +199 -0
- package/src/core/handoff/INTERFACE-GAPS.md +166 -0
- package/src/core/handoff/NOTES.md +206 -0
- package/src/core/handoff/index.ts +957 -0
- package/src/core/mint.ts +279 -0
- package/src/core/observer.ts +28 -0
- package/src/core/physics/CONTRACT.md +341 -0
- package/src/core/physics/NOTES.md +155 -0
- package/src/core/physics/clock.ts +51 -0
- package/src/core/physics/index.ts +1054 -0
- package/src/core/prospective/CONTRACT.md +137 -0
- package/src/core/prospective/INTERFACE-GAPS.md +112 -0
- package/src/core/prospective/NOTES.md +160 -0
- package/src/core/prospective/derive.ts +188 -0
- package/src/core/prospective/index.ts +1030 -0
- package/src/core/prospective/tunables.ts +72 -0
- package/src/core/prospective/windows.ts +187 -0
- package/src/core/recall/CONTRACT.md +326 -0
- package/src/core/recall/INTERFACE-GAPS.md +163 -0
- package/src/core/recall/NOTES.md +472 -0
- package/src/core/recall/activate.ts +521 -0
- package/src/core/recall/cues.ts +275 -0
- package/src/core/recall/gate.ts +441 -0
- package/src/core/recall/index.ts +692 -0
- package/src/core/recall/probe.ts +239 -0
- package/src/core/recall/reference.ts +201 -0
- package/src/core/recall/render.ts +285 -0
- package/src/core/recall/session.ts +403 -0
- package/src/core/recall/tunables.ts +329 -0
- package/src/core/remember/CONTRACT.md +293 -0
- package/src/core/remember/INTERFACE-GAPS.md +189 -0
- package/src/core/remember/NOTES.md +373 -0
- package/src/core/remember/fallback.ts +452 -0
- package/src/core/remember/index.ts +103 -0
- package/src/core/remember/owner-strike-seam.ts +479 -0
- package/src/core/remember/proposals.ts +609 -0
- package/src/core/remember/spans.ts +1310 -0
- package/src/core/remember/tunables.ts +111 -0
- package/src/core/remember/updates.ts +198 -0
- package/src/core/retrieval.ts +96 -0
- package/src/core/revision.ts +441 -0
- package/src/core/schemas/CONTRACT.md +190 -0
- package/src/core/schemas/INTERFACE-GAPS.md +172 -0
- package/src/core/schemas/NOTES.md +260 -0
- package/src/core/schemas/aliases.ts +160 -0
- package/src/core/schemas/index.ts +1459 -0
- package/src/core/schemas/tunables.ts +44 -0
- package/src/core/schemas/types.ts +387 -0
- package/src/core/self/CONTRACT.md +459 -0
- package/src/core/self/INTERFACE-GAPS.md +284 -0
- package/src/core/self/NOTES.md +1057 -0
- package/src/core/self/briefing.ts +980 -0
- package/src/core/self/episodes.ts +483 -0
- package/src/core/self/freeze.ts +103 -0
- package/src/core/self/identity.ts +604 -0
- package/src/core/self/index.ts +2130 -0
- package/src/core/self/journal-file.ts +760 -0
- package/src/core/self/page.ts +404 -0
- package/src/core/self/tunables.ts +244 -0
- package/src/core/self/writer.ts +714 -0
- package/src/core/sleep/CONTRACT.md +298 -0
- package/src/core/sleep/INTERFACE-GAPS.md +262 -0
- package/src/core/sleep/NOTES.md +770 -0
- package/src/core/sleep/briefing.ts +86 -0
- package/src/core/sleep/consolidate.ts +241 -0
- package/src/core/sleep/cycle.ts +598 -0
- package/src/core/sleep/decay.ts +237 -0
- package/src/core/sleep/dedup.ts +373 -0
- package/src/core/sleep/index.ts +112 -0
- package/src/core/sleep/log.ts +116 -0
- package/src/core/sleep/markers.ts +164 -0
- package/src/core/sleep/prune.ts +170 -0
- package/src/core/sleep/strength-cache.ts +176 -0
- package/src/core/sleep/tunables.ts +135 -0
- package/src/core/sleep/types.ts +542 -0
- package/src/core/store/CONTRACT.md +446 -0
- package/src/core/store/NOTES.md +1068 -0
- package/src/core/store/cache.ts +709 -0
- package/src/core/store/db.ts +275 -0
- package/src/core/store/errors.ts +134 -0
- package/src/core/store/index.ts +2450 -0
- package/src/core/store/operational.ts +610 -0
- package/src/core/store/owner-op-seam.ts +428 -0
- package/src/core/store/paths.ts +494 -0
- package/src/core/store/prose.ts +165 -0
- package/src/core/store/render.ts +87 -0
- package/src/core/store/walk-seam.ts +78 -0
- package/src/core/types.ts +68 -0
- package/tools/install-loop/run.sh +1063 -0
|
@@ -0,0 +1,766 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `export` — the only way memory leaves this machine, and it leaves by hand.
|
|
3
|
+
*
|
|
4
|
+
* The property is **no silent egress** (contract §4, owner rescope 2): the core
|
|
5
|
+
* has no egress path at all, and this command is an explicit owner action. That
|
|
6
|
+
* makes export the one place the constitution's line 6 — "data leaves the
|
|
7
|
+
* machine only by the owner's explicit choice, encrypted, owner-keyed" — is
|
|
8
|
+
* either honored or quietly broken.
|
|
9
|
+
*
|
|
10
|
+
* **So there is no default.** `--passphrase` encrypts; `--plaintext` is the
|
|
11
|
+
* loud, deliberate opt-out for the ordinary case of copying a store to another
|
|
12
|
+
* directory on the same disk. Neither flag is a REFUSAL, not a guess. An export
|
|
13
|
+
* that silently wrote plaintext because nobody said otherwise is exactly the
|
|
14
|
+
* shape of accident line 6 exists to prevent.
|
|
15
|
+
*
|
|
16
|
+
* Contract §7 OQ1 — "does export encrypt to a key the owner already has, or does
|
|
17
|
+
* it mint one?" — is answered PROVISIONALLY here as: the owner supplies a
|
|
18
|
+
* passphrase, and nothing is minted. Minting is friendlier and is also how an
|
|
19
|
+
* owner ends up with a backup they cannot open. Recorded in NOTES.md as an open
|
|
20
|
+
* owner call, not as a settled one.
|
|
21
|
+
*
|
|
22
|
+
* Crypto is `node:crypto` only: scrypt for the KDF, AES-256-GCM for the payload.
|
|
23
|
+
* No dependency, and the format is documented in the plaintext README written
|
|
24
|
+
* beside the blob — an encrypted archive whose format is undocumented is a
|
|
25
|
+
* different way of losing the data.
|
|
26
|
+
*/
|
|
27
|
+
import { randomBytes, createCipheriv, createDecipheriv, scryptSync } from "node:crypto";
|
|
28
|
+
import {
|
|
29
|
+
existsSync,
|
|
30
|
+
mkdirSync,
|
|
31
|
+
mkdtempSync,
|
|
32
|
+
readFileSync,
|
|
33
|
+
readdirSync,
|
|
34
|
+
rmSync,
|
|
35
|
+
statSync,
|
|
36
|
+
writeFileSync,
|
|
37
|
+
} from "node:fs";
|
|
38
|
+
import { tmpdir } from "node:os";
|
|
39
|
+
import { gunzipSync, gzipSync } from "node:zlib";
|
|
40
|
+
import { join, relative } from "node:path";
|
|
41
|
+
|
|
42
|
+
import {
|
|
43
|
+
DATABASE_FILE,
|
|
44
|
+
confidentialByMeta,
|
|
45
|
+
paths,
|
|
46
|
+
renderMarkdown,
|
|
47
|
+
rowTombstoned,
|
|
48
|
+
} from "../../core/store/index.js";
|
|
49
|
+
import type { MemoryRow, ProseDoc, Store } from "../../core/store/index.js";
|
|
50
|
+
import { isSelfPageRow } from "../../core/self/page.js";
|
|
51
|
+
import { journalRelativePath } from "../../core/self/journal-file.js";
|
|
52
|
+
import { assertSafeTarget, vacuumInto } from "./snapshot.js";
|
|
53
|
+
|
|
54
|
+
/** The KDF's cost parameters travel WITH the blob: a hardcoded N is a format
|
|
55
|
+
* that cannot be strengthened without orphaning every existing export. */
|
|
56
|
+
export const KDF = { N: 16384, r: 8, p: 1, keyBytes: 32, saltBytes: 16 } as const;
|
|
57
|
+
export const CIPHER = "aes-256-gcm";
|
|
58
|
+
export const EXPORT_FORMAT = "counterparts-export-1";
|
|
59
|
+
export const BLOB_NAME = "counterparts-export.cpx";
|
|
60
|
+
|
|
61
|
+
export type ExportMode = "plaintext" | "encrypted";
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* WHAT KIND OF COPY. `database` is the whole store as one SQLite file — exact,
|
|
65
|
+
* complete, and openable by anything that speaks SQLite. `markdown` is the
|
|
66
|
+
* readable tree: one `.md` per memory, the journal as it stands, the self page
|
|
67
|
+
* as its own file. They are different promises and neither replaces the other,
|
|
68
|
+
* which is why the report names which one ran.
|
|
69
|
+
*/
|
|
70
|
+
export type ExportKind = "database" | "markdown";
|
|
71
|
+
|
|
72
|
+
export interface ExportOptions {
|
|
73
|
+
target: string;
|
|
74
|
+
/** Present ⇒ encrypted. Absent AND `plaintext` false ⇒ refusal. */
|
|
75
|
+
passphrase?: string;
|
|
76
|
+
/** The loud opt-out. */
|
|
77
|
+
plaintext?: boolean;
|
|
78
|
+
/** `--markdown`: the readable tree instead of the database file. */
|
|
79
|
+
markdown?: boolean;
|
|
80
|
+
/** `--include-confidential`: ruling 4's opt-in. Markdown only. */
|
|
81
|
+
includeConfidential?: boolean;
|
|
82
|
+
/** `--with-versions` on the console: every archived wording as its own file.
|
|
83
|
+
* Markdown only. */
|
|
84
|
+
versions?: boolean;
|
|
85
|
+
/** `--into-non-empty`: write into a directory that already holds something. */
|
|
86
|
+
intoNonEmpty?: boolean;
|
|
87
|
+
/** `--overwrite`: replace files this export's own paths collide with. Without
|
|
88
|
+
* it a collision is a REFUSAL — the flag that says "I know this directory has
|
|
89
|
+
* things in it" is not the same as "replace them without telling me". */
|
|
90
|
+
overwrite?: boolean;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface ExportReport {
|
|
94
|
+
readonly ok: boolean;
|
|
95
|
+
readonly mode: ExportMode | "refused";
|
|
96
|
+
readonly kind: ExportKind;
|
|
97
|
+
readonly target: string;
|
|
98
|
+
readonly files: number;
|
|
99
|
+
readonly bytes: number;
|
|
100
|
+
readonly reason: string;
|
|
101
|
+
/** Live memory-bearing rows written. Zero for a database export, which
|
|
102
|
+
* carries them all without counting them. */
|
|
103
|
+
readonly rows: number;
|
|
104
|
+
/** Rows left out because they are confidential and nobody said otherwise
|
|
105
|
+
* (ruling 4, 2026-09-18). ALWAYS reported, including at zero. */
|
|
106
|
+
readonly omittedConfidential: number;
|
|
107
|
+
/** Ids whose markdown could not be rendered — named, never silently absent. */
|
|
108
|
+
readonly notRendered: readonly string[];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** path (relative, portable) -> file bytes. */
|
|
112
|
+
type Bundle = Map<string, Buffer>;
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* THE BUNDLE IS THE DATABASE.
|
|
116
|
+
*
|
|
117
|
+
* It used to be the database plus a walk of `prose/**.md`, because that is where
|
|
118
|
+
* the memories were. Since the floor (schema v6) the bodies, their archived
|
|
119
|
+
* versions and their metadata are rows, so the one file IS the export and the
|
|
120
|
+
* walk had nothing left to find. That makes the §2.11 rule the whole of this
|
|
121
|
+
* function rather than a footnote on it: the copy goes through `VACUUM INTO`,
|
|
122
|
+
* which is SQLite's own consistent-snapshot path, and never a file copy of a
|
|
123
|
+
* live database — doubly so now that a torn copy would lose the words and not
|
|
124
|
+
* just the bookkeeping.
|
|
125
|
+
*
|
|
126
|
+
* `--markdown`, `journal/` and `spans/` are F7's; this phase owns the deletion
|
|
127
|
+
* of the prose walk and the move of the scratch file, nothing more.
|
|
128
|
+
*/
|
|
129
|
+
function collect(store: Store, tmpDb: string): Bundle {
|
|
130
|
+
const bundle: Bundle = new Map();
|
|
131
|
+
const copied = vacuumInto(paths.operational(store.dir), tmpDb);
|
|
132
|
+
if (copied.ok) bundle.set(DATABASE_FILE, readFileSync(tmpDb));
|
|
133
|
+
return bundle;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** What a markdown walk found, beside the files it produced. */
|
|
137
|
+
interface MarkdownCensus {
|
|
138
|
+
readonly rows: number;
|
|
139
|
+
readonly omittedConfidential: number;
|
|
140
|
+
readonly notRendered: string[];
|
|
141
|
+
readonly journal: number;
|
|
142
|
+
readonly versions: number;
|
|
143
|
+
/** True when the store HOLDS a self page, whether or not it was exported. */
|
|
144
|
+
readonly page: boolean;
|
|
145
|
+
/** …and true when it was left out for being confidential. The manifest must
|
|
146
|
+
* not print "this store has no written self page" over a store that has
|
|
147
|
+
* one (review f6f7 MINOR-1). */
|
|
148
|
+
readonly pageOmitted: boolean;
|
|
149
|
+
/** Earlier wordings left out as confidential — counted APART from rows,
|
|
150
|
+
* because they are a different unit and mixing them made both wrong
|
|
151
|
+
* (MINOR-2). */
|
|
152
|
+
readonly omittedVersions: number;
|
|
153
|
+
/** Live rows that are ARCHIVED — faded, superseded or merged. Exported, and
|
|
154
|
+
* counted so the manifest can say so. */
|
|
155
|
+
readonly archived: number;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* THE READABLE TREE (F7, owner ruling 4 of 2026-09-18).
|
|
160
|
+
*
|
|
161
|
+
* The database export above is exact and complete and can be opened by anything
|
|
162
|
+
* that speaks SQLite. This is the other promise — constitution line 6's "prose
|
|
163
|
+
* the owner can view" — and it is built from the ROWS, never from a walk of
|
|
164
|
+
* `<store>/journal/`:
|
|
165
|
+
*
|
|
166
|
+
* - the journal copy on disk is derived, and a stale one (a file whose episode
|
|
167
|
+
* was removed while the copy could not be written) would be exported as
|
|
168
|
+
* though it were live. Reading the rows cannot do that.
|
|
169
|
+
* - it is the SAME renderer and the SAME path function the copy uses, so the
|
|
170
|
+
* bytes are identical either way. "Included as is" is kept by using the copy's
|
|
171
|
+
* own code, not by copying its files.
|
|
172
|
+
*
|
|
173
|
+
* Grouped **by kind** — `memories/fact/`, `memories/person/`, … — because kind is
|
|
174
|
+
* the axis the owner already sees in `status` and in the dashboard, it is a
|
|
175
|
+
* closed set of six, and it does not change when a memory is revised. By month
|
|
176
|
+
* was the alternative and it splits one belief's life across directories.
|
|
177
|
+
*
|
|
178
|
+
* **Filenames are ids.** Never titles: a title can be as sensitive as a body,
|
|
179
|
+
* and a directory listing is the one part of an export that gets read over
|
|
180
|
+
* somebody's shoulder.
|
|
181
|
+
*
|
|
182
|
+
* Confidential rows are OMITTED unless asked for, and **counted either way** —
|
|
183
|
+
* in the terminal report and in the manifest at the top of the tree. A removed
|
|
184
|
+
* (tombstoned) row is never exported at all; it has no words left to export and
|
|
185
|
+
* its id is on the deny-list.
|
|
186
|
+
*
|
|
187
|
+
* **ARCHIVED rows ARE exported**, and the manifest says how many. A memory that
|
|
188
|
+
* faded, was superseded or was merged is still the owner's own words, and an
|
|
189
|
+
* export that quietly dropped them would be a copy he could not tell was
|
|
190
|
+
* partial — the failure mode the confidential count exists to prevent, one class
|
|
191
|
+
* over. They are NOT marked file by file: the frontmatter is
|
|
192
|
+
* `renderMarkdown`'s, which carries the payload the row holds and not its
|
|
193
|
+
* physics, and that renderer is shared with the journal copy. A count in the
|
|
194
|
+
* manifest is the honest version of what this export knows.
|
|
195
|
+
*/
|
|
196
|
+
function collectMarkdown(store: Store, opts: ExportOptions): { bundle: Bundle; census: MarkdownCensus } {
|
|
197
|
+
const bundle: Bundle = new Map();
|
|
198
|
+
const census: MarkdownCensus = {
|
|
199
|
+
rows: 0,
|
|
200
|
+
omittedConfidential: 0,
|
|
201
|
+
notRendered: [],
|
|
202
|
+
journal: 0,
|
|
203
|
+
versions: 0,
|
|
204
|
+
page: false,
|
|
205
|
+
pageOmitted: false,
|
|
206
|
+
omittedVersions: 0,
|
|
207
|
+
archived: 0,
|
|
208
|
+
};
|
|
209
|
+
const counts = census as {
|
|
210
|
+
rows: number;
|
|
211
|
+
omittedConfidential: number;
|
|
212
|
+
notRendered: string[];
|
|
213
|
+
journal: number;
|
|
214
|
+
versions: number;
|
|
215
|
+
page: boolean;
|
|
216
|
+
pageOmitted: boolean;
|
|
217
|
+
omittedVersions: number;
|
|
218
|
+
archived: number;
|
|
219
|
+
};
|
|
220
|
+
const denied = new Set(store.deniedIds());
|
|
221
|
+
|
|
222
|
+
const put = (path: string, text: string): void => {
|
|
223
|
+
bundle.set(path, Buffer.from(text, "utf8"));
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
const render = (id: string, doc: ProseDoc): string | null => {
|
|
227
|
+
try {
|
|
228
|
+
return renderMarkdown(doc);
|
|
229
|
+
} catch {
|
|
230
|
+
// The id, never the reason's detail: a render refusal can name a title.
|
|
231
|
+
counts.notRendered.push(id);
|
|
232
|
+
return null;
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
for (const id of store.list()) {
|
|
237
|
+
if (denied.has(id)) continue;
|
|
238
|
+
const row = store.row(id);
|
|
239
|
+
if (row === undefined || rowTombstoned(row)) continue;
|
|
240
|
+
// WHETHER THE STORE HAS A PAGE is asked BEFORE the confidentiality gate: it
|
|
241
|
+
// is a fact about the store, not about this export, and answering it after
|
|
242
|
+
// the `continue` made the manifest assert there was no page over a store
|
|
243
|
+
// that had a confidential one (MINOR-1).
|
|
244
|
+
const isPage = row.type === "schema" && isSelfPageRow(store, id);
|
|
245
|
+
if (isPage) counts.page = true;
|
|
246
|
+
if (row.confidential === 1 && opts.includeConfidential !== true) {
|
|
247
|
+
counts.omittedConfidential += 1;
|
|
248
|
+
if (isPage) counts.pageOmitted = true;
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
let doc: ProseDoc;
|
|
252
|
+
try {
|
|
253
|
+
doc = store.readProse(id);
|
|
254
|
+
} catch {
|
|
255
|
+
counts.notRendered.push(id);
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
const text = render(id, doc);
|
|
259
|
+
if (text === null) continue;
|
|
260
|
+
put(pathFor(store, row, doc), text);
|
|
261
|
+
counts.rows += 1;
|
|
262
|
+
if (row.type === "episode") counts.journal += 1;
|
|
263
|
+
if (row.archived === 1) counts.archived += 1;
|
|
264
|
+
|
|
265
|
+
if (opts.versions !== true) continue;
|
|
266
|
+
for (const version of store.versions(id)) {
|
|
267
|
+
let prior: ProseDoc;
|
|
268
|
+
try {
|
|
269
|
+
prior = store.readVersion(id, version.seq);
|
|
270
|
+
} catch {
|
|
271
|
+
counts.notRendered.push(`${id}@${String(version.seq)}`);
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
// A version of a confidential row is confidential; the `versions` table
|
|
275
|
+
// has no column of its own, so the LIVE row's class governs (the loop
|
|
276
|
+
// above has already skipped the whole row) and the version's own meta is
|
|
277
|
+
// asked too, through `confidentialByMeta` — the ONE truth table, never a
|
|
278
|
+
// second reading of the class in the egress door. A gate re-implemented
|
|
279
|
+
// at a call site is a gate that will one day fail open (store/index.ts).
|
|
280
|
+
if (opts.includeConfidential !== true && confidentialByMeta(prior.meta)) {
|
|
281
|
+
counts.omittedVersions += 1;
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
const priorText = render(`${id}@${String(version.seq)}`, prior);
|
|
285
|
+
if (priorText === null) continue;
|
|
286
|
+
put(`versions/${id}/${String(version.seq).padStart(4, "0")}.md`, priorText);
|
|
287
|
+
counts.versions += 1;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
put("README.md", markdownReadme(census, opts));
|
|
292
|
+
return { bundle, census };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Where one row's markdown goes in the tree. Ids only; never a title. */
|
|
296
|
+
function pathFor(store: Store, row: MemoryRow, doc: ProseDoc): string {
|
|
297
|
+
if (row.type === "episode") return journalRelativePath(doc);
|
|
298
|
+
if (row.type === "schema") {
|
|
299
|
+
// THE SELF PAGE IS ITS OWN FILE, at the top, because it is the one document
|
|
300
|
+
// in the store the owner is most likely to want on its own.
|
|
301
|
+
return isSelfPageRow(store, row.id) ? "self-page.md" : `schemas/${row.id}.md`;
|
|
302
|
+
}
|
|
303
|
+
return `memories/${row.kind}/${row.id}.md`;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Remove any `.export-scratch-*` an interrupted export of an OLDER BUILD left in
|
|
308
|
+
* this target.
|
|
309
|
+
*
|
|
310
|
+
* Belt and braces for exactly one window: a build between the floor landing and
|
|
311
|
+
* this fix wrote its scratch here, and a kill during the vacuum left a
|
|
312
|
+
* plaintext copy of the store behind under a timestamped name that the next
|
|
313
|
+
* export would never collide with. Nothing writes that name any more; this is
|
|
314
|
+
* how the ones already on disk go. It never throws — an export must not fail
|
|
315
|
+
* because a stale file would not delete.
|
|
316
|
+
*/
|
|
317
|
+
function sweepStaleScratch(target: string): void {
|
|
318
|
+
try {
|
|
319
|
+
for (const name of readdirSync(target)) {
|
|
320
|
+
if (!name.startsWith(".export-scratch-")) continue;
|
|
321
|
+
rmSync(join(target, name), { recursive: true, force: true });
|
|
322
|
+
}
|
|
323
|
+
} catch {
|
|
324
|
+
/* an unreadable target fails for its own reasons, further down */
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** What the report says when this export cleaned up after an interrupted one. */
|
|
329
|
+
function sweptNote(swept: readonly string[]): string {
|
|
330
|
+
if (swept.length === 0) return "";
|
|
331
|
+
return (
|
|
332
|
+
` Also removed ${String(swept.length)} abandoned scratch ` +
|
|
333
|
+
`director${swept.length === 1 ? "y" : "ies"} an interrupted export had left in the temp dir ` +
|
|
334
|
+
"(each held an unencrypted copy of the store)."
|
|
335
|
+
);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** The prefix this module's scratch directories wear, in the OS temp dir. */
|
|
339
|
+
export const EXPORT_SCRATCH_PREFIX = "counterparts-export-";
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* How old an abandoned scratch directory must be before a later export removes
|
|
343
|
+
* it. **The bound is the whole point**: without it this sweep would delete a
|
|
344
|
+
* CONCURRENT export's directory mid-vacuum, which is a collision the target
|
|
345
|
+
* sweep above cannot have (it matches a name nothing writes any more).
|
|
346
|
+
*
|
|
347
|
+
* Same reasoning and the same number as `adapters/snapshots.ts#PARTIAL_STALE_MS`:
|
|
348
|
+
* comfortably longer than any single export could plausibly still be running.
|
|
349
|
+
*/
|
|
350
|
+
export const EXPORT_SCRATCH_STALE_MS = 60 * 60_000;
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Remove abandoned `counterparts-export-*` directories from the OS temp dir.
|
|
354
|
+
*
|
|
355
|
+
* An interrupted `--passphrase` export leaves a PLAINTEXT SQLite copy of the
|
|
356
|
+
* whole store in one (0700, so only this user can read it) and nothing swept
|
|
357
|
+
* it: on macOS `/var/folders` is reaped after roughly three days of non-access,
|
|
358
|
+
* otherwise it sits there (review f5c, NEW-MINOR-6). Moving it out of the
|
|
359
|
+
* target was the big win; this is the rest of it.
|
|
360
|
+
*
|
|
361
|
+
* Exact prefix, `mtime` older than the bound, and only entries this user owns —
|
|
362
|
+
* the temp dir is shared on some systems, and a sweep that took somebody else's
|
|
363
|
+
* directory would be a worse bug than the one it fixes. Never throws.
|
|
364
|
+
*/
|
|
365
|
+
export function sweepStaleExportScratch(now = Date.now()): string[] {
|
|
366
|
+
const swept: string[] = [];
|
|
367
|
+
const root = tmpdir();
|
|
368
|
+
let names: string[];
|
|
369
|
+
try {
|
|
370
|
+
names = readdirSync(root);
|
|
371
|
+
} catch {
|
|
372
|
+
return swept;
|
|
373
|
+
}
|
|
374
|
+
for (const name of names) {
|
|
375
|
+
if (!name.startsWith(EXPORT_SCRATCH_PREFIX)) continue;
|
|
376
|
+
const full = join(root, name);
|
|
377
|
+
try {
|
|
378
|
+
const st = statSync(full);
|
|
379
|
+
if (!st.isDirectory()) continue;
|
|
380
|
+
if (st.uid !== process.getuid?.()) continue;
|
|
381
|
+
if (now - st.mtimeMs < EXPORT_SCRATCH_STALE_MS) continue;
|
|
382
|
+
rmSync(full, { recursive: true, force: true });
|
|
383
|
+
swept.push(name);
|
|
384
|
+
} catch {
|
|
385
|
+
/* a directory that will not stat or will not go is not this export's problem */
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
return swept;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
export function exportStore(store: Store, opts: ExportOptions): ExportReport {
|
|
392
|
+
const kind: ExportKind = opts.markdown === true ? "markdown" : "database";
|
|
393
|
+
const refused = (reason: string): ExportReport => ({
|
|
394
|
+
ok: false,
|
|
395
|
+
mode: "refused",
|
|
396
|
+
kind,
|
|
397
|
+
target: opts.target,
|
|
398
|
+
files: 0,
|
|
399
|
+
bytes: 0,
|
|
400
|
+
reason,
|
|
401
|
+
rows: 0,
|
|
402
|
+
omittedConfidential: 0,
|
|
403
|
+
notRendered: [],
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
const encrypting = typeof opts.passphrase === "string" && opts.passphrase.length > 0;
|
|
407
|
+
if (!encrypting && opts.plaintext !== true) {
|
|
408
|
+
return refused(
|
|
409
|
+
"export refuses to choose for you: pass --passphrase <secret> to encrypt, or --plaintext to say out loud that this copy is unencrypted.",
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
if (kind === "database" && (opts.includeConfidential === true || opts.versions === true)) {
|
|
413
|
+
// NOT A HALF-KEPT PROMISE. `--include-confidential` and `--versions` decide
|
|
414
|
+
// what goes into the readable tree; a database export carries every row
|
|
415
|
+
// there is, so honouring either flag there would be a lie in one direction
|
|
416
|
+
// and honouring neither, silently, a lie in the other.
|
|
417
|
+
return refused(
|
|
418
|
+
"--include-confidential and --with-versions are about the readable tree: pass --markdown with them, or drop them (a database export carries every row, confidential ones and every archived wording included).",
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
let target: string;
|
|
423
|
+
try {
|
|
424
|
+
target = assertSafeTarget(store.dir, opts.target);
|
|
425
|
+
mkdirSync(target, { recursive: true });
|
|
426
|
+
// …and the ones an interrupted export of an older build left HERE, swept
|
|
427
|
+
// BEFORE the emptiness question below: `.export-scratch-*` is a name nothing
|
|
428
|
+
// writes any more, and a target holding only that is a target that is empty
|
|
429
|
+
// as far as the owner is concerned.
|
|
430
|
+
sweepStaleScratch(target);
|
|
431
|
+
const existing = readdirSync(target);
|
|
432
|
+
if (existing.length > 0 && opts.intoNonEmpty !== true) {
|
|
433
|
+
return refused(
|
|
434
|
+
`refusing to write into a directory that is not empty: ${target} already holds ${String(existing.length)} ` +
|
|
435
|
+
`entr${existing.length === 1 ? "y" : "ies"}. An export is a whole copy, and writing one over another leaves a ` +
|
|
436
|
+
"mixture of two that nothing can tell apart. Name an empty directory, or pass --into-non-empty.",
|
|
437
|
+
);
|
|
438
|
+
}
|
|
439
|
+
} catch (err) {
|
|
440
|
+
return refused(String((err as Error).message ?? err));
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// THE SCRATCH GOES IN THE OS TEMP DIR — not in the store, and NOT IN THE
|
|
444
|
+
// TARGET.
|
|
445
|
+
//
|
|
446
|
+
// It lived in `<store>/tmp/` until the floor deleted that directory with the
|
|
447
|
+
// staging it existed for, and a scratch file in the store would now fail the
|
|
448
|
+
// next `assertLayout()` as an unclassified top-level path (§5 G11). The first
|
|
449
|
+
// fix moved it into the target, which `assertSafeTarget` proves is outside
|
|
450
|
+
// the store — and that was the wrong outside. The scratch is a PLAINTEXT
|
|
451
|
+
// SQLite copy of the whole store, and the target of a `--passphrase` export
|
|
452
|
+
// is by definition the place the copy is going: an external disk, a synced
|
|
453
|
+
// folder, the directory the owner is about to hand somebody. Review B killed
|
|
454
|
+
// an exporter mid-`VACUUM INTO` and found a 4 MB unencrypted copy of the
|
|
455
|
+
// memories left behind under a timestamped name that nothing would ever
|
|
456
|
+
// overwrite or sweep (MAJOR-4). `--passphrase` exists precisely to say "this
|
|
457
|
+
// copy leaves the machine".
|
|
458
|
+
//
|
|
459
|
+
// `mkdtempSync` gives it a private directory (0700 by construction) that the
|
|
460
|
+
// OS reaps, so an interrupted export leaks at worst into a temp dir rather
|
|
461
|
+
// than into the artefact. The whole directory goes in the `finally`.
|
|
462
|
+
//
|
|
463
|
+
// …and the ones an interrupted export of our own left in the OS temp dir.
|
|
464
|
+
// Said out loud rather than done in silence: it is the owner's plaintext.
|
|
465
|
+
const sweptScratch = sweepStaleExportScratch();
|
|
466
|
+
let bundle: Bundle;
|
|
467
|
+
let census: MarkdownCensus | null = null;
|
|
468
|
+
if (kind === "markdown") {
|
|
469
|
+
// NO SCRATCH AT ALL. The readable tree is rendered from rows into memory,
|
|
470
|
+
// so a `--markdown --passphrase` export never puts one plaintext byte
|
|
471
|
+
// anywhere: not in the target, not in the temp dir. The pair is supported
|
|
472
|
+
// properly rather than refused — the whole bundle is built, then encrypted,
|
|
473
|
+
// then one blob is written, which is the same path the database export's
|
|
474
|
+
// encrypted arm already takes.
|
|
475
|
+
const built = collectMarkdown(store, opts);
|
|
476
|
+
bundle = built.bundle;
|
|
477
|
+
census = built.census;
|
|
478
|
+
} else {
|
|
479
|
+
const scratchDir = mkdtempSync(join(tmpdir(), EXPORT_SCRATCH_PREFIX));
|
|
480
|
+
const tmpDb = join(scratchDir, "scratch.sqlite");
|
|
481
|
+
try {
|
|
482
|
+
bundle = collect(store, tmpDb);
|
|
483
|
+
} finally {
|
|
484
|
+
rmSync(scratchDir, { recursive: true, force: true });
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
let bytes = 0;
|
|
489
|
+
for (const buf of bundle.values()) bytes += buf.length;
|
|
490
|
+
const counted = {
|
|
491
|
+
rows: census?.rows ?? 0,
|
|
492
|
+
omittedConfidential: census?.omittedConfidential ?? 0,
|
|
493
|
+
omittedVersions: census?.omittedVersions ?? 0,
|
|
494
|
+
notRendered: census?.notRendered ?? [],
|
|
495
|
+
};
|
|
496
|
+
|
|
497
|
+
if (!encrypting) {
|
|
498
|
+
// A COLLISION IS A REFUSAL, unless the owner said to replace.
|
|
499
|
+
//
|
|
500
|
+
// `--into-non-empty` means "I know this directory has things in it"; it
|
|
501
|
+
// does not mean "replace them without telling me". The review watched an
|
|
502
|
+
// export overwrite a README.md that said "SOMEBODY ELSE'S README —
|
|
503
|
+
// irreplaceable" and report nothing (MINOR-3). Nothing is written until
|
|
504
|
+
// every path has been checked, so a refused export leaves the directory
|
|
505
|
+
// exactly as it found it.
|
|
506
|
+
const collisions = [...bundle.keys()].filter((path) => existsSync(join(target, path))).sort();
|
|
507
|
+
if (collisions.length > 0 && opts.overwrite !== true) {
|
|
508
|
+
return refused(
|
|
509
|
+
`refusing to replace ${String(collisions.length)} file${collisions.length === 1 ? "" : "s"} that ${collisions.length === 1 ? "is" : "are"} already in ${target}: ` +
|
|
510
|
+
`${collisions.slice(0, 5).join(", ")}${collisions.length > 5 ? `, and ${String(collisions.length - 5)} more` : ""}. ` +
|
|
511
|
+
"Name an empty directory, or pass --overwrite to replace exactly those.",
|
|
512
|
+
);
|
|
513
|
+
}
|
|
514
|
+
for (const [path, buf] of bundle) {
|
|
515
|
+
const out = join(target, path);
|
|
516
|
+
mkdirSync(join(out, ".."), { recursive: true });
|
|
517
|
+
writeFileSync(out, buf);
|
|
518
|
+
}
|
|
519
|
+
// The markdown tree writes its OWN manifest, as one of its files, so the
|
|
520
|
+
// count and the omission are inside the artefact as well as on the
|
|
521
|
+
// terminal (ruling 4: "and says how many it omitted").
|
|
522
|
+
if (kind === "database") {
|
|
523
|
+
writeFileSync(join(target, "README.md"), plaintextReadme(bundle.size, bytes), "utf8");
|
|
524
|
+
}
|
|
525
|
+
return {
|
|
526
|
+
ok: true,
|
|
527
|
+
mode: "plaintext",
|
|
528
|
+
kind,
|
|
529
|
+
target,
|
|
530
|
+
files: bundle.size,
|
|
531
|
+
bytes,
|
|
532
|
+
reason:
|
|
533
|
+
(kind === "markdown"
|
|
534
|
+
? "Unencrypted, at the owner's explicit request. Every file is plain markdown."
|
|
535
|
+
: "Unencrypted, at the owner's explicit request. The database is readable by any SQLite.") +
|
|
536
|
+
confidentialNote(counted.omittedConfidential, counted.omittedVersions, opts) +
|
|
537
|
+
notRenderedNote(counted.notRendered) +
|
|
538
|
+
replacedNote(collisions) +
|
|
539
|
+
sweptNote(sweptScratch),
|
|
540
|
+
...counted,
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
const blob = encryptBundle(bundle, opts.passphrase as string);
|
|
545
|
+
writeFileSync(join(target, BLOB_NAME), blob);
|
|
546
|
+
writeFileSync(join(target, "README.md"), encryptedReadme(bundle.size, bytes, kind), "utf8");
|
|
547
|
+
return {
|
|
548
|
+
ok: true,
|
|
549
|
+
mode: "encrypted",
|
|
550
|
+
kind,
|
|
551
|
+
target,
|
|
552
|
+
files: bundle.size,
|
|
553
|
+
bytes,
|
|
554
|
+
reason:
|
|
555
|
+
`Encrypted with ${CIPHER} under a key derived from your passphrase. Lose the passphrase and this archive is gone.` +
|
|
556
|
+
confidentialNote(counted.omittedConfidential, counted.omittedVersions, opts) +
|
|
557
|
+
notRenderedNote(counted.notRendered) +
|
|
558
|
+
sweptNote(sweptScratch),
|
|
559
|
+
...counted,
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* What the report says about confidential rows — ALWAYS, including at zero.
|
|
565
|
+
*
|
|
566
|
+
* Ruling 4 says the export "says how many it omitted", and a line that appears
|
|
567
|
+
* only when something was left out is one whose absence means two different
|
|
568
|
+
* things: nothing was confidential, or nobody checked.
|
|
569
|
+
*/
|
|
570
|
+
function confidentialNote(omitted: number, omittedVersions: number, opts: ExportOptions): string {
|
|
571
|
+
if (opts.markdown !== true) return "";
|
|
572
|
+
if (opts.includeConfidential === true) {
|
|
573
|
+
return " Confidential rows are INCLUDED, because --include-confidential was passed.";
|
|
574
|
+
}
|
|
575
|
+
if (omitted === 0 && omittedVersions === 0) {
|
|
576
|
+
return " No confidential rows were left out (there were none).";
|
|
577
|
+
}
|
|
578
|
+
const versions =
|
|
579
|
+
omittedVersions === 0
|
|
580
|
+
? ""
|
|
581
|
+
: ` and ${String(omittedVersions)} confidential earlier wording${omittedVersions === 1 ? "" : "s"}`;
|
|
582
|
+
const one = omitted === 1 && versions === "";
|
|
583
|
+
return (
|
|
584
|
+
` ${String(omitted)} confidential row${omitted === 1 ? "" : "s"}${versions}` +
|
|
585
|
+
`${one ? " was" : " were"} left out;` +
|
|
586
|
+
` pass --include-confidential to take ${one ? "it" : "them"} too.`
|
|
587
|
+
);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/** WHICH files this export replaced, when the owner said to. The flag whose
|
|
591
|
+
* whole purpose is "I know this directory has things in it" is the one place
|
|
592
|
+
* the report must say which of them went (review f6f7 MINOR-3). */
|
|
593
|
+
function replacedNote(collisions: readonly string[]): string {
|
|
594
|
+
if (collisions.length === 0) return "";
|
|
595
|
+
return (
|
|
596
|
+
` Replaced ${String(collisions.length)} existing file${collisions.length === 1 ? "" : "s"}, at your request: ` +
|
|
597
|
+
`${collisions.slice(0, 5).join(", ")}${collisions.length > 5 ? `, and ${String(collisions.length - 5)} more` : ""}.`
|
|
598
|
+
);
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/** Rows that could not be rendered, by id — named, never silently absent. */
|
|
602
|
+
function notRenderedNote(ids: readonly string[]): string {
|
|
603
|
+
if (ids.length === 0) return "";
|
|
604
|
+
return ` ${String(ids.length)} row${ids.length === 1 ? "" : "s"} could not be rendered and ${ids.length === 1 ? "is" : "are"} NOT in this copy: ${ids.join(", ")}.`;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
export function encryptBundle(bundle: Bundle, passphrase: string): Buffer {
|
|
608
|
+
const salt = randomBytes(KDF.saltBytes);
|
|
609
|
+
const iv = randomBytes(12);
|
|
610
|
+
const key = scryptSync(passphrase, salt, KDF.keyBytes, { N: KDF.N, r: KDF.r, p: KDF.p });
|
|
611
|
+
const manifest: Record<string, string> = {};
|
|
612
|
+
for (const [path, buf] of bundle) manifest[path] = buf.toString("base64");
|
|
613
|
+
const plain = gzipSync(Buffer.from(JSON.stringify(manifest), "utf8"));
|
|
614
|
+
const cipher = createCipheriv(CIPHER, key, iv);
|
|
615
|
+
const body = Buffer.concat([cipher.update(plain), cipher.final()]);
|
|
616
|
+
const envelope = {
|
|
617
|
+
format: EXPORT_FORMAT,
|
|
618
|
+
cipher: CIPHER,
|
|
619
|
+
kdf: { name: "scrypt", ...KDF },
|
|
620
|
+
salt: salt.toString("base64"),
|
|
621
|
+
iv: iv.toString("base64"),
|
|
622
|
+
tag: cipher.getAuthTag().toString("base64"),
|
|
623
|
+
payload: body.toString("base64"),
|
|
624
|
+
};
|
|
625
|
+
return Buffer.from(JSON.stringify(envelope), "utf8");
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/**
|
|
629
|
+
* The read-back half. It exists because a backup nobody has ever opened is not
|
|
630
|
+
* evidence of anything (contract §7 OQ3, and §2.17's "an untried path is
|
|
631
|
+
* unproven"): `test/cli.test.ts` round-trips a real export through it.
|
|
632
|
+
*/
|
|
633
|
+
export function decryptBundle(blob: Buffer, passphrase: string): Map<string, Buffer> {
|
|
634
|
+
const envelope = JSON.parse(blob.toString("utf8")) as {
|
|
635
|
+
format: string;
|
|
636
|
+
kdf: { N: number; r: number; p: number; keyBytes: number };
|
|
637
|
+
salt: string;
|
|
638
|
+
iv: string;
|
|
639
|
+
tag: string;
|
|
640
|
+
payload: string;
|
|
641
|
+
};
|
|
642
|
+
if (envelope.format !== EXPORT_FORMAT) throw new Error(`unknown export format: ${envelope.format}`);
|
|
643
|
+
const salt = Buffer.from(envelope.salt, "base64");
|
|
644
|
+
const key = scryptSync(passphrase, salt, envelope.kdf.keyBytes, {
|
|
645
|
+
N: envelope.kdf.N,
|
|
646
|
+
r: envelope.kdf.r,
|
|
647
|
+
p: envelope.kdf.p,
|
|
648
|
+
});
|
|
649
|
+
const decipher = createDecipheriv(CIPHER, key, Buffer.from(envelope.iv, "base64"));
|
|
650
|
+
decipher.setAuthTag(Buffer.from(envelope.tag, "base64"));
|
|
651
|
+
const plain = gunzipSync(
|
|
652
|
+
Buffer.concat([decipher.update(Buffer.from(envelope.payload, "base64")), decipher.final()]),
|
|
653
|
+
);
|
|
654
|
+
const manifest = JSON.parse(plain.toString("utf8")) as Record<string, string>;
|
|
655
|
+
const out = new Map<string, Buffer>();
|
|
656
|
+
for (const [path, b64] of Object.entries(manifest)) out.set(path, Buffer.from(b64, "base64"));
|
|
657
|
+
return out;
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
function plaintextReadme(files: number, bytes: number): string {
|
|
661
|
+
return [
|
|
662
|
+
"# Counterparts export (UNENCRYPTED)",
|
|
663
|
+
"",
|
|
664
|
+
`${files} files, ${bytes} bytes, written at the owner's explicit request with --plaintext.`,
|
|
665
|
+
"",
|
|
666
|
+
`- \`${DATABASE_FILE}\` — the whole store: the memories themselves, their`,
|
|
667
|
+
" archived versions, and every structured field. Copied through SQLite's own",
|
|
668
|
+
" VACUUM INTO, never as a file copy of a live database.",
|
|
669
|
+
"",
|
|
670
|
+
"The rebuildable cache is deliberately not included: it is reconstructed from",
|
|
671
|
+
"the database above.",
|
|
672
|
+
"",
|
|
673
|
+
"This copy is not encrypted. Treat it the way you would treat the store itself.",
|
|
674
|
+
"",
|
|
675
|
+
].join("\n");
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/**
|
|
679
|
+
* THE MANIFEST, and it is a file INSIDE the tree.
|
|
680
|
+
*
|
|
681
|
+
* Ruling 4 asks the export to say how many confidential rows it omitted. The
|
|
682
|
+
* terminal says it, and the terminal scrolls away; six months later the only
|
|
683
|
+
* thing left is the directory, and a directory that does not say what is
|
|
684
|
+
* missing from it reads as complete. So the count lives here too — and at zero,
|
|
685
|
+
* for the same reason.
|
|
686
|
+
*/
|
|
687
|
+
function markdownReadme(census: MarkdownCensus, opts: ExportOptions): string {
|
|
688
|
+
// TWO UNITS, SAID APART. A row and an earlier wording of a row are different
|
|
689
|
+
// things, and one counter for both reported 3 for an open memory with three
|
|
690
|
+
// confidential wordings and 1 for a confidential memory with three — four
|
|
691
|
+
// things omitted either way (review f6f7 MINOR-2). The version count is only
|
|
692
|
+
// meaningful when versions were being exported at all.
|
|
693
|
+
const omitted =
|
|
694
|
+
opts.includeConfidential === true
|
|
695
|
+
? "- Confidential memories are **included**: `--include-confidential` was passed."
|
|
696
|
+
: census.omittedConfidential === 0 && census.omittedVersions === 0
|
|
697
|
+
? "- Confidential memories omitted: **0** (there were none)."
|
|
698
|
+
: `- Confidential memories omitted: **${String(census.omittedConfidential)}**` +
|
|
699
|
+
(opts.versions === true
|
|
700
|
+
? `, and **${String(census.omittedVersions)}** confidential earlier wording${census.omittedVersions === 1 ? "" : "s"} of memories that are otherwise here.`
|
|
701
|
+
: ". (Earlier wordings were not being exported; `--with-versions` writes them, confidential ones excepted.)") +
|
|
702
|
+
" They are still in your store; re-run with `--include-confidential` to take them too.";
|
|
703
|
+
return [
|
|
704
|
+
"# Counterparts export (markdown)",
|
|
705
|
+
"",
|
|
706
|
+
`${census.rows} rows, readable in any editor — memories, the journal, and the self page.`,
|
|
707
|
+
"Rendered from the database; this is a COPY, and the store itself is still where the",
|
|
708
|
+
"memories live.",
|
|
709
|
+
"",
|
|
710
|
+
"## What is here",
|
|
711
|
+
"",
|
|
712
|
+
"- `memories/<kind>/<id>.md` — one file per memory, grouped by kind. The file name is",
|
|
713
|
+
" the memory's id; the title, dates and everything else are in the frontmatter.",
|
|
714
|
+
census.archived === 0
|
|
715
|
+
? " None of them is archived: every memory here is a live one."
|
|
716
|
+
: ` ${String(census.archived)} of them ${census.archived === 1 ? "is" : "are"} ARCHIVED — faded, superseded or merged.` +
|
|
717
|
+
" They are still your words, so they are here; the files do not mark which," +
|
|
718
|
+
" and `counterparts status` is where that is readable.",
|
|
719
|
+
census.pageOmitted
|
|
720
|
+
? "- `self-page.md` — **omitted as confidential**. This store HAS a written self page; it was left out of this copy. `--include-confidential` takes it."
|
|
721
|
+
: census.page
|
|
722
|
+
? "- `self-page.md` — the written self page, as it stands."
|
|
723
|
+
: "- `self-page.md` — absent: this store has no written self page.",
|
|
724
|
+
"- `schemas/<id>.md` — the structured rows that are not the page (the identity core, beliefs).",
|
|
725
|
+
`- \`journal/<year>/<date>-<id>.md\` — the first-person episode journal, as is: ` +
|
|
726
|
+
`${String(census.journal)} episode${census.journal === 1 ? "" : "s"}.`,
|
|
727
|
+
census.versions > 0
|
|
728
|
+
? `- \`versions/<id>/<seq>.md\` — ${String(census.versions)} earlier wording${census.versions === 1 ? "" : "s"}, oldest first (\`--with-versions\`).`
|
|
729
|
+
: "- `versions/` — not included. Pass `--with-versions` to export every earlier wording too.",
|
|
730
|
+
"",
|
|
731
|
+
"## What is NOT here",
|
|
732
|
+
"",
|
|
733
|
+
omitted,
|
|
734
|
+
"- Removed memories. A removal is permanent; a tombstoned row has no words left to export.",
|
|
735
|
+
census.notRendered.length === 0
|
|
736
|
+
? "- Nothing else. Every live row this export could reach is in it."
|
|
737
|
+
: `- ${String(census.notRendered.length)} row(s) whose markdown could not be rendered: ${census.notRendered.join(", ")}.`,
|
|
738
|
+
"- The structured physics — strengths, edges, the association graph, the event log.",
|
|
739
|
+
" Those are in the database, and `counterparts export --out <dir> --plaintext` (without",
|
|
740
|
+
" `--markdown`) copies the whole thing as one SQLite file.",
|
|
741
|
+
"",
|
|
742
|
+
"Nothing reads this tree back in. Editing a file here changes nothing in your store.",
|
|
743
|
+
"",
|
|
744
|
+
].join("\n");
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
function encryptedReadme(files: number, bytes: number, kind: ExportKind): string {
|
|
748
|
+
return [
|
|
749
|
+
"# Counterparts export (encrypted)",
|
|
750
|
+
"",
|
|
751
|
+
`\`${BLOB_NAME}\` holds ${files} files (${bytes} bytes before compression) — ` +
|
|
752
|
+
(kind === "markdown"
|
|
753
|
+
? "the readable markdown tree, including its own manifest."
|
|
754
|
+
: "the whole store as one SQLite database."),
|
|
755
|
+
"",
|
|
756
|
+
"Format, so this is never an archive you cannot open:",
|
|
757
|
+
"",
|
|
758
|
+
`1. The blob is JSON: \`{format, cipher, kdf, salt, iv, tag, payload}\` — all base64.`,
|
|
759
|
+
`2. Key = scrypt(passphrase, salt, N/r/p from the \`kdf\` field), ${KDF.keyBytes} bytes.`,
|
|
760
|
+
`3. Payload = ${CIPHER}(gzip(JSON manifest of path -> base64 file bytes)).`,
|
|
761
|
+
"",
|
|
762
|
+
"The passphrase is yours and is not stored anywhere. There is no recovery path;",
|
|
763
|
+
"that is the point of it being owner-keyed.",
|
|
764
|
+
"",
|
|
765
|
+
].join("\n");
|
|
766
|
+
}
|