gcf-aif-ext 0.16.1 → 0.18.3

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.
@@ -0,0 +1,228 @@
1
+ // The inbox's categories (Board-PRD §2.6, decision 32): what a record asks of the operator, one
2
+ // per record from a fixed vocabulary. The vocabulary is data in layers merged in the read: this
3
+ // base fits any product, a domain adds its own rows (lib/domain.js: a game's playtest and tune),
4
+ // a project's rows in gcf/config.yml are reserved. The core checks every add and change against
5
+ // the merged list; the board draws from it and hard-codes none of it.
6
+
7
+ /**
8
+ * The screen's groups, top to bottom: Needs you leads and alone counts, the rest waits folded.
9
+ * `order`: `rank` (then the oldest first) or `newest` (the newest first); `holds_later`: the
10
+ * group that holds every record put away to Later, whatever its category.
11
+ */
12
+ export const GROUPS = [
13
+ {
14
+ id: 'needs-you',
15
+ label: 'Needs you',
16
+ help: 'Only you can move these on: the work, or an agent, waits for you',
17
+ folded: false,
18
+ counts: true,
19
+ order: 'rank',
20
+ },
21
+ {
22
+ id: 'to-sort',
23
+ label: 'To sort',
24
+ help: 'Raw input about the product: make an item of it, or erase it',
25
+ folded: false,
26
+ counts: false,
27
+ order: 'rank',
28
+ },
29
+ {
30
+ id: 'agent-feedback',
31
+ label: 'Agent feedback',
32
+ help: "What got in the agents' way, and what they assumed: read when you have time",
33
+ folded: true,
34
+ counts: false,
35
+ order: 'rank',
36
+ },
37
+ {
38
+ id: 'ideas',
39
+ label: 'Ideas & notes',
40
+ help: 'Your shelf: ideas and notes to turn into work later',
41
+ folded: true,
42
+ counts: false,
43
+ order: 'newest',
44
+ },
45
+ {
46
+ id: 'later',
47
+ label: 'Later',
48
+ help: 'What you put away: nothing here asks for you now',
49
+ folded: true,
50
+ counts: false,
51
+ order: 'rank',
52
+ holds_later: true,
53
+ },
54
+ ];
55
+
56
+ /** Where a record comes from: the channel, not its writer's choice. */
57
+ export const ORIGINS = ['you', 'agent', 'automation'];
58
+
59
+ /** The kinds of an agent's lesson (lib/lessons.js asks one question each): a lesson's details. */
60
+ export const LESSON_KINDS = ['tool', 'rules', 'framework', 'template', 'other'];
61
+
62
+ /** A detail: one lowercase word after the category (`lesson:framework`, `request:asset`). */
63
+ export const DETAIL = /^[a-z0-9][a-z0-9-]{0,29}$/;
64
+
65
+ // `set_by`: the origins that may file it; `question`: a question record only (D1, D2), never an
66
+ // entry. `details`: the closed list, or null for a free one. `later`: whether Later may hold it.
67
+ const row = (id, label, help, rank, group, setBy, { details = null, later = true } = {}) => ({
68
+ id,
69
+ label,
70
+ help,
71
+ rank,
72
+ group,
73
+ set_by: setBy,
74
+ details,
75
+ later,
76
+ });
77
+
78
+ /** The framework's base: any product. */
79
+ export const BASE_CATEGORIES = [
80
+ row(
81
+ 'decision',
82
+ 'Decision needed',
83
+ 'A question only you can answer; the work it holds waits for your answer',
84
+ 1,
85
+ 'needs-you',
86
+ ['question'],
87
+ { later: false },
88
+ ),
89
+ row(
90
+ 'failure',
91
+ 'Check failed',
92
+ 'An automatic check broke on the main line: a CI job, a build, a scheduled test',
93
+ 2,
94
+ 'needs-you',
95
+ ['automation'],
96
+ { later: false },
97
+ ),
98
+ row(
99
+ 'request',
100
+ 'Agent request',
101
+ 'What only a person can give: a file, an asset, an account, an access',
102
+ 3,
103
+ 'needs-you',
104
+ ['agent'],
105
+ ),
106
+ row('bug', 'Bug', 'The product does what a rule or a test says it must not', 4, 'to-sort', [
107
+ 'you',
108
+ 'agent',
109
+ 'automation',
110
+ ]),
111
+ row(
112
+ 'finding',
113
+ 'Finding',
114
+ "A remark about the code or the project: a risk, debt, an analyzer's warning, a slow path",
115
+ 6,
116
+ 'to-sort',
117
+ ['agent', 'automation'],
118
+ ),
119
+ row(
120
+ 'unsorted',
121
+ 'Not sorted',
122
+ 'An entry from before the categories: give it one',
123
+ 7,
124
+ 'to-sort',
125
+ [],
126
+ ),
127
+ row('lesson', 'Lesson', "What got in an agent's way in its run", 8, 'agent-feedback', ['agent'], {
128
+ details: LESSON_KINDS,
129
+ }),
130
+ // No Later either (the operator, 2026-10-22): it waits folded already, an answer moves it.
131
+ row(
132
+ 'assumption',
133
+ 'Assumption to check',
134
+ 'A decision an agent took and works with; overrule it if it is wrong',
135
+ 9,
136
+ 'agent-feedback',
137
+ ['question'],
138
+ { later: false },
139
+ ),
140
+ row('idea', 'Idea', 'A change someone proposes, not decided', 10, 'ideas', ['you', 'agent']),
141
+ row('note', 'Note', 'A reminder, a plan, a reference', 11, 'ideas', ['you']),
142
+ ];
143
+
144
+ /**
145
+ * The vocabulary of layers merged, each row with its `layer`, by rank. A domain or a project row
146
+ * that names a base id, or a group the base lacks, is a mistake of its author: thrown.
147
+ */
148
+ export function mergeVocabulary(base, domain = [], project = []) {
149
+ const groups = new Set(GROUPS.map((g) => g.id));
150
+ const seen = new Map();
151
+ for (const [layer, rows] of [
152
+ ['base', base],
153
+ ['domain', domain],
154
+ ['project', project],
155
+ ])
156
+ for (const r of rows) {
157
+ if (seen.has(r.id))
158
+ throw new Error(`inbox category ${r.id} of the ${layer} is named by the ${seen.get(r.id)}`);
159
+ if (!groups.has(r.group)) throw new Error(`inbox category ${r.id}: no group ${r.group}`);
160
+ seen.set(r.id, layer);
161
+ }
162
+ const rows = [
163
+ ...base.map((r) => ({ ...r, layer: 'base' })),
164
+ ...domain.map((r) => ({ ...r, layer: 'domain' })),
165
+ ...project.map((r) => ({ ...r, layer: 'project' })),
166
+ ];
167
+
168
+ return { groups: GROUPS, categories: rows.sort((a, b) => a.rank - b.rank) };
169
+ }
170
+
171
+ /** The base alone: what the core files without a domain (an agent's lessons). */
172
+ export const BASE_VOCABULARY = mergeVocabulary(BASE_CATEGORIES);
173
+
174
+ /** Whether a category belongs to question records only: no entry is filed or moved into it. */
175
+ export const questionOnly = (c) => c.set_by.includes('question');
176
+
177
+ /** The categories `origin` may file, by id. */
178
+ export const fileableBy = (vocab, origin) =>
179
+ vocab.categories.filter((c) => c.set_by.includes(origin)).map((c) => c.id);
180
+
181
+ /** Category `id` of the vocabulary, or the refusal that lists the ones there are. */
182
+ export function categoryOf(vocab, id) {
183
+ const c = vocab.categories.find((x) => x.id === id);
184
+ if (!c)
185
+ throw new Error(
186
+ `no inbox category ${id}: ${vocab.categories.map((x) => x.id).join(' | ')} ` +
187
+ '(ai-factory gcf inbox categories)',
188
+ );
189
+
190
+ return c;
191
+ }
192
+
193
+ /** Refuse a detail that is not one lowercase word, or not of its category's closed list. */
194
+ export function checkDetail(c, detail) {
195
+ if (detail == null) return;
196
+ if (!DETAIL.test(detail))
197
+ throw new Error(`detail "${detail}" must be one lowercase word up to 30: letters, digits, -`);
198
+ if (c.details && !c.details.includes(detail))
199
+ throw new Error(`a ${c.id}'s detail is ${c.details.join(' | ')}`);
200
+ }
201
+
202
+ /** Who makes the move as an origin: an agent's run or session is `agent`, else `you`. */
203
+ export const actorOrigin = (by) => (by === 'operator' ? 'you' : 'agent');
204
+
205
+ /**
206
+ * The lesson kinds met in at least `min` different items, Later left out: an obstacle that
207
+ * repeats is the operator's to remove now (decision 32). Each with its items and records.
208
+ */
209
+ export function lessonRepeats(entries, min = 3) {
210
+ const by = new Map();
211
+ for (const e of entries) {
212
+ if (e.category !== 'lesson' || e.later || !e.detail || !e.item) continue;
213
+ const r = by.get(e.detail) ?? { items: new Set(), records: [] };
214
+ r.items.add(e.item);
215
+ r.records.push(e.id);
216
+ by.set(e.detail, r);
217
+ }
218
+
219
+ return [...by]
220
+ .filter(([, r]) => r.items.size >= min)
221
+ .map(([detail, r]) => ({
222
+ category: 'lesson',
223
+ detail,
224
+ count: r.items.size,
225
+ items: [...r.items],
226
+ records: r.records,
227
+ }));
228
+ }
package/lib/inbox.js CHANGED
@@ -1,9 +1,10 @@
1
1
  // gcf/inbox/ (Methodology §5.1): raw input waiting for triage — playtest notes, CI failures,
