@iiiokojiadbi/shift 0.32.0 → 0.34.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/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)