lattris 0.2.3 → 0.2.5

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/README.md CHANGED
@@ -41,7 +41,7 @@ sign you up.
41
41
  ## What it does
42
42
 
43
43
  ```
44
- lattris capture write a note, a session or a recording, or rows of a dataset
44
+ lattris capture write a note, a session, a recording or a source, or rows of a dataset
45
45
  lattris note a single note
46
46
  lattris session a session and its turns
47
47
  lattris recording a recording and its transcript
package/dist/build.json CHANGED
@@ -1 +1 @@
1
- {"commit":"2cc00908002bab8c075247652ee18d6d2f82515a","builtAt":"2026-10-11T22:49:48Z"}
1
+ {"commit":"e8530aa15f1fe801130caa1d6405e9ac2288edf5","builtAt":"2026-11-17T04:12:13Z"}
@@ -59,9 +59,13 @@ export const runForm = async (cfg, io, form, rest) => {
59
59
  if (body && form.request.emptyBodyMessage && Object.keys(body).length === 0) {
60
60
  return refuse(form.request.emptyBodyMessage);
61
61
  }
62
- const accessToken = await signedIn(io, cfg);
63
- if (typeof accessToken !== 'string')
64
- return accessToken;
62
+ let accessToken;
63
+ if (form.credential !== 'none') {
64
+ const signed = await signedIn(io, cfg);
65
+ if (typeof signed !== 'string')
66
+ return signed;
67
+ accessToken = signed;
68
+ }
65
69
  let missingName;
66
70
  let recording = false;
67
71
  const reserved = [
@@ -139,6 +143,13 @@ export const runForm = async (cfg, io, form, rest) => {
139
143
  return refusalOf(fetched, ambiguousText(fetched.body));
140
144
  }
141
145
  }
146
+ if (steps.subscriber) {
147
+ const fetched = await io.api(accessToken, `${cfg.apiUrl}/subscribers/${encodeURIComponent(typed.positionals[0])}`);
148
+ if (!fetched.ok) {
149
+ return refusalOf(fetched, ambiguousText(fetched.body));
150
+ }
151
+ context.subscriber = fetched.data;
152
+ }
142
153
  if (steps.noAudienceReport &&
143
154
  typed.flags[steps.noAudienceReport.key] === undefined &&
144
155
  context.gone) {
@@ -168,6 +179,7 @@ export const runForm = async (cfg, io, form, rest) => {
168
179
  'memory.id': context.memory?.id ?? sanitizeForTerminal(typed.positionals[0] ?? ''),
169
180
  'contact.id': context.contact?.id ?? '',
170
181
  email: sanitizeForTerminal(context.email ?? ''),
182
+ 'subscriber.email': sanitizeForTerminal(context.subscriber?.email ?? ''),
171
183
  audience: context.contact?.displayName ?? describeAudience(selector ?? '')
172
184
  });
173
185
  const answer = await confirmAction(io, question);
@@ -229,6 +241,10 @@ export const runForm = async (cfg, io, form, rest) => {
229
241
  context.contact?.claimedPersonId) {
230
242
  result = await send(new URL(`${cfg.apiUrl}${fillPath(fallback.path, typed, context)}`));
231
243
  }
244
+ const instead = result.ok ? undefined : form.refusalInstead?.[result.body.code ?? ''];
245
+ if (!result.ok && instead !== undefined) {
246
+ return refuse(fillIn(instead, { 'subscriber.email': sanitizeForTerminal(context.subscriber?.email ?? '') }), result.exit);
247
+ }
232
248
  if (!result.ok) {
233
249
  return refusalOf(result, (form.ambiguousRefusal ? ambiguousText(result.body) : '') +
234
250
  (form.refusalWords?.(result.body, context) ?? ''));
@@ -86,8 +86,10 @@ export const readWords = (form, rest) => {
86
86
  export const valueOf = (source, typed, stdin, context) => {
87
87
  if ('flag' in source)
88
88
  return typed.flags[source.flag];
89
- if ('positional' in source)
90
- return typed.positionals[source.positional];
89
+ if ('positional' in source) {
90
+ const value = typed.positionals[source.positional];
91
+ return source.trim && value !== undefined ? value.trim() : value;
92
+ }
91
93
  if ('stdin' in source)
92
94
  return stdin;
93
95
  if ('context' in source) {
package/dist/help.js CHANGED
@@ -40,7 +40,7 @@ export const usage = (term) => {
40
40
  ' LATTRIS_API lattris-api base (http://localhost:54301)',
41
41
  ' LATTRIS_CLIENT_ID OAuth client id (lattris-cli)',
42
42
  ' LATTRIS_REDIRECT_PORT loopback callback (4577)',
43
- ' LATTRIS_SESSION_ID names this session on every note write (required off a terminal)',
43
+ ' LATTRIS_SESSION_ID names this session on every note or source write (required off a terminal)',
44
44
  ' LATTRIS_AGENT a readable label for it (optional)',
45
45
  '',
46
46
  'Session resolution (which identity a command acts as), in order:',
@@ -168,4 +168,13 @@ export const SESSION_ONLY_FLAGS = [
168
168
  ['--forked-from', 'forkedFrom']
169
169
  ];
170
170
  export const retryWords = (path) => renderRunHint(['resend', path]);
171
+ export const readTextFile = (io, path) => {
172
+ try {
173
+ const text = io.store.files.readFileSync(path, 'utf8');
174
+ return text.length === 0 ? refusal(`The text is empty: ${path}\n`) : text;
175
+ }
176
+ catch {
177
+ return refusal(`Cannot read the text file: ${path}\n`);
178
+ }
179
+ };
171
180
  //# sourceMappingURL=capture-common.js.map
@@ -5,6 +5,8 @@ export const CAPTURE_INDEX = [
5
5
  ' note written words — --type defaults to it',
6
6
  ' session a conversation with an AI, kept as an append-only ledger',
7
7
  ' recording audio, its source, and its transcript',
8
+ ' source a link you keep: a page, a post, a video',
9
+ ' engagement the numbers a source had on a day: impressions, likes, comments, shares',
8
10
  ' rows rows of a dataset, newline-delimited JSON',
9
11
  '',
10
12
  'Go one word deeper:',
@@ -13,6 +15,8 @@ export const CAPTURE_INDEX = [
13
15
  ' lattris capture memory --type session how to save a conversation (capture session accepted too)',
14
16
  ' lattris capture session <transcript.jsonl> save a Claude Code conversation, whole chain',
15
17
  ' lattris capture recording how to save audio + transcript',
18
+ ' lattris capture source how to keep a link, its text and its numbers',
19
+ ' lattris capture engagement how to add a dated reading of a source\u2019s numbers',
16
20
  ' lattris capture rows how to save rows into a dataset',
17
21
  '',
18
22
  'To read what you have kept: lattris get memories',
@@ -40,6 +44,9 @@ If it came from somewhere else, say so in the words.
40
44
 
41
45
  Offer a one-line title — what this is about. It's how they'll find it later.
42
46
 
47
+ To add a video, paste a YouTube link on a line by itself. Put words in
48
+ [brackets](link) to give it a title.
49
+
43
50
  Which intent? Take the first that fits.
44
51
 
45
52
  already done it → action
@@ -60,7 +67,7 @@ noticed "Mum seemed quieter than usual today."
60
67
  no intent "That thing about the school waiting list — look into it."
61
68
  "Summary of the article on sleep — haven't decided what I make of it."
62
69
 
63
- to save text arrives on stdin — no quoting; up to 5MB.
70
+ to save text arrives on stdin — no quoting; up to 128KB.
64
71
 
65
72
  lattris capture which forms exist
66
73
  lattris capture memory prints this (capture note accepted too)
@@ -0,0 +1,98 @@
1
+ import { COUNTS, formatCounts } from "../memory/views.js";
2
+ import { emit } from "../render/output.js";
3
+ import { signedIn } from "../request/access-token.js";
4
+ import { refusalOf } from "../request/api-fetch.js";
5
+ import { parseArgs } from "../request/flags.js";
6
+ import { isRefusal, refusal } from "../store/exit.js";
7
+ export const READING_FLAG_NAMES = {
8
+ '--impressions': 'impressions',
9
+ '--likes': 'likes',
10
+ '--comments': 'comments',
11
+ '--shares': 'shares',
12
+ '--as-of': 'asOf'
13
+ };
14
+ const NOT_FOUND = 404;
15
+ const WHOLE_NUMBER = /^\d+$/;
16
+ export const givesNumbers = (flags) => COUNTS.some((name) => flags[name] !== undefined) || flags.asOf !== undefined;
17
+ export const buildReading = (flags, nowMs) => {
18
+ const given = COUNTS.filter((name) => flags[name] !== undefined);
19
+ if (given.length === 0) {
20
+ return refusal('A reading needs at least one of --impressions, --likes, --comments, --shares.\n');
21
+ }
22
+ const counts = {};
23
+ for (const name of given) {
24
+ const value = flags[name];
25
+ if (value === undefined || !WHOLE_NUMBER.test(value) || !Number.isSafeInteger(Number(value))) {
26
+ return refusal(`--${name} must be a whole number, 0 or more: ${value}\n`);
27
+ }
28
+ counts[name] = Number(value);
29
+ }
30
+ const asOf = flags.asOf === undefined ? new Date(nowMs).toISOString() : flags.asOf;
31
+ return Object.assign({ asOf }, counts);
32
+ };
33
+ export const postReading = (cfg, io, accessToken, id, reading) => io.api(accessToken, `${cfg.apiUrl}/memories/${encodeURIComponent(id)}/engagement`, {
34
+ method: 'POST',
35
+ headers: { 'Content-Type': 'application/json' },
36
+ body: JSON.stringify(reading)
37
+ });
38
+ export const ownerSourceFacts = async (cfg, io, accessToken, id) => {
39
+ const result = await io.api(accessToken, `${cfg.apiUrl}/memories/${encodeURIComponent(id)}`);
40
+ if (result.ok) {
41
+ return { body: result.data.body, engagement: result.data.engagement };
42
+ }
43
+ return result.status === NOT_FOUND ? undefined : refusalOf(result);
44
+ };
45
+ export const readingHistory = (cfg, io, accessToken, id) => io.api(accessToken, `${cfg.apiUrl}/memories/${encodeURIComponent(id)}/engagement`);
46
+ export const CAPTURE_ENGAGEMENT_USAGE = 'Usage: lattris capture engagement <source-id> [--impressions N] [--likes N] [--comments N] [--shares N] [--as-of <date>]';
47
+ export const CAPTURE_ENGAGEMENT_HELP = `capture engagement — keep the numbers a source had on a day.
48
+
49
+ Lattris never visits the page: the numbers are what you read off it and type
50
+ here. Each run adds one dated reading; none is ever edited, so the history
51
+ shows how the numbers moved.
52
+
53
+ ${CAPTURE_ENGAGEMENT_USAGE}
54
+
55
+ <source-id> a full id or a >=4-char prefix of a source you kept
56
+ --impressions how many saw it
57
+ --likes how many liked it
58
+ --comments how many comments it had
59
+ --shares how many times it was shared
60
+ --as-of the day the numbers were true (2026-11-16, or a full time
61
+ with its zone); default now, and no more than a day ahead
62
+
63
+ Give at least one count, each a whole number, 0 or more. Only you read the
64
+ numbers. lattris get memory <id> prints the latest; --engagement prints every
65
+ reading, latest first.
66
+
67
+ saved → prints the reading.`;
68
+ const formatReadingReceipt = (id, r) => `Saved reading for ${id}\n asOf ${r.asOf}\n ${formatCounts(r)}`;
69
+ export const captureEngagement = async (cfg, io, args) => {
70
+ if (args.length === 0) {
71
+ io.stdout.write(`${CAPTURE_ENGAGEMENT_HELP}\n`);
72
+ return;
73
+ }
74
+ const { flags, positionals, unknown, notAnId } = parseArgs(READING_FLAG_NAMES, args, [0]);
75
+ if (unknown !== undefined) {
76
+ return refusal(`Unknown flag: ${unknown}\n`);
77
+ }
78
+ if (notAnId !== undefined) {
79
+ return refusal(notAnId);
80
+ }
81
+ if (positionals.length !== 1) {
82
+ return refusal(`${CAPTURE_ENGAGEMENT_USAGE}\n`);
83
+ }
84
+ const reading = buildReading(flags, io.store.now());
85
+ if (isRefusal(reading)) {
86
+ return reading;
87
+ }
88
+ const accessToken = await signedIn(io, cfg);
89
+ if (typeof accessToken !== 'string') {
90
+ return accessToken;
91
+ }
92
+ const saved = await postReading(cfg, io, accessToken, positionals[0], reading);
93
+ if (!saved.ok) {
94
+ return refusalOf(saved);
95
+ }
96
+ emit(io, saved.data, saved.rawText, (r) => formatReadingReceipt(positionals[0], r));
97
+ };
98
+ //# sourceMappingURL=engagement.js.map
@@ -12,7 +12,7 @@ export const GET_HELP = [
12
12
  'Usage:',
13
13
  ' lattris get memories [--shared-with-me] [--q <words>] [--type <name>] [--intent <name>] [--with <audience>] [--for <contact> | --for-phone <number>] [--limit <n>] [--cursor <token>] [--content 0|1]',
14
14
  ' lattris get memories --by <owner-handle> [--limit <n>] [--cursor <token>] [--content 0|1]',
15
- ' lattris get memory <website-address|id> [--by <owner-handle>] [--links 0|1] [--depth <n>] [--content 0|1]',
15
+ ' lattris get memory <website-address|id> [--by <owner-handle>] [--links 0|1] [--depth <n>] [--content 0|1] [--engagement]',
16
16
  ' lattris get memory <id-or-prefix> --revision <n> one revision, as history kept it',
17
17
  ' lattris get history <id-or-prefix> [--limit <n>] [--before <operation-id>]',
18
18
  ' lattris get deleted [--limit <n>] [--cursor <token>]',
@@ -31,7 +31,8 @@ export const GET_HELP = [
31
31
  ' --limit <n> page size, 1-100 (default 50)',
32
32
  ' --cursor <token> the nextCursor from a previous page',
33
33
  ' --by <handle> one wall on the website address; an id without a',
34
- ' session needs it, while a full address carries it',
34
+ ' session needs it, while a full address carries it;',
35
+ ' an id shared with you is found without it',
35
36
  ' --shared-with-me list memories other people granted to you; each row',
36
37
  ' names its owner and whether it is on your graph',
37
38
  ' --for <contact> what one of your contacts may see of your memories and',
@@ -54,6 +55,10 @@ export const GET_HELP = [
54
55
  ' field a writer needs (fingerprint, revisionNo, structureHash)',
55
56
  ' --mine (questions) the ones YOU asked, with how each closed',
56
57
  '',
58
+ ' --engagement (a source you own) every dated reading of its numbers,',
59
+ ' latest first. A source you own always shows its latest',
60
+ ' numbers and its text.',
61
+ '',
57
62
  ' --revision <n> the snapshot numbered n: title, words, metadata, its',
58
63
  ' fingerprint and who recorded it. Restore it with',
59
64
  ' `lattris restore memory <id> --revision <n> --base-fingerprint <head>`.',
@@ -66,6 +71,7 @@ export const GET_HELP = [
66
71
  'Your own read of a memory also prints `access`: every allow and deny on it.',
67
72
  '',
68
73
  "A memory's web address is <site>/by/<owner-handle>/memories/<slug>-<memory-handle>.",
74
+ 'A website address keeps its own links, depth and content; a flag typed here wins for that lever.',
69
75
  'A /by read asks for JSON with Accept: application/json; it sends a bearer',
70
76
  'only when the session has a live one. `get memory` prints the address at a TTY.',
71
77
  '',
@@ -1,28 +1,77 @@
1
1
  import { parseArgs } from "../request/flags.js";
2
2
  import { contactIdFor } from "../memory/access.js";
3
3
  import { getRevision } from "../memory/history.js";
4
- import { composeAddress, formatMemoryDetail, formatMemoryPage, formatNodeWalk, ownHandleFor, parseWebsiteMemoryAddress } from "../memory/views.js";
4
+ import { composeAddress, formatMemoryDetail, formatMemoryPage, formatNodeWalk, leversFor, leversInAddress, ownHandleFor, parseWebsiteMemoryAddress } from "../memory/views.js";
5
+ import { ownerSourceFacts, readingHistory } from "../memory/engagement.js";
5
6
  import { emit } from "../render/output.js";
6
7
  import { ambiguousText } from "../render/rows.js";
7
- import { renderRunHint } from "../render/text.js";
8
+ import { renderRunHint, sanitizeForTerminal } from "../render/text.js";
8
9
  import { optionalAccessToken, signedIn } from "../request/access-token.js";
9
10
  import { refusalOf } from "../request/api-fetch.js";
10
- import { refusal } from "../store/exit.js";
11
+ import { EXIT, isRefusal, refusal } from "../store/exit.js";
11
12
  import { loadSession, saveSession } from "../store/session.js";
13
+ import { isUuidKey } from "../store/write-identity.js";
14
+ const valuesOf = (value) => (Array.isArray(value) ? value : [value]);
12
15
  export const buildGetMemoryUrl = (webUrl, ownerHandle, ref, flags) => {
13
16
  const url = new URL(`${webUrl}/by/${encodeURIComponent(ownerHandle)}/memories/${encodeURIComponent(ref)}`);
14
17
  const links = flags.links ?? '1';
15
18
  const bare = links === '0' && flags.depth === undefined && flags.content === undefined;
16
19
  if (!bare) {
17
- url.searchParams.set('links', links);
18
- if (flags.depth !== undefined)
19
- url.searchParams.set('depth', flags.depth);
20
- if (flags.content !== undefined)
21
- url.searchParams.set('content', flags.content);
20
+ for (const value of valuesOf(links)) {
21
+ url.searchParams.append('links', value);
22
+ }
23
+ if (flags.depth !== undefined) {
24
+ for (const value of valuesOf(flags.depth)) {
25
+ url.searchParams.append('depth', value);
26
+ }
27
+ }
28
+ if (flags.content !== undefined) {
29
+ for (const value of valuesOf(flags.content)) {
30
+ url.searchParams.append('content', value);
31
+ }
32
+ }
22
33
  }
23
34
  return url;
24
35
  };
25
- const getMemory = async (cfg, io, idOrAddress, flags, by) => {
36
+ const SHARED_PAGE_SIZE = '100';
37
+ const SHARED_PAGES_MAX = 5;
38
+ const isSharedRow = (row) => typeof row.ownerHandle === 'string' && row.ownerHandle !== '';
39
+ const answersRef = (ref) => (row) => isUuidKey(ref)
40
+ ? row.id === ref.toLowerCase()
41
+ : row.handle === ref.slice(ref.lastIndexOf('-') + 1);
42
+ const sharedRows = async (cfg, io, accessToken, cursor, pagesLeft) => {
43
+ const url = new URL(`${cfg.apiUrl}/memories`);
44
+ url.searchParams.set('sharedWithMe', '1');
45
+ url.searchParams.set('content', '0');
46
+ url.searchParams.set('limit', SHARED_PAGE_SIZE);
47
+ if (cursor !== null) {
48
+ url.searchParams.set('cursor', cursor);
49
+ }
50
+ const result = await io.api(accessToken, url);
51
+ if (!result.ok) {
52
+ return undefined;
53
+ }
54
+ const rows = result.data.items.filter(isSharedRow);
55
+ if (!result.data.nextCursor || pagesLeft === 1) {
56
+ return rows;
57
+ }
58
+ const rest = await sharedRows(cfg, io, accessToken, result.data.nextCursor, pagesLeft - 1);
59
+ return rest === undefined ? undefined : rows.concat(rest);
60
+ };
61
+ const sharedMatches = async (cfg, io, accessToken, ref) => {
62
+ const rows = await sharedRows(cfg, io, accessToken, null, SHARED_PAGES_MAX);
63
+ if (rows === undefined) {
64
+ return [];
65
+ }
66
+ const byId = new Map(rows.filter(answersRef(ref)).map((row) => [row.id, row]));
67
+ return Array.from(byId.values());
68
+ };
69
+ const sharedAmbiguityText = (matches) => 'That handle names memories shared with you by more than one owner.\n' +
70
+ matches
71
+ .map((m) => ` ${m.id} @${sanitizeForTerminal(m.ownerHandle)} ${sanitizeForTerminal(m.title ?? '(untitled)')}\n`)
72
+ .join('') +
73
+ 'Use get memory <id> --by <owner-handle>.\n';
74
+ const getMemory = async (cfg, io, idOrAddress, flags, by, lookShared, withHistory) => {
26
75
  const isAddress = /^https?:\/\//i.test(idOrAddress);
27
76
  const address = isAddress ? parseWebsiteMemoryAddress(cfg.webUrl, idOrAddress) : undefined;
28
77
  if (isAddress && !address) {
@@ -50,25 +99,69 @@ const getMemory = async (cfg, io, idOrAddress, flags, by) => {
50
99
  return refusal('A memory id needs its wall: use get memory <website-address> or get memory <id> --by <owner-handle>.\n');
51
100
  }
52
101
  accessToken ??= await optionalAccessToken(io, cfg);
53
- const url = buildGetMemoryUrl(cfg.webUrl, ownerHandle, address?.ref ?? idOrAddress, flags);
54
- const enveloped = url.search !== '';
102
+ const session = loadSession(io.store);
103
+ const mine = session !== undefined && session.handle === ownerHandle;
104
+ if (withHistory && (!mine || accessToken === undefined)) {
105
+ return refusal('--engagement reads your own sources: sign in, and read one on your own wall.\n');
106
+ }
107
+ const levers = address === undefined ? flags : leversFor(flags, leversInAddress(idOrAddress));
108
+ const url = buildGetMemoryUrl(cfg.webUrl, ownerHandle, address?.ref ?? idOrAddress, levers);
55
109
  const result = await io.api(accessToken, url, {
56
110
  headers: { Accept: 'application/json' },
57
111
  retryAnonymousOn401: true
58
112
  }, 'web');
59
113
  if (!result.ok) {
114
+ if (lookShared &&
115
+ result.body.code === 'memory:not-found' &&
116
+ !address &&
117
+ !by &&
118
+ accessToken !== undefined) {
119
+ const matches = await sharedMatches(cfg, io, accessToken, idOrAddress);
120
+ if (matches.length === 1) {
121
+ return getMemory(cfg, io, matches[0].id, flags, matches[0].ownerHandle, false, withHistory);
122
+ }
123
+ if (matches.length > 1) {
124
+ return refusal(sharedAmbiguityText(matches), EXIT.GENERIC);
125
+ }
126
+ }
60
127
  return refusalOf(result, ambiguousText(result.body) +
61
128
  (result.body.code === 'memory:not-found' && !address && !by
62
129
  ? 'For another wall, use get memory <website-address> or get memory <id> --by <owner-handle>.\n'
63
130
  : ''));
64
131
  }
65
- const record = enveloped ? result.data.node : result.data;
132
+ const data = result.data;
133
+ const record = 'node' in data ? data.node : data;
66
134
  const displayAddress = io.stdout.isTTY
67
135
  ? composeAddress(cfg.webUrl, ownerHandle, record)
68
136
  : undefined;
69
- emit(io, result.data, result.rawText, () => enveloped
70
- ? formatNodeWalk(result.data, displayAddress)
71
- : formatMemoryDetail(result.data, displayAddress));
137
+ if (withHistory && record.type !== 'source') {
138
+ return refusal('--engagement is for a source; this memory is not one.\n');
139
+ }
140
+ const extras = mine && accessToken !== undefined && record.type === 'source' && 'capturedAt' in record
141
+ ? await sourceExtras(cfg, io, accessToken, record.id, withHistory)
142
+ : undefined;
143
+ if (isRefusal(extras)) {
144
+ return extras;
145
+ }
146
+ const whole = extras === undefined
147
+ ? data
148
+ : 'node' in data
149
+ ? Object.assign({}, data, { node: Object.assign({}, data.node, extras) })
150
+ : Object.assign({}, data, extras);
151
+ emit(io, whole, extras === undefined ? result.rawText : JSON.stringify(whole), () => 'node' in whole
152
+ ? formatNodeWalk(whole, displayAddress)
153
+ : formatMemoryDetail(whole, displayAddress));
154
+ };
155
+ const sourceExtras = async (cfg, io, accessToken, id, withHistory) => {
156
+ const owned = await ownerSourceFacts(cfg, io, accessToken, id);
157
+ if (isRefusal(owned) || !withHistory) {
158
+ return owned;
159
+ }
160
+ const history = await readingHistory(cfg, io, accessToken, id);
161
+ if (!history.ok) {
162
+ return refusalOf(history);
163
+ }
164
+ return Object.assign({}, owned, { engagementHistory: history.data.items });
72
165
  };
73
166
  const GET_FLAG_NAMES = {
74
167
  '--by': 'by',
@@ -189,7 +282,8 @@ export const getMemories = async (cfg, io, rest, noun) => {
189
282
  if (sharedWithMeCount > 1) {
190
283
  return refusal('--shared-with-me was given more than once. Send it once.\n');
191
284
  }
192
- const { flags, positionals, unknown, notAnId } = parseArgs(GET_FLAG_NAMES, rest.filter((arg) => arg !== '--shared-with-me'), [0]);
285
+ const withHistory = rest.includes('--engagement');
286
+ const { flags, positionals, unknown, notAnId } = parseArgs(GET_FLAG_NAMES, rest.filter((arg) => arg !== '--shared-with-me' && arg !== '--engagement'), [0]);
193
287
  if (sharedWithMeCount === 1)
194
288
  flags.sharedWithMe = '1';
195
289
  if (unknown) {
@@ -201,6 +295,9 @@ export const getMemories = async (cfg, io, rest, noun) => {
201
295
  return refusal(`Unexpected argument: ${positionals[1]}\n`);
202
296
  }
203
297
  const id = positionals[0];
298
+ if (withHistory && id === undefined) {
299
+ return refusal('--engagement applies to a single source, not the list.\n');
300
+ }
204
301
  if (id !== undefined) {
205
302
  const inapplicable = LIST_ONLY_FLAGS.find((k) => flags[k] !== undefined);
206
303
  if (inapplicable !== undefined) {
@@ -214,9 +311,12 @@ export const getMemories = async (cfg, io, rest, noun) => {
214
311
  if (walkFlag !== undefined) {
215
312
  return refusal(`--${walkFlag} does not apply to a revision read.\n`);
216
313
  }
314
+ if (withHistory) {
315
+ return refusal('--engagement does not apply to a revision read.\n');
316
+ }
217
317
  return getRevision(cfg, io, id, flags.revision);
218
318
  }
219
- return getMemory(cfg, io, id, { links: flags.links, depth: flags.depth, content: flags.content }, flags.by);
319
+ return getMemory(cfg, io, id, { links: flags.links, depth: flags.depth, content: flags.content }, flags.by, true, withHistory);
220
320
  }
221
321
  else if (noun === 'memories') {
222
322
  const walkFlag = WALK_ONLY_FLAGS.find((k) => flags[k] !== undefined);
@@ -0,0 +1,141 @@
1
+ import { READING_FLAG_NAMES, buildReading, givesNumbers, postReading } from "../memory/engagement.js";
2
+ import { readTextFile } from "../memory/capture-common.js";
3
+ import { COUNTS, sourceFacts } from "../memory/views.js";
4
+ import { emit } from "../render/output.js";
5
+ import { sanitizeForTerminal } from "../render/text.js";
6
+ import { signedIn } from "../request/access-token.js";
7
+ import { refusalOf } from "../request/api-fetch.js";
8
+ import { parseArgs } from "../request/flags.js";
9
+ import { isRefusal, refusal } from "../store/exit.js";
10
+ import { SOURCE_SESSION_ID_DOOR, noteWriteHeaders, requireWriteIdentity } from "../store/write-identity.js";
11
+ const CAPTURE_SOURCE_USAGE = 'Usage: lattris capture source <url> [--title-at-source "…"] [--site "…"] [--author "…"] [--published-at <time>] [--title "…"] [--body-file <path>] [--impressions N] [--likes N] [--comments N] [--shares N] [--as-of <date>]';
12
+ export const CAPTURE_SOURCE_HELP = `capture source — keep a link: a page, a post, a video.
13
+
14
+ Lattris never visits the page: its title, site, author and date are what you
15
+ say here.
16
+
17
+ Keeping a link you already keep answers the source you have, even when the
18
+ address differs a little, and changes nothing, so running it again is safe.
19
+
20
+ ${CAPTURE_SOURCE_USAGE}
21
+
22
+ <url> the page's full address, starting https:// or http://
23
+ --title-at-source the page's own title, as the page gives it
24
+ --site the site it is on, such as a publication
25
+ --author who wrote it, as the page says
26
+ --published-at when it was published (ISO 8601, with its time and zone)
27
+ --title your own one line for it
28
+ --body-file a file holding the page's own text, kept with the source
29
+ --impressions how many saw it, as of --as-of
30
+ --likes how many liked it
31
+ --comments how many comments it had
32
+ --shares how many times it was shared
33
+ --as-of the day those numbers were true (2026-11-16, or a full
34
+ time with its zone); default now
35
+
36
+ The text is up to 128KB and only you read it; lattris get memory <id> says it is
37
+ kept, and prints it. Replace or clear it later with lattris update memory.
38
+ Give at least one count to keep the first reading of its numbers with the
39
+ source; each run that gives counts adds one reading. Later readings:
40
+ lattris capture engagement <id>.
41
+
42
+ It is private until you share it (lattris share memory <id> --with <audience>).
43
+ Your thoughts on it go in a note, linked to it with lattris link, from the
44
+ source to the note or from the note to the source; a verb the pair cannot take
45
+ is refused with the ones it can.
46
+
47
+ saved → prints the id and what the source keeps. lattris get memories --type
48
+ source lists your sources, and --q finds one by words of its title or address.`;
49
+ const FACT_FLAG_NAMES = {
50
+ '--title-at-source': 'titleAtSource',
51
+ '--site': 'site',
52
+ '--author': 'author',
53
+ '--published-at': 'publishedAt',
54
+ '--title': 'title'
55
+ };
56
+ const SOURCE_FLAG_NAMES = Object.assign({}, FACT_FLAG_NAMES, READING_FLAG_NAMES, {
57
+ '--body-file': 'bodyFile'
58
+ });
59
+ const CREATED = 201;
60
+ const countFlags = (r) => COUNTS.filter((name) => r[name] !== undefined)
61
+ .map((name) => `--${name} ${r[name]}`)
62
+ .join(' ');
63
+ const formatSourceReceipt = (s, created) => {
64
+ const lines = [
65
+ created ? `Saved source ${s.id}` : `Already kept source ${s.id}; nothing changed.`
66
+ ];
67
+ if (s.title) {
68
+ lines.push(` title ${sanitizeForTerminal(s.title)}`);
69
+ }
70
+ for (const fact of sourceFacts(s)) {
71
+ lines.push(` ${fact}`);
72
+ }
73
+ lines.push(` capturedAt ${s.capturedAt}`);
74
+ return lines.join('\n');
75
+ };
76
+ const bodyText = (io, bodyFile) => {
77
+ if (bodyFile === undefined) {
78
+ return {};
79
+ }
80
+ const text = readTextFile(io, bodyFile);
81
+ return isRefusal(text) ? text : { body: text };
82
+ };
83
+ export const captureSource = async (cfg, io, args) => {
84
+ if (args.length === 0) {
85
+ io.stdout.write(`${CAPTURE_SOURCE_HELP}\n`);
86
+ return;
87
+ }
88
+ const { flags, positionals, unknown } = parseArgs(SOURCE_FLAG_NAMES, args);
89
+ if (unknown !== undefined) {
90
+ return refusal(`Unknown flag: ${unknown}\n`);
91
+ }
92
+ if (positionals.length !== 1) {
93
+ return refusal(`${CAPTURE_SOURCE_USAGE}\n`);
94
+ }
95
+ const text = bodyText(io, flags.bodyFile);
96
+ if (isRefusal(text)) {
97
+ return text;
98
+ }
99
+ const reading = givesNumbers(flags)
100
+ ? buildReading(flags, io.store.now())
101
+ : undefined;
102
+ if (isRefusal(reading)) {
103
+ return reading;
104
+ }
105
+ const identity = requireWriteIdentity(io.store, io.stdin.isTTY, SOURCE_SESSION_ID_DOOR);
106
+ if (isRefusal(identity)) {
107
+ return identity;
108
+ }
109
+ const accessToken = await signedIn(io, cfg);
110
+ if (typeof accessToken !== 'string') {
111
+ return accessToken;
112
+ }
113
+ const facts = {};
114
+ for (const key of Object.values(FACT_FLAG_NAMES)) {
115
+ const value = flags[key];
116
+ if (value !== undefined) {
117
+ facts[key] = value;
118
+ }
119
+ }
120
+ const saved = await io.api(accessToken, `${cfg.apiUrl}/memories/sources`, {
121
+ method: 'POST',
122
+ headers: Object.assign({ 'Content-Type': 'application/json' }, noteWriteHeaders(identity)),
123
+ body: JSON.stringify(Object.assign({ url: positionals[0] }, facts, text))
124
+ });
125
+ if (!saved.ok) {
126
+ return refusalOf(saved);
127
+ }
128
+ const created = saved.status === CREATED;
129
+ if (reading === undefined) {
130
+ emit(io, saved.data, saved.rawText, (s) => formatSourceReceipt(s, created));
131
+ return;
132
+ }
133
+ const kept = await postReading(cfg, io, accessToken, saved.data.id, reading);
134
+ if (!kept.ok) {
135
+ emit(io, saved.data, saved.rawText, (s) => formatSourceReceipt(s, created));
136
+ return refusalOf(kept, `The source is kept, but its numbers were not. Add them with: lattris capture engagement ${saved.data.id} ${countFlags(reading)}\n`);
137
+ }
138
+ const whole = Object.assign({}, saved.data, { engagement: kept.data });
139
+ emit(io, whole, JSON.stringify(whole), (s) => formatSourceReceipt(s, created));
140
+ };
141
+ //# sourceMappingURL=source.js.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -18,6 +18,8 @@ export const UPDATE_HELP = [
18
18
  ' lattris update memory <id> --base-fingerprint <fp> --intent <word>',
19
19
  ' lattris update memory <id> --base-fingerprint <fp> --clear-intent',
20
20
  ' echo "..." | lattris update memory <id> --overwrite --reason "..." replace on purpose',
21
+ ' lattris update memory <source-id> --expected-updated-at <time> --source-body-file <path>',
22
+ ' lattris update memory <source-id> --expected-updated-at <time> --clear-source-body',
21
23
  '',
22
24
  ' --base-fingerprint <fp>',
23
25
  ' a NOTE\u2019s guard: the fingerprint the read you built this edit',
@@ -44,6 +46,12 @@ export const UPDATE_HELP = [
44
46
  ' or video carries no intent and says so.',
45
47
  ' --contributor optional; whose expression this is — a contact id, the same',
46
48
  ' flag capture takes (`lattris contact list` shows yours)',
49
+ ' --source-body-file <path>',
50
+ ' a SOURCE\u2019s own text, replaced whole from this file (up to',
51
+ ' 128KB). Only you read it. A source takes the',
52
+ ' --expected-updated-at guard; a note refuses this flag.',
53
+ ' --clear-source-body',
54
+ ' forget the source\u2019s text',
47
55
  ' --clear-intent remove the declared intent (there is no magic value —',
48
56
  ' "none" is not vocabulary and would refuse)',
49
57
  ' --allow-banned-words',
@@ -52,9 +60,12 @@ export const UPDATE_HELP = [
52
60
  ' names every word found. Rephrase first; override only when',
53
61
  ' the wording is meant.',
54
62
  '',
55
- ' Content arrives on stdin, like capture — no quoting, up to 5MB. Pipe',
63
+ ' Content arrives on stdin, like capture — no quoting, up to 128KB. Pipe',
56
64
  ' nothing and the words are left exactly as they were.',
57
65
  '',
66
+ ' To add a video, paste a YouTube link on a line by itself. Put words in',
67
+ ' [brackets](link) to give it a title.',
68
+ '',
58
69
  ' The write carries the fingerprint you read. If another session changed',
59
70
  ' the note in between, the door refuses (memory:stale-write), nothing is',
60
71
  ' written, your draft is kept under drafts/ in the machine dir (0600) and',
@@ -107,7 +118,8 @@ export const UPDATE_FLAG_NAMES = {
107
118
  '--expected-updated-at': 'expectedUpdatedAt',
108
119
  '--reason': 'reason',
109
120
  '--idempotency-key': 'idempotencyKey',
110
- '--contributor': 'contributor'
121
+ '--contributor': 'contributor',
122
+ '--source-body-file': 'sourceBodyFile'
111
123
  };
112
124
  export const FINGERPRINT_SHAPE = /^[0-9a-f]{64}$/;
113
125
  const ISO_INSTANT = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-]\d{2}:\d{2})$/;
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { parseArgs } from "../request/flags.js";
3
- import { retryWords } from "../memory/capture-common.js";
3
+ import { readTextFile, retryWords } from "../memory/capture-common.js";
4
4
  import { FINGERPRINT_SHAPE, UPDATE_FLAG_NAMES, isIsoInstant } from "../memory/update-help.js";
5
5
  import { composeAddressFor, formatBlockLine, formatMemoryDetail } from "../memory/views.js";
6
6
  import { emit } from "../render/output.js";
@@ -15,7 +15,11 @@ export const updateMemory = async (cfg, io, args) => {
15
15
  const clearIntent = args.includes('--clear-intent');
16
16
  const allowBanned = args.includes('--allow-banned-words');
17
17
  const overwrite = args.includes('--overwrite');
18
- const { flags, positionals, unknown, notAnId } = parseArgs(UPDATE_FLAG_NAMES, args.filter((a) => a !== '--clear-intent' && a !== '--allow-banned-words' && a !== '--overwrite'), [0]);
18
+ const clearSourceBody = args.includes('--clear-source-body');
19
+ const { flags, positionals, unknown, notAnId } = parseArgs(UPDATE_FLAG_NAMES, args.filter((a) => a !== '--clear-intent' &&
20
+ a !== '--allow-banned-words' &&
21
+ a !== '--overwrite' &&
22
+ a !== '--clear-source-body'), [0]);
19
23
  if (unknown) {
20
24
  return refusal(`Unknown flag: ${unknown}\n`);
21
25
  }
@@ -61,6 +65,13 @@ export const updateMemory = async (cfg, io, args) => {
61
65
  if (flags.idempotencyKey !== undefined && !isUuidKey(flags.idempotencyKey)) {
62
66
  return refusal(`--idempotency-key must be the UUID a draft printed: ${flags.idempotencyKey}\n`);
63
67
  }
68
+ if (clearSourceBody && flags.sourceBodyFile !== undefined) {
69
+ return refusal('--source-body-file and --clear-source-body contradict each other; pass one.\n');
70
+ }
71
+ const fileText = flags.sourceBodyFile === undefined ? undefined : readTextFile(io, flags.sourceBodyFile);
72
+ if (isRefusal(fileText)) {
73
+ return fileText;
74
+ }
64
75
  const identity = requireWriteIdentity(io.store, io.stdin.isTTY);
65
76
  if (isRefusal(identity))
66
77
  return identity;
@@ -72,6 +83,7 @@ export const updateMemory = async (cfg, io, args) => {
72
83
  const sendContent = content !== undefined;
73
84
  const sendIntent = flags.intent !== undefined;
74
85
  const sendContributor = flags.contributor !== undefined;
86
+ const sendSourceBody = fileText !== undefined || clearSourceBody;
75
87
  if (sendContributor && !isUuidKey(flags.contributor)) {
76
88
  return refusal(`--contributor must be a valid UUID (contact id): ${flags.contributor}\n`);
77
89
  }
@@ -83,8 +95,9 @@ export const updateMemory = async (cfg, io, args) => {
83
95
  !sendContent &&
84
96
  !sendIntent &&
85
97
  !clearIntent &&
86
- !sendContributor) {
87
- return refusal('Nothing to update: pipe new words in, or pass --title, --ai-summary, --intent, --clear-intent or --contributor.\n');
98
+ !sendContributor &&
99
+ !sendSourceBody) {
100
+ return refusal('Nothing to update: pipe new words in, or pass --title, --ai-summary, --intent, --clear-intent, --contributor, --source-body-file or --clear-source-body.\n');
88
101
  }
89
102
  const accessToken = await signedIn(io, cfg);
90
103
  if (typeof accessToken !== 'string')
@@ -102,6 +115,8 @@ export const updateMemory = async (cfg, io, args) => {
102
115
  body.intent = null;
103
116
  if (sendContributor)
104
117
  body.contributor = flags.contributor;
118
+ if (sendSourceBody)
119
+ body.sourceBody = fileText === undefined ? null : fileText;
105
120
  if (allowBanned)
106
121
  body.allowBannedWords = true;
107
122
  if (overwrite)
@@ -125,7 +140,8 @@ export const updateMemory = async (cfg, io, args) => {
125
140
  ...(sendAiSummary ? { aiSummary: body.aiSummary } : {}),
126
141
  ...(sendIntent || clearIntent ? { intent: body.intent } : {}),
127
142
  ...(sendContent ? { content: body.content } : {}),
128
- ...(sendContributor ? { contributor: body.contributor } : {})
143
+ ...(sendContributor ? { contributor: body.contributor } : {}),
144
+ ...(sendSourceBody ? { sourceBody: body.sourceBody } : {})
129
145
  }
130
146
  });
131
147
  const keepWords = () => saveEditDraft(io.store, positionals[0], editDraft());
@@ -207,7 +223,9 @@ export const updateMemory = async (cfg, io, args) => {
207
223
  sendAiSummary ? 'ai summary' : undefined,
208
224
  sendContent ? 'words' : undefined,
209
225
  sendIntent ? 'intent' : undefined,
210
- clearIntent ? 'intent (cleared)' : undefined
226
+ clearIntent ? 'intent (cleared)' : undefined,
227
+ fileText !== undefined ? 'source text' : undefined,
228
+ clearSourceBody ? 'source text (cleared)' : undefined
211
229
  ]
212
230
  .filter((c) => c !== undefined)
213
231
  .join(' and ');
@@ -4,9 +4,54 @@ import { stripTrailingSlash } from "../store/environment.js";
4
4
  export const formatDeletedLine = (b) => `${b.id} ${b.deletedAt ?? '-'} rev ${b.revisionNo ?? '-'} ${b.fingerprint ?? '-'} ${sanitizeForTerminal(b.title ?? '(untitled)')}`;
5
5
  export const formatDeletedPage = (page) => page.items.map((i) => formatDeletedLine(i)).join('\n');
6
6
  const graphWord = (b) => b.consented === undefined ? '' : `${b.consented ? 'on graph' : 'off graph'} `;
7
+ const rowLabel = (b) => {
8
+ if (b.source === undefined) {
9
+ return sanitizeForTerminal(b.title ?? '(untitled)');
10
+ }
11
+ const named = b.title === null ? b.source.titleAtSource : b.title;
12
+ return `${sanitizeForTerminal(named ?? '(untitled)')} ${sanitizeForTerminal(b.source.url, Infinity)}`;
13
+ };
7
14
  export const formatBlockLine = (b) => b.ownerHandle === undefined
8
- ? `${b.id} ${b.handle} ${b.capturedAt} ${b.intent ?? '-'} ${b.visibility.public ? 'public' : '-'} ${sanitizeForTerminal(b.title ?? '(untitled)')}`
9
- : `${b.id} ${b.handle} ${b.capturedAt} by ${sanitizeForTerminal(b.ownerDisplayName ?? b.ownerHandle)} (@${b.ownerHandle}) ${graphWord(b)}${sanitizeForTerminal(b.title ?? '(untitled)')}`;
15
+ ? `${b.id} ${b.handle} ${b.capturedAt} ${b.intent ?? '-'} ${b.visibility.public ? 'public' : '-'} ${rowLabel(b)}`
16
+ : `${b.id} ${b.handle} ${b.capturedAt} by ${sanitizeForTerminal(b.ownerDisplayName ?? b.ownerHandle)} (@${b.ownerHandle}) ${graphWord(b)}${rowLabel(b)}`;
17
+ export const COUNTS = ['impressions', 'likes', 'comments', 'shares'];
18
+ export const formatCounts = (r) => COUNTS.flatMap((name) => {
19
+ const count = r[name];
20
+ return count === null ? [] : [`${name} ${count}`];
21
+ }).join(' ');
22
+ export const sourceFacts = (s) => {
23
+ if (s.url === undefined) {
24
+ return [];
25
+ }
26
+ const lines = [`url ${sanitizeForTerminal(s.url, Infinity)}`];
27
+ if (s.titleAtSource) {
28
+ lines.push(`page title ${sanitizeForTerminal(s.titleAtSource)}`);
29
+ }
30
+ if (s.site) {
31
+ lines.push(`site ${sanitizeForTerminal(s.site)}`);
32
+ }
33
+ if (s.author) {
34
+ lines.push(`author ${sanitizeForTerminal(s.author)}`);
35
+ }
36
+ if (s.publishedAt) {
37
+ lines.push(`published ${s.publishedAt}`);
38
+ }
39
+ if (s.engagement) {
40
+ lines.push(`numbers ${formatCounts(s.engagement)} (as of ${s.engagement.asOf})`);
41
+ }
42
+ if (s.body !== undefined) {
43
+ lines.push(s.body === null || s.body.length === 0 ? 'text kept no' : 'text kept yes');
44
+ }
45
+ if (s.engagementHistory !== undefined) {
46
+ if (s.engagementHistory.length === 0) {
47
+ lines.push('readings none');
48
+ }
49
+ for (const r of s.engagementHistory) {
50
+ lines.push(`reading ${r.asOf} ${formatCounts(r)}`);
51
+ }
52
+ }
53
+ return lines;
54
+ };
10
55
  const SLUG_MAX = 60;
11
56
  const slugify = (title) => (title ?? '')
12
57
  .toLowerCase()
@@ -42,6 +87,39 @@ export const parseWebsiteMemoryAddress = (webUrl, value) => {
42
87
  return undefined;
43
88
  }
44
89
  };
90
+ const WALK_LEVERS = ['links', 'depth', 'content'];
91
+ export const leversInAddress = (value) => {
92
+ const levers = {};
93
+ if (!URL.canParse(value)) {
94
+ return levers;
95
+ }
96
+ const { searchParams } = new URL(value);
97
+ for (const lever of WALK_LEVERS) {
98
+ const values = searchParams.getAll(lever);
99
+ if (values.length === 1) {
100
+ levers[lever] = values[0];
101
+ }
102
+ if (values.length > 1) {
103
+ levers[lever] = values;
104
+ }
105
+ }
106
+ return levers;
107
+ };
108
+ export const leversFor = (flags, address) => {
109
+ const levers = {};
110
+ const bareTyped = flags.links === '0';
111
+ for (const lever of WALK_LEVERS) {
112
+ const typed = flags[lever];
113
+ const carried = address[lever];
114
+ if (typed !== undefined) {
115
+ levers[lever] = typed;
116
+ }
117
+ else if (carried !== undefined && !bareTyped) {
118
+ levers[lever] = carried;
119
+ }
120
+ }
121
+ return levers;
122
+ };
45
123
  export const ownHandleFor = async (cfg, io, accessToken) => {
46
124
  try {
47
125
  const me = await io.api(accessToken, `${cfg.apiUrl}/person/me`);
@@ -74,6 +152,9 @@ export const formatMemoryDetail = (m, address) => {
74
152
  lines.push(`title ${sanitizeForTerminal(m.title)}`);
75
153
  if (m.source)
76
154
  lines.push(`source ${sanitizeForTerminal(m.source)}`);
155
+ for (const fact of sourceFacts(m)) {
156
+ lines.push(fact);
157
+ }
77
158
  lines.push(`audiences ${formatAudiences(m.audiences)}`);
78
159
  if (Array.isArray(m.access))
79
160
  lines.push(`access ${formatAccess(m.access)}`);
@@ -90,9 +171,12 @@ export const formatMemoryDetail = (m, address) => {
90
171
  if (Array.isArray(m.turns)) {
91
172
  lines.push('', m.turns.map((t) => formatSessionTurn(t)).join('\n\n'));
92
173
  }
93
- else {
174
+ else if (m.url === undefined) {
94
175
  lines.push('', sanitizeForTerminal(m.content ?? '', Infinity));
95
176
  }
177
+ else if (m.body) {
178
+ lines.push('', sanitizeForTerminal(m.body, Infinity));
179
+ }
96
180
  return lines.join('\n');
97
181
  };
98
182
  export const formatMemoryPage = (page, asked) => {
@@ -116,12 +200,21 @@ export const formatFindingAid = (a) => {
116
200
  lines.push(`structure ${a.structureHash}`);
117
201
  return lines.join('\n');
118
202
  };
203
+ const treeOf = (owner) => owner.displayName === null
204
+ ? "on another person's tree"
205
+ : `on ${sanitizeForTerminal(owner.displayName)}'s tree`;
119
206
  export const formatWalkLink = (l) => {
120
207
  const arrow = l.direction === 'out' ? '\u2192' : '\u2190';
121
208
  const title = l.node.title ? ` ${sanitizeForTerminal(l.node.title)}` : '';
122
209
  const reason = l.reason ? ` \u2014 ${sanitizeForTerminal(l.reason, Infinity)}` : '';
123
210
  const dir = l.direction === 'out' ? 'out' : 'in ';
124
- return `${dir} ${sanitizeForTerminal(l.verb)} ${arrow} ${l.node.handle} (${l.node.type})${title}${reason}`;
211
+ const foreign = l.node.foreign;
212
+ if (foreign === undefined) {
213
+ return `${dir} ${sanitizeForTerminal(l.verb)} ${arrow} ${l.node.handle} (${l.node.type})${title}${reason}`;
214
+ }
215
+ const name = l.node.title ? sanitizeForTerminal(l.node.title) : l.node.handle;
216
+ const why = l.reason ? ` \u2014 ${sanitizeForTerminal(l.reason, Infinity)}` : '';
217
+ return `${dir} ${sanitizeForTerminal(l.verb)} ${arrow} ${name} \u00b7 ${treeOf(foreign.owner)}${why}`;
125
218
  };