2
2
  // the agent's ideas and requests, the operator's ideas and notes, the agents' lessons. One file
3
- // per entry, `gcf/inbox/in-<8 hex>.md`: frontmatter `source`, `at`, `tags` (a lesson also `kind`
4
- // and `item`), then the text as markdown; its first line is its title. Pictures go beside it in
5
- // `in-<hex>/attachments/`. A triaged entry is erased, not marked: the folder holds what still
6
- // waits. Branches add different files, so nothing needs a union merge.
3
+ // per entry, `gcf/inbox/in-<8 hex>.md`: frontmatter `category`, `detail`, `origin`, `later`,
4
+ // `item`, `at` (Board-PRD §2.6, decision 32), then the text as markdown; its first line is its
5
+ // title. Pictures go beside it in `in-<hex>/attachments/`. A triaged entry is erased, not marked:
6
+ // the folder holds what still waits. Branches add different files, so nothing needs a union merge.
7
+ // An entry from before the categories (`source`, `tags`) reads as `inbox migrate` would write it.
7
8
  import { readdir, readFile, rm, unlink } from 'node:fs/promises';
8
9
  import { existsSync } from 'node:fs';
9
10
  import { createHash } from 'node:crypto';
@@ -11,11 +12,21 @@ import { spawnSync } from 'node:child_process';
11
12
  import path from 'node:path';
