gcf-aif-ext 0.10.0 → 0.11.1

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/lib/domain.js CHANGED
@@ -142,6 +142,13 @@ const ITEM_SPECS = {
142
142
  ],
143
143
  rare: true,
144
144
  },
145
+ attach: {
146
+ label: 'attach',
147
+ help: 'Give the item a file (a chat image, a reference): committed in its attachments',
148
+ args: ['gcf', 'item', 'attach', '{id}'],
149
+ fields: [{ key: 'file', label: 'File path', kind: 'text', required: true }],
150
+ rare: true,
151
+ },
145
152
  };
146
153
 
147
154
  // The agent's move: a session of the gcf-run skill builds the item, driven by the harness.
@@ -219,10 +226,10 @@ const BLOCK_SPECS = {
219
226
  },
220
227
  'inbox-add': {
221
228
  label: 'add',
222
- help: 'A raw note for triage: an idea, a playtest note, a CI finding',
229
+ help: 'A raw note for triage (an idea, a playtest note, a CI finding); line 1 is its title',
223
230
  args: ['gcf', 'inbox', 'add', '--commit'],
224
231
  fields: [
225
- { key: 'text', label: 'Text', kind: 'text', required: true },
232
+ { key: 'text', label: 'Text', kind: 'longtext', required: true },
226
233
  {
227
234
  key: 'source',
228
235
  label: 'Source',
package/lib/gcf-paths.js CHANGED
@@ -48,6 +48,29 @@ function runModeOf(v = 'worktree') {
48
48
  return v;
49
49
  }
50
50
 
51
+ // A run's chat with the operator (Harness-PRD §10 "чат"): what the agent asks by a question card
52
+ // (`d1`: only the human's decisions; `all`: every question of substance; `none`: nothing) and
53
+ // how long a question waits for an answer (0: nobody watches, the default answer goes at once).
54
+ export const CHAT_ASK = ['d1', 'all', 'none'];
55
+ export const CHAT_DEFAULTS = { ask: 'd1', answer_timeout_min: 15 };
56
+
57
+ function chatOf(v = {}) {
58
+ if (typeof v !== 'object' || v === null || Array.isArray(v))
59
+ throw new Error('gcf/config.yml: chat must be a key: value mapping');
60
+ const set = Object.fromEntries(Object.entries(v).filter(([, x]) => x !== null));
61
+ const chat = { ...CHAT_DEFAULTS, ...set };
62
+ if (!CHAT_ASK.includes(chat.ask))
63
+ throw new Error(`gcf/config.yml: chat.ask must be ${CHAT_ASK.join(' | ')}, got ${chat.ask}`);
64
+ const min = chat.answer_timeout_min;
65
+ if (!Number.isFinite(min) || min < 0)
66
+ throw new Error(
67
+ 'gcf/config.yml: chat.answer_timeout_min must be a non-negative number, ' +
68
+ `got ${JSON.stringify(min)}`,
69
+ );
70
+
71
+ return chat;
72
+ }
73
+
51
74
  /** @returns {Promise<Record<string, any>>} */
52
75
  export async function readConfig(root) {
53
76
  return configOf(await readRawConfig(root));
@@ -62,7 +85,8 @@ export async function readRawConfig(root) {
62
85
 
63
86
  /**
64
87
  * The config a parsed config.yml gives, checked: defaults for what it does not set, every limit
65
- * a non-negative number, the shares 0-100, the run mode one of RUN_MODES. Throws on the first
88
+ * a non-negative number, the shares 0-100, the run mode one of RUN_MODES, the chat as chatOf
89
+ * checks it. Throws on the first
66
90
  * key that breaks a rule. `gcf config set` checks a change with it before it writes.
67
91
  * @returns {Record<string, any>}
68
92
  */
@@ -96,7 +120,7 @@ export function configOf(parsed) {
96
120
  `(${handoff + 15}), or the compaction comes before the handoff`,
97
121
  );
98
122
 
99
- return { ...config, run_mode: runModeOf(config.run_mode) };
123
+ return { ...config, run_mode: runModeOf(config.run_mode), chat: chatOf(config.chat) };
100
124
  }
101
125
 
102
126
  /** Token estimate: ceil(chars/4). Stability over accuracy (GCF-PRD §9.1). */
package/lib/git.js CHANGED
@@ -28,6 +28,13 @@ const tracked = (projectDir, p) =>
28
28
  spawnSync('git', ['ls-files', '--error-unmatch', '--', p], { cwd: projectDir, stdio: 'ignore' })
29
29
  .status === 0;
30
30
 
31
+ /** Whether the last commit holds `p`: a file only staged is not in it. */
32
+ export const inHead = (projectDir, p) =>
33
+ spawnSync('git', ['ls-tree', '--name-only', 'HEAD', '--', p], {
34
+ cwd: projectDir,
35
+ encoding: 'utf8',
36
+ }).stdout?.trim() !== '';
37
+
31
38
  /**
32
39
  * Paths with uncommitted changes, staged or not. A move stages whole files, so a user's own
33
40
  * edit in one of them would ride along in the move's commit unseen.
@@ -50,8 +57,10 @@ export function dirtyPaths(projectDir, paths) {
50
57
  * is tracked is left out — git refuses a pathspec that matches nothing. Returns the new HEAD.
51
58
  */
52
59
  export function commitPaths(projectDir, message, paths) {
53
- const real = paths.filter((p) => existsSync(p) || tracked(projectDir, p));
54
- for (const p of real) spawnSync('git', ['add', '--', p], { cwd: projectDir, stdio: 'ignore' });
60
+ const staged = paths.filter((p) => existsSync(p) || tracked(projectDir, p));
61
+ for (const p of staged) spawnSync('git', ['add', '--', p], { cwd: projectDir, stdio: 'ignore' });
62
+ // A file staged but never committed and now deleted is out of the index too: no pathspec.
63
+ const real = staged.filter((p) => existsSync(p) || inHead(projectDir, p));
55
64
  const res = spawnSync('git', ['commit', '-m', message, '--only', '--', ...real], {
56
65
  cwd: projectDir,
57
66
  encoding: 'utf8',
package/lib/inbox.js CHANGED
@@ -1,154 +1,311 @@
1
- // gcf/inbox.md (Methodology §5.1): raw input waiting for triage — playtest notes, CI failures,
2
- // the agent's ideas and requests, the operator's ideas and notes. One line per entry,
3
- // `- <in-id> | <source> | <text>[ | tags: a, b]`; a triaged line is erased, not marked: the file
4
- // holds what is still waiting, not what happened to it. Tags sort it; an older core reads the
5
- // tags field as part of the text, which loses nothing.
6
- import { readFile } from 'node:fs/promises';
1
+ // gcf/inbox/ (Methodology §5.1): raw input waiting for triage — playtest notes, CI failures,
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.
7
+ import { readdir, readFile, rm, unlink } from 'node:fs/promises';
7
8
  import { existsSync } from 'node:fs';
8
9
  import { createHash } from 'node:crypto';
10
+ import { spawnSync } from 'node:child_process';
9
11
  import path from 'node:path';
12
+ import { parse, serialize } from './frontmatter.js';
10
13
  import { atomicWrite } from './safe-path.js';
11
14
 
12
- export const INBOX_HEAD =
13
- '# Inbox — `- <in-id> | <source> | <text>[ | tags: a, b]`, raw input waiting for triage; a ' +
14
- 'triaged line is erased\n';
15
15
  export const SOURCES = ['playtest', 'ci', 'agent', 'operator'];
16
- const LINE = /^- (in-[0-9a-f]+) \| (\S+) \| (.+)$/;
17
- // The text may hold ` | ` itself: the tags are only the field at the very end.
18
- const TAGS = / \| tags: ([^|]*)$/;
19
- const TAG = /^[a-z0-9][a-z0-9:-]{0,39}$/;
20
- // An agent's lesson (lessons.js): `lesson:<kind>:<item-id>`.
21
- const LESSON = /^lesson:([a-z]+):([a-z0-9][a-z0-9-]*)$/;
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
+ const ID = /^in-[0-9a-f]{8}$/;
22
20
 
23
- const inboxFile = (root) => path.join(root, 'inbox.md');
21
+ export const inboxDir = (root) => path.join(root, 'inbox');
22
+ const fileOf = (root, id) => path.join(inboxDir(root), `${id}.md`);
23
+ const attachDir = (root, id) => path.join(inboxDir(root), id, 'attachments');
24
24
 
25
- /**
26
- * The text and the tags of a line's last field. A field that is not a clean tag list (a bad
27
- * tag, a tag twice, no text before it) stays part of the text: nothing written is lost.
28
- */
29
- function textAndTags(rest) {
30
- const m = rest.match(TAGS);
31
- const tags = m ? m[1].split(',').map((t) => t.trim()) : [];
32
- const text = m ? rest.slice(0, m.index).trim() : '';
33
- const clean = tags.every((t) => TAG.test(t)) && new Set(tags).size === tags.length;
34
- if (!m || !clean || !text) return { text: rest.trim(), tags: [] };
25
+ /** The one-line inbox of a core before 0.11: read by nothing now, the audit names it. */
26
+ export const legacyInbox = (root) => existsSync(path.join(root, 'inbox.md'));
35
27
 
36
- return { text, tags };
37
- }
28
+ /** An entry's title: its first line with words, without a markdown heading's `#`. */
29
+ export const titleOf = (text) =>
30
+ (
31
+ String(text)
32
+ .split('\n')
33
+ .find((l) => l.trim()) ?? ''
34
+ )
35
+ .trim()
36
+ .replace(/^#{1,6}\s+/, '');
37
+
38
+ /** Text as an entry keeps it: LF line ends, no blank edges, its inner lines as written. */
39
+ const cleanText = (text) => String(text).replace(/\r\n?/g, '\n').trim();
38
40
 
39
- const lineOf = (e) =>
40
- `- ${e.id} | ${e.source} | ${e.text}${e.tags.length ? ` | tags: ${e.tags.join(', ')}` : ''}`;
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
+ }
41
48
 
42
- /** The entry of one line as written, or null. */
43
- function rawOf(line) {
44
- const m = line.match(LINE);
49
+ /** Every file under a folder, deepest last; none when it is not there. */
50
+ async function filesUnder(dir) {
51
+ if (!existsSync(dir)) return [];
52
+ const entries = await readdir(dir, { recursive: true, withFileTypes: true });
45
53
 
46
- return m ? { id: m[1], source: m[2], ...textAndTags(m[3]) } : null;
54
+ return entries.filter((e) => e.isFile()).map((e) => path.join(e.parentPath, e.name));
47
55
  }
48
56
 
49
57
  /**
50
- * One entry per id. A union merge of two branches that tagged an entry differently leaves two
51
- * lines with its id: they read as one, its first line's text with the tags of both.
58
+ * 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}>}
52
63
  */
53
- function mergeById(raws) {
54
- /** @type {Map<string, {id: string, source: string, text: string, tags: string[]}>} */
55
- const byId = new Map();
56
- for (const r of raws) {
57
- const seen = byId.get(r.id);
58
- if (seen) seen.tags = [...new Set([...seen.tags, ...r.tags])];
59
- else byId.set(r.id, { ...r });
64
+ async function readEntry(root, name) {
65
+ const id = name.replace(/\.md$/, '');
66
+ if (!ID.test(id)) return { bad: `${name}: not an entry name (in-<8 hex>.md)` };
67
+ let doc;
68
+ try {
69
+ doc = parse(await readFile(fileOf(root, id), 'utf8'));
70
+ } catch (e) {
71
+ return { bad: `${name}: ${e.message}` };
60
72
  }
61
73
 
62
- return [...byId.values()];
74
+ const files = await filesUnder(attachDir(root, id));
75
+ 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 {
89
+ id,
90
+ source,
91
+ at: at === null ? null : String(at),
92
+ title: titleOf(text),
93
+ text,
94
+ tags: tags.map(String),
95
+ ...(lesson ? { kind: String(kind), item: String(item) } : {}),
96
+ ...(attachments.length ? { attachments } : {}),
97
+ };
98
+ }
99
+
100
+ /** Each entry and each file that is none, by name. */
101
+ async function readAll(root) {
102
+ const dir = inboxDir(root);
103
+ if (!existsSync(dir)) return [];
104
+ const names = (await readdir(dir, { withFileTypes: true }))
105
+ .filter((d) => d.isFile())
106
+ .map((d) => d.name);
107
+
108
+ return Promise.all(names.map((n) => readEntry(root, n)));
63
109
  }
64
110
 
65
111
  /**
66
- * Every entry; a lesson reads as source `lesson` with its `kind` and the `item` it came from.
67
- * @typedef {{id: string, source: string, text: string, tags: string[], kind?: string,
68
- * item?: string}} Entry
112
+ * Every entry, oldest first (an entry without `at` first, then by id). A file that is no entry
113
+ * is left out: the audit names it.
69
114
  * @returns {Promise<Entry[]>}
70
115
  */
71
116
  export async function listInbox(root) {
72
- const file = inboxFile(root);
73
- if (!existsSync(file)) return [];
74
- const raws = (await readFile(file, 'utf8')).split(/\r?\n/).map(rawOf).filter(Boolean);
117
+ const entries = (await readAll(root)).flatMap((r) => ('entry' in r ? [r.entry] : []));
118
+
119
+ return entries.sort((a, b) => (a.at ?? '').localeCompare(b.at ?? '') || a.id.localeCompare(b.id));
120
+ }
75
121
 
76
- return mergeById(/** @type {any[]} */ (raws)).map((entry) => {
77
- const lesson = entry.source.match(LESSON);
122
+ /**
123
+ * What the audit says of the inbox folder: the old one-line file, files that are no entry,
124
+ * entries without a title, links to attachments that are not there, attachment folders whose
125
+ * entry is gone.
126
+ */
127
+ export async function inboxProblems(root) {
128
+ const all = await readAll(root);
129
+ const entries = all.flatMap((r) => ('entry' in r ? [r.entry] : []));
130
+ const dir = inboxDir(root);
131
+ const folders = existsSync(dir)
132
+ ? (await readdir(dir, { withFileTypes: true })).filter((d) => d.isDirectory())
133
+ : [];
134
+ const brokenLinks = entries.flatMap((e) =>
135
+ [...e.text.matchAll(/\]\((in-[0-9a-f]{8}\/attachments\/[^)\s]+)\)/g)]
136
+ .filter((m) => !existsSync(path.join(dir, m[1])))
137
+ .map((m) => `${e.id}: ${m[1]}`),
138
+ );
78
139
 
79
- return lesson ? { ...entry, source: 'lesson', kind: lesson[1], item: lesson[2] } : entry;
80
- });
140
+ return {
141
+ legacy: legacyInbox(root),
142
+ bad_names: all.flatMap((r) => ('bad' in r ? [r.bad] : [])),
143
+ untitled: entries.filter((e) => !e.title).map((e) => e.id),
144
+ broken_links: brokenLinks,
145
+ orphan_dirs: folders.filter((d) => !existsSync(fileOf(root, d.name))).map((d) => d.name),
146
+ };
81
147
  }
82
148
 
83
- /** Refuse a tag that is not a lowercase word (`idea`, `later`, `ui:hud`). */
84
- function checkTags(tags) {
85
- const bad = tags.find((t) => !TAG.test(t));
86
- if (bad !== undefined)
87
- throw new Error(`tag "${bad}" must be a lowercase word: letters, digits, - and :`);
88
- if (new Set(tags).size !== tags.length) throw new Error('a tag is named twice');
149
+ /** Entry `id`, or the refusal for an id the inbox does not hold. */
150
+ async function entryOf(root, id) {
151
+ const r = ID.test(id) && existsSync(fileOf(root, id)) ? await readEntry(root, `${id}.md`) : null;
152
+ if (!r || !('entry' in r)) throw new Error(`${id} is not in gcf/inbox/`);
153
+
154
+ return r.entry;
155
+ }
156
+
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
+ };
162
+
163
+ /**
164
+ * The id `seed` hashes to, hashed again while the folder holds it or `taken` (the ids a batch
165
+ * planned before, not on disk yet) names it.
166
+ */
167
+ function freeId(root, seed, taken) {
168
+ for (let n = 0; ; n++) {
169
+ const salt = n ? `\n${n}` : '';
170
+ const id = `in-${createHash('sha1').update(`${seed}${salt}`).digest('hex').slice(0, 8)}`;
171
+ if (!taken.has(id) && !existsSync(fileOf(root, id))) return id;
172
+ }
89
173
  }
90
174
 
91
175
  /**
92
- * Append an entry with its `tags`; its id hashes the text and the moment (`now`), so two
93
- * branches never collide.
176
+ * 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.
94
178
  */
95
- export async function addInbox(
179
+ export function planAdd(
96
180
  root,
97
181
  text,
98
182
  source = 'operator',
99
- { now = new Date().toISOString(), tags = [] } = {},
183
+ { now = new Date().toISOString(), tags = [], taken = new Set() } = {},
100
184
  ) {
101
- const clean = String(text).replace(/\s+/g, ' ').trim();
185
+ const clean = cleanText(text);
102
186
  if (!clean) throw new Error('an inbox entry needs text');
103
- if (!SOURCES.includes(source) && !LESSON.test(source))
187
+ const lesson = String(source).match(LESSON);
188
+ if (!SOURCES.includes(source) && !lesson)
104
189
  throw new Error(`source must be ${SOURCES.join(' | ')}`);
105
- if (textAndTags(clean).tags.length)
106
- throw new Error('the text ends like a tags field: give tags as tags');
107
190
  checkTags(tags);
108
- const id = `in-${createHash('sha1').update(`${now}\n${clean}`).digest('hex').slice(0, 8)}`;
109
- const file = inboxFile(root);
110
- const old = existsSync(file) ? await readFile(file, 'utf8') : INBOX_HEAD;
111
- const eol = old.includes('\r\n') ? '\r\n' : '\n';
112
- const head = old.endsWith('\n') ? old : old + eol;
113
- const entry = { id, source, text: clean, tags };
114
- await atomicWrite(file, `${head}${lineOf(entry)}${eol}`);
191
+ const id = freeId(root, `${now}\n${clean}`, taken);
192
+ const entry = {
193
+ id,
194
+ source: lesson ? 'lesson' : source,
195
+ at: now,
196
+ title: titleOf(clean),
197
+ text: clean,
198
+ tags,
199
+ ...(lesson ? { kind: lesson[1], item: lesson[2] } : {}),
200
+ };
201
+ const file = fileOf(root, id);
115
202
 
116
- return entry;
203
+ return { entry, files: [file], apply: () => atomicWrite(file, fileText(entry)) };
117
204
  }
118
205
 
119
- /**
120
- * Add tags to entry `id` and remove others; refuses one it has, or lacks, already. Lines a
121
- * union merge doubled become one again, at the first one's place.
122
- */
123
- export async function tagInbox(root, id, { add = [], remove = [] }) {
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 = [] }) {
124
208
  if (!add.length && !remove.length) throw new Error('name tags to --add or --remove');
125
209
  checkTags([...add, ...remove]);
126
- const file = inboxFile(root);
127
- const lines = (existsSync(file) ? await readFile(file, 'utf8') : '').split(/(?<=\n)/);
128
- const bodyOf = (l) => l.replace(/\r?\n$/, '');
129
- const mine = lines.flatMap((l, i) => (rawOf(bodyOf(l))?.id === id ? [i] : []));
130
- if (!mine.length) throw new Error(`${id} is not in gcf/inbox.md`);
131
- const [entry] = mergeById(mine.map((i) => /** @type {any} */ (rawOf(bodyOf(lines[i])))));
132
- const had = add.filter((x) => entry.tags.includes(x));
133
- if (had.length) throw new Error(`${id} is tagged ${had.join(', ')} already`);
134
- const missing = remove.filter((x) => !entry.tags.includes(x));
135
- if (missing.length) throw new Error(`${id} has no tag ${missing.join(', ')}`);
136
- entry.tags = [...entry.tags.filter((x) => !remove.includes(x)), ...add];
137
- // The line keeps its own ending: a CRLF file stays CRLF.
138
- const first = lines[mine[0]];
139
- lines[mine[0]] = `${lineOf(entry)}${first.slice(bodyOf(first).length)}`;
140
- await atomicWrite(file, lines.filter((_, i) => !mine.slice(1).includes(i)).join(''));
141
-
142
- return entry;
143
- }
144
-
145
- /** Erase entry `id`; refuses an id the inbox does not hold. */
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 };
220
+
221
+ // Read again where the move writes, under its lock: a tag set meanwhile is not lost.
222
+ 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 }));
226
+ }
227
+
228
+ return plan;
229
+ }
230
+
231
+ /** Erase entry `id`: its file, its pictures and their folder. */
232
+ export async function planDrop(root, id) {
233
+ await entryOf(root, id);
234
+ // Everything in its folder: what is not under attachments/ goes with it, snapshotted too.
235
+ const pictures = await filesUnder(path.join(inboxDir(root), id));
236
+
237
+ return {
238
+ files: [fileOf(root, id), ...pictures],
239
+ // The pictures first: one a viewer holds stops the erase before the entry is gone.
240
+ apply: async () => {
241
+ for (const f of pictures) await unlink(f);
242
+ await rm(path.join(inboxDir(root), id), { recursive: true, force: true, maxRetries: 3 });
243
+ await unlink(fileOf(root, id));
244
+ },
245
+ };
246
+ }
247
+
248
+ /**
249
+ * Entry `id` taken into an item (`item new --from`): its title, its text, its pictures moved
250
+ * into `toDir`, the entry erased. `files` names every path it touches, `inputs` the ones that
251
+ * may carry edits not yet committed.
252
+ */
253
+ export async function planTake(root, id, toDir) {
254
+ const entry = await entryOf(root, id);
255
+ const pictures = await filesUnder(attachDir(root, id));
256
+ const from = attachDir(root, id);
257
+ const moves = pictures.map((f) => [f, path.join(toDir, path.relative(from, f))]);
258
+ const drop = await planDrop(root, id);
259
+
260
+ return {
261
+ entry,
262
+ files: [...drop.files, ...moves.map((m) => m[1])],
263
+ inputs: drop.files,
264
+ apply: async () => {
265
+ for (const [src, dst] of moves) await atomicWrite(dst, await readFile(src));
266
+ await drop.apply();
267
+ },
268
+ };
269
+ }
270
+
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);
274
+ await plan.apply();
275
+
276
+ return plan.entry;
277
+ }
278
+
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
+ /** Erase entry `id` at once (planDrop). */
146
288
  export async function dropInbox(root, id) {
147
- const file = inboxFile(root);
148
- const text = existsSync(file) ? await readFile(file, 'utf8') : '';
149
- const lines = text.split(/(?<=\n)/);
150
- // Each split line keeps its own ending, and `$` without the m flag does not stop before it.
151
- const kept = lines.filter((l) => l.replace(/\r?\n$/, '').match(LINE)?.[1] !== id);
152
- if (kept.length === lines.length) throw new Error(`${id} is not in gcf/inbox.md`);
153
- await atomicWrite(file, kept.join(''));
289
+ await (await planDrop(root, id)).apply();
290
+ }
291
+
292
+ /**
293
+ * The entry files of `projectDir` git does not track yet: raw input added without a commit, which
294
+ * rides along with the next inbox move.
295
+ */
296
+ export function untrackedEntries(projectDir) {
297
+ const list = (args) =>
298
+ (spawnSync('git', args, { cwd: projectDir, encoding: 'utf8' }).stdout ?? '').split(
299
+ String.fromCharCode(0),
300
+ );
301
+ // Never committed: not tracked at all, or only staged.
302
+ const names = [
303
+ ...list(['ls-files', '--others', '--exclude-standard', '-z', '--', 'gcf/inbox']),
304
+ ...list(['diff', '--cached', '--name-only', '--diff-filter=A', '-z', '--', 'gcf/inbox']),
305
+ ];
306
+
307
+ // Entries and their pictures only: not an editor's swap file, nor a write's tmp in flight.
308
+ return [...new Set(names)]
309
+ .filter((f) => /^gcf\/inbox\/in-[0-9a-f]{8}(\.md|\/attachments\/.+)$/.test(f))
310
+ .map((f) => path.resolve(projectDir, f));
154
311
  }
package/lib/index-gen.js CHANGED
@@ -1,4 +1,4 @@
1
- import { readFile } from 'node:fs/promises';
1
+ import { readdir, readFile } from 'node:fs/promises';
2
2
  import { existsSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { listItems, listSystems, firstBullet } from './gcf-paths.js';
@@ -65,9 +65,12 @@ async function workRows(root, row) {
65
65
  row(['item', `work/${c.name}`, c.data.status ?? '?', system, descr]);
66
66
  }
67
67
 
68
- const inbox = await readIfExists(root, 'inbox.md');
69
- if (inbox !== null)
70
- row(['inbox', 'inbox.md', '-', '-', `${count(inbox, /^- in-\S+ \|/gm)} entries to triage`]);
68
+ const inbox = path.join(root, 'inbox');
69
+ if (existsSync(inbox)) {
70
+ const n = (await readdir(inbox)).filter((f) => /^in-[0-9a-f]{8}\.md$/.test(f)).length;
71
+ row(['inbox', 'inbox/', '-', '-', `${n} entries to triage`]);
72
+ }
73
+
71
74
  const live = await readIfExists(root, 'LIVE.md');
72
75
  if (live === null) return;
73
76
  const { capabilities: caps, knownIssues: known } = parseLive(live);