126
219
  export const formatNodeWalk = (w, address) => {
127
220
  const parts = [
@@ -20,7 +20,9 @@ const LINK_HELP = [
20
20
  ' <from> the cause-side block — full id or a >=4-char prefix; an',
21
21
  ' ambiguous prefix refuses and lists the matches',
22
22
  ' <to> the effect-side block — the FULL id (the wire addresses the',
23
- ' edge by it; it does not search)',
23
+ ' edge by it; it does not search): one of your own, or a',
24
+ ' block on another person’s tree that is public now — only',
25
+ ' references crosses',
24
26
  ' --verb required; the server’s registry is the ONE authority on the',
25
27
  ' vocabulary — an unknown verb refuses WITH the accepted set',
26
28
  ' for the exact pair sent, and the CLI carries no copy',
@@ -7,9 +7,20 @@ import { LINK_HELP, edges } from "./edges.js";
7
7
  import { INVITE_HELP, invites } from "./invite.js";
8
8
  import { ACCEPT_HELP, ACCEPT_USAGE, ASK_HELP, CLOSE_HELP, CLOSE_USAGE, DECLINE_HELP, DECLINE_USAGE, questions } from "./questions.js";
9
9
  import { DENY_HELP, REMOVE_DENY_HELP, SHARE_HELP, UNSHARE_HELP, grants } from "./share.js";
10
- export const listNouns = [contacts, questions, edges, invites, grants, datasets];
10
+ import { SUBSCRIBE_HELP, subscribers, subscriptions } from "./subscribers.js";
11
+ export const listNouns = [
12
+ contacts,
13
+ questions,
14
+ edges,
15
+ invites,
16
+ grants,
17
+ datasets,
18
+ subscribers,
19
+ subscriptions
20
+ ];
11
21
  export const listVerbs = {
12
22
  ask: { help: ASK_HELP, helpBeforeAuth: true },
23
+ subscribe: { help: SUBSCRIBE_HELP, helpBeforeAuth: true },
13
24
  close: {
14
25
  help: CLOSE_HELP,
15
26
  helpBeforeAuth: true,
@@ -1,6 +1,10 @@
1
1
  import { formatContact } from "../render/rows.js";
2
2
  import { sanitizeForTerminal } from "../render/text.js";
3
- const inviteLink = (webUrl, token) => `${webUrl}/i/${token}`;
3
+ export const inviteLink = (webUrl, token) => `${webUrl}/i/${token}`;
4
+ const NOT_EMAILED = 'Not emailed: an internal Lattris address. Hand them this link.';
5
+ export const mintedLines = (webUrl, minted, address) => `${minted.emailed ? `Sending the invite to ${address}.` : NOT_EMAILED}\n\n` +
6
+ ` ${inviteLink(webUrl, minted.token)}\n\n` +
7
+ `You can see it again with: lattris get invites`;
4
8
  const formatInvite = (webUrl, i) => {
5
9
  const label = i.targetName ? ` — ${sanitizeForTerminal(i.targetName)}` : '';
6
10
  const admits = i.email ? `\n admits ${sanitizeForTerminal(i.email)}` : '';
@@ -12,18 +16,18 @@ const formatInvite = (webUrl, i) => {
12
16
  }
13
17
  if (i.revokedAt)
14
18
  return `revoked${label}${admits}\n minted ${i.createdAt}`;
19
+ if (i.email === null || i.token === null) {
20
+ return `out of date${label}\n minted ${i.createdAt}`;
21
+ }
15
22
  return `live${label}${admits}\n ${inviteLink(webUrl, i.token)}\n minted ${i.createdAt}`;
16
23
  };
17
24
  const INVITE_HELP = [
18
25
  'invite — bring one person in.',
19
26
  '',
20
- 'Mints a single-use invitation and prints the link. Hand it to ONE person.',
21
- 'It is spent when someone signs up with it.',
22
- '',
23
- 'AN INVITATION IS NOT PERMISSION. It records who brought someone. Whether an',
24
- 'address may register at all is a separate decision, made by hand — so a',
25
- 'person can hold a good invitation and still be turned away. Tell them that',
26
- 'when you send it.',
27
+ 'Mints a single-use invitation, emails the link to the address it admits,',
28
+ 'and prints it. Only an account signed in with that address can take it, and',
29
+ 'it is spent when it is taken. An invitation from the Lattris account to a',
30
+ 'lattris.com address is not emailed: hand the person the link.',
27
31
  '',
28
32
  'Usage:',
29
33
  ' lattris invite <contact-name-or-id> [--email <address>] [--yes]',
@@ -93,12 +97,7 @@ const inviteVerb = {
93
97
  : context.recordedEmail
94
98
  ? `Recorded ${admitted} on ${sanitizeForTerminal(contact.displayName)}.\n\n`
95
99
  : '';
96
- return (first +
97
- `Invitation minted${i.targetName ? ` for ${sanitizeForTerminal(i.targetName)}` : ''}, admitting ${admitted}.\n\n` +
98
- ` ${inviteLink(context.webUrl, i.token)}\n\n` +
99
- `Hand it to ONE person — it is spent when someone signs up with it.\n` +
100
- `It is not permission to join; whether they may register is decided separately.\n` +
101
- `You can see it again with: lattris get invites`);
100
+ return first + mintedLines(context.webUrl, i, admitted);
102
101
  }
103
102
  }
104
103
  };
@@ -0,0 +1,163 @@
1
+ import { sanitizeForTerminal } from "../render/text.js";
2
+ import { mintedLines } from "./invite.js";
3
+ import { verbsOf } from "./form.js";
4
+ const relationWords = (relation) => relation.replace(/-/g, ' ');
5
+ export const formatSubscriber = (s, asking = false) => `${sanitizeForTerminal(s.email)} · ${sanitizeForTerminal(s.status)} · ${s.id}` +
6
+ `${s.name ? ` · ${sanitizeForTerminal(s.name)}` : ''}` +
7
+ `${s.relation ? ` · ${sanitizeForTerminal(relationWords(s.relation))}` : ''}` +
8
+ `${s.wantsAccess && !asking ? ' · wants to try Lattris' : ''}` +
9
+ `${s.reason ? ` · “${sanitizeForTerminal(s.reason)}”` : ''}`;
10
+ export const SUBSCRIBE_HELP = [
11
+ 'subscribe — leave your email on someone’s public page, to stay in touch.',
12
+ '',
13
+ 'Needs no account and no session: a reader’s own AI can do it for them. The',
14
+ 'page owner reads the list; nothing is sent to the address but a confirmation,',
15
+ 'and the subscription stands only once that confirmation is clicked.',
16
+ '',
17
+ 'Usage:',
18
+ ' lattris subscribe <handle> <email> [--try]',
19
+ '',
20
+ ' <handle> the page’s address, as it appears at /by/<handle>',
21
+ ' <email> the address the confirmation goes to',
22
+ ' --try say you would like to try Lattris',
23
+ '',
24
+ 'The answer is the same whatever is already true about the address: "Check',
25
+ 'your inbox to confirm." An address already confirmed is sent nothing; one',
26
+ 'that asked recently waits a minute between confirmations, three a day.',
27
+ 'The confirm page the email links to asks the optional questions. A page',
28
+ 'with nothing public, or a handle that names nobody, is answered not found,',
29
+ 'and the two are not told apart.'
30
+ ].join('\n');
31
+ const SUBSCRIBERS_HELP = [
32
+ 'subscribers — the readers who left their email on your public page.',
33
+ '',
34
+ 'Usage:',
35
+ ' lattris subscribers list [--status pending|confirmed|unsubscribed] [--wants-access]',
36
+ ' every subscriber of yours, newest first;',
37
+ ' --wants-access: only the ones who asked to',
38
+ ' try Lattris',
39
+ ' lattris subscribers get <id> one subscriber, by its full id or a unique prefix',
40
+ ' lattris subscribers delete <id> [--yes] forget one: their address and answers are',
41
+ ' deleted; asks at a terminal, needs --yes on a pipe',
42
+ ' lattris subscribers admit <id> [--yes] invite one who asked to try Lattris; asks at a',
43
+ ' terminal, needs --yes on a pipe',
44
+ '',
45
+ 'A subscriber is not an account and not a contact: an address, whether it was',
46
+ 'confirmed, and what the reader chose to say (a name, how they know you, what',
47
+ 'brought them, whether they would like to try Lattris). pending has not clicked',
48
+ 'the confirmation yet and is forgotten with its link after seven days;',
49
+ 'unsubscribed stays, with the answers cleared, so a return needs a fresh',
50
+ 'confirmation.'
51
+ ].join('\n');
52
+ const subscribeVerb = {
53
+ verb: 'subscribe',
54
+ form: {
55
+ usage: 'Usage: lattris subscribe <handle> <email> [--try]',
56
+ switches: ['--try'],
57
+ positionals: 2,
58
+ credential: 'none',
59
+ request: {
60
+ method: 'POST',
61
+ path: '/by/{p0}/subscribers',
62
+ body: {
63
+ email: { positional: 1, trim: true },
64
+ wantsAccess: { switch: '--try', value: true }
65
+ }
66
+ },
67
+ render: (data) => sanitizeForTerminal(data.message)
68
+ }
69
+ };
70
+ export const subscriptions = {
71
+ name: 'subscriptions',
72
+ words: { singular: 'subscription', plural: 'subscriptions' },
73
+ help: SUBSCRIBE_HELP,
74
+ verbs: [subscribeVerb]
75
+ };
76
+ export const subscribers = {
77
+ name: 'subscribers',
78
+ words: { singular: 'subscribers', plural: 'subscribers' },
79
+ grammar: 'noun-first',
80
+ help: SUBSCRIBERS_HELP,
81
+ helpBeforeAuth: true,
82
+ unknownVerb: 'Unknown subscribers verb: {verb}\n\n' + SUBSCRIBERS_HELP + '\n',
83
+ verbs: verbsOf({
84
+ list: {
85
+ usage: 'Usage: lattris subscribers list [--status pending|confirmed|unsubscribed] [--wants-access]',
86
+ flags: { '--status': 'status' },
87
+ switches: ['--wants-access'],
88
+ positionals: 0,
89
+ unknownFlagIsUsage: true,
90
+ request: {
91
+ method: 'GET',
92
+ path: '/subscribers',
93
+ query: {
94
+ status: { flag: 'status' },
95
+ wantsAccess: { switch: '--wants-access', value: 'true' }
96
+ }
97
+ },
98
+ render: (list, context) => {
99
+ const rows = list;
100
+ const asking = context.on.has('--wants-access');
101
+ if (rows.length === 0) {
102
+ return asking
103
+ ? 'Nobody has asked to try Lattris yet.'
104
+ : 'No subscribers yet. Nobody has left their email on your page.';
105
+ }
106
+ return rows.map((s) => formatSubscriber(s, asking)).join('\n');
107
+ }
108
+ },
109
+ get: {
110
+ usage: 'Usage: lattris subscribers get <id>',
111
+ positionals: 1,
112
+ idPositionals: [0],
113
+ unknownFlagIsUsage: true,
114
+ request: { method: 'GET', path: '/subscribers/{p0}' },
115
+ render: (s) => formatSubscriber(s)
116
+ },
117
+ delete: {
118
+ usage: 'Usage: lattris subscribers delete <id> [--yes]',
119
+ switches: ['--yes'],
120
+ positionals: 1,
121
+ idPositionals: [0],
122
+ steps: {
123
+ pipedNeedsYes: {
124
+ message: 'Refusing to forget a subscriber without confirmation on a non-interactive session. Pass --yes to skip the prompt.\n'
125
+ },
126
+ confirm: {
127
+ question: 'Forget subscriber {p0}? Their address and answers are deleted. [y/N] ',
128
+ onNo: { text: 'Cancelled.\n', to: 'stderr' },
129
+ onInterrupted: { text: 'Cancelled.\n', exit: 1 }
130
+ }
131
+ },
132
+ request: { method: 'DELETE', path: '/subscribers/{p0}' },
133
+ renderTo: 'stderr',
134
+ render: (_answer, context) => `Forgot subscriber ${sanitizeForTerminal(context.positionals[0])}`
135
+ },
136
+ admit: {
137
+ usage: 'Usage: lattris subscribers admit <id> [--yes]',
138
+ switches: ['--yes'],
139
+ positionals: 1,
140
+ idPositionals: [0],
141
+ steps: {
142
+ pipedNeedsYes: {
143
+ message: 'Refusing to admit a subscriber without confirmation on a non-interactive session. Pass --yes to skip the prompt.\n'
144
+ },
145
+ subscriber: true,
146
+ confirm: {
147
+ question: 'Invite {subscriber.email} to Lattris? [y/N] ',
148
+ onNo: { text: 'Not invited.\n', to: 'stdout' }
149
+ }
150
+ },
151
+ request: { method: 'POST', path: '/subscribers/{p0}/admit' },
152
+ refusalInstead: {
153
+ 'subscriber:already-invited': '{subscriber.email} already has an invite. Revoke it in Settings to send a new one.\n',
154
+ 'subscriber:already-joined': '{subscriber.email} has already joined.\n'
155
+ },
156
+ render: (data, context) => {
157
+ const i = data;
158
+ return mintedLines(context.webUrl, i, sanitizeForTerminal(i.email));
159
+ }
160
+ }
161
+ })
162
+ };
163
+ //# sourceMappingURL=subscribers.js.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -23,10 +23,14 @@ export const USAGE_LINES = [
23
23
  ' lattris capture memory Capture a memory — `echo "…" | lattris capture memory`',
24
24
  ' lattris capture session <transcript> Save an AI conversation — the whole chain from its file',
25
25
  ' lattris capture recording Keep a recording \u2014 held audio, a source, or a transcript file',
26
+ ' lattris capture source <url> Keep a link \u2014 a page, a post, a video \u2014 with its title, site, author, date, text and numbers',
27
+ ' lattris capture engagement <id> Add a dated reading of a source\u2019s numbers \u2014 impressions, likes, comments, shares',
26
28
  ' lattris get memories List your memories, newest first, with filters (--for <contact> for what they may see)',
27
29
  ' lattris contact create "<name>" Record a person or an AI you work with (--ai, --phone); add, list, get, update, delete, link',
28
30
  ' lattris invite <contact> [--email <address>] Mint an invitation for one of your person contacts, admitting one address',
29
31
  ' lattris get invites List the invitations you have minted',
32
+ ' lattris subscribe <handle> <email> Leave your email on someone’s public page, no account needed (--try)',
33
+ ' lattris subscribers list The readers who left their email on your page (--status, --wants-access); get, delete, admit',
30
34
  ' lattris get memory <id> Read one memory back \u2014 words and edges (--links/--depth/--content)',
31
35
  ' lattris ask <handle> Leave a question on someone\u2019s tree \u2014 `echo "\u2026" | lattris ask <handle>`',
32
36
  ' lattris get questions The questions on your tree, open first (--mine: ones you asked)',
@@ -86,6 +90,8 @@ export const COMMAND_WORDS = new Set([
86
90
  'erase',
87
91
  'resend',
88
92
  'contact',
93
+ 'subscribe',
94
+ 'subscribers',
89
95
  'logout',
90
96
  '--as'
91
97
  ]);
@@ -13,6 +13,8 @@ import { CAPTURE_RECORDING_HELP, captureRecording } from "../memory/recording.js
13
13
  import { updateRecording } from "../memory/recording-update.js";
14
14
  import { RESEND_HELP, resend } from "../memory/resend.js";
15
15
  import { RESTORE_HELP, restoreMemory } from "../memory/restore.js";
16
+ import { CAPTURE_ENGAGEMENT_HELP, captureEngagement } from "../memory/engagement.js";
17
+ import { CAPTURE_SOURCE_HELP, captureSource } from "../memory/source.js";
16
18
  import { UPDATE_HELP } from "../memory/update-help.js";
17
19
  import { updateMemory } from "../memory/update.js";
18
20
  export const memoryNouns = [
@@ -55,6 +57,15 @@ export const memoryNouns = [
55
57
  { verb: 'capture', nouns: ['recording'], handler: captureRecording },
56
58
  { verb: 'update', nouns: ['recording', 'recordings'], handler: updateRecording }
57
59
  ]
60
+ },
61
+ {
62
+ name: 'sources',
63
+ words: { singular: 'source', plural: 'sources' },
64
+ help: CAPTURE_SOURCE_HELP,
65
+ verbs: [
66
+ { verb: 'capture', nouns: ['source'], handler: captureSource },
67
+ { verb: 'capture', nouns: ['engagement'], handler: captureEngagement }
68
+ ]
58
69
  }
59
70
  ];
60
71
  const captureHelp = (args) => {
@@ -66,6 +77,10 @@ const captureHelp = (args) => {
66
77
  return CAPTURE_NOTE_HELP;
67
78
  if (args[0] === 'recording')
68
79
  return CAPTURE_RECORDING_HELP;
80
+ if (args[0] === 'source')
81
+ return CAPTURE_SOURCE_HELP;
82
+ if (args[0] === 'engagement')
83
+ return CAPTURE_ENGAGEMENT_HELP;
69
84
  return CAPTURE_INDEX;
70
85
  };
71
86
  export const memoryVerbs = {
@@ -43,6 +43,8 @@ export const alreadySaved = (sent, current) => {
43
43
  return false;
44
44
  if (sent.contributor !== undefined && sent.contributor !== (current.contributor?.id ?? null))
45
45
  return false;
46
+ if (sent.sourceBody !== undefined && sent.sourceBody !== (current.body ?? null))
47
+ return false;
46
48
  return true;
47
49
  };
48
50
  //# sourceMappingURL=drafts.js.map
@@ -133,16 +133,17 @@ export const resolveWriteIdentityDetail = (store, atTerminal) => {
133
133
  const sessionId = mintTerminalIdentity(store, join(sessionDir(store), 'sessions'), key);
134
134
  return { kind: 'ok', identity: { sessionId, agentLabel } };
135
135
  };
136
- export const requireWriteIdentity = (store, atTerminal) => {
136
+ export const requireWriteIdentity = (store, atTerminal, door = SESSION_ID_DOOR) => {
137
137
  const r = resolveWriteIdentityDetail(store, atTerminal);
138
138
  if (r.kind === 'ok')
139
139
  return r.identity;
140
- return refusal(`${r.kind === 'invalid' ? r.words : SESSION_ID_DOOR}\n`, EXIT.USAGE);
140
+ return refusal(`${r.kind === 'invalid' ? r.words : door}\n`, EXIT.USAGE);
141
141
  };
142
- export const SESSION_ID_DOOR = 'This write changes a note’s history and has to name the session doing it. ' +
143
- 'Off a terminal there is no session to infer: set LATTRIS_SESSION_ID to a stable ' +
142
+ const NAME_THE_SESSION = 'Off a terminal there is no session to infer: set LATTRIS_SESSION_ID to a stable ' +
144
143
  'name for this worker or run (1 to 128 characters), and LATTRIS_AGENT to a readable ' +
145
144
  'label if you want one. Nothing was written.';
145
+ export const SESSION_ID_DOOR = `This write changes a note’s history and has to name the session doing it. ${NAME_THE_SESSION}`;
146
+ export const SOURCE_SESSION_ID_DOOR = `Saving a source has to name the session doing it. ${NAME_THE_SESSION}`;
146
147
  export const noteWriteHeaders = (identity, idempotencyKey) => ({
147
148
  'X-Lattris-Session-Id': identity.sessionId,
148
149
  ...(identity.agentLabel ? { 'X-Lattris-Agent': identity.agentLabel } : {}),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lattris",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
4
4
  "type": "module",
5
5
  "description": "First-party CLI for Lattris — sign in, capture notes and sessions, and read your own tree from the terminal.",
6
6
  "keywords": [