@iiiokojiadbi/shift 0.33.0 → 0.34.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/core/markdown.ts CHANGED
@@ -9,12 +9,23 @@ export type Heading = { level: number; title: string; line: number; note: string
9
9
  const HEADING = /^ {0,3}(#{1,6}) +(.+?)\s*$/
10
10
  const FENCE = /^ {0,3}(`{3,}|~{3,})(.*)$/
11
11
 
12
+ // The text with its fenced lines left out: a check over raw text never reads an example as the record.
13
+ export function unfenced(text: string): string {
14
+ const lines = text.split('\n')
15
+ const inside = fenced(lines)
16
+
17
+ return lines.filter((_, at) => !inside.has(at)).join('\n')
18
+ }
19
+
12
20
  // The lines inside code fences, the fences included: an opener of three or more backticks or tildes, closed by a line
13
21
  // of the same character at least as long with nothing else on it. A backtick opener with a backtick after it is
14
- // inline code, and an opener never closed is no fence, so a stray one never hides the rest of a record.
22
+ // inline code, and an opener never closed is no fence, so a stray one never hides the rest of a record. A leading
23
+ // frontmatter is fenced too: a `# ` comment in it is no title.
15
24
  function fenced(lines: readonly string[]): Set<number> {
16
25
  const inside = new Set<number>()
17
- for (let at = 0; at < lines.length; at++) {
26
+ const front = lines[0]?.trimEnd() === '---' ? lines.findIndex((line, index) => index > 0 && line.trimEnd() === '---') : -1
27
+ for (let index = 0; index <= front; index++) inside.add(index)
28
+ for (let at = front + 1; at < lines.length; at++) {
18
29
  const [, mark = '', info = ''] = FENCE.exec(lines[at] ?? '') ?? []
19
30
  if (mark === '' || (mark.startsWith('`') && info.includes('`'))) continue
20
31
  const closer = new RegExp(`^ {0,3}${mark.startsWith('`') ? '`' : '~'}{${mark.length},}\\s*$`)
@@ -27,6 +38,36 @@ function fenced(lines: readonly string[]): Set<number> {
27
38
  return inside
28
39
  }
29
40
 
41
+ // The first line at or after `from` outside code fences that `matches`; -1 when there is none. A marker the mod
42
+ // writes is found only on a line of its own, never in an example or a sentence that names it.
43
+ export function lineOutside(lines: readonly string[], matches: (line: string) => boolean, from = 0): number {
44
+ const inside = fenced(lines)
45
+
46
+ return lines.findIndex((line, index) => index >= from && !inside.has(index) && matches(line))
47
+ }
48
+
49
+ // The targets of a text's Markdown links outside code fences — inline, in `<…>` or bare, with or without a title, and
50
+ // reference definitions — each as written, without its `?query` and `#fragment`, and as the file is named:
51
+ // `my%20guide.md` is `my guide.md`, `a%23b.md` is `a#b.md`; null when it does not decode.
52
+ export function linkTargets(text: string): { link: string; file: string | null }[] {
53
+ const bare = unfenced(text)
54
+ const found = [
55
+ ...bare.matchAll(/\]\(<([^<>\n]+)>(?:\s[^)]*)?\)/g),
56
+ ...bare.matchAll(/\]\(([^)\s<>]+)(?:\s[^)]*)?\)/g),
57
+ ...bare.matchAll(/^ {0,3}\[[^\]]+\]:[ \t]*<([^<>\n]+)>/gm),
58
+ ...bare.matchAll(/^ {0,3}\[[^\]]+\]:[ \t]*([^\s<>]+)/gm),
59
+ ]
60
+
61
+ return found.map(match => {
62
+ const link = (match[1] ?? '').replace(/[?#].*$/, '')
63
+ try {
64
+ return { link, file: decodeURIComponent(link) }
65
+ } catch {
66
+ return { link, file: null }
67
+ }
68
+ })
69
+ }
70
+
30
71
  // Every heading outside code fences: its level, its title, its line from 1, and the `> ` line right under it.
31
72
  export function headings(text: string): Heading[] {
32
73
  const lines = text.split('\n')
@@ -130,16 +171,27 @@ export function missingSections(text: string, required: readonly string[], where
130
171
  return null
131
172
  }
132
173
 
133
- const DATES = [/\b(19|20)\d{2}-\d{2}-\d{2}\b/, /\b\d{1,2}\.\d{1,2}\.(19|20)\d{2}\b/]
174
+ // A real day of a real month, in a name or a range too, never part of a version such as 0.32.2026 or v1.2.2026.
175
+ const DATES = [
176
+ { pattern: /(?<![\d.])((?:19|20)\d{2})-(\d{2})-(\d{2})(?!\d|\.\d)/g, year: 1, month: 2, day: 3 },
177
+ { pattern: /(?<![\w.])(\d{1,2})\.(\d{1,2})\.((?:19|20)\d{2})(?!\d|\.\d)/g, year: 3, month: 2, day: 1 },
178
+ ]
134
179
 
135
180
  export function findDate(text: string): string | null {
136
181
  for (const line of text.split('\n')) {
137
- if (DATES.some(re => re.test(line))) return line.trim()
182
+ if (DATES.some(({ pattern, ...at }) => [...line.matchAll(pattern)].some(found => isDay(found, at)))) return line.trim()
138
183
  }
139
184
 
140
185
  return null
141
186
  }
142
187
 
188
+ function isDay(found: RegExpMatchArray, at: { year: number; month: number; day: number }): boolean {
189
+ const [year, month, day] = [at.year, at.month, at.day].map(index => Number(found[index]))
190
+ const date = new Date(Date.UTC(year ?? 0, (month ?? 0) - 1, day ?? 0))
191
+
192
+ return date.getUTCFullYear() === year && date.getUTCMonth() === (month ?? 0) - 1 && date.getUTCDate() === day
193
+ }
194
+
143
195
  // Every `- ` line of a text as an item; a line without a `[status]` has an empty one, a track item without `#<id>`
144
196
  // a null id.
145
197
  export function itemsOf(text: string): Item[] {
@@ -155,7 +207,8 @@ export function itemsOf(text: string): Item[] {
155
207
  return [
156
208
  {
157
209
  status: match?.[1] ?? '',
158
- id: id === null ? null : Number(id[1]),
210
+ // An id past the safe integers cannot be counted on: the item is numbered anew.
211
+ id: id === null || !Number.isSafeInteger(Number(id[1])) ? null : Number(id[1]),
159
212
  name: cut === -1 ? named : named.slice(0, cut),
160
213
  note: cut === -1 ? null : named.slice(cut + 3),
161
214
  rest,
@@ -177,8 +230,8 @@ export function formatK(n: number): string {
177
230
  // `key: value` lines between the leading `---` fences.
178
231
  export function frontmatter(text: string): Map<string, string> {
179
232
  const found = new Map<string, string>()
180
- const match = /^---\n([\s\S]*?)\n---/.exec(text)
181
- for (const line of (match?.[1] ?? '').split('\n')) {
233
+ const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)
234
+ for (const line of (match?.[1] ?? '').split(/\r?\n/)) {
182
235
  const colon = line.indexOf(':')
183
236
  if (colon > 0) found.set(line.slice(0, colon).trim(), line.slice(colon + 1).trim())
184
237
  }
package/core/records.ts CHANGED
@@ -24,7 +24,7 @@ import {
24
24
  TASK_SECTIONS,
25
25
  TASKS,
26
26
  } from './layout'
27
- import { blocks, dated, frontmatter, itemsOf, missingSections, overLimit, quote, sections, title } from './markdown'
27
+ import { blocks, dated, frontmatter, itemsOf, linkTargets, missingSections, overLimit, quote, sections, title, unfenced } from './markdown'
28
28
  import type { Project } from './project'
29
29
  import { checkTaskList, type ListedTask, parseTaskList } from './tasks'
30
30
  import type { Kind, KnowledgeFile, TaskFiles, Work } from './types'
@@ -170,8 +170,8 @@ export function checkTask({ name, task, track, notes: notes_ }: TaskFiles): stri
170
170
  if (missing !== null) return missing
171
171
  const date = dated(where, task, 'Tasks have no dates.') ?? dated(where, track, 'Tasks have no dates.')
172
172
  if (date !== null) return date
173
- if (/^continues:/m.test(task))
174
- return `${where}task.md has a "continues:" line: links live in ${TASK_LIST} now, under the task's line. Move it there.`
173
+ if (/^continues:/m.test(unfenced(task)) || frontmatter(task).has('continues'))
174
+ return `${where}task.md has a "continues:" line: links live in ${TASK_LIST} now. Remove it, and under the task's line there write it as " - continues: [<name>](archive/<name>/)".`
175
175
  const rejected = badRejected(task, `${where}task.md`)
176
176
  if (rejected !== null) return rejected
177
177
  const notes = checkNotes(where, task, track, notes_)
@@ -194,7 +194,7 @@ function badRejected(text: string, where: string): string | null {
194
194
  }
195
195
 
196
196
  function checkOwner(owner: string | null): string | null {
197
- if (owner === null) return `No ${OWNER}: create it beside ${BOARD} with the owner's decisions in force for the whole project, or "none".`
197
+ if (owner === null) return `No ${OWNER}: create it with the owner's decisions in force for the whole project, or "none".`
198
198
  if (owner.trim() === '') return `${OWNER} is empty. No decisions yet — write "none".`
199
199
  return (
200
200
  overLimit(
@@ -209,16 +209,21 @@ function checkOwner(owner: string | null): string | null {
209
209
  // A task's notes: each with its description, each linked from track.md or task.md, every link reaching a note. Beside
210
210
  // the description a note is free: research, a decision worked out, evidence.
211
211
  function checkNotes(where: string, task: string, track: string, notes: TaskFiles['notes']): string | null {
212
+ // The notes the links reach, as Markdown reads a link outside code fences: its `#fragment` and `?query` are not the
213
+ // file's, and `%23` is a `#` in its name.
214
+ const linked = linkTargets(`${task}\n${track}`).flatMap(({ file }) => {
215
+ const path = file?.replace(/^\.\//, '') ?? ''
216
+ return path.startsWith(`${NAMES.notes}/`) ? [path.slice(NAMES.notes.length + 1)] : []
217
+ })
212
218
  for (const note of notes) {
213
219
  if ((frontmatter(note.text).get('description') ?? '') === '') {
214
220
  return `${where}${NAMES.notes}/${note.name} needs a frontmatter "description": what is in it, as the list after a shift shows it.`
215
221
  }
216
- if (!`${task}\n${track}`.includes(`${NAMES.notes}/${note.name}`)) {
217
- return `${where}${NAMES.notes}/${note.name} is linked from nowhere: link it from its item in track.md, or from task.md, as [what it holds](${NAMES.notes}/${note.name}).`
222
+ if (!linked.includes(note.name)) {
223
+ return `${where}${NAMES.notes}/${note.name} is linked from nowhere: link it from its item in ${NAMES.track}, or from ${NAMES.task}, as [what it holds](${NAMES.notes}/${encodeURIComponent(note.name)}).`
218
224
  }
219
225
  }
220
226
  const names = new Set(notes.map(note => note.name))
221
- const linked = [...`${task}\n${track}`.matchAll(new RegExp(`\\]\\(${NAMES.notes}/([^)#\\s]+)\\)`, 'g'))].map(found => found[1] ?? '')
222
227
  const missing = linked.filter(name => !names.has(name))
223
228
 
224
229
  return missing.length === 0
@@ -229,7 +234,7 @@ function checkNotes(where: string, task: string, track: string, notes: TaskFiles
229
234
  export const isKind = (kind: string): kind is Kind => Object.hasOwn(KINDS, kind)
230
235
 
231
236
  // An entry's command: a fenced block or an indented one.
232
- const hasCommand = (body: string) => /^```/m.test(body) || /^ {4}\S/m.test(body)
237
+ const hasCommand = (body: string) => /^ {0,3}(```|~~~)/m.test(body) || /^ {4}\S/m.test(body)
233
238
 
234
239
  export function checkKnowledge({ name, text }: KnowledgeFile): string | null {
235
240
  const where = `${KNOWLEDGE}/${name}`
package/core/settings.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
- import { DOCS_MAP_MAX_CHARS, DOCS_PINNED_MAX_CHARS, GLOSSARY, OWNER, SETTINGS, SHIFT_FILE } from './layout'
2
+ import { DOCS_MAP_MAX_CHARS, DOCS_MAX_DEPTH, DOCS_PINNED_MAX_CHARS, GLOSSARY, OWNER, SETTINGS, SHIFT_FILE } from './layout'
3
3
  import { quote } from './markdown'
4
- import { isInside } from './paths'
4
+ import { isInside, normalize } from './paths'
5
5
 
6
6
  // The owner's settings for one project; the agent does not edit them.
7
7
  export type Settings = {
@@ -107,8 +107,7 @@ export const SETTING_KEYS: readonly Key[] = [
107
107
  since: '0.3.0',
108
108
  kind: 'docs',
109
109
  at: ['docs', 'dirs'],
110
- about:
111
- 'the folders of documents the mod keeps, or single documents such as "AGENTS.md" (since 0.9.0): the map in SHIFT.md, the toc, the checks, the docs tools; [] — none, the docs are left alone',
110
+ about: `the folders of documents the mod keeps, ${DOCS_MAX_DEPTH} folders deep at most, or single documents such as "AGENTS.md" (since 0.9.0): the map in SHIFT.md, the toc, the checks, the docs tools; [] — none, the docs are left alone`,
112
111
  },
113
112
  {
114
113
  key: 'docs.max_chars',
@@ -164,11 +163,16 @@ export function parseSettings(text: string): ParsedSettings | string {
164
163
  const settings: Settings = { ...DEFAULT_SETTINGS, files: { ...DEFAULT_SETTINGS.files }, docs: { ...DEFAULT_SETTINGS.docs } }
165
164
  const set = new Set<string>()
166
165
  let table = ''
166
+ const tables = new Set<string>()
167
167
  for (const [index, raw] of text.split('\n').entries()) {
168
168
  const line = withoutComment(raw).trim()
169
169
  if (line === '') continue
170
170
  const header = /^\[([A-Za-z0-9_.-]+)\]$/.exec(line)
171
171
  if (header !== null) {
172
+ if (!TABLES.has(header[1] ?? ''))
173
+ return `${SETTINGS}, line ${index + 1}: unknown table \`[${header[1]}]\`; the tables are ${[...TABLES].map(each => `\`[${each}]\``).join(', ')}.`
174
+ if (tables.has(header[1] ?? '')) return `${SETTINGS}, line ${index + 1}: \`[${header[1]}]\` is opened twice; keep its keys under one.`
175
+ tables.add(header[1] ?? '')
172
176
  table = `${header[1]}.`
173
177
  continue
174
178
  }
@@ -180,10 +184,12 @@ export function parseSettings(text: string): ParsedSettings | string {
180
184
  const key = SETTING_KEYS.find(each => each.key === name)
181
185
  if (key === undefined)
182
186
  return `${SETTINGS}: unknown key \`${name}\`; the keys are ${SETTING_KEYS.map(each => `\`${each.key}\``).join(', ')}.`
183
- const wanted = KINDS[key.kind](value)
187
+ if (set.has(name)) return `${SETTINGS}, line ${index + 1}: \`${name}\` is set twice; keep one.`
188
+ const given = PATH_KINDS.has(key.kind) ? asPaths(value) : value
189
+ const wanted = KINDS[key.kind](given)
184
190
  if (wanted !== null) return `${SETTINGS}: \`${name}\` is ${wanted}, got ${JSON.stringify(value)}.`
185
191
  const [holder, field] = slot(settings, key)
186
- holder[field] = value
192
+ holder[field] = given
187
193
  set.add(name)
188
194
  }
189
195
 
@@ -200,6 +206,19 @@ export function settingValue(settings: Settings, key: string): string | null {
200
206
  return value === null || value === undefined ? null : JSON.stringify(value).replace(/","/g, '", "')
201
207
  }
202
208
 
209
+ // The tables the keys live in: a header naming anything else is a mistake.
210
+ const TABLES = new Set(SETTING_KEYS.flatMap(({ key }) => (key.includes('.') ? [key.slice(0, key.indexOf('.'))] : [])))
211
+
212
+ // Paths as the mod writes them, from the root: `./OWNER.md` is `OWNER.md`, `.` the root itself (no file or folder),
213
+ // a path that climbs out left as given for the check to refuse.
214
+ const PATH_KINDS = new Set<string>(['path', 'files', 'docs'])
215
+
216
+ function asPaths(value: Value): Value {
217
+ const one = (path: string) => (path.startsWith('/') ? path : (normalize(path) ?? path))
218
+
219
+ return typeof value === 'string' ? one(value) : Array.isArray(value) ? value.map(one) : value
220
+ }
221
+
203
222
  function withoutComment(line: string): string {
204
223
  let quote: string | null = null
205
224
  for (let index = 0; index < line.length; index++) {
@@ -219,19 +238,31 @@ function tomlValue(raw: string): Value | undefined {
219
238
  if (value === 'false') return false
220
239
  if (/^[+-]?\d+(\.\d+)?$/.test(value)) return Number(value)
221
240
  const list = /^\[(.*)\]$/.exec(value)
222
- if (list !== null) {
223
- const items = (list[1] ?? '')
224
- .split(',')
225
- .map(item => item.trim())
226
- .filter(item => item !== '')
227
- .map(quoted)
228
-
229
- return items.every(item => item !== undefined) ? (items as string[]) : undefined
230
- }
241
+ if (list !== null) return strings(list[1] ?? '')
231
242
 
232
243
  return quoted(value)
233
244
  }
234
245
 
246
+ // The strings of a one-line array, each quoted, commas between them and one allowed after the last; undefined for
247
+ // anything else, such as `[,]`. A comma inside quotes is part of its string.
248
+ function strings(inside: string): string[] | undefined {
249
+ const items: string[] = []
250
+ const item = /\s*("[^"\\]*"|'[^']*')\s*(,|$)/y
251
+ let at = 0
252
+ while (at < inside.length && inside.slice(at).trim() !== '') {
253
+ item.lastIndex = at
254
+ const found = item.exec(inside)
255
+ if (found === null) return undefined
256
+ const value = quoted(found[1] ?? '')
257
+ if (value === undefined) return undefined
258
+ items.push(value)
259
+ at = item.lastIndex
260
+ if (found[2] === '' && at < inside.length) return undefined
261
+ }
262
+
263
+ return items
264
+ }
265
+
235
266
  function quoted(value: string): string | undefined {
236
267
  const found = /^"([^"\\]*)"$|^'([^']*)'$/.exec(value)
237
268
 
package/core/setup.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
2
  import { docsReport } from './docs'
3
3
  import { sessionFiles, staleLayout } from './flows'
4
- import { atPlaces, BOARD, GUIDE_TOOL, MOD, SETTINGS } from './layout'
4
+ import { atPlaces, BOARD, GUIDE_TOOL, MOD, SETTINGS, TASK_LIST } from './layout'
5
5
  import { formatK } from './markdown'
6
6
  import type { Project } from './project'
7
7
  import { checkWork } from './records'
8
- import { SETTING_KEYS, settingValue } from './settings'
8
+ import { DEFAULT_SETTINGS, SETTING_KEYS, settingValue } from './settings'
9
9
  import { readRecords } from './store'
10
10
  import { doctrine, SETUP_LAYOUT, SETUP_MIGRATION } from './texts/doctrine'
11
11
  import { fileBlock } from './texts/prompts'
@@ -24,26 +24,41 @@ export async function setupReport(project: Project, loaded: string | null): Prom
24
24
  : 'It parses.'
25
25
  const keys = SETTING_KEYS.map(({ key, since, about }) => {
26
26
  const value = settingValue(settings, key)
27
- const where = project.set.has(key) ? 'set here' : 'default'
27
+ const where = project.set.has(key) ? `set here, default ${settingValue(DEFAULT_SETTINGS, key) ?? 'unset'}` : 'default'
28
28
 
29
29
  return `- \`${tomlKey(key)}\` = ${value ?? 'unset'} — ${where}, since ${since}: ${about}`
30
30
  })
31
31
 
32
- const files = await sessionFiles(project)
32
+ // Read as they are: a report writes nothing, not even the docs' tocs and map.
33
+ const files = await sessionFiles(project, { refresh: false })
33
34
  const doctrineChars = atPlaces(doctrine(shownTools(settings).map(tool => tool.name)), settings.files).length
34
- const stale = loaded === null ? [] : files.filter(file => !loaded.includes(fileBlock(file.path, file.text))).map(file => file.path)
35
- const block =
36
- files.length === 0
37
- ? 'None: the mod is off here, or the records are in an older layout.'
38
- : [
39
- ...files.map(file => `- \`${file.path}\` — ${weight(fileBlock(file.path, file.text).length)}`),
40
- `- the doctrine, the system prompt's "Shift" section — ${weight(doctrineChars)}`,
41
- `- in all — ${weight(doctrineChars + files.reduce((sum, file) => sum + fileBlock(file.path, file.text).length, 0))}; tokens are estimated at ${CHARS_PER_TOKEN} characters each, more for text that is not English`,
42
- '',
43
- stale.length === 0
44
- ? "This session's block matches them."
45
- : `Changed since this session's block was read: ${stale.map(path => `\`${path}\``).join(', ')}. The block is read at a session's start and after each shift, so the changes reach it after the next shift or in a new session; read the files themselves meanwhile.`,
46
- ].join('\n')
35
+ // The files the block held, each tag where a block starts — after the block's opening or a file's end — so a
36
+ // record's own example of a tag is no file.
37
+ const held = [...(loaded ?? '').matchAll(/(?:^<[^\n]*>|<\/file>)\n+<file path="([^"]+)">\n/g)].map(found => found[1] ?? '')
38
+ const gone = held.filter(path => !files.some(file => file.path === path))
39
+ const stale = [
40
+ ...(loaded === null ? [] : files.filter(file => !loaded.includes(fileBlock(file.path, file.text))).map(file => file.path)),
41
+ ...gone,
42
+ ]
43
+ const none = !settings.enabled
44
+ ? 'None: the mod is off here, `enabled = false`.'
45
+ : (await staleLayout(project)) !== null
46
+ ? 'None: the records are in an older layout; the Records section says what to move.'
47
+ : `None yet: none of ${[settings.files.shift, settings.files.owner, settings.files.glossary, TASK_LIST].map(path => `\`${path}\``).join(', ')} is here.`
48
+ const shown = settings.enabled ? doctrineChars : 0
49
+ const block = [
50
+ ...(files.length === 0 ? [none] : files.map(file => `- \`${file.path}\` — ${weight(fileBlock(file.path, file.text).length)}`)),
51
+ ...(settings.enabled ? [`- the doctrine, the system prompt's "Shift" section — ${weight(doctrineChars)}`] : []),
52
+ `- in all — ${weight(shown + files.reduce((sum, file) => sum + fileBlock(file.path, file.text).length, 0))}; tokens are estimated at ${CHARS_PER_TOKEN} characters each, more for text that is not English`,
53
+ '',
54
+ stale.length === 0
55
+ ? "This session's block matches them."
56
+ : `Changed or removed since this session's block was read: ${stale.map(path => `\`${path}\``).join(', ')}. The block is read at a session's start and after each shift, so the changes reach it after the next shift or in a new session; read the files themselves meanwhile.`,
57
+ ].join('\n')
58
+ // The tree shows the records where they are by default; the settings may keep some elsewhere.
59
+ const moved = (['owner', 'glossary', 'shift'] as const)
60
+ .filter(key => settings.files[key] !== DEFAULT_SETTINGS.files[key])
61
+ .map(key => `\`${DEFAULT_SETTINGS.files[key]}\` is at \`${settings.files[key]}\` here`)
47
62
 
48
63
  return [
49
64
  `# The ${MOD} mod in this project`,
@@ -73,8 +88,9 @@ export async function setupReport(project: Project, loaded: string | null): Prom
73
88
  `## Files`,
74
89
  '',
75
90
  SETUP_LAYOUT,
91
+ ...(moved.length === 0 ? [] : ['', `Moved by the settings: ${moved.join('; ')}.`]),
76
92
  '',
77
- SETUP_MIGRATION,
93
+ atPlaces(SETUP_MIGRATION, settings.files),
78
94
  ].join('\n')
79
95
  }
80
96
 
@@ -88,7 +104,9 @@ async function recordsState(project: Project): Promise<string> {
88
104
  if (work === null) return `No board yet: create ${BOARD} by the sections in ${GUIDE_TOOL} before the first shift.`
89
105
  const problem = checkWork(work, null, project)
90
106
 
91
- return problem === null ? 'They pass every check a shift makes.' : `A shift would refuse them now: ${problem}`
107
+ return problem === null
108
+ ? 'They pass every check a shift makes of the records, but whether anything changed since the last shift; the letter is checked by the shift itself.'
109
+ : `A shift would refuse them now: ${problem}`
92
110
  }
93
111
 
94
112
  // What a text costs in the context: its characters and the tokens they come to, roughly.
package/core/store.ts CHANGED
@@ -114,17 +114,20 @@ export async function readSnapshot(store: Store, base: string, index: string): P
114
114
  return work === null ? null : { work, index: await store.read(index) }
115
115
  }
116
116
 
117
- // Shift folder names, oldest first: they are UTC stamps, so they sort by time.
118
- export function shiftNames({ store, root }: Project): Promise<string[]> {
119
- return store.list(`${root}/${SHIFTS}`, 'dir')
120
- }
121
-
122
- // The newest earlier shift folder, whose snapshots the new state is checked against.
123
- export async function previousShift(project: Project): Promise<string | null> {
124
- const { root } = project
125
- const last = (await shiftNames(project)).at(-1)
117
+ // Shift folder names, oldest first: UTC stamps sort by time, and a second taken twice by its number, -10 after -9.
118
+ export async function shiftNames({ store, root }: Project): Promise<string[]> {
119
+ // Only the mod's own folders: one the owner keeps there, a backup, is no shift.
120
+ const names = (await store.list(`${root}/${SHIFTS}`, 'dir')).filter(name => /^\d{8}-\d{6}(?:-\d+)?$/.test(name))
121
+ const order = (name: string) => {
122
+ const [, stamp = name, n = '1'] = /^(\d{8}-\d{6})(?:-(\d+))?$/.exec(name) ?? []
123
+ return { stamp, n: Number(n) }
124
+ }
126
125
 
127
- return last === undefined ? null : `${root}/${SHIFTS}/${last}`
126
+ return names.toSorted((a, b) => {
127
+ const x = order(a)
128
+ const y = order(b)
129
+ return x.stamp === y.stamp ? x.n - y.n : x.stamp < y.stamp ? -1 : 1
130
+ })
128
131
  }
129
132
 
130
133
  // The last `count` shifts' about.md, oldest first, and how many shifts the project has in all.
package/core/tasks.ts CHANGED
@@ -80,6 +80,9 @@ export function checkTaskList(text: string | null, folders: readonly string[], a
80
80
  const badName = tasks.filter(t => !NAME.test(t.name))
81
81
  if (badName.length > 0) return `Task names are ${NAME_RULE}: ${quote(badName.map(t => t.name))}.`
82
82
 
83
+ const twice = tasks.filter((t, at) => tasks.findIndex(other => other.name === t.name) !== at).map(t => t.name)
84
+ if (twice.length > 0) return `${TASK_LIST} lists a task twice: ${quote([...new Set(twice)])}. One line each, its links under it.`
85
+
83
86
  const listed = new Set(tasks.map(t => t.name))
84
87
  const unlisted = folders.filter(name => !listed.has(name))
85
88
  if (unlisted.length > 0)
@@ -95,6 +98,8 @@ export function checkTaskList(text: string | null, folders: readonly string[], a
95
98
  if (link.kind === 'needs' && link.place !== 'tasks') {
96
99
  return `${TASK_LIST}: ${task.name} needs ${link.name}, which is archived: what it gave is done — write "after:".`
97
100
  }
101
+ if (link.kind === 'after' && link.place !== 'archive')
102
+ return `${TASK_LIST}: ${task.name} is after ${link.name}, which is still open: write "needs:" until it is archived.`
98
103
  if (link.kind === 'continues' && link.place !== 'archive')
99
104
  return `${TASK_LIST}: ${task.name} continues ${link.name}, which is not archived: only an archived task is continued.`
100
105
  if (link.place === 'tasks' && link.name === task.name) return `${TASK_LIST}: ${task.name} links itself.`
@@ -129,6 +134,24 @@ function needsCycle(tasks: readonly ListedTask[]): string[] | null {
129
134
  return null
130
135
  }
131
136
 
137
+ // A link line of another task once `name` is archived: its link points into the archive, and a "needs:" on it becomes
138
+ // "after:" — on a line of its own when the same line needs other tasks still open.
139
+ function archivedLink(line: string, name: string): string[] {
140
+ const moved = line.replaceAll(`](tasks/${name}/)`, `](archive/${name}/)`).replaceAll(`](tasks/${name})`, `](archive/${name}/)`)
141
+ const needs = /^(\s+)- needs: (.+)$/.exec(moved)
142
+ if (moved === line || needs === null) return [moved]
143
+ const [, indent = '', rest = ''] = needs
144
+ const cut = rest.indexOf(' — ')
145
+ // The links themselves, however the line joins them: a comma, "and", a space.
146
+ const targets = [...(cut === -1 ? rest : rest.slice(0, cut)).matchAll(/\[[^\]]*\]\([^)]*\)/g)].map(found => found[0])
147
+ const why = cut === -1 ? '' : rest.slice(cut)
148
+ const done = targets.filter(target => target.includes(`](archive/${name}/)`))
149
+ const open = targets.filter(target => !done.includes(target))
150
+ if (open.length === 0) return [`${indent}- after: ${rest}`]
151
+
152
+ return [`${indent}- needs: ${open.join(', ')}${why}`, `${indent}- after: ${done.join(', ')}`]
153
+ }
154
+
132
155
  // TASKS.md with a new task's line and its links appended; a link points into the archive when the task is archived.
133
156
  // A list that said "none" says it no more.
134
157
  export function withTask(text: string | null, input: OpenInput, archived: readonly string[]): string {
@@ -156,11 +179,11 @@ export function archiveInList(text: string, name: string): string {
156
179
  let skipping = false
157
180
  for (const line of text.split('\n')) {
158
181
  const task = taskLine(line)
182
+ // A blank line between a task and its links does not end them.
159
183
  if (task !== null) skipping = task.name === name
160
- else if (!LINK_LINE.test(line)) skipping = false
161
- if (skipping) continue
162
- const moved = line.replaceAll(`](tasks/${name}/)`, `](archive/${name}/)`).replaceAll(`](tasks/${name})`, `](archive/${name}/)`)
163
- out.push(moved !== line && /^\s+- needs: /.test(moved) ? moved.replace('- needs: ', '- after: ') : moved)
184
+ else if (line.trim() !== '' && !LINK_LINE.test(line)) skipping = false
185
+ if (skipping && line.trim() !== '') continue
186
+ out.push(...archivedLink(line, name))
164
187
  }
165
188
  const kept = out.join('\n')
166
189
  const left = parseTaskList(kept)
@@ -42,6 +42,7 @@ import {
42
42
  TASK_LIST,
43
43
  TASK_SECTIONS,
44
44
  TASKS,
45
+ TASKS_MAX_LINES,
45
46
  TOOL,
46
47
  TRACK_TOOL,
47
48
  } from '../layout'
@@ -75,7 +76,7 @@ const LIST_RULES = `\`${TASK_LIST}\` lists every open task, one line each, and u
75
76
  - continues: [old-adapters](archive/old-adapters/)
76
77
  \`\`\`
77
78
 
78
- Status: ${FOCUS.join(', ')}; deferred and waiting — with the reason in the line. Links: \`needs\` — an open task this one cannot finish without; \`after\` — a done task it stands on; \`continues\` — an archived task it picks up. No task yet — "none".`
79
+ Status: ${FOCUS.join(', ')}; deferred and waiting — with the reason in the line. Links: \`needs\` — an open task this one cannot finish without; \`after\` — an archived task it stands on; \`continues\` — an archived task it picks up. No task yet — "none". At most ${TASKS_MAX_LINES} lines.`
79
80
 
80
81
  const OWNER_RULES = `\`${OWNER}\` is the owner's decisions in force for the whole project: a code of rules as it stands now, not a log. Verbatim where the owner's words matter, grouped under \`##\` headings by meaning, no dates, no "revoked" marks, no more than ${OWNER_MAX_LINES} lines; no decisions yet — "none". A new word is checked against what is written: it contradicts a rule — the rule is rewritten; it narrows, widens or refines one — the rule is rewritten to cover both; it is new — a new line. A rule changes or goes only on the owner's word. A decision that binds one task goes to that task's "${OWNER_SECTION}".`
81
82
 
@@ -127,13 +128,13 @@ Where: the owner says «отрезок».
127
128
  Unconfirmed: is a stretch ever longer than a session?
128
129
  \`\`\`
129
130
 
130
- \`Means\` says what the thing is, not what it does, in one or two sentences; \`Avoid\` — words not to use for it, so one thing has one name; \`Variants\` and \`Where\` as needed. Labels are in English; the term and its meaning in the language the term lives in. Write an article as a term settles in the talk, not at a shift. A meaning you inferred and did not check with the owner carries \`Unconfirmed: <what to ask>\` — ask, then drop the line. Only this project's words; no general programming terms.`
131
+ Each field is one line. \`Means\` says what the thing is, not what it does, in one or two sentences; \`Avoid\` — words not to use for it, so one thing has one name; \`Variants\` and \`Where\` as needed. Labels are in English; the term and its meaning in the language the term lives in. Write an article as a term settles in the talk, not at a shift. A meaning you inferred and did not check with the owner carries \`Unconfirmed: <what to ask>\` — ask, then drop the line. Only this project's words; no general programming terms.`
131
132
 
132
133
  const SHIFT_RULES = `\`${SHIFT_FILE}\` is how this project keeps its knowledge: rules written on the owner's word — where each kind of knowledge goes, how the documents are kept — and a map of the documents the mod writes between its markers. The map lists each document the settings name — a folder of them, or one such as \`AGENTS.md\` — with its \`description:\` (frontmatter: what is in the file and when to open it) and its \`##\` sections. The map only points: numbers, commands and names come from the document itself. A document without a description shows as such — give it one. A folder or a document of the settings with nothing to list is named in the map as \`no such folder\`, \`no documents\` or \`no such file\`: the project has no docs there, do not go searching. With \`[docs] dirs = []\` the owner turned the map off: leave the project's docs as they are.
133
134
 
134
135
  A \`> [!IMPORTANT]\` block in one of those documents is pinned: the map shows it under its document with its section, so it is in front of you in every session without opening the document. Pin only what you would get wrong in any task without it, in a line or two; change it in the document, never in the map. Nothing is pinned until you pin it. Past \`[docs] max_pinned\` the map says so and still shows every block — unpin what is not needed in every task.
135
136
 
136
- Those documents the mod keeps as you write them. After an Edit or a Write the map follows at once; with \`[docs] toc = true\` each document carries a toc between \`${TOC_START}\` and \`${TOC_END}\` under its \`# \` title, written by the mod from its \`##\` and \`###\` and the \`> \` line under a heading — never edit it by hand. The rest waits until the run is over, so a set of documents can be written in any order: with the next message the mod writes the tocs of the files you wrote and checks them, in one note — the tocs it wrote, so read such a file again before editing it, and the remarks: no description, a description or a file over the limits the settings set, a link to a document that is not there. Silence means all is well. The documents with remarks also come after a shift.`
137
+ Those documents the mod keeps as you write them. After an Edit or a Write the map follows at once; with \`[docs] toc = true\` each document carries a toc between \`${TOC_START}\` and \`${TOC_END}\` under its \`# \` title, written by the mod from its \`##\` and \`###\` and the \`> \` line under a heading — never edit it by hand. The rest waits until the run is over, so a set of documents can be written in any order: with the next message the mod writes the tocs of the files you wrote — by any tool, a script's change is found by its file's stamp — and checks them, in one note — the tocs it wrote, so read such a file again before editing it, and the remarks: no description, a description or a file over the limits the settings set, a link to a document that is not there. Silence means all is well. The documents with remarks also come after a shift.`
137
138
 
138
139
  // The section's text without its tag, for a harness that wraps a prompt section in a tag of its own; the tools are the
139
140
  // ones shown in this project, in the order given.
@@ -204,7 +205,7 @@ First the flow of a shift, then the rules of each record it checks.
204
205
  - \`letter\` — the path to the letter, usually \`${LETTER}\`;
205
206
  - \`after\` — \`continue\` if there is work to do without the owner; \`wait\` if the owner is needed or the work is over;
206
207
  - \`about\` — one line up to ${ABOUT_MAX} characters: what the stretch did and where you stand. This is the history line you will look the stretch up by, and it comes back after the next shifts: write the work, not whether you continue or wait.
207
- 4. End the turn, no further actions: with \`continue\` — one line; with \`wait\` — your answer to the owner, whole: what you did and found, what you ask them to decide. The owner reads that message, not your letter or records.
208
+ 4. End the turn, nothing more but what the call's result asks: with \`continue\` — one line; with \`wait\` — your answer to the owner, whole: what you did and found, what you ask them to decide. The owner reads that message, not your letter or records.
208
209
 
209
210
  After the shift, the first message is "Shift done": the board and the tasks in progress, whole, with their notes listed, and the map of knowledge — \`${SHIFT_FILE}\`, \`${OWNER}\`, \`${GLOSSARY}\` and \`${TASK_LIST}\` are read again into the session's own block; then the descriptions of the last ${RECENT_SHIFTS} shifts, an open task unchanged through ${STUCK_SHIFTS} shifts and the documents with remarks, if any; your letter last. Continue from "${NEXT}". With \`wait\` they come together with the owner's next message.
210
211
 
@@ -226,9 +227,9 @@ The mod looks at the records around every tool you run. A record you changed —
226
227
  - no \`${OWNER}\`, an empty one, more than ${OWNER_MAX_LINES} lines, \`${OLD_OWNER}\` still under the old name;
227
228
  - a knowledge file with an unknown \`kind\`, a name not of its kind, no \`about\`, more than ${KNOWLEDGE_MAX_LINES} lines, an entry without its fields, a glossary kept as knowledge;
228
229
  - \`${GLOSSARY}\`: an article without \`Means\`, an unknown label, a word in two articles, an avoided word used as a term, more than ${GLOSSARY_MAX_LINES} lines;
229
- - a date (\`YYYY-MM-DD\` or \`DD.MM.YYYY\`) in any record;
230
+ - a date (\`YYYY-MM-DD\` or \`DD.MM.YYYY\`) in the board, \`${TASK_LIST}\`, a task, the owner's decisions, the glossary or knowledge;
230
231
  - \`${DIR}/\` not ignored by the project's git, \`commit\` not set, and no exclude file to add it to;
231
- - \`${TASK_LIST}\`: a task with an unknown status or name, a folder not listed, a listed task without a folder, a link to nothing, \`needs\` on an archived task, tasks needing each other in a circle;
232
+ - \`${TASK_LIST}\`: a task with an unknown status or name, a folder not listed, a listed task without a folder, a link to nothing, \`needs\` on an archived task, \`after\` on an open one, tasks needing each other in a circle;
232
233
  - a task without \`task.md\` or \`track.md\`, without a title or a section, a track item without a status, a \`continues:\` line left in \`task.md\`, a note without its \`description\` or linked from nowhere, a link to a note that is not there;
233
234
  - nothing changed in the records since the last shift;
234
235
  - \`about\` empty, multi-line or longer than ${ABOUT_MAX} characters.
@@ -303,7 +304,7 @@ ${KNOWLEDGE_RULES}
303
304
 
304
305
  ## No dates
305
306
 
306
- No record carries a date: a model writes them everywhere, and records turn into a diary. Which of two rules is newer is never a question — a newer word rewrites the older line in place and a revoked one is removed, so only what is in force stands. When something was decided, the shift snapshots tell: \`${HISTORY_TOOL}\` finds the stretch, its folder holds the records as they were.
307
+ No record carries a date — the board, \`${TASK_LIST}\`, the tasks, \`${OWNER}\`, the glossary, the knowledge; the mod refuses a shift on one. A model writes dates everywhere, and records turn into a diary. The letter is not checked: keep a date there only where it is part of what must stay exact, such as an error's text. Which of two rules is newer is never a question — a newer word rewrites the older line in place and a revoked one is removed, so only what is in force stands. When something was decided, the shift snapshots tell: \`${HISTORY_TOOL}\` finds the stretch, its folder holds the records as they were.
307
308
 
308
309
  ## Archive — \`${ARCHIVE}/\`
309
310
 
@@ -316,35 +317,42 @@ The tool moves the folder to \`${ARCHIVE}/<name>/\` and adds \`- [<outcome>] [<t
316
317
 
317
318
  To come back to an archived topic, open a new task with \`${OPEN_TOOL}\` and \`continues: ["<name>"]\`, which puts \`- continues: [<name>](archive/<name>/)\` under its line in \`${TASK_LIST}\`; read the archived folder first.`
318
319
 
320
+ // The tree's rows: the prefix, the name, padded to its level's column, and what it is.
321
+ const row = (prefix: string, name: string, width: number, what: string) => `${prefix}${name.padEnd(width)}${what}`
322
+
323
+ const LAYOUT_TREE = [
324
+ `${DIR}/`,
325
+ row('├── ', NAMES.board, 18, 'the board — the goal, project-wide decisions and dead ends'),
326
+ row('├── ', NAMES.taskList, 18, 'the open tasks, what you do now, their links — every session'),
327
+ row('├── ', NAMES.owner, 18, "the owner's decisions in force for the whole project — every session"),
328
+ row('├── ', NAMES.glossary, 18, "the project's own words — every session"),
329
+ row('├── ', NAMES.shift, 18, 'how the project keeps its knowledge, and the map of its docs — every session'),
330
+ row('├── ', NAMES.settings, 18, "the owner's settings, optional — above"),
331
+ row('├── ', NAMES.letter, 18, 'the letter to yourself — written anew before every shift'),
332
+ row('├── ', `${NAMES.knowledge}/`, 18, 'traps, lessons, commands, facts — read on demand'),
333
+ '│ └── <kind>[-<topic>].md',
334
+ `├── ${NAMES.tasks}/`,
335
+ '│ └── <name>/',
336
+ row('│ ├── ', NAMES.task, 10, 'what the task is, its decisions and dead ends'),
337
+ row('│ ├── ', NAMES.track, 10, "the task's tracker"),
338
+ row('│ └── ', `${NAMES.notes}/`, 10, `notes on its items, each linked from ${NAMES.track} or ${NAMES.task}`),
339
+ row('├── ', `${NAMES.archive}/`, 18, `written by ${ARCHIVE_TOOL}; do not edit`),
340
+ row('│ ├── ', NAMES.index, 14, 'one line per archived task'),
341
+ row('│ └── ', '<name>/', 14, "the task's folder as it was"),
342
+ row('└── ', `${NAMES.shifts}/`, 18, 'history, written by the mod; do not edit'),
343
+ ' └── <YYYYMMDD-hhmmss UTC>/',
344
+ row(' ├── ', NAMES.about, 14, `the shift in brief — its structure is in ${GUIDE_TOOL}`),
345
+ row(' ├── ', NAMES.letter, 14, 'a copy of the letter'),
346
+ row(' ├── ', NAMES.board, 14, 'a snapshot of the board'),
347
+ row(' ├── ', `${[NAMES.taskList, NAMES.owner, NAMES.glossary, NAMES.shift, NAMES.settings].join(', ')}`, 0, ' snapshots'),
348
+ row(' ├── ', NAMES.index, 14, 'a snapshot of the archive index'),
349
+ row(' ├── ', `${NAMES.tasks}/`, 14, 'snapshots of the open tasks'),
350
+ row(' ├── ', `${NAMES.knowledge}/`, 14, 'a snapshot of the knowledge'),
351
+ row(' └── ', NAMES.summary, 14, 'what stayed in memory after the shift'),
352
+ ].join('\n')
353
+
319
354
  export const SETUP_LAYOUT = `\`\`\`
320
- ${DIR}/
321
- ├── board.md the board — the goal, project-wide decisions and dead ends
322
- ├── TASKS.md the open tasks, what you do now, their links — every session
323
- ├── OWNER.md the owner's decisions in force for the whole project — every session
324
- ├── GLOSSARY.md the project's own words — every session
325
- ├── SHIFT.md how the project keeps its knowledge, and the map of its docs — every session
326
- ├── settings.toml the owner's settings, optional — above
327
- ├── letter.md the letter to yourself — written anew before every shift
328
- ├── knowledge/ traps, lessons, commands, facts — read on demand
329
- │ └── <kind>[-<topic>].md
330
- ├── tasks/
331
- │ └── <name>/
332
- │ ├── task.md what the task is, its decisions and dead ends
333
- │ ├── track.md the task's tracker
334
- │ └── ${NAMES.notes}/ notes on its items, each linked from track.md or task.md
335
- ├── archive/ written by ${ARCHIVE_TOOL}; do not edit
336
- │ ├── index.md one line per archived task
337
- │ └── <name>/ the task's folder as it was
338
- └── shifts/ history, written by the mod; do not edit
339
- └── <YYYYMMDD-hhmmss UTC>/
340
- ├── about.md the shift in brief — its structure is in ${GUIDE_TOOL}
341
- ├── letter.md a copy of the letter
342
- ├── board.md a snapshot of the board
343
- ├── TASKS.md, OWNER.md, GLOSSARY.md, SHIFT.md, settings.toml snapshots
344
- ├── index.md a snapshot of the archive index
345
- ├── tasks/ snapshots of the open tasks
346
- ├── knowledge/ a snapshot of the knowledge
347
- └── summary.md what stayed in memory after the shift
355
+ ${LAYOUT_TREE}
348
356
  \`\`\`
349
357
 
350
358
  \`${DIR}/\` is yours. Whether the project's git takes it in is the owner's choice (\`commit\` above); by default it stays out: when the project's git does not ignore it, the mod adds it to the repository's local exclude file, which is never committed, and says so. It needs no git of its own: every shift snapshots the board, the owner's decisions, the tasks and the knowledge, so removing a line is safe.`