12
13
  import { parse, serialize } from './frontmatter.js';
13
14
  import { atomicWrite } from './safe-path.js';
15
+ import { moveBy } from './git.js';
16
+ import { isValidId } from './id.js';
17
+ import {
18
+ actorOrigin,
19
+ BASE_CATEGORIES,
20
+ BASE_VOCABULARY,
21
+ categoryOf,
22
+ checkDetail,
23
+ DETAIL,
24
+ fileableBy,
25
+ LESSON_KINDS,
26
+ ORIGINS,
27
+ questionOnly,
28
+ } from './inbox-categories.js';
14
29
 
15
- export const SOURCES = ['playtest', 'ci', 'agent', 'operator'];
16
- export const TAG = /^[a-z0-9][a-z0-9:-]{0,39}$/;
17
- // An agent's lesson (lessons.js) is added as `lesson:<kind>:<item-id>`.
18
- export const LESSON = /^lesson:([a-z]+):([a-z0-9][a-z0-9-]*)$/;
19
30
  const ID = /^in-[0-9a-f]{8}$/;
20
31
 
21
32
  export const inboxDir = (root) => path.join(root, 'inbox');
@@ -38,14 +49,6 @@ export const titleOf = (text) =>
38
49
  /** Text as an entry keeps it: LF line ends, no blank edges, its inner lines as written. */
39
50
  const cleanText = (text) => String(text).replace(/\r\n?/g, '\n').trim();
40
51
 
41
- /** Refuse a tag that is not a lowercase word (`idea`, `later`, `ui:hud`). */
42
- export function checkTags(tags) {
43
- const bad = tags.find((t) => !TAG.test(t));
44
- if (bad !== undefined)
45
- throw new Error(`tag "${bad}" must be a lowercase word: letters, digits, - and :`);
46
- if (new Set(tags).size !== tags.length) throw new Error('a tag is named twice');
47
- }
48
-
49
52
  /** Every file under a folder, deepest last; none when it is not there. */
50
53
  export async function filesUnder(dir) {
51
54
  if (!existsSync(dir)) return [];
@@ -54,12 +57,56 @@ export async function filesUnder(dir) {
54
57
  return entries.filter((e) => e.isFile()).map((e) => path.join(e.parentPath, e.name));
55
58
  }
56
59
 
60
+ // An entry before the categories: its source as a category and the origin it came by.
61
+ const OLD_SOURCES = {
62
+ playtest: ['playtest', 'you'],
63
+ ci: ['failure', 'automation'],
64
+ agent: ['unsorted', 'agent'],
65
+ operator: ['note', 'you'],
66
+ };
67
+
68
+ /**
69
+ * The frontmatter of an entry from before the categories (`source`, `tags`, a lesson's `kind`
70
+ * and `item`) as the categories have it, with what did not fit (Board-PRD §2.6 Migration): the
71
+ * tag `later` becomes the flag, the first other tag the detail, a lesson's kind its detail.
72
+ * Null when it is no old entry.
73
+ * @returns {{data: {category: string, detail: string | null, origin: string, later: boolean,
74
+ * item: string | null}, dropped: string[]} | null}
75
+ */
76
+ export function fromOld({ source, tags = [], kind, item }) {
77
+ const lesson = source === 'lesson' && kind && item;
78
+ const [category, origin] = lesson ? ['lesson', 'agent'] : (OLD_SOURCES[source] ?? []);
79
+ if (!category || !Array.isArray(tags)) return null;
80
+ const words = tags.map(String);
81
+ // Later only where its category may go there: an old CI failure never did.
82
+ const laterOk = BASE_CATEGORIES.find((c) => c.id === category)?.later ?? true;
83
+ const later = words.includes('later') && laterOk;
84
+ const rest = words.filter((t) => t !== 'later');
85
+ let detail = null;
86
+ if (lesson) detail = LESSON_KINDS.includes(String(kind)) ? String(kind) : 'other';
87
+ else if (rest.length) {
88
+ const word = rest[0].replaceAll(':', '-').slice(0, 30).replace(/-+$/, '');
89
+ if (DETAIL.test(word)) {
90
+ detail = word;
91
+ rest.shift();
92
+ }
93
+ }
94
+ const lostLater = words.includes('later') && !laterOk ? ['later (never on its category)'] : [];
95
+
96
+ return {
97
+ data: { category, detail, origin, later, item: lesson ? String(item) : null },
98
+ dropped: [...rest, ...lostLater],
99
+ };
100
+ }
101
+
57
102
  /**
58
103
  * Entry `id` as its file has it, or a reason it is no entry: a name that is no id, frontmatter
59
- * that does not parse, a source the inbox does not know.
60
- * @typedef {{id: string, source: string, at: string | null, title: string, text: string,
61
- * tags: string[], kind?: string, item?: string, attachments?: string[]}} Entry
62
- * @returns {Promise<{entry: Entry} | {bad: string}>}
104
+ * that does not parse, neither a category nor an old source. `old`: written before the
105
+ * categories, read as the migration would write it.
106
+ * @typedef {{id: string, category: string, detail: string | null, origin: string, later: boolean,
107
+ * item: string | null, at: string | null, title: string, text: string,
108
+ * attachments?: string[]}} Entry
109
+ * @returns {Promise<{entry: Entry, old: boolean, dropped: string[]} | {bad: string}>}
63
110
  */
64
111
  async function readEntry(root, name) {
65
112
  const id = name.replace(/\.md$/, '');
@@ -73,28 +120,34 @@ async function readEntry(root, name) {
73
120
 
74
121
  const files = await filesUnder(attachDir(root, id));
75
122
  const attachments = files.map((f) => path.relative(path.dirname(root), f).replaceAll('\\', '/'));
76
- const entry = entryFrom(id, doc, attachments);
77
-
78
- return entry ? { entry } : { bad: `${name}: no known source or tags list` };
79
- }
80
-
81
- /** The entry a parsed file holds, or null when its source or tags are not an entry's. */
82
- function entryFrom(id, { data, body }, attachments) {
83
- const { source, at = null, tags = [], kind, item } = data;
84
- const lesson = source === 'lesson' && kind && item;
85
- if (!(SOURCES.includes(source) || lesson) || !Array.isArray(tags)) return null;
86
- const text = cleanText(body);
87
-
88
- return {
123
+ const old = doc.data.category === undefined ? fromOld(doc.data) : null;
124
+ const fields = old ? old.data : fieldsOf(doc.data);
125
+ if (!fields) return { bad: `${name}: no category, or an origin that is none of ${ORIGINS}` };
126
+ const text = cleanText(doc.body);
127
+ const at = doc.data.at ?? null;
128
+ const entry = {
89
129
  id,
90
- source,
130
+ ...fields,
91
131
  at: at === null ? null : String(at),
92
132
  title: titleOf(text),
93
133
  text,
94
- tags: tags.map(String),
95
- ...(lesson ? { kind: String(kind), item: String(item) } : {}),
96
134
  ...(attachments.length ? { attachments } : {}),
97
135
  };
136
+
137
+ return { entry, old: Boolean(old), dropped: old?.dropped ?? [] };
138
+ }
139
+
140
+ /** The fields of an entry's frontmatter, or null when its category or origin is not one. */
141
+ function fieldsOf({ category, detail = null, origin, later = false, item = null }) {
142
+ if (typeof category !== 'string' || !category || !ORIGINS.includes(origin)) return null;
143
+
144
+ return {
145
+ category,
146
+ detail: detail === null ? null : String(detail),
147
+ origin,
148
+ later: later === true,
149
+ item: item === null ? null : String(item),
150
+ };
98
151
  }
99
152
 
100
153
  /** Each entry and each file that is none, by name. */
@@ -122,11 +175,13 @@ export async function listInbox(root) {
122
175
  /**
123
176
  * What the audit says of the inbox folder: the old one-line file, files that are no entry,
124
177
  * entries without a title, links to attachments that are not there, attachment folders whose
125
- * entry is gone.
178
+ * entry is gone, entries from before the categories, a category `vocab` lacks, unsorted ones.
126
179
  */
127
- export async function inboxProblems(root) {
180
+ export async function inboxProblems(root, vocab = BASE_VOCABULARY) {
128
181
  const all = await readAll(root);
129
- const entries = all.flatMap((r) => ('entry' in r ? [r.entry] : []));
182
+ const read = all.flatMap((r) => ('entry' in r ? [r] : []));
183
+ const entries = read.map((r) => r.entry);
184
+ const known = new Set(vocab.categories.map((c) => c.id));
130
185
  const dir = inboxDir(root);
131
186
  const folders = existsSync(dir)
132
187
  ? (await readdir(dir, { withFileTypes: true })).filter((d) => d.isDirectory())
@@ -143,22 +198,33 @@ export async function inboxProblems(root) {
143
198
  untitled: entries.filter((e) => !e.title).map((e) => e.id),
144
199
  broken_links: brokenLinks,
145
200
  orphan_dirs: folders.filter((d) => !existsSync(fileOf(root, d.name))).map((d) => d.name),
201
+ unmigrated: read.filter((r) => r.old).map((r) => r.entry.id),
202
+ unknown_category: entries.filter((e) => !known.has(e.category)).map((e) => e.id),
203
+ unsorted: entries.filter((e) => e.category === 'unsorted').map((e) => e.id),
146
204
  };
147
205
  }
148
206
 
149
207
  /** Entry `id`, or the refusal for an id the inbox does not hold. */
150
- async function entryOf(root, id) {
208
+ export async function inboxEntry(root, id) {
151
209
  const r = ID.test(id) && existsSync(fileOf(root, id)) ? await readEntry(root, `${id}.md`) : null;
152
210
  if (!r || !('entry' in r)) throw new Error(`${id} is not in gcf/inbox/`);
153
211
 
154
212
  return r.entry;
155
213
  }
156
214
 
157
- const fileText = (e) => {
158
- const lesson = e.source === 'lesson' ? { kind: e.kind, item: e.item } : {};
159
-
160
- return serialize({ source: e.source, at: e.at, tags: e.tags, ...lesson }, `${e.text}\n`);
161
- };
215
+ // Only what a field holds: no `detail: null`, no `later: false`.
216
+ const fileText = (e) =>
217
+ serialize(
218
+ {
219
+ category: e.category,
220
+ ...(e.detail ? { detail: e.detail } : {}),
221
+ origin: e.origin,
222
+ ...(e.later ? { later: true } : {}),
223
+ ...(e.item ? { item: e.item } : {}),
224
+ at: e.at,
225
+ },
226
+ `${e.text}\n`,
227
+ );
162
228
 
163
229
  /**
164
230
  * The id `seed` hashes to, hashed again while the folder holds it or `taken` (the ids a batch
@@ -172,65 +238,159 @@ function freeId(root, seed, taken) {
172
238
  }
173
239
  }
174
240
 
241
+ /**
242
+ * The origin of a new entry: `origin` when given, else who makes the move (`by`, moveBy). An
243
+ * agent's run or session files as `agent` only: the channel, not the writer, says where it
244
+ * came from (Board-PRD §2.6).
245
+ */
246
+ function originOf(origin, by) {
247
+ const actor = actorOrigin(by);
248
+ if (origin === undefined) return actor;
249
+ if (!ORIGINS.includes(origin)) throw new Error(`origin must be ${ORIGINS.join(' | ')}`);
250
+ if (actor === 'agent' && origin !== 'agent')
251
+ throw new Error(`an agent files as agent, not ${origin}: leave --origin out`);
252
+
253
+ return origin;
254
+ }
255
+
175
256
  /**
176
257
  * A new entry's plan: its file and how to write it. Its id hashes the text and the moment
177
- * (`now`), so two branches never collide; a clash in this folder hashes again.
258
+ * (`now`), so two branches never collide; a clash in this folder hashes again. The category
259
+ * must be one its origin may file in `vocab`; a lesson's detail is its kind.
178
260
  */
179
261
  export function planAdd(
180
262
  root,
181
263
  text,
182
- source = 'operator',
183
- { now = new Date().toISOString(), tags = [], taken = new Set() } = {},
264
+ {
265
+ category,
266
+ detail = null,
267
+ origin,
268
+ item = null,
269
+ by = moveBy(),
270
+ vocab = BASE_VOCABULARY,
271
+ now = new Date().toISOString(),
272
+ taken = new Set(),
273
+ } = {},
184
274
  ) {
185
275
  const clean = cleanText(text);
186
276
  if (!clean) throw new Error('an inbox entry needs text');
187
- const lesson = String(source).match(LESSON);
188
- if (!SOURCES.includes(source) && !lesson)
189
- throw new Error(`source must be ${SOURCES.join(' | ')}`);
190
- checkTags(tags);
277
+ if (!category)
278
+ throw new Error(
279
+ `name its --category: ${fileableBy(vocab, actorOrigin(by)).join(' | ')} ` +
280
+ '(ai-factory gcf inbox categories)',
281
+ );
282
+ const c = categoryOf(vocab, category);
283
+ const from = originOf(origin, by);
284
+ if (questionOnly(c))
285
+ throw new Error(`a ${c.id} is an open question, not an entry: ai-factory gcf question add`);
286
+ if (!c.set_by.includes(from))
287
+ throw new Error(
288
+ `${from} files no ${c.id}: ${fileableBy(vocab, from).join(' | ') || 'none'} ` +
289
+ '(ai-factory gcf inbox categories)',
290
+ );
291
+ checkDetail(c, detail);
292
+ if (item !== null && !isValidId(item)) throw new Error(`${item} is not an item id`);
191
293
  const id = freeId(root, `${now}\n${clean}`, taken);
192
294
  const entry = {
193
295
  id,
194
- source: lesson ? 'lesson' : source,
296
+ category: c.id,
297
+ detail,
298
+ origin: from,
299
+ later: false,
300
+ item,
195
301
  at: now,
196
302
  title: titleOf(clean),
197
303
  text: clean,
198
- tags,
199
- ...(lesson ? { kind: lesson[1], item: lesson[2] } : {}),
200
304
  };
201
305
  const file = fileOf(root, id);
202
306
 
203
307
  return { entry, files: [file], apply: () => atomicWrite(file, fileText(entry)) };
204
308
  }
205
309
 
206
- /** Tags added to entry `id` and others removed; refuses one it has, or lacks, already. */
207
- export async function planTag(root, id, { add = [], remove = [] }) {
208
- if (!add.length && !remove.length) throw new Error('name tags to --add or --remove');
209
- checkTags([...add, ...remove]);
210
- const retag = (entry) => {
211
- const had = add.filter((x) => entry.tags.includes(x));
212
- if (had.length) throw new Error(`${id} is tagged ${had.join(', ')} already`);
213
- const missing = remove.filter((x) => !entry.tags.includes(x));
214
- if (missing.length) throw new Error(`${id} has no tag ${missing.join(', ')}`);
215
-
216
- return [...entry.tags.filter((x) => !remove.includes(x)), ...add];
217
- };
218
-
219
- const plan = { tags: retag(await entryOf(root, id)), files: [fileOf(root, id)], apply };
310
+ /**
311
+ * Plan a change of entry `id` (`change(entry)` gives the new one, or throws) read again under
312
+ * the move's lock where it writes: a change made meanwhile is not lost. An entry from before the
313
+ * categories is written as they have it.
314
+ */
315
+ async function planChange(root, id, change) {
316
+ const plan = { entry: change(await inboxEntry(root, id)), files: [fileOf(root, id)], apply };
220
317
 
221
- // Read again where the move writes, under its lock: a tag set meanwhile is not lost.
222
318
  async function apply() {
223
- const entry = await entryOf(root, id);
224
- plan.tags = retag(entry);
225
- await atomicWrite(fileOf(root, id), fileText({ ...entry, tags: plan.tags }));
319
+ plan.entry = change(await inboxEntry(root, id));
320
+ await atomicWrite(fileOf(root, id), fileText(plan.entry));
226
321
  }
227
322
 
228
323
  return plan;
229
324
  }
230
325
 
326
+ /**
327
+ * Entry `id` moved to `category` (its own when none) with `detail` (none when the category
328
+ * changes and no detail is given). The operator moves it to any category but a question's and
329
+ * `unsorted`; an agent only to one it may file. Its origin stays: it says where it came from.
330
+ */
331
+ export async function planCategory(
332
+ root,
333
+ id,
334
+ { category, detail, by = moveBy(), vocab = BASE_VOCABULARY } = {},
335
+ ) {
336
+ if (category === undefined && detail === undefined)
337
+ throw new Error('name a --category, a --detail, or both');
338
+
339
+ return planChange(root, id, (e) => {
340
+ const c = categoryOf(vocab, category ?? e.category);
341
+ const actor = actorOrigin(by);
342
+ if (questionOnly(c) || !c.set_by.length)
343
+ throw new Error(
344
+ `no entry moves into ${c.id}: ${c.set_by.length ? 'it is an open question' : 'it is for entries from before the categories'}`,
345
+ );
346
+ if (actor === 'agent' && !c.set_by.includes('agent'))
347
+ throw new Error(
348
+ `an agent moves no entry into ${c.id}: ${fileableBy(vocab, 'agent').join(' | ')}`,
349
+ );
350
+ const next = detail === undefined ? (c.id === e.category ? e.detail : null) : detail || null;
351
+ checkDetail(c, next);
352
+ if (c.id === e.category && next === e.detail)
353
+ throw new Error(`${id} is ${c.id}${next ? `:${next}` : ''} already`);
354
+
355
+ return { ...e, category: c.id, detail: next, later: e.later && c.later };
356
+ });
357
+ }
358
+
359
+ /** Entry `id` put away to Later (`on`), or back; refused on a category Later never holds. */
360
+ export async function planLater(root, id, on, vocab = BASE_VOCABULARY) {
361
+ return planChange(root, id, (e) => {
362
+ const c = categoryOf(vocab, e.category);
363
+ if (on && !c.later) throw new Error(`a ${c.id} never goes to Later: it waits for you`);
364
+ if (e.later === on) throw new Error(`${id} is ${on ? 'in Later' : 'not in Later'} already`);
365
+
366
+ return { ...e, later: on };
367
+ });
368
+ }
369
+
370
+ /**
371
+ * The entries from before the categories written as they have them (`inbox migrate`): the
372
+ * files, the entries moved, what did not fit (by entry), and how to write them.
373
+ */
374
+ export async function planMigrate(root) {
375
+ const oldOnes = async () =>
376
+ (await readAll(root)).flatMap((r) => ('old' in r && r.old ? [r] : []));
377
+ const old = await oldOnes();
378
+ const ids = new Set(old.map((r) => r.entry.id));
379
+
380
+ return {
381
+ files: old.map((r) => fileOf(root, r.entry.id)),
382
+ migrated: old.map((r) => ({ id: r.entry.id, category: r.entry.category, dropped: r.dropped })),
383
+ // Read again under the move's lock: an entry erased or sorted meanwhile is left as it is.
384
+ apply: async () => {
385
+ for (const r of await oldOnes())
386
+ if (ids.has(r.entry.id)) await atomicWrite(fileOf(root, r.entry.id), fileText(r.entry));
387
+ },
388
+ };
389
+ }
390
+
231
391
  /** Erase entry `id`: its file, its pictures and their folder. */
232
392
  export async function planDrop(root, id) {
233
- await entryOf(root, id);
393
+ await inboxEntry(root, id);
234
394
  // Everything in its folder: what is not under attachments/ goes with it, snapshotted too.
235
395
  const pictures = await filesUnder(path.join(inboxDir(root), id));
236
396
 
@@ -251,7 +411,7 @@ export async function planDrop(root, id) {
251
411
  * may carry edits not yet committed.
252
412
  */
253
413
  export async function planTake(root, id, toDir) {
254
- const entry = await entryOf(root, id);
414
+ const entry = await inboxEntry(root, id);
255
415
  const pictures = await filesUnder(attachDir(root, id));
256
416
  const from = attachDir(root, id);
257
417
  const moves = pictures.map((f) => [f, path.join(toDir, path.relative(from, f))]);
@@ -268,22 +428,14 @@ export async function planTake(root, id, toDir) {
268
428
  };
269
429
  }
270
430
 
271
- /** Add an entry at once (planAdd); returns it. */
272
- export async function addInbox(root, text, source, opts) {
273
- const plan = planAdd(root, text, source, opts);
431
+ /** Add an entry at once (planAdd), the operator's note unless `opts` say; returns it. */
432
+ export async function addInbox(root, text, opts = {}) {
433
+ const plan = planAdd(root, text, { by: 'operator', category: 'note', ...opts });
274
434
  await plan.apply();
275
435
 
276
436
  return plan.entry;
277
437
  }
278
438
 
279
- /** Tag entry `id` at once (planTag); returns its tags. */
280
- export async function tagInbox(root, id, change) {
281
- const plan = await planTag(root, id, change);
282
- await plan.apply();
283
-
284
- return { id, tags: plan.tags };
285
- }
286
-
287
439
  /** Erase entry `id` at once (planDrop). */
288
440
  export async function dropInbox(root, id) {
289
441
  await (await planDrop(root, id)).apply();