@iiiokojiadbi/shift 0.0.0-stage → 0.28.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/hint.ts ADDED
@@ -0,0 +1,241 @@
1
+ // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
+ import { BOARD, TASK_LIST, TASKS, TOOL } from './layout'
3
+ import { formatK } from './markdown'
4
+ import type { Gauge, Reading } from './types'
5
+
6
+ // Every step is a share of the limit — the harness's own threshold, or the window when it is unknown — so the rhythm is the same on any window.
7
+ // Soft hints come every max(100K, 25%) of growth: a shorter stretch does not pay for its own letter and records.
8
+ export function softStep(limit: number): number {
9
+ return Math.max(100_000, Math.round(limit / 4))
10
+ }
11
+
12
+ // The final hint comes at 80% of the limit, with room left to finish a stage, and again every 5% after it.
13
+ export function finalAt(limit: number): number {
14
+ return Math.round(limit * 0.8)
15
+ }
16
+
17
+ export function finalStep(limit: number): number {
18
+ return Math.round(limit / 20)
19
+ }
20
+
21
+ export const FRESH_GAUGE: Gauge = { base: null, hinted: null, unassisted: false, growth: {}, whole: false }
22
+
23
+ // Where a row of the history came from, as hints name it.
24
+ export const SOURCES = {
25
+ responses: 'your responses',
26
+ owner: "the owner's messages",
27
+ attachments: 'attachments and reminders',
28
+ tools: 'tool results',
29
+ } as const
30
+
31
+ // A history smaller than the base or the last hint was let go by a way the mod did not see (a cleared session, a
32
+ // compaction it was not told of): counting from the old base would put the next hint far off, so it starts again here.
33
+ function rebased(gauge: Gauge, tokens: number): Gauge {
34
+ return gauge.base !== null && tokens < (gauge.hinted ?? gauge.base) ? { ...gauge, base: tokens, hinted: null, growth: {} } : gauge
35
+ }
36
+
37
+ // One hint at most per new growth; an ignored one is not repeated until the history grows again.
38
+ export function shiftHint(current: Gauge, { tokens, window, threshold }: Reading): { gauge: Gauge; text: string | null } {
39
+ if (tokens === undefined) return { gauge: current, text: null }
40
+ const gauge = rebased(current, tokens)
41
+ if (gauge.base === null) return { gauge: { ...gauge, base: tokens, unassisted: false }, text: gauge.unassisted ? UNASSISTED_HINT : null }
42
+
43
+ const limit = threshold ?? window
44
+ const final = finalAt(limit)
45
+ const grown = tokens - gauge.base
46
+ const since = tokens - (gauge.hinted ?? gauge.base)
47
+ const hinted = { ...gauge, hinted: tokens }
48
+ if (grown < finalStep(limit)) return { gauge, text: null }
49
+
50
+ if (tokens >= final) {
51
+ const isFirst = gauge.hinted === null || gauge.hinted < final
52
+ return isFirst || since >= finalStep(limit) ? { gauge: hinted, text: finalHint(tokens, limit, gauge.growth) } : { gauge, text: null }
53
+ }
54
+ // No soft hint right before the final one: it would come twice in a row.
55
+ const step = softStep(limit)
56
+ if (since >= step && tokens + step / 2 <= final) return { gauge: hinted, text: softHint(grown, gauge.growth) }
57
+
58
+ return { gauge, text: null }
59
+ }
60
+
61
+ function softHint(grown: number, growth: Record<string, number>): string {
62
+ return `Shift hint: the history has grown by ${formatK(grown)} since the last shift.${sources(growth)} This is not an alarm — running out of room gets a hint of its own. If you are at a stage boundary and the stretch's history is not needed whole any more, shift; if not, go on — the next hint comes after new growth.`
63
+ }
64
+
65
+ function finalHint(tokens: number, limit: number, growth: Record<string, number>): string {
66
+ return `Shift hint: ${formatK(tokens)} of ${formatK(limit)} used — close to the point where the harness lets the history go by itself, without your letter.${sources(growth)} Shift at the nearest stage boundary: board, tasks, letter, \`${TOOL}\`.`
67
+ }
68
+
69
+ // Token counts per row are not known, so the growth is counted in characters and named by shares.
70
+ export function addGrowth(gauge: Gauge, source: string, chars: number): Gauge {
71
+ if (chars <= 0) return gauge
72
+ return { ...gauge, growth: { ...gauge.growth, [source]: (gauge.growth[source] ?? 0) + chars } }
73
+ }
74
+
75
+ // The sources of at least 5% of the growth, largest first, three at most.
76
+ export function growthShares(growth: Record<string, number>): { source: string; share: number }[] {
77
+ const total = Object.values(growth).reduce((sum, chars) => sum + chars, 0)
78
+ if (total === 0) return []
79
+ return Object.entries(growth)
80
+ .map(([source, chars]) => ({ source, share: Math.round((chars / total) * 100) }))
81
+ .filter(each => each.share >= 5)
82
+ .sort((a, b) => b.share - a.share)
83
+ .slice(0, 3)
84
+ }
85
+
86
+ function sources(growth: Record<string, number>): string {
87
+ const shares = growthShares(growth)
88
+ return shares.length === 0 ? '' : ` Mostly from: ${shares.map(each => `${each.source} ${each.share}%`).join(', ')}.`
89
+ }
90
+
91
+ // Characters of a row's content, whatever its blocks: text, tool calls and their results, thinking; an image counts as a fixed size.
92
+ export function contentChars(content: unknown): number {
93
+ if (typeof content === 'string') return content.length
94
+ if (Array.isArray(content)) return content.reduce((sum: number, block) => sum + contentChars(block), 0)
95
+ if (typeof content !== 'object' || content === null) return 0
96
+ const block = content as Record<string, unknown>
97
+ if (block.type === 'image') return IMAGE_CHARS
98
+ if (typeof block.text === 'string') return block.text.length
99
+ if (typeof block.thinking === 'string') return block.thinking.length
100
+ if (block.type === 'tool_use') return JSON.stringify(block.input ?? {}).length
101
+ if (block.type === 'toolCall') return JSON.stringify(block.arguments ?? {}).length
102
+ if (block.type === 'tool_result') return contentChars(block.content)
103
+ return 0
104
+ }
105
+
106
+ const IMAGE_CHARS = 6000
107
+
108
+ // The growth of a history already there, counted the way rows are counted as they come: a tool result by the tool's name.
109
+ export function growthOf(messages: readonly { role: string; content: unknown }[]): Record<string, number> {
110
+ const tools = new Map<string, string>()
111
+ let gauge: Gauge = FRESH_GAUGE
112
+ for (const message of messages) {
113
+ const blocks = Array.isArray(message.content)
114
+ ? (message.content as Record<string, unknown>[])
115
+ : [{ type: 'text', text: message.content }]
116
+ if (message.role === 'assistant') {
117
+ for (const block of blocks) if (block.type === 'tool_use') tools.set(String(block.id), String(block.name))
118
+ gauge = addGrowth(gauge, SOURCES.responses, contentChars(blocks))
119
+ continue
120
+ }
121
+ for (const block of blocks) {
122
+ const source =
123
+ block.type === 'tool_result'
124
+ ? (tools.get(String(block.tool_use_id)) ?? SOURCES.tools)
125
+ : typeof block.text === 'string' && block.text.trimStart().startsWith('<system-reminder>')
126
+ ? SOURCES.attachments
127
+ : SOURCES.owner
128
+ gauge = addGrowth(gauge, source, contentChars(block))
129
+ }
130
+ }
131
+
132
+ return gauge.growth
133
+ }
134
+
135
+ // What the status tool answers: the fill, the limit, the growth since the last shift, when the next hints come, and what grew.
136
+ export function renderStatus(current: Gauge, { tokens, window, threshold }: Reading): string {
137
+ if (tokens === undefined) return 'No reading yet: the first response since the last let-go has not come back.'
138
+ const gauge = rebased(current, tokens)
139
+ const limit = threshold ?? window
140
+ const final = finalAt(limit)
141
+ const lines = [
142
+ `Used: ${formatK(tokens)} of ${formatK(window)} window; ${threshold === undefined ? 'the harness threshold is not read yet, the window stands for it' : `the harness lets the history go by itself at ${formatK(threshold)}`}.`,
143
+ ]
144
+ if (gauge.base !== null) lines.push(`Since the last shift: +${formatK(Math.max(0, tokens - gauge.base))}.`)
145
+ if (tokens >= final) lines.push(`Past the final hint at ${formatK(final)}: shift at the nearest stage boundary.`)
146
+ else {
147
+ const soft = (gauge.hinted ?? gauge.base ?? tokens) + softStep(limit)
148
+ const next = soft + softStep(limit) / 2 <= final ? `next soft hint at ${formatK(soft)}` : 'no soft hint before the final'
149
+ lines.push(`Hints: ${next}; final at ${formatK(final)}.`)
150
+ }
151
+ const shares = growthShares(gauge.growth)
152
+ if (shares.length > 0) lines.push(`Grown mostly from: ${shares.map(each => `${each.source} ${each.share}%`).join(', ')}.`)
153
+
154
+ return lines.join('\n')
155
+ }
156
+
157
+ export const UNASSISTED_HINT = `The harness let the history go by itself, without your shift: there is no letter, only its digest is in memory. Before going on, read the board \`${BOARD}\`, \`${TASK_LIST}\` and the tasks in progress in \`${TASKS}/\`, and check where you stand against them.`
158
+
159
+ // The gauge as an adapter keeps it, and what only the harness knows; how it is kept is the core's. A fresh process
160
+ // (a restart, a reload, a resumed session) starts with none of the stretch counted and restores it once.
161
+ export type GaugeKeeper = {
162
+ // The gauge as kept; null or a gauge of an older version of the mod is completed with the fields added since.
163
+ read(): Promise<Gauge | null>
164
+ // A change applied to the gauge as it is then: a harness that serializes state changes applies it atomically.
165
+ update(change: (current: Gauge) => Gauge): Promise<void>
166
+ // The growth of the history as it is now, per source: what a fresh process counts from.
167
+ history(): Promise<Record<string, number>>
168
+ // The fill the stretch started from, if the last shift was this session's.
169
+ base(): Promise<number | null>
170
+ // How full the history is.
171
+ reading(): Promise<Reading>
172
+ }
173
+
174
+ // A gauge after any let-go of the main history: a new stretch, whole from its start; one the agent did not ask for
175
+ // is told to it at its next look.
176
+ export function letGoGauge(unassisted: boolean): Gauge {
177
+ return { ...FRESH_GAUGE, unassisted, whole: true }
178
+ }
179
+
180
+ // A hint for the agent if the fill since the last shift calls for one.
181
+ export async function takeHint(keeper: GaugeKeeper): Promise<string | null> {
182
+ await restore(keeper)
183
+ const reading = await keeper.reading()
184
+ let text: string | null = null
185
+ await keeper.update(current => {
186
+ const hint = shiftHint(complete(current), reading)
187
+ text = hint.text
188
+
189
+ return hint.gauge
190
+ })
191
+
192
+ return text
193
+ }
194
+
195
+ // What a row added to the stretch's history, by where it came from.
196
+ export async function countGrowth(keeper: GaugeKeeper, source: string, chars: number): Promise<void> {
197
+ await restore(keeper)
198
+ await keeper.update(current => addGrowth(complete(current), source, chars))
199
+ }
200
+
201
+ // What shift_status answers.
202
+ export async function gaugeStatus(keeper: GaugeKeeper): Promise<string> {
203
+ await restore(keeper)
204
+ const reading = await keeper.reading()
205
+
206
+ return renderStatus(complete(await keeper.read()), reading)
207
+ }
208
+
209
+ function complete(current: Gauge | null): Gauge {
210
+ return { ...FRESH_GAUGE, ...current }
211
+ }
212
+
213
+ // The base from the last shift of this session, the growth from the history plus whatever this process counted before
214
+ // the restore finished, and the last hint as given before. Once; a let-go marks the count whole itself.
215
+ async function restore(keeper: GaugeKeeper): Promise<void> {
216
+ if (complete(await keeper.read()).whole) return
217
+ const base = await keeper.base()
218
+ const growth = await keeper.history()
219
+ const reading = await keeper.reading()
220
+ await keeper.update(current => {
221
+ const now = complete(current)
222
+ if (now.whole) return now
223
+ const merged = Object.entries(now.growth).reduce((sum, [source, chars]) => addGrowth(sum, source, chars), { ...now, growth })
224
+ const from = now.base ?? base
225
+
226
+ return { ...merged, base: from, hinted: now.hinted ?? lastStep(from, reading), whole: true }
227
+ })
228
+ }
229
+
230
+ // The last step the history has passed since the base: its hint was given before the restart, so it is not repeated,
231
+ // and the next step still hints.
232
+ export function lastStep(base: number | null, { tokens, window, threshold }: Reading): number | null {
233
+ if (base === null || tokens === undefined || tokens < base) return null
234
+ const limit = threshold ?? window
235
+ const final = finalAt(limit)
236
+ if (tokens >= final) return final + Math.floor((tokens - final) / finalStep(limit)) * finalStep(limit)
237
+ const step = softStep(limit)
238
+ const passed = Math.floor((tokens - base) / step)
239
+
240
+ return passed > 0 ? base + passed * step : null
241
+ }
@@ -0,0 +1,73 @@
1
+ // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
+ import { readAbout } from './about'
3
+ import { CLOSED, SHIFTS } from './layout'
4
+ import { itemsOf } from './markdown'
5
+ import { listedTasks } from './records'
6
+ import type { HistoryEntry, Segment, Snapshot } from './types'
7
+
8
+ export function stamp(ms: number): string {
9
+ const d = new Date(ms)
10
+ const pad = (n: number) => String(n).padStart(2, '0')
11
+
12
+ return `${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}-${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}${pad(d.getUTCSeconds())}`
13
+ }
14
+
15
+ export function shiftDir(root: string, ms: number): string {
16
+ return `${root}/${SHIFTS}/${stamp(ms)}`
17
+ }
18
+
19
+ export function segment(now: Snapshot, previous: Snapshot | null): Segment {
20
+ const closedBefore = new Map<string, Set<string>>()
21
+ for (const task of previous?.work.tasks ?? []) {
22
+ closedBefore.set(
23
+ task.name,
24
+ new Set(
25
+ itemsOf(task.track ?? '')
26
+ .filter(i => CLOSED.has(i.status))
27
+ .map(i => i.name),
28
+ ),
29
+ )
30
+ }
31
+ const fresh = now.work.tasks.flatMap(task =>
32
+ itemsOf(task.track ?? '')
33
+ .filter(item => CLOSED.has(item.status) && !(closedBefore.get(task.name)?.has(item.name) ?? false))
34
+ .map(item => ({ status: item.status, text: `${task.name}: ${item.rest}` })),
35
+ )
36
+ const indexed = new Set(itemsOf(previous?.index ?? '').map(i => i.line))
37
+
38
+ return {
39
+ done: fresh.filter(f => f.status === 'done').map(f => f.text),
40
+ dropped: fresh.filter(f => f.status === 'dropped').map(f => f.text),
41
+ archived: itemsOf(now.index ?? '')
42
+ .filter(i => !indexed.has(i.line))
43
+ .map(i => i.line.slice(2)),
44
+ open: listedTasks(now.work).map(t => t.line.slice(2)),
45
+ }
46
+ }
47
+
48
+ export function renderSummary(messages: readonly { role: string; text: string }[]): string {
49
+ return `${messages.map(m => `## ${m.role}\n\n${m.text}`).join('\n\n')}\n`
50
+ }
51
+
52
+ export function renderHistory(entries: HistoryEntry[], total: number): string {
53
+ if (entries.length === 0) return `No shifts in this project yet: ${SHIFTS}/ is empty.`
54
+
55
+ const blocks = entries.map((entry, index) => {
56
+ if (entry.about === null) return `### ${entry.name}\n\nNo about.md.`
57
+ const about = readAbout(entry.about)
58
+ const lines = [`### ${entry.name} · ${about.after ?? '?'} · ${about.result ?? '?'}`, '', about.description ?? '']
59
+ for (const [heading, listed] of [
60
+ ['Done', about.done],
61
+ ['Dropped', about.dropped],
62
+ ['Archived', about.archived],
63
+ ] as const) {
64
+ if (listed.length > 0) lines.push('', `${heading}: ${listed.join('; ')}`)
65
+ }
66
+ if (index === entries.length - 1) lines.push('', `Open: ${about.open.length === 0 ? 'none' : about.open.join('; ')}`)
67
+
68
+ return lines.join('\n')
69
+ })
70
+ const head = `Shifts, oldest first: ${entries.length} of ${total}. Folders — ${SHIFTS}/<name>/.`
71
+
72
+ return [head, ...blocks].join('\n\n')
73
+ }
package/core/index.ts ADDED
@@ -0,0 +1,25 @@
1
+ // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
+ export * from './about'
3
+ export * from './archive'
4
+ export * from './delivery'
5
+ export * from './docs'
6
+ export * from './flows'
7
+ export * from './hint'
8
+ export * from './history'
9
+ export * from './input'
10
+ export * from './layout'
11
+ export * from './loop'
12
+ export * from './markdown'
13
+ export * from './paths'
14
+ export * from './project'
15
+ export * from './records'
16
+ export * from './settings'
17
+ export * from './setup'
18
+ export * from './store'
19
+ export * from './texts/doctrine'
20
+ export * from './texts/prompts'
21
+ export * from './texts/rows'
22
+ export * from './texts/tools'
23
+ export * from './tools'
24
+ export * from './track'
25
+ export * from './types'
package/core/input.ts ADDED
@@ -0,0 +1,198 @@
1
+ // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
+ import {
3
+ ABOUT_MAX,
4
+ AFTER,
5
+ FOCUS,
6
+ HISTORY_DEFAULT,
7
+ HISTORY_MAX,
8
+ LETTER,
9
+ NAME,
10
+ NAME_RULE,
11
+ OUTCOMES,
12
+ STATUSES,
13
+ TASK_LIST,
14
+ TASKS,
15
+ } from './layout'
16
+ import { dated, isOneOf, quote } from './markdown'
17
+ import type { ArchiveInput, ItemChange, OpenInput, ShiftInput, TrackInput } from './types'
18
+
19
+ // A string argument, trimmed; '' when it is missing or not a string.
20
+ function text(raw: Record<string, unknown>, key: string): string {
21
+ const value = raw[key]
22
+
23
+ return typeof value === 'string' ? value.trim() : ''
24
+ }
25
+
26
+ // A string argument that may be left out: null when it is missing or empty.
27
+ function optional(raw: Record<string, unknown>, key: string): string | null {
28
+ return text(raw, key) === '' ? null : text(raw, key)
29
+ }
30
+
31
+ // What is wrong with a one-line argument — a line break, past `max` characters, a date where records have none;
32
+ // null when it is fine.
33
+ function lineProblem(key: string, value: string, rules: { max?: number; noDates?: boolean }): string | null {
34
+ if (value.includes('\n')) return `${key} is one line, without line breaks.`
35
+ if (rules.max !== undefined && value.length > rules.max)
36
+ return `${key} is ${value.length} characters, the limit is ${rules.max}. Shorten it.`
37
+
38
+ return rules.noDates ? dated(key, value, 'Records have no dates.') : null
39
+ }
40
+
41
+ // The `about` of a shift or an archived task: required, one line, within the limit.
42
+ function about(raw: Record<string, unknown>, what: string): string | null {
43
+ const value = text(raw, 'about')
44
+
45
+ return value === '' ? `about is empty: one line — ${what}.` : lineProblem('about', value, { max: ABOUT_MAX })
46
+ }
47
+
48
+ // A task folder name argument, or what is wrong with it.
49
+ function taskName(raw: Record<string, unknown>, key: string): string | { problem: string } {
50
+ const name = text(raw, key)
51
+
52
+ return NAME.test(name) ? name : { problem: `${key} is a task folder name in ${TASKS}/: ${NAME_RULE}.` }
53
+ }
54
+
55
+ export function parseShiftInput(raw: Record<string, unknown>): ShiftInput | string {
56
+ const letter = text(raw, 'letter')
57
+ const after = raw.after
58
+ if (letter === '') return `letter is empty: write the letter to yourself (${LETTER}) and pass its path.`
59
+ if (!isOneOf(AFTER, after)) return `after must be ${quote(AFTER, ' or ')}.`
60
+
61
+ return about(raw, 'what the stretch did and where you stand') ?? { letter, after, about: text(raw, 'about') }
62
+ }
63
+
64
+ export function parseArchiveInput(raw: Record<string, unknown>): ArchiveInput | string {
65
+ const name = taskName(raw, 'name')
66
+ if (typeof name !== 'string') return name.problem
67
+ const outcome = raw.outcome
68
+ if (!isOneOf(OUTCOMES, outcome)) return `outcome must be ${quote(OUTCOMES, ' or ')}.`
69
+
70
+ return about(raw, 'what the task was and how it ended') ?? { name, outcome, about: text(raw, 'about') }
71
+ }
72
+
73
+ // The lines of a list argument, each `words — what matters` split at its first " — "; what is wrong with one otherwise.
74
+ function splitLines(raw: Record<string, unknown>, key: string): { name: string; note: string | null }[] | string {
75
+ const value = raw[key] ?? []
76
+ if (!Array.isArray(value) || value.some(each => typeof each !== 'string')) return `${key} is a list of lines.`
77
+ const lines: { name: string; note: string | null }[] = []
78
+ for (const each of value as string[]) {
79
+ const line = each.trim()
80
+ const problem = line === '' ? `${key} has an empty line.` : lineProblem(key, line, { noDates: true })
81
+ if (problem !== null) return problem
82
+ const at = line.indexOf(' — ')
83
+ lines.push(at === -1 ? { name: line, note: null } : { name: line.slice(0, at).trim(), note: line.slice(at + 3).trim() || null })
84
+ }
85
+
86
+ return lines
87
+ }
88
+
89
+ export function parseOpenInput(raw: Record<string, unknown>): OpenInput | string {
90
+ const name = taskName(raw, 'name')
91
+ if (typeof name !== 'string') return name.problem
92
+ const status = text(raw, 'status') || 'in progress'
93
+ if (!(FOCUS as readonly string[]).includes(status)) return `status is one of ${quote(FOCUS)}.`
94
+ const fields = { title: text(raw, 'title'), goal: text(raw, 'goal'), doneWhen: text(raw, 'done_when') }
95
+ for (const [key, value] of [
96
+ ['title', fields.title],
97
+ ['goal', fields.goal],
98
+ ['done_when', fields.doneWhen],
99
+ ] as const) {
100
+ if (value === '') return `${key} is empty.`
101
+ const problem = key === 'title' ? lineProblem(key, value, { noDates: true }) : dated(key, value, 'Tasks have no dates.')
102
+ if (problem !== null) return problem
103
+ }
104
+ const what = status === 'in progress' ? 'what the task is' : `what the task is and why it is ${status}`
105
+ const line = about(raw, what)
106
+ if (line !== null) return line
107
+ const items = splitLines(raw, 'items')
108
+ if (typeof items === 'string') return items
109
+ const links: OpenInput['links'] = []
110
+ for (const kind of ['needs', 'after', 'continues'] as const) {
111
+ const listed = splitLines(raw, kind)
112
+ if (typeof listed === 'string') return listed
113
+ for (const each of listed) {
114
+ if (!NAME.test(each.name)) return `${kind}: "${each.name}" is not a task name — ${NAME_RULE}, then " — why" if it needs one.`
115
+ links.push({ kind, name: each.name, why: each.note })
116
+ }
117
+ }
118
+
119
+ return { name, status, ...fields, about: text(raw, 'about'), items, links }
120
+ }
121
+
122
+ export function parseHistoryCount(raw: Record<string, unknown>): number | string {
123
+ const count = raw.count ?? HISTORY_DEFAULT
124
+ if (typeof count !== 'number' || !Number.isInteger(count) || count < 1 || count > HISTORY_MAX) {
125
+ return `count is an integer from 1 to ${HISTORY_MAX}.`
126
+ }
127
+
128
+ return count
129
+ }
130
+
131
+ // The one path argument of a docs tool; null when it is missing or empty.
132
+ export function parsePath(raw: Record<string, unknown>, key: 'path' | 'file'): string | null {
133
+ return optional(raw, key)
134
+ }
135
+
136
+ export function parseTrackInput(raw: Record<string, unknown>): TrackInput | string {
137
+ const task = taskName(raw, 'task')
138
+ if (typeof task !== 'string') return task.problem
139
+ const status = optional(raw, 'status')
140
+ const note = optional(raw, 'note')
141
+ if (Array.isArray(raw.items) && raw.items.length > 0) {
142
+ if (optional(raw, 'item') !== null || raw.id !== undefined) return 'Pass id and item inside items, or leave items out.'
143
+ const items: ItemChange[] = []
144
+ for (const [n, each] of raw.items.entries()) {
145
+ const change = itemChange(typeof each === 'object' && each !== null ? (each as Record<string, unknown>) : {})
146
+ if (typeof change === 'string') return `items[${n}]: ${change}`
147
+ items.push(change)
148
+ }
149
+ if (status === null) return { task, items, own: null }
150
+ const own = ownStatus(status, note)
151
+
152
+ return typeof own === 'string' ? own : { task, items, own }
153
+ }
154
+ if (optional(raw, 'item') === null && raw.id === undefined) {
155
+ const own = ownStatus(status ?? '', note)
156
+
157
+ return typeof own === 'string' ? own : { task, items: [], own }
158
+ }
159
+ const change = itemChange(raw)
160
+
161
+ return typeof change === 'string' ? change : { task, items: [change], own: null }
162
+ }
163
+
164
+ // One item's change: its id, or the text of a new item; a status of a track item, a one-line note.
165
+ function itemChange(raw: Record<string, unknown>): ItemChange | string {
166
+ const item = optional(raw, 'item')
167
+ const id = itemId(raw.id)
168
+ const status = text(raw, 'status')
169
+ const note = optional(raw, 'note')
170
+ if (raw.id !== undefined && id === null) return 'id is the number of a track item, as in its #<id>.'
171
+ if ((id === null) === (item === null)) return 'Pass id to change an item, or item to add a new one.'
172
+ if (!isOneOf(STATUSES, status)) return `status for a track item is one of ${quote(STATUSES)}.`
173
+ for (const [key, value] of [
174
+ ['item', item],
175
+ ['note', note],
176
+ ] as const) {
177
+ const problem = value === null ? null : lineProblem(key, value, { noDates: true })
178
+ if (problem !== null) return problem
179
+ }
180
+
181
+ return id === null ? { item: item ?? '', status, note } : { id, status, note }
182
+ }
183
+
184
+ // A positive whole number, given as one or as a string, with or without its `#`.
185
+ function itemId(raw: unknown): number | null {
186
+ const id = typeof raw === 'string' ? Number(raw.replace(/^#/, '')) : raw
187
+ return typeof id === 'number' && Number.isInteger(id) && id > 0 ? id : null
188
+ }
189
+
190
+ // The task's own status in TASKS.md: a waiting or deferred one carries its reason.
191
+ function ownStatus(status: string, note: string | null): { status: string; note: string | null } | string {
192
+ if (!isOneOf(FOCUS, status)) return `status for a task in ${TASK_LIST} is one of ${quote(FOCUS)}.`
193
+ const problem = note === null ? null : lineProblem('note', note, { noDates: true })
194
+ if (problem !== null) return problem
195
+ if (status !== 'in progress' && note === null) return `A ${status} task carries its reason in its line: pass note.`
196
+
197
+ return { status, note }
198
+ }