@iiiokojiadbi/shift 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/core/flows.ts ADDED
@@ -0,0 +1,468 @@
1
+ // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
+ import { OUTCOME, renderAbout, shiftFill } from './about'
3
+ import { addToIndex, checkArchive, indexLine } from './archive'
4
+ import { docsReport, refreshDocs } from './docs'
5
+ import { renderHistory, renderSummary, segment, shiftDir } from './history'
6
+ import {
7
+ ARCHIVE,
8
+ BOARD,
9
+ CLOSED,
10
+ DIR,
11
+ GUIDE_TOOL,
12
+ HOLD,
13
+ INDEX,
14
+ KNOWLEDGE,
15
+ LETTER,
16
+ MAX_AUTO_STREAK,
17
+ NAMES,
18
+ OLD_DIR,
19
+ SETTINGS,
20
+ SHIFTS,
21
+ STUCK_LOOKBACK,
22
+ STUCK_SHIFTS,
23
+ TASK_LIST,
24
+ TASK_SECTIONS,
25
+ TASKS,
26
+ TRACK_TOOL,
27
+ taskFile,
28
+ } from './layout'
29
+ import { formatItem, formatK, itemsOf, sections } from './markdown'
30
+ import { basename, dirname, join, resolvePath } from './paths'
31
+ import type { Project } from './project'
32
+ import { checkLetter, checkTask, checkWork, checkWritten, listedTasks } from './records'
33
+ import { lastShifts, previousShift, readRecords, readSnapshot, readTask, recentShifts, shiftNames, writeSnapshot } from './store'
34
+ import { archiveInList, checkTaskList, formatTaskLine, parseTaskList, withTask } from './tasks'
35
+ import {
36
+ ACCEPTED,
37
+ ARCHIVED,
38
+ continuePrompt,
39
+ deliveredFiles,
40
+ EXCLUDED,
41
+ NOT_IGNORED,
42
+ OPENED,
43
+ resumePrompt,
44
+ waitContext,
45
+ } from './texts/prompts'
46
+ import { CONTINUING, NOT_MADE, renderTasks, type TaskView, UNSETTLED, WAITING } from './texts/rows'
47
+ import type { ArchiveInput, HandedBack, OpenInput, PendingShift, SessionFile, Settled, ShiftInput, Stuck, TaskFiles, Work } from './types'
48
+
49
+ // The flows that do not depend on the harness: an adapter hands them the loaded project and what only it knows.
50
+
51
+ export type ShiftCall = { input: ShiftInput; at: number; sessionId: string }
52
+
53
+ // What the mod last saw of the records: per file, by its path from the project's root, its stamp and a fingerprint of
54
+ // its text as `<stamp>#<fingerprint>`.
55
+ export type Seen = Record<string, string>
56
+
57
+ // Who changed the records since the mod last looked: the agent's own tool — a write, a shell command, a script — or
58
+ // someone else between its tools: the owner's hand, another session.
59
+ export type ChangedBy = 'agent' | 'other'
60
+
61
+ // The records changed since the mod last looked, each checked by the checks of its file, so what the shift would refuse
62
+ // is told as it is written, not hundreds of K later. The agent's own change is told only when broken; someone else's
63
+ // is told always, so the agent reads it before writing over it. The first look only remembers; a removed file is the
64
+ // shift's to tell.
65
+ export async function changedRecords(project: Project, seen: Seen | null, by: ChangedBy): Promise<{ seen: Seen; body: string | null }> {
66
+ if (!project.settings.enabled) return { seen: seen ?? {}, body: null }
67
+ // A new stamp alone is not a change: a file rewritten with the same text, or edited and put back, says nothing.
68
+ const now: Seen = {}
69
+ const changed: string[] = []
70
+ for (const [path, stamp] of Object.entries(await recordStamps(project))) {
71
+ const was = seen?.[path] ?? ''
72
+ const at = was.lastIndexOf('#')
73
+ if (at !== -1 && was.slice(0, at) === stamp) {
74
+ now[path] = was
75
+ continue
76
+ }
77
+ const text = await project.store.read(`${project.root}/${path}`)
78
+ if (text === null) continue
79
+ const hash = String(fingerprint(text))
80
+ now[path] = `${stamp}#${hash}`
81
+ if (seen !== null && was.slice(at + 1) !== hash) changed.push(path)
82
+ }
83
+ if (changed.length === 0) return { seen: now, body: null }
84
+
85
+ const work = await readRecords(project)
86
+ const lines: string[] = []
87
+ let broken = false
88
+ for (const path of changed) {
89
+ const problem = path === LETTER ? await letterProblem(project) : work === null ? null : checkWritten(path, work, project)
90
+ broken ||= problem !== null
91
+ if (by === 'other') lines.push(`\`${path}\` changed outside your tools — by the owner or another session: read it before you write it.`)
92
+ if (problem !== null) lines.push(`\`${path}\`: ${problem}`)
93
+ }
94
+ if (broken) lines.push('The shift refuses until they are fixed; if you are still writing them, go on.')
95
+
96
+ return { seen: now, body: lines.length === 0 ? null : lines.join('\n') }
97
+ }
98
+
99
+ // Every file the record checks look at, by its path from the project's root, with its stamp: a listing per folder,
100
+ // no file read.
101
+ async function recordStamps({ store, root, settings }: Project): Promise<Seen> {
102
+ const stamped = async (dir: string, only?: (name: string) => boolean): Promise<Seen> =>
103
+ Object.fromEntries(
104
+ Object.entries(await store.stamps(join(root, dir)))
105
+ .filter(([name]) => (name.endsWith('.md') || join(dir, name) === SETTINGS) && (only?.(name) ?? true))
106
+ .map(([name, stamp]) => [join(dir, name), stamp]),
107
+ )
108
+ const own = new Set([BOARD, TASK_LIST, LETTER, SETTINGS, settings.files.owner, settings.files.glossary])
109
+ const tasks = await store.list(`${root}/${TASKS}`, 'dir')
110
+ const parts = await Promise.all([
111
+ ...[...new Set([DIR, dirname(settings.files.owner), dirname(settings.files.glossary)])].map(dir =>
112
+ stamped(dir, name => own.has(join(dir, name))),
113
+ ),
114
+ ...tasks.flatMap(name => [
115
+ stamped(`${TASKS}/${name}`, file => file === NAMES.task || file === NAMES.track),
116
+ stamped(`${TASKS}/${name}/${NAMES.notes}`),
117
+ ]),
118
+ stamped(KNOWLEDGE),
119
+ ])
120
+
121
+ return Object.assign({}, ...parts)
122
+ }
123
+
124
+ // FNV-1a over the text: whether a file restamped really changed, without keeping its text.
125
+ function fingerprint(text: string): number {
126
+ let hash = 0x811c9dc5
127
+ for (let i = 0; i < text.length; i++) hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193)
128
+
129
+ return hash >>> 0
130
+ }
131
+
132
+ async function letterProblem({ store, root }: Project): Promise<string | null> {
133
+ const letter = await store.read(`${root}/${LETTER}`)
134
+
135
+ return letter === null ? null : checkLetter(letter)
136
+ }
137
+
138
+ // Checks the letter and the records, snapshots them into the new shift folder and leaves a pending about.md there.
139
+ export async function acceptShift(project: Project, call: ShiftCall): Promise<{ deny: string } | { shift: PendingShift; result: string }> {
140
+ const { store, root, settings } = project
141
+ const { input } = call
142
+ const stale = await staleLayout(project)
143
+ if (stale !== null) return { deny: stale }
144
+ const letter = await store.read(resolvePath(root, input.letter))
145
+ if (letter === null) return { deny: `No letter at ${input.letter}. Write it (usually ${LETTER}) and call again.` }
146
+ const letterProblem = checkLetter(letter)
147
+ if (letterProblem !== null) return { deny: letterProblem }
148
+
149
+ if (settings.enabled) await refreshDocs(project)
150
+ const work = await readRecords(project)
151
+ if (work === null) return { deny: `No board: create ${BOARD} by the sections in ${GUIDE_TOOL} and call again.` }
152
+ const previousDir = await previousShift(project)
153
+ const previous = previousDir === null ? null : await readSnapshot(store, previousDir, `${previousDir}/${NAMES.index}`)
154
+ const workProblem = checkWork(work, previous?.work ?? null, project)
155
+ if (workProblem !== null) return { deny: workProblem }
156
+ const kept = await keepRecordsOut(project)
157
+ if ('deny' in kept) return kept
158
+
159
+ const index = await store.read(`${root}/${INDEX}`)
160
+ const dir = shiftDir(root, call.at)
161
+ const shift: PendingShift = {
162
+ after: input.after,
163
+ letter,
164
+ hold: sections(letter).get(HOLD) ?? '',
165
+ dir,
166
+ board: `${root}/${BOARD}`,
167
+ owner: `${root}/${settings.files.owner}`,
168
+ sessionId: call.sessionId,
169
+ about: input.about,
170
+ at: call.at,
171
+ segment: segment({ work, index }, previous),
172
+ focus: focusOf(work),
173
+ }
174
+ await writeSnapshot(store, dir, { work, letter, index, settings: project.settingsText })
175
+ // Rewritten with the outcome once the turn ends; `pending` stays if the session dies first.
176
+ await store.write(`${dir}/${NAMES.about}`, renderAbout({ ...shift, result: OUTCOME.pending }))
177
+
178
+ // Knowledge is rarely written: a stretch that added none is asked once, while its history is still whole.
179
+ const learned = previous === null || knowledgeText(work) !== knowledgeText(previous.work)
180
+ const accepted = ACCEPTED(dir, learned, input.after)
181
+
182
+ return { shift, result: kept.excluded === null ? accepted : `${EXCLUDED(kept.excluded)}\n\n${accepted}` }
183
+ }
184
+
185
+ // The tasks in progress, each with the names of its items in progress.
186
+ function focusOf(work: Work): string[] {
187
+ return listedTasks(work)
188
+ .filter(listed => listed.status === 'in progress')
189
+ .map(listed => {
190
+ const track = work.tasks.find(task => task.name === listed.name)?.track ?? ''
191
+ const doing = itemsOf(track)
192
+ .filter(item => item.status === 'in progress')
193
+ .map(item => item.name)
194
+
195
+ return doing.length === 0 ? listed.name : `${listed.name}: ${doing.join('; ')}`
196
+ })
197
+ }
198
+
199
+ function knowledgeText(work: Work): string {
200
+ return work.knowledge.map(file => `${file.name}\n${file.text}`).join('\n')
201
+ }
202
+
203
+ // Moves a finished or dropped task's folder to the archive and adds its line to the index.
204
+ // A task opened valid by construction: task.md by its sections, track.md with its first items, and its line with the
205
+ // links in TASKS.md — all checked before anything is written, so a refusal leaves the records as they were.
206
+ export async function openTask(project: Project, input: OpenInput): Promise<{ deny: string } | { result: string }> {
207
+ const { store, root } = project
208
+ const folder = `${root}/${TASKS}/${input.name}`
209
+ if (await store.exists(folder)) return { deny: `${TASKS}/${input.name}/ already exists: set its status with ${TRACK_TOOL}.` }
210
+ const archived = await store.list(`${root}/${ARCHIVE}`, 'dir')
211
+ if (archived.includes(input.name))
212
+ return { deny: `${input.name} is archived: open a task under another name with continues: ${input.name}.` }
213
+ const task: TaskFiles = {
214
+ name: input.name,
215
+ task: renderTask(input),
216
+ track: input.items.map(item => `${formatItem('open', item.name, item.note)}\n`).join(''),
217
+ notes: [],
218
+ }
219
+ const listPath = `${root}/${TASK_LIST}`
220
+ const list = withTask(await store.read(listPath), input, archived)
221
+ const folders = [...(await store.list(`${root}/${TASKS}`, 'dir')), input.name]
222
+ const problem = checkTask(task) ?? checkTaskList(list, folders, archived)
223
+ if (problem !== null) return { deny: `Nothing was written. ${problem}` }
224
+
225
+ await store.write(`${folder}/${NAMES.task}`, task.task ?? '')
226
+ await store.write(`${folder}/${NAMES.track}`, task.track ?? '')
227
+ await store.write(listPath, list)
228
+
229
+ return { result: OPENED(input.name, formatTaskLine(input.status, input.name, input.name, input.about)) }
230
+ }
231
+
232
+ function renderTask(input: OpenInput): string {
233
+ const body: Record<string, string> = { Goal: input.goal, 'Done when': input.doneWhen }
234
+
235
+ return `# ${input.title}\n${TASK_SECTIONS.map(section => `\n## ${section}\n\n${body[section] ?? 'none'}\n`).join('')}`
236
+ }
237
+
238
+ export async function archiveTask(project: Project, input: ArchiveInput): Promise<{ deny: string } | { result: string }> {
239
+ const { store, root } = project
240
+ const from = `${root}/${TASKS}/${input.name}`
241
+ const to = `${root}/${ARCHIVE}/${input.name}`
242
+ const task = await readTask(store, `${root}/${DIR}`, input.name)
243
+ const problem = checkArchive(input, task, await store.exists(to))
244
+ if (problem !== null) return { deny: problem }
245
+
246
+ const listPath = `${root}/${TASK_LIST}`
247
+ const list = await store.read(listPath)
248
+ const listed = list === null ? [] : parseTaskList(list)
249
+ const entry = typeof listed === 'string' ? undefined : listed.find(t => t.name === input.name)
250
+ const continued = (entry?.links ?? []).filter(link => link.kind === 'continues').map(link => link.name)
251
+
252
+ const failed = await store.move(from, to)
253
+ if (failed !== null) return { deny: `Could not move ${from} to ${to}: ${failed}` }
254
+ const index = await store.read(`${root}/${INDEX}`)
255
+ await store.write(`${root}/${INDEX}`, addToIndex(index, indexLine(input, task.task ?? '', continued)))
256
+ if (list !== null) await store.write(listPath, archiveInList(list, input.name))
257
+
258
+ return { result: ARCHIVED(input.name) }
259
+ }
260
+
261
+ export async function shiftHistory(project: Project, count: number): Promise<string> {
262
+ const { entries, total } = await lastShifts(project, count)
263
+
264
+ return renderHistory(entries, total)
265
+ }
266
+
267
+ // The last shift picked up in a session that has not seen it: the text for the owner, and the prompt when there is one.
268
+ export async function resumeShift(project: Project): Promise<{ text: string; prompt?: string }> {
269
+ const dir = await previousShift(project)
270
+ if (dir === null) return { text: `No shifts in this project: ${SHIFTS}/ is empty.` }
271
+ const letter = await project.store.read(`${dir}/${NAMES.letter}`)
272
+ if (letter === null) return { text: `No letter.md in ${dir}/ — nothing to pick up.` }
273
+
274
+ return { text: `Picking up shift ${basename(dir)}.`, prompt: resumePrompt(letter, await handBack(project, dir)) }
275
+ }
276
+
277
+ // The records, the last shifts and the documents' remarks as they are now, for the message after a shift.
278
+ async function handBack(project: Project, dir: string): Promise<HandedBack> {
279
+ return {
280
+ work: await readRecords(project),
281
+ knowledge: project.settings.knowledge,
282
+ owner: project.settings.files.owner,
283
+ recent: await recentShifts(project),
284
+ dir,
285
+ remarks: await docsReport(project),
286
+ stuck: await stuckTasks(project),
287
+ }
288
+ }
289
+
290
+ // The listed tasks whose task.md and track.md are the same in the latest shifts' snapshots as now, through at least
291
+ // STUCK_SHIFTS of them: counted from the snapshots, since the records carry no dates.
292
+ export async function stuckTasks(project: Project): Promise<Stuck[]> {
293
+ const { store, root } = project
294
+ const work = await readRecords(project)
295
+ if (work === null) return []
296
+ const shifts = (await shiftNames(project)).slice(-STUCK_LOOKBACK).reverse()
297
+ const stuck: Stuck[] = []
298
+ for (const listed of listedTasks(work)) {
299
+ const now = work.tasks.find(task => task.name === listed.name)
300
+ if (now === undefined) continue
301
+ let count = 0
302
+ for (const name of shifts) {
303
+ const base = `${root}/${SHIFTS}/${name}`
304
+ const same =
305
+ (await store.read(taskFile(base, listed.name, 'task'))) === now.task &&
306
+ (await store.read(taskFile(base, listed.name, 'track'))) === now.track
307
+ if (!same) break
308
+ count++
309
+ }
310
+ if (count >= STUCK_SHIFTS) stuck.push({ name: listed.name, status: listed.status, shifts: count })
311
+ }
312
+
313
+ return stuck
314
+ }
315
+
316
+ // The harness did not let the history go: about.md says why, the row tells the owner — even when about.md fails.
317
+ export async function shiftNotMade(project: Project, shift: PendingShift, why: string, tokensBefore: number | undefined): Promise<string> {
318
+ const row = NOT_MADE(basename(shift.dir), why)
319
+
320
+ return recordFailure(project, shift, renderAbout({ ...shift, tokensBefore, result: OUTCOME.notShifted(why) }), row)
321
+ }
322
+
323
+ // The harness let the history go, but what follows failed: about.md and the row say so, the letter stays on disk.
324
+ export async function shiftUnsettled(
325
+ project: Project,
326
+ shift: PendingShift,
327
+ why: string,
328
+ tokensBefore: number | undefined,
329
+ ): Promise<string> {
330
+ const row = UNSETTLED(basename(shift.dir), why)
331
+
332
+ return recordFailure(project, shift, renderAbout({ ...shift, tokensBefore, result: OUTCOME.unsettled(why) }), row)
333
+ }
334
+
335
+ // A failure's about.md, written before the row is told; a failed write still leaves the row.
336
+ async function recordFailure(project: Project, shift: PendingShift, about: string, row: string): Promise<string> {
337
+ try {
338
+ await project.store.write(`${shift.dir}/${NAMES.about}`, about)
339
+
340
+ return row
341
+ } catch (error) {
342
+ return `${row} (and ${NAMES.about} was not written: ${String(error)})`
343
+ }
344
+ }
345
+
346
+ export type LetGo = {
347
+ shift: PendingShift
348
+ // What the history was let go into, as the harness gives it back.
349
+ messages: readonly { role: string; text: string }[]
350
+ before: number | undefined
351
+ after: number
352
+ // `continue` shifts in a row without the owner before this one.
353
+ streak: number
354
+ }
355
+
356
+ // After the let-go: the summary and the outcome on disk, then continue, or wait — asked for, or forced after
357
+ // `MAX_AUTO_STREAK` continues in a row without the owner.
358
+ export async function settleShift(project: Project, letGo: LetGo): Promise<Settled> {
359
+ const { store } = project
360
+ const { shift, before, after } = letGo
361
+ const summary = renderSummary(letGo.messages)
362
+ await store.write(`${shift.dir}/${NAMES.summary}`, summary)
363
+ const streak = letGo.streak + 1
364
+ const isCapped = shift.after === 'continue' && streak > MAX_AUTO_STREAK
365
+ const shrank = `${formatK(before ?? 0)} → ${formatK(after)}`
366
+ const outcome = (result: string) =>
367
+ store.write(
368
+ `${shift.dir}/${NAMES.about}`,
369
+ renderAbout({ ...shift, tokensBefore: before, tokensAfter: after, summaryChars: summary.length, result }),
370
+ )
371
+ const back = await handBack(project, shift.dir)
372
+ const name = basename(shift.dir)
373
+
374
+ if (shift.after === 'continue' && !isCapped) {
375
+ await outcome(OUTCOME.continuing(shrank))
376
+
377
+ return {
378
+ after: 'continue',
379
+ streak,
380
+ prompt: continuePrompt(shift.letter, back),
381
+ row: CONTINUING(name, shrank, shift.dir),
382
+ }
383
+ }
384
+
385
+ const why = isCapped ? `waiting: ${MAX_AUTO_STREAK} shifts in a row without the owner` : 'waiting for the owner'
386
+ await outcome(OUTCOME.waiting(shrank, why))
387
+ const note = { context: waitContext(shift.letter, back), dir: shift.dir, files: deliveredFiles(back.work) }
388
+
389
+ return { after: 'wait', note, row: WAITING(name, shrank, isCapped) }
390
+ }
391
+
392
+ // The fill the stretch started from, if the last shift was this session's: a fresh process counts from there.
393
+ export async function shiftBase(project: Project, sessionId: string): Promise<number | null> {
394
+ const dir = await previousShift(project)
395
+ const about = dir === null ? null : await project.store.read(`${dir}/${NAMES.about}`)
396
+
397
+ return about === null ? null : shiftFill(about, sessionId)
398
+ }
399
+
400
+ // Unless the owner lets the project commit them, the records stay out of its git: when they are not ignored, the mod
401
+ // adds them to the repository's own exclude file. The exclude file's path when it did; null when nothing was needed.
402
+ export async function keepRecordsOut(project: Project): Promise<{ excluded: string | null } | { deny: string }> {
403
+ const { store, root } = project
404
+ if (project.settings.commit) return { excluded: null }
405
+ // 1 — not ignored; any other answer, or no git at all, means nothing to keep the records out of.
406
+ const ignored = await store.git(root, ['check-ignore', '-q', DIR])
407
+ if (ignored === null || ignored.code !== 1) return { excluded: null }
408
+ // git names it relative to the root, or absolute in a linked worktree.
409
+ const found = await store.git(root, ['rev-parse', '--git-path', 'info/exclude'])
410
+ const path = found === null || found.code !== 0 ? '' : found.stdout.trim()
411
+ if (path === '') return { deny: NOT_IGNORED }
412
+ const file = path.startsWith('/') ? path : `${root}/${path}`
413
+ const text = (await store.read(file)) ?? ''
414
+ await store.write(file, `${text}${text === '' || text.endsWith('\n') ? '' : '\n'}${DIR}/\n`)
415
+
416
+ return { excluded: file }
417
+ }
418
+
419
+ // What comes into every session: SHIFT.md with a fresh map of the docs, OWNER.md, GLOSSARY.md and TASKS.md, with
420
+ // paths from the project's root; none when the mod is off here.
421
+ export async function sessionFiles(project: Project): Promise<SessionFile[]> {
422
+ const { store, root, settings } = project
423
+ if (!settings.enabled || (await staleLayout(project)) !== null) return []
424
+ await refreshDocs(project)
425
+ const paths = [settings.files.shift, settings.files.owner, settings.files.glossary, TASK_LIST, ...settings.files.always]
426
+ const files = await Promise.all(paths.map(async path => ({ path, text: await store.read(`${root}/${path}`) })))
427
+
428
+ return files.filter((file): file is SessionFile => file.text !== null)
429
+ }
430
+
431
+ // Records the mod cannot work on yet: an older name of its folder, or the folder the shift skill left. Then the mod writes
432
+ // nothing — a map appended to the skill's own SHIFT.md would come into every session — and says what to move.
433
+ export async function staleLayout({ store, root }: Project): Promise<string | null> {
434
+ if (await store.exists(`${root}/${OLD_DIR}`)) {
435
+ return (await store.exists(`${root}/${DIR}`))
436
+ ? `Both ${OLD_DIR}/ and ${DIR}/ are here: the records live in ${DIR}/ now. Merge what ${OLD_DIR}/ holds into ${DIR}/ by ${GUIDE_TOOL}, then remove ${OLD_DIR}/.`
437
+ : `The records are in ${OLD_DIR}/, the mod's old name: rename the folder to ${DIR}/ as it is, and call again.`
438
+ }
439
+ if ((await store.exists(`${root}/${DIR}/sessions`)) && !(await store.exists(`${root}/${BOARD}`))) {
440
+ return `${DIR}/ here is the shift skill's: it has sessions/ and no board. Move it in place by "Coming from the shift skill" in ${GUIDE_TOOL}, then call again.`
441
+ }
442
+
443
+ return null
444
+ }
445
+
446
+ // What /shift-tasks shows: the open tasks as listed, with their items' count, and the items not closed of those in
447
+ // progress. Read only; a list the shift would refuse is shown as far as it parses.
448
+ export async function tasksView(project: Project): Promise<string> {
449
+ const { store, root } = project
450
+ const parsed = parseTaskList((await store.read(`${root}/${TASK_LIST}`)) ?? '')
451
+ if (typeof parsed === 'string') return `${TASK_LIST}: ${parsed}`
452
+ const views: TaskView[] = []
453
+ for (const task of parsed) {
454
+ const track = (await store.read(taskFile(`${root}/${DIR}`, task.name, 'track'))) ?? ''
455
+ const items = itemsOf(track).filter(item => item.status !== '')
456
+ const open = items.filter(item => !CLOSED.has(item.status))
457
+ views.push({
458
+ status: task.status,
459
+ name: task.name,
460
+ about: task.about,
461
+ items: task.status === 'in progress' ? open.map(item => ({ status: item.status, name: item.name })) : null,
462
+ closed: items.length - open.length,
463
+ total: items.length,
464
+ })
465
+ }
466
+
467
+ return renderTasks(views)
468
+ }
@@ -0,0 +1,75 @@
1
+ // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
+ import { GLOSSARY_MAX_LINES } from './layout'
3
+ import { blocks, dated, overLimit } from './markdown'
4
+
5
+ // GLOSSARY.md: the project's own words, one article each, loaded whole into every session.
6
+ //
7
+ // ## Shift
8
+ // Variants: shifts, shifted
9
+ // Means: the boundary between stretches of work: records updated, a letter written, the history let go.
10
+ // Avoid: compaction, handoff
11
+ // Where: everywhere the agent reads; the owner says «сдвиг».
12
+ // Unconfirmed: is a stretch the same as a session?
13
+
14
+ export const GLOSSARY_LABELS = ['Variants', 'Means', 'Avoid', 'Where', 'Unconfirmed'] as const
15
+ export type GlossaryLabel = (typeof GLOSSARY_LABELS)[number]
16
+ export type Article = { term: string; fields: Partial<Record<GlossaryLabel, string>> }
17
+
18
+ // The articles, or what is wrong with a line; text before the first article is the file's own heading and intro.
19
+ export function parseGlossary(text: string, where: string): Article[] | string {
20
+ const articles: Article[] = []
21
+ for (const block of blocks(text, 2)) {
22
+ const article: Article = { term: block.title, fields: {} }
23
+ articles.push(article)
24
+ for (const line of block.body.split('\n').map(each => each.trim())) {
25
+ if (line === '') continue
26
+ const signed = /^([A-Za-z]+): *(.*)$/.exec(line)
27
+ const label = signed?.[1] as GlossaryLabel | undefined
28
+ if (signed === null || label === undefined || !(GLOSSARY_LABELS as readonly string[]).includes(label)) {
29
+ return `${where}, "${article.term}": "${line}" is not a signed line; the labels are ${GLOSSARY_LABELS.join(', ')}.`
30
+ }
31
+ if (article.fields[label] !== undefined) return `${where}, "${article.term}": "${label}:" twice; one line each.`
32
+ article.fields[label] = (signed[2] ?? '').trim()
33
+ }
34
+ }
35
+
36
+ return articles
37
+ }
38
+
39
+ export function checkGlossary(text: string | null, where: string): string | null {
40
+ if (text === null) return null
41
+ const size =
42
+ overLimit(where, text, GLOSSARY_MAX_LINES, 'it comes into every session. Drop general words and terms no longer in use.') ??
43
+ dated(where, text, 'A term means what it means now.')
44
+ if (size !== null) return size
45
+ const articles = parseGlossary(text, where)
46
+ if (typeof articles === 'string') return articles
47
+
48
+ const seen = new Map<string, string>()
49
+ for (const article of articles) {
50
+ if (!article.fields.Means) return `${where}, "${article.term}" has no "Means:" — what it is, in one or two sentences.`
51
+ for (const name of [article.term, ...words(article.fields.Variants)]) {
52
+ const key = name.toLowerCase()
53
+ const earlier = seen.get(key)
54
+ if (earlier !== undefined) return `${where}: "${name}" is in both "${earlier}" and "${article.term}". One word, one article.`
55
+ seen.set(key, article.term)
56
+ }
57
+ }
58
+ for (const article of articles) {
59
+ for (const avoided of words(article.fields.Avoid)) {
60
+ const owner = seen.get(avoided.toLowerCase())
61
+ if (owner !== undefined) {
62
+ return `${where}: "${article.term}" says to avoid "${avoided}", but "${owner}" uses that word. Keep one of them.`
63
+ }
64
+ }
65
+ }
66
+
67
+ return null
68
+ }
69
+
70
+ function words(list: string | undefined): string[] {
71
+ return (list ?? '')
72
+ .split(',')
73
+ .map(word => word.trim())
74
+ .filter(word => word !== '')
75
+ }