@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.
@@ -0,0 +1,272 @@
1
+ // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
+ import { checkGlossary } from './glossary'
3
+ import {
4
+ atPlaces,
5
+ BOARD,
6
+ BOARD_MAX_LINES,
7
+ BOARD_SECTIONS,
8
+ DIR,
9
+ GLOSSARY,
10
+ GUIDE_TOOL,
11
+ KINDS,
12
+ KNOWLEDGE,
13
+ KNOWLEDGE_MAX_LINES,
14
+ LETTER_SECTIONS,
15
+ NAMES,
16
+ OLD_OWNER,
17
+ OLD_TASKS_SECTION,
18
+ OWNER,
19
+ OWNER_MAX_LINES,
20
+ OWNER_SECTION,
21
+ SETTINGS,
22
+ STATUSES,
23
+ TASK_LIST,
24
+ TASK_SECTIONS,
25
+ TASKS,
26
+ } from './layout'
27
+ import { blocks, dated, frontmatter, itemsOf, missingSections, overLimit, quote, sections, title } from './markdown'
28
+ import type { Project } from './project'
29
+ import { checkTaskList, type ListedTask, parseTaskList } from './tasks'
30
+ import type { Kind, KnowledgeFile, TaskFiles, Work } from './types'
31
+
32
+ export function checkLetter(text: string): string | null {
33
+ const missing = missingSections(text, LETTER_SECTIONS, 'The letter')
34
+ if (missing !== null) return missing
35
+ const found = sections(text)
36
+ const empty = LETTER_SECTIONS.filter(name => found.get(name) === '')
37
+ if (empty.length > 0) return `The letter has empty sections: ${quote(empty)}. Nothing to say — write "none".`
38
+
39
+ return null
40
+ }
41
+
42
+ // The open tasks as TASKS.md lists them; none when it is missing or does not parse.
43
+ export function listedTasks(work: Work): ListedTask[] {
44
+ const listed = work.taskList === null ? [] : parseTaskList(work.taskList)
45
+
46
+ return typeof listed === 'string' ? [] : listed
47
+ }
48
+
49
+ // The whole state of the work as one text, to tell whether anything moved since the last shift.
50
+ export function workText(work: Work): string {
51
+ const tasks = [...work.tasks].sort((a, b) => a.name.localeCompare(b.name))
52
+
53
+ return [
54
+ work.board.trim(),
55
+ (work.owner ?? '').trim(),
56
+ (work.taskList ?? '').trim(),
57
+ (work.glossary ?? '').trim(),
58
+ (work.shift ?? '').trim(),
59
+ ...tasks.map(
60
+ t => `${t.name}\n${(t.task ?? '').trim()}\n${(t.track ?? '').trim()}\n${t.notes.map(n => `${n.name}\n${n.text.trim()}`).join('\n')}`,
61
+ ),
62
+ ...work.knowledge.map(k => `${k.name}\n${k.text.trim()}`),
63
+ ].join('\n\n')
64
+ }
65
+
66
+ // The records against the previous shift's snapshot; a refusal names the files at the places the settings give.
67
+ export function checkWork(work: Work, previous: Work | null, project: Pick<Project, 'settings' | 'problem'>): string | null {
68
+ const problem = checkRecords(work, previous, project)
69
+
70
+ return problem === null ? null : atPlaces(problem, project.settings.files)
71
+ }
72
+
73
+ function checkRecords(work: Work, previous: Work | null, project: Pick<Project, 'settings' | 'problem'>): string | null {
74
+ const settingsProblem = checkSettings(project)
75
+ if (settingsProblem !== null) return settingsProblem
76
+ if (work.oldOwner) return `${OLD_OWNER} is the old name: owner decisions live in ${OWNER} now. Rename it and call again.`
77
+ const boardProblem = checkBoard(work.board)
78
+ if (boardProblem !== null) return boardProblem
79
+
80
+ const listProblem = checkTaskList(
81
+ work.taskList,
82
+ work.tasks.map(t => t.name),
83
+ work.archived,
84
+ )
85
+ if (listProblem !== null) return listProblem
86
+
87
+ const ownerProblem = checkOwner(work.owner)
88
+ if (ownerProblem !== null) return ownerProblem
89
+
90
+ for (const task of work.tasks) {
91
+ const problem = checkTask(task)
92
+ if (problem !== null) return problem
93
+ }
94
+
95
+ for (const file of work.knowledge) {
96
+ const problem = checkKnowledge(file)
97
+ if (problem !== null) return problem
98
+ }
99
+
100
+ const glossaryProblem = checkGlossary(work.glossary, GLOSSARY)
101
+ if (glossaryProblem !== null) return glossaryProblem
102
+
103
+ if (previous !== null && workText(previous) === workText(work)) {
104
+ return 'Nothing changed in the records since the last shift. Update the tracks, statuses and decisions, then shift.'
105
+ }
106
+
107
+ return null
108
+ }
109
+
110
+ // After the agent wrote one record: only the checks of that file, so a broken record is seen as it is written, not
111
+ // hundreds of K later at the shift. `path` is from the project's root; null for a file that is not a record.
112
+ export function checkWritten(path: string, work: Work, project: Pick<Project, 'settings' | 'problem'>): string | null {
113
+ const { files } = project.settings
114
+ const [dir, name = '', rest] = path.split('/').slice(1)
115
+ const inShift = path.startsWith(`${DIR}/`)
116
+ let problem: string | null = null
117
+ if (path === SETTINGS) problem = checkSettings(project)
118
+ else if (path === BOARD) problem = checkBoard(work.board)
119
+ else if (path === TASK_LIST)
120
+ problem = checkTaskList(
121
+ work.taskList,
122
+ work.tasks.map(t => t.name),
123
+ work.archived,
124
+ )
125
+ else if (path === files.owner) problem = checkOwner(work.owner)
126
+ else if (path === files.glossary) problem = checkGlossary(work.glossary, GLOSSARY)
127
+ else if (inShift && dir === NAMES.tasks && rest !== undefined) {
128
+ const task = work.tasks.find(each => each.name === name)
129
+ problem = task === undefined ? null : checkTask(task)
130
+ } else if (inShift && dir === NAMES.knowledge && rest === undefined && name.endsWith('.md')) {
131
+ const file = work.knowledge.find(each => each.name === name)
132
+ problem = file === undefined ? null : checkKnowledge(file)
133
+ }
134
+
135
+ return problem === null ? null : atPlaces(problem, files)
136
+ }
137
+
138
+ function checkSettings(project: Pick<Project, 'problem'>): string | null {
139
+ return project.problem === null ? null : `${project.problem} The file is the owner's: tell them, and do not shift until it is fixed.`
140
+ }
141
+
142
+ function checkBoard(board: string): string | null {
143
+ if (sections(board).has(OWNER_SECTION)) {
144
+ return `The board has an "## ${OWNER_SECTION}" section: owner decisions live in ${OWNER}. Move its lines there as they are, remove the section from the board, and call again.`
145
+ }
146
+ if (sections(board).has(OLD_TASKS_SECTION)) {
147
+ return `The board has a "## ${OLD_TASKS_SECTION}" section: the open tasks live in ${TASK_LIST} now, one line each with links under it — see ${GUIDE_TOOL}. Move them there and remove the section.`
148
+ }
149
+ const boardMissing = missingSections(board, BOARD_SECTIONS, 'The board')
150
+ if (boardMissing !== null) return boardMissing
151
+
152
+ return (
153
+ overLimit(
154
+ 'The board',
155
+ board,
156
+ BOARD_MAX_LINES,
157
+ 'it has become a diary. Move what belongs to one task into that task, keep only decisions in force.',
158
+ ) ??
159
+ dated('the board', board, "The board has no dates — each shift's time is recorded by itself.") ??
160
+ badRejected(board, 'The board')
161
+ )
162
+ }
163
+
164
+ export function checkTask({ name, task, track, notes: notes_ }: TaskFiles): string | null {
165
+ const where = `${TASKS}/${name}/`
166
+ if (task === null) return `${where} has no task.md.`
167
+ if (track === null) return `${where} has no track.md.`
168
+ if (title(task) === null) return `${where}task.md has no "# <title>" line.`
169
+ const missing = missingSections(task, TASK_SECTIONS, `${where}task.md`)
170
+ if (missing !== null) return missing
171
+ const date = dated(where, task, 'Tasks have no dates.') ?? dated(where, track, 'Tasks have no dates.')
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.`
175
+ const rejected = badRejected(task, `${where}task.md`)
176
+ if (rejected !== null) return rejected
177
+ const notes = checkNotes(where, task, track, notes_)
178
+ if (notes !== null) return notes
179
+ const bad = itemsOf(track).filter(item => !(STATUSES as readonly string[]).includes(item.status))
180
+ if (bad.length > 0)
181
+ return `Track items without a status (${STATUSES.join(', ')}) in ${where}track.md: ${quote(
182
+ bad.map(i => i.line),
183
+ '; ',
184
+ )}.`
185
+
186
+ return null
187
+ }
188
+
189
+ // A decision may name what it turned down: "rejected: <option> — <why>".
190
+ function badRejected(text: string, where: string): string | null {
191
+ const bad = (sections(text).get('Decisions') ?? '').split('\n').find(line => /rejected:/.test(line) && !/rejected: .+ — .+/.test(line))
192
+
193
+ return bad === undefined ? null : `${where}: "${bad.trim()}" — a rejected option needs its reason: "rejected: <option> — <why>".`
194
+ }
195
+
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".`
198
+ if (owner.trim() === '') return `${OWNER} is empty. No decisions yet — write "none".`
199
+ return (
200
+ overLimit(
201
+ OWNER,
202
+ owner,
203
+ OWNER_MAX_LINES,
204
+ 'it has become a log. Merge rules that say the same, drop revoked ones, move what binds one task into that task.',
205
+ ) ?? dated(OWNER, owner, "The owner's decisions have no dates: a newer word rewrites the older line.")
206
+ )
207
+ }
208
+
209
+ // A task's notes: each with its description, each linked from track.md or task.md, every link reaching a note. Beside
210
+ // the description a note is free: research, a decision worked out, evidence.
211
+ function checkNotes(where: string, task: string, track: string, notes: TaskFiles['notes']): string | null {
212
+ for (const note of notes) {
213
+ if ((frontmatter(note.text).get('description') ?? '') === '') {
214
+ return `${where}${NAMES.notes}/${note.name} needs a frontmatter "description": what is in it, as the list after a shift shows it.`
215
+ }
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}).`
218
+ }
219
+ }
220
+ 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
+ const missing = linked.filter(name => !names.has(name))
223
+
224
+ return missing.length === 0
225
+ ? null
226
+ : `${where} links to notes that are not there: ${quote(missing.map(name => `${NAMES.notes}/${name}`))}.`
227
+ }
228
+
229
+ export const isKind = (kind: string): kind is Kind => Object.hasOwn(KINDS, kind)
230
+
231
+ // An entry's command: a fenced block or an indented one.
232
+ const hasCommand = (body: string) => /^```/m.test(body) || /^ {4}\S/m.test(body)
233
+
234
+ export function checkKnowledge({ name, text }: KnowledgeFile): string | null {
235
+ const where = `${KNOWLEDGE}/${name}`
236
+ const meta = frontmatter(text)
237
+ const kind = meta.get('kind') ?? ''
238
+ if (kind === 'glossary')
239
+ return `${where} is a glossary: terms live in ${GLOSSARY} now, one article each — see ${GUIDE_TOOL}. Move them there and remove the file.`
240
+ if (!isKind(kind)) return `${where} needs a frontmatter "kind": one of ${Object.keys(KINDS).join(', ')}.`
241
+ if (name !== `${kind}.md` && !name.startsWith(`${kind}-`)) {
242
+ return `${where} is of kind "${kind}": name it ${kind}.md or ${kind}-<topic>.md.`
243
+ }
244
+ if ((meta.get('about') ?? '') === '') return `${where} needs a frontmatter "about": what is in it and where the neighbouring files are.`
245
+ const size =
246
+ overLimit(where, text, KNOWLEDGE_MAX_LINES, `drop what is dead, then split the rest by topic into ${kind}-<topic>.md files.`) ??
247
+ dated(where, text, 'Knowledge has no dates: an entry that lied is fixed or removed when it is used.')
248
+ if (size !== null) return size
249
+
250
+ const fields: readonly string[] = KINDS[kind]
251
+ const lacking = blocks(text, 3).filter(e => fields.some(f => !e.body.includes(f)) || (kind === 'runbook' && !hasCommand(e.body)))
252
+ if (lacking.length > 0) {
253
+ const need = kind === 'runbook' ? `a command block and ${quote(fields)}` : quote(fields)
254
+ return `Entries in ${where} lack ${need}: ${lacking.map(e => `"### ${e.title}"`).join(', ')}.`
255
+ }
256
+
257
+ return null
258
+ }
259
+
260
+ // What each knowledge file holds, one line per file: it is read on demand, not handed over.
261
+ export function knowledgeMap(files: readonly KnowledgeFile[]): string {
262
+ if (files.length === 0) return `${KNOWLEDGE}/ is empty.`
263
+
264
+ return files
265
+ .map(({ name, text }) => {
266
+ const kind = frontmatter(text).get('kind') ?? ''
267
+ const count = kind === 'glossary' ? text.split('\n').filter(line => line.startsWith('- **')).length : blocks(text, 3).length
268
+
269
+ return `- ${KNOWLEDGE}/${name} — ${frontmatter(text).get('about') ?? ''} (${count} ${kind === 'glossary' ? 'terms' : 'entries'})`
270
+ })
271
+ .join('\n')
272
+ }
@@ -0,0 +1,239 @@
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'
3
+ import { quote } from './markdown'
4
+ import { isInside } from './paths'
5
+
6
+ // The owner's settings for one project; the agent does not edit them.
7
+ export type Settings = {
8
+ // false turns the mod off in this project: no tools, no doctrine, no hints, no shifts.
9
+ enabled: boolean
10
+ // Where knowledge goes; null until the owner said, and then it stays in the records' knowledge folder.
11
+ knowledge: Placement | null
12
+ // true lets the project's git take the records in; false keeps them out, the mod excludes them itself.
13
+ commit: boolean
14
+ // Where the files loaded into every session live, relative to the project's root; `always` are the project's own
15
+ // files the owner wants whole in every session too.
16
+ files: { shift: string; owner: string; glossary: string; always: string[] }
17
+ docs: DocsSettings
18
+ }
19
+
20
+ // The project's documents the mod keeps: the folders, relative to the project's root (none — the mod touches no
21
+ // document), how long the map in SHIFT.md may be, whether each document carries a toc, and the limits a document is
22
+ // checked against after an edit (null — no such check).
23
+ export type DocsSettings = {
24
+ dirs: string[]
25
+ maxChars: number
26
+ maxPinned: number
27
+ toc: boolean
28
+ maxDescription: number | null
29
+ maxLines: number | null
30
+ }
31
+
32
+ export const PLACEMENTS = ['local', 'project', 'split'] as const
33
+ export type Placement = (typeof PLACEMENTS)[number]
34
+
35
+ export const DEFAULT_SETTINGS: Settings = {
36
+ enabled: true,
37
+ knowledge: null,
38
+ commit: false,
39
+ files: { shift: SHIFT_FILE, owner: OWNER, glossary: GLOSSARY, always: [] },
40
+ docs: {
41
+ dirs: ['docs'],
42
+ maxChars: DOCS_MAP_MAX_CHARS,
43
+ maxPinned: DOCS_PINNED_MAX_CHARS,
44
+ toc: false,
45
+ maxDescription: null,
46
+ maxLines: null,
47
+ },
48
+ }
49
+
50
+ type Value = string | boolean | number | string[]
51
+
52
+ // What a key's value is, and what is wrong with a value of another sort; null when it fits.
53
+ const KINDS = {
54
+ flag: (value: Value) => (typeof value === 'boolean' ? null : 'true or false'),
55
+ path: (value: Value) => (typeof value === 'string' && isInside(value) ? null : 'a path inside the project'),
56
+ files: (value: Value) => (Array.isArray(value) && value.every(isInside) ? null : 'a list of files inside the project'),
57
+ docs: (value: Value) => (Array.isArray(value) && value.every(isInside) ? null : 'a list of folders or documents inside the project'),
58
+ limit: (value: Value) => (typeof value === 'number' && Number.isInteger(value) && value > 0 ? null : 'a whole number above 0'),
59
+ placement: (value: Value) => ((PLACEMENTS as readonly unknown[]).includes(value) ? null : `one of ${quote(PLACEMENTS)}`),
60
+ }
61
+
62
+ // A key of the settings file: the mod's version it came in, what it does, the sort of its value and where it lives in
63
+ // the settings — a field, or a table and a field. One row is all a new key needs.
64
+ type Key = { key: string; since: string; kind: keyof typeof KINDS; at: [keyof Settings] | ['files' | 'docs', string]; about: string }
65
+
66
+ // Every key, so an agent after an update sees what is new.
67
+ export const SETTING_KEYS: readonly Key[] = [
68
+ {
69
+ key: 'enabled',
70
+ since: '0.2.9',
71
+ kind: 'flag',
72
+ at: ['enabled'],
73
+ about: 'false turns the mod off in this project from the next session: no tools, no doctrine, no hints',
74
+ },
75
+ {
76
+ key: 'knowledge',
77
+ since: '0.2.9',
78
+ kind: 'placement',
79
+ at: ['knowledge'],
80
+ about: 'where knowledge goes: "local", "project" or "split"; unset — local, and ask the owner once',
81
+ },
82
+ {
83
+ key: 'commit',
84
+ since: '0.2.9',
85
+ kind: 'flag',
86
+ at: ['commit'],
87
+ about: "true lets the project's git take the records in; false — the mod keeps them out by the local exclude file",
88
+ },
89
+ { key: 'files.shift', since: '0.3.0', kind: 'path', at: ['files', 'shift'], about: "where SHIFT.md lives, from the project's root" },
90
+ { key: 'files.owner', since: '0.3.0', kind: 'path', at: ['files', 'owner'], about: "where OWNER.md lives, from the project's root" },
91
+ {
92
+ key: 'files.glossary',
93
+ since: '0.3.0',
94
+ kind: 'path',
95
+ at: ['files', 'glossary'],
96
+ about: "where GLOSSARY.md lives, from the project's root",
97
+ },
98
+ {
99
+ key: 'files.always',
100
+ since: '0.5.0',
101
+ kind: 'files',
102
+ at: ['files', 'always'],
103
+ about: "the project's own files loaded whole into every session, beside SHIFT.md and OWNER.md",
104
+ },
105
+ {
106
+ key: 'docs.dirs',
107
+ since: '0.3.0',
108
+ kind: 'docs',
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',
112
+ },
113
+ {
114
+ key: 'docs.max_chars',
115
+ since: '0.4.3',
116
+ kind: 'limit',
117
+ at: ['docs', 'maxChars'],
118
+ about: 'how long the map may be: past it the sections go, then the descriptions, and the map says so',
119
+ },
120
+ {
121
+ key: 'docs.max_pinned',
122
+ since: '0.13.0',
123
+ kind: 'limit',
124
+ at: ['docs', 'maxPinned'],
125
+ about: 'how long the pinned `> [!IMPORTANT]` blocks of the docs may be together: past it the map says so and still shows them all',
126
+ },
127
+ {
128
+ key: 'docs.toc',
129
+ since: '0.5.0',
130
+ kind: 'flag',
131
+ at: ['docs', 'toc'],
132
+ about: 'true — the mod keeps a toc in each document under its # title',
133
+ },
134
+ {
135
+ key: 'docs.max_description',
136
+ since: '0.5.0',
137
+ kind: 'limit',
138
+ at: ['docs', 'maxDescription'],
139
+ about: "a document's description longer than this is a remark; unset — no such check",
140
+ },
141
+ {
142
+ key: 'docs.max_lines',
143
+ since: '0.5.0',
144
+ kind: 'limit',
145
+ at: ['docs', 'maxLines'],
146
+ about: 'a document longer than this many lines is a remark; unset — no such check',
147
+ },
148
+ ]
149
+
150
+ // Where a key's value lives: the settings or one of their tables, and the field in it.
151
+ function slot(settings: Settings, { at }: Key): [Record<string, unknown>, string] {
152
+ const [first, second] = at
153
+
154
+ return second === undefined ? [settings, first] : [settings[first as 'files' | 'docs'], second]
155
+ }
156
+
157
+ // The settings a file gives and the keys it sets itself; what is wrong with it otherwise.
158
+ export type ParsedSettings = { settings: Settings; set: ReadonlySet<string> }
159
+
160
+ // A flat subset of TOML: `key = value` lines with a string, a boolean, a number or a one-line array of strings,
161
+ // `#` comments, `[table]` headers that prefix the keys after them. A key outside the known ones is a mistake, not a
162
+ // setting the mod skips.
163
+ export function parseSettings(text: string): ParsedSettings | string {
164
+ const settings: Settings = { ...DEFAULT_SETTINGS, files: { ...DEFAULT_SETTINGS.files }, docs: { ...DEFAULT_SETTINGS.docs } }
165
+ const set = new Set<string>()
166
+ let table = ''
167
+ for (const [index, raw] of text.split('\n').entries()) {
168
+ const line = withoutComment(raw).trim()
169
+ if (line === '') continue
170
+ const header = /^\[([A-Za-z0-9_.-]+)\]$/.exec(line)
171
+ if (header !== null) {
172
+ table = `${header[1]}.`
173
+ continue
174
+ }
175
+ const pair = /^([A-Za-z0-9_-]+)\s*=\s*(.+)$/.exec(line)
176
+ const value = pair === null ? undefined : tomlValue(pair[2] ?? '')
177
+ if (pair === null || value === undefined)
178
+ return `${SETTINGS}, line ${index + 1}: expected \`key = value\` with a string, true/false, a number or ["strings"], got "${raw.trim()}".`
179
+ const name = `${table}${pair[1]}`
180
+ const key = SETTING_KEYS.find(each => each.key === name)
181
+ if (key === undefined)
182
+ return `${SETTINGS}: unknown key \`${name}\`; the keys are ${SETTING_KEYS.map(each => `\`${each.key}\``).join(', ')}.`
183
+ const wanted = KINDS[key.kind](value)
184
+ if (wanted !== null) return `${SETTINGS}: \`${name}\` is ${wanted}, got ${JSON.stringify(value)}.`
185
+ const [holder, field] = slot(settings, key)
186
+ holder[field] = value
187
+ set.add(name)
188
+ }
189
+
190
+ return { settings, set }
191
+ }
192
+
193
+ // A key's value in the settings, as TOML; null when the key is unset and has no value of its own.
194
+ export function settingValue(settings: Settings, key: string): string | null {
195
+ const row = SETTING_KEYS.find(each => each.key === key)
196
+ if (row === undefined) return null
197
+ const [holder, field] = slot(settings, row)
198
+ const value = holder[field]
199
+
200
+ return value === null || value === undefined ? null : JSON.stringify(value).replace(/","/g, '", "')
201
+ }
202
+
203
+ function withoutComment(line: string): string {
204
+ let quote: string | null = null
205
+ for (let index = 0; index < line.length; index++) {
206
+ const char = line[index]
207
+ if (quote !== null) {
208
+ if (char === quote) quote = null
209
+ } else if (char === '"' || char === "'") quote = char
210
+ else if (char === '#') return line.slice(0, index)
211
+ }
212
+
213
+ return line
214
+ }
215
+
216
+ function tomlValue(raw: string): Value | undefined {
217
+ const value = raw.trim()
218
+ if (value === 'true') return true
219
+ if (value === 'false') return false
220
+ if (/^[+-]?\d+(\.\d+)?$/.test(value)) return Number(value)
221
+ 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
+ }
231
+
232
+ return quoted(value)
233
+ }
234
+
235
+ function quoted(value: string): string | undefined {
236
+ const found = /^"([^"\\]*)"$|^'([^']*)'$/.exec(value)
237
+
238
+ return found === null ? undefined : (found[1] ?? found[2])
239
+ }
package/core/setup.ts ADDED
@@ -0,0 +1,105 @@
1
+ // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
+ import { docsReport } from './docs'
3
+ import { sessionFiles, staleLayout } from './flows'
4
+ import { atPlaces, BOARD, GUIDE_TOOL, MOD, SETTINGS } from './layout'
5
+ import { formatK } from './markdown'
6
+ import type { Project } from './project'
7
+ import { checkWork } from './records'
8
+ import { SETTING_KEYS, settingValue } from './settings'
9
+ import { readRecords } from './store'
10
+ import { doctrine, SETUP_LAYOUT, SETUP_MIGRATION } from './texts/doctrine'
11
+ import { fileBlock } from './texts/prompts'
12
+ import { shownTools } from './tools'
13
+
14
+ // How the mod is set up in this project: every setting with its value here and the version it came in, the files of
15
+ // the session's block and whether the block the session holds is older than them, the layout and the migrations.
16
+ // `loaded` is the block as this session read it; null when the harness does not keep one.
17
+ export async function setupReport(project: Project, loaded: string | null): Promise<string> {
18
+ const { settings } = project
19
+ const state =
20
+ project.settingsText === null
21
+ ? 'No settings file: every key is at its default.'
22
+ : project.problem !== null
23
+ ? `It does not parse — ${project.problem} The mod stays on with the defaults, and a shift is refused until it is fixed.`
24
+ : 'It parses.'
25
+ const keys = SETTING_KEYS.map(({ key, since, about }) => {
26
+ const value = settingValue(settings, key)
27
+ const where = project.set.has(key) ? 'set here' : 'default'
28
+
29
+ return `- \`${tomlKey(key)}\` = ${value ?? 'unset'} — ${where}, since ${since}: ${about}`
30
+ })
31
+
32
+ const files = await sessionFiles(project)
33
+ 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')
47
+
48
+ return [
49
+ `# The ${MOD} mod in this project`,
50
+ '',
51
+ `## Settings — \`${SETTINGS}\``,
52
+ '',
53
+ `The owner's file: change it only on their word. ${state} A change takes effect for the session's block at the next shift or in a new session, for everything else at once. Every key, its value here, the mod's version it came in, what it does:`,
54
+ '',
55
+ ...keys,
56
+ '',
57
+ '## Records',
58
+ '',
59
+ await recordsState(project),
60
+ '',
61
+ '## The session block',
62
+ '',
63
+ 'Loaded whole into every session, with what each costs:',
64
+ '',
65
+ block,
66
+ '',
67
+ '## Documents',
68
+ '',
69
+ settings.docs.dirs.length === 0
70
+ ? 'Off: `[docs] dirs = []`, the mod leaves the documents alone.'
71
+ : ((await docsReport(project)) ?? 'No remarks.'),
72
+ '',
73
+ `## Files`,
74
+ '',
75
+ SETUP_LAYOUT,
76
+ '',
77
+ SETUP_MIGRATION,
78
+ ].join('\n')
79
+ }
80
+
81
+ // The records as they are, by every check a shift makes but "nothing changed": a rule added in a newer version, or a
82
+ // record broken by a hand outside the agent's tools before the mod looked, shows here and not only at the shift.
83
+ async function recordsState(project: Project): Promise<string> {
84
+ if (!project.settings.enabled) return 'Off: `enabled = false`, the mod keeps no records here.'
85
+ const stale = await staleLayout(project)
86
+ if (stale !== null) return stale
87
+ const work = await readRecords(project)
88
+ if (work === null) return `No board yet: create ${BOARD} by the sections in ${GUIDE_TOOL} before the first shift.`
89
+ const problem = checkWork(work, null, project)
90
+
91
+ return problem === null ? 'They pass every check a shift makes.' : `A shift would refuse them now: ${problem}`
92
+ }
93
+
94
+ // What a text costs in the context: its characters and the tokens they come to, roughly.
95
+ const CHARS_PER_TOKEN = 4
96
+
97
+ function weight(chars: number): string {
98
+ return `${formatK(chars)} characters, ~${formatK(Math.round(chars / CHARS_PER_TOKEN))} tokens`
99
+ }
100
+
101
+ function tomlKey(key: string): string {
102
+ const dot = key.indexOf('.')
103
+
104
+ return dot === -1 ? key : `[${key.slice(0, dot)}] ${key.slice(dot + 1)}`
105
+ }