@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.
@@ -0,0 +1,46 @@
1
+ // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
+ import { MAX_AUTO_STREAK, NAMES, TASK_LIST } from '../layout'
3
+
4
+ // The owner's rows in the transcript: what became of a shift. Short, one line each.
5
+
6
+ // A note the agent got — a hint, a check — shown to the owner too: the owner sees what the agent is told, and it is
7
+ // not their message. One line, however many the note has.
8
+ export const TOLD = (body: string) => `to the agent — ${body.split('\n').join(' ')}`
9
+
10
+ export const NOT_MADE = (name: string, why: string) => `shift ${name} not made — ${why}`
11
+
12
+ export const CONTINUING = (name: string, shrank: string, dir: string) =>
13
+ `shift ${name} done (${shrank}), continuing from the letter — ${dir}/${NAMES.letter}`
14
+
15
+ export const WAITING = (name: string, shrank: string, capped: boolean) =>
16
+ `shift ${name} done (${shrank})${capped ? `, ${MAX_AUTO_STREAK} in a row without you` : ''} — waiting for you, the letter goes with your next message`
17
+
18
+ export const UNSETTLED = (name: string, why: string) =>
19
+ `shift ${name}: the history was let go, but the message after it failed — ${why}; the letter is in the shift's folder`
20
+
21
+ export const DELIVERED = (files: readonly string[], dir: string) => `went with your message: ${files.join(', ')} — ${dir}/${NAMES.letter}`
22
+
23
+ export const NOT_CONTINUED = (why: string) => `the next turn did not start after the shift — ${why}; send any message to go on`
24
+
25
+ // What /shift-tasks shows the owner: every open task, and under one in progress its items not closed yet. The harness
26
+ // puts the plugin's name before the first line only, so a heading takes it and every task starts at the same column.
27
+ export type TaskView = {
28
+ status: string
29
+ name: string
30
+ about: string
31
+ items: { status: string; name: string }[] | null
32
+ closed: number
33
+ total: number
34
+ }
35
+
36
+ export function renderTasks(tasks: readonly TaskView[]): string {
37
+ if (tasks.length === 0) return `no open tasks in ${TASK_LIST}`
38
+ const blocks = tasks.map(task => {
39
+ const count = task.total === 0 ? 'no items' : `${task.closed} of ${task.total} items closed`
40
+ const items = (task.items ?? []).map(item => ` [${item.status}] ${item.name}`)
41
+
42
+ return [`[${task.status}] ${task.name} — ${count}`, ` ${task.about}`, ...items].join('\n')
43
+ })
44
+
45
+ return [`open tasks in ${TASK_LIST}`, '', blocks.join('\n\n')].join('\n')
46
+ }
@@ -0,0 +1,243 @@
1
+ // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
+ import {
3
+ ABOUT_MAX,
4
+ AFTER,
5
+ ARCHIVE,
6
+ ARCHIVE_TOOL,
7
+ FOCUS,
8
+ GUIDE_TOOL,
9
+ HISTORY_DEFAULT,
10
+ HISTORY_MAX,
11
+ HISTORY_TOOL,
12
+ INDEX,
13
+ LETTER,
14
+ MENTIONS_TOOL,
15
+ NAME_RULE,
16
+ OPEN_TOOL,
17
+ OUTCOMES,
18
+ OUTLINE_TOOL,
19
+ SETUP_TOOL,
20
+ STATUS_TOOL,
21
+ STATUSES,
22
+ TASK_LIST,
23
+ TASKS,
24
+ TOOL,
25
+ TRACK_TOOL,
26
+ } from '../layout'
27
+ import { quote } from '../markdown'
28
+
29
+ export const TOOL_DESCRIPTION = `Make a shift: the stretch's history is let go, and you continue from your letter to yourself (after: continue) or wait for the owner (after: wait). Before the call the board, the tasks and the letter must be ready — how is in ${GUIDE_TOOL}, read once per project. After the call, end the turn: one line with continue; with wait, your whole answer to the owner — it is all they read.`
30
+
31
+ export const GUIDE_DESCRIPTION =
32
+ 'How to shift: the steps, the letter, when the mod refuses, the strict structure of about.md, then the rules of the board, the tasks, the archive and the other records a shift checks. Read it once, before your first shift in a project; after that only when a refusal sends you to it — the steps do not change between shifts.'
33
+
34
+ export const SETUP_DESCRIPTION =
35
+ "How the mod is set up in this project: every key of settings.toml with its value here, its default and the mod's version it came in; the records by every check a shift makes; the files loaded into every session and whether this session's copy is older than them; the documents with remarks; the layout of .shift/ and moving from earlier layouts. Call it when setting a project up, after the mod or the settings changed, or when the session's files look stale."
36
+
37
+ export const TASKS_DESCRIPTION = 'The open tasks and the items of those in progress, read from .shift/; the agent is not asked'
38
+
39
+ export const RESUME_DESCRIPTION = 'Pick up the work from the last shift: the letter, the board and the tasks in progress go to the agent'
40
+
41
+ export const SETUP_SCHEMA = { type: 'object', properties: {} }
42
+
43
+ export const HISTORY_DESCRIPTION = `Past shifts in brief, oldest first: time, outcome, description, what the stretch did, dropped and archived, and for the last one what is open. count — how many of the latest (default ${HISTORY_DEFAULT}).`
44
+
45
+ export const OPEN_DESCRIPTION = `Open a task instead of creating its files by hand: writes ${TASKS}/<name>/task.md with its sections, track.md with the first items, and the task's line with its links in ${TASK_LIST}, all checked first — a refusal writes nothing. Decisions, dead ends and owner decisions start as "none".`
46
+
47
+ const LINK_LINES = (what: string) => ({
48
+ type: 'array',
49
+ items: { type: 'string' },
50
+ description: `Task names, each optionally followed by " — why": ${what}.`,
51
+ })
52
+
53
+ export const OPEN_SCHEMA = {
54
+ type: 'object',
55
+ properties: {
56
+ name: { type: 'string', description: `The folder name in ${TASKS}/: ${NAME_RULE}.` },
57
+ title: { type: 'string', description: "One line: the task.md's # title." },
58
+ goal: { type: 'string', description: 'What the task is for: the "Goal" section.' },
59
+ done_when: { type: 'string', description: 'When it is finished: the "Done when" section.' },
60
+ status: { type: 'string', enum: [...FOCUS], description: 'in progress by default; deferred or waiting carries its reason in about.' },
61
+ about: {
62
+ type: 'string',
63
+ description: `One line up to ${ABOUT_MAX} characters after the task's line in ${TASK_LIST}: what it is, and why it waits if it does.`,
64
+ },
65
+ items: {
66
+ type: 'array',
67
+ items: { type: 'string' },
68
+ description: 'The first track items, each "item — what matters" or just "item"; all open.',
69
+ },
70
+ needs: LINK_LINES('open tasks this one cannot finish without'),
71
+ after: LINK_LINES('archived tasks it stands on'),
72
+ continues: LINK_LINES('archived tasks it picks up'),
73
+ },
74
+ required: ['name', 'title', 'goal', 'done_when', 'about'],
75
+ }
76
+
77
+ export const ARCHIVE_DESCRIPTION = `Archive a finished or dropped task: moves ${TASKS}/<name>/ to ${ARCHIVE}/<name>/ and adds its line to ${INDEX}. It also takes the task out of ${TASK_LIST}.`
78
+
79
+ export const TRACK_DESCRIPTION = `Set a status instead of editing the records by hand. With id: the track item with that id, the number in its "#<id>". With item: a new item with that text, given the next id. Without either: the task's own status in ${TASK_LIST}. status — for an item ${quote(STATUSES)}; for a task ${quote(FOCUS)}. note — replaces what follows " — ": what matters, or the reason a task is deferred or waits (required then). Several items at once — when a stage closes one item and opens the next: items, a list of {id or item, status, note}, applied together or not at all; status beside items is then the task's own.`
80
+
81
+ export const TRACK_SCHEMA = {
82
+ type: 'object',
83
+ properties: {
84
+ task: { type: 'string', description: `The task's folder name in ${TASKS}/.` },
85
+ id: { type: 'integer', description: 'The track item to change: the number in its "#<id>".' },
86
+ item: { type: 'string', description: 'The text of a new track item; what matters goes in note.' },
87
+ status: { type: 'string', enum: [...new Set([...STATUSES, ...FOCUS])] },
88
+ note: { type: 'string', description: 'One line: replaces what follows " — ".' },
89
+ items: {
90
+ type: 'array',
91
+ description: 'Several items in one call, in place of id and item: each changed or added as alone; one that fails writes nothing.',
92
+ items: {
93
+ type: 'object',
94
+ properties: {
95
+ id: { type: 'integer' },
96
+ item: { type: 'string' },
97
+ status: { type: 'string', enum: [...STATUSES] },
98
+ note: { type: 'string' },
99
+ },
100
+ required: ['status'],
101
+ },
102
+ },
103
+ },
104
+ required: ['task'],
105
+ }
106
+
107
+ export const STATUS_DESCRIPTION =
108
+ 'How full the history is: used of the window, where the harness lets it go by itself, the growth since the last shift, when the next shift hints come, and what the history grew from most. Read-only.'
109
+
110
+ export const STATUS_SCHEMA = { type: 'object', properties: {} }
111
+
112
+ export const OUTLINE_DESCRIPTION =
113
+ "A document's description and its ## and ### sections with line numbers, to read only the section you need. path — from the project's root."
114
+
115
+ export const OUTLINE_SCHEMA = {
116
+ type: 'object',
117
+ properties: { path: { type: 'string', description: "The document, from the project's root." } },
118
+ required: ['path'],
119
+ }
120
+
121
+ export const MENTIONS_DESCRIPTION =
122
+ 'Which documents of the project mention a file: its name without the folder, as a whole word. Call it after changing code, before calling the work done, to check those documents against the change.'
123
+
124
+ export const MENTIONS_SCHEMA = {
125
+ type: 'object',
126
+ properties: { file: { type: 'string', description: 'The file whose name to look for; a path or just the name.' } },
127
+ required: ['file'],
128
+ }
129
+
130
+ export const GUIDE_SCHEMA = { type: 'object', properties: {} }
131
+
132
+ export const HISTORY_SCHEMA = {
133
+ type: 'object',
134
+ properties: {
135
+ count: {
136
+ type: 'integer',
137
+ minimum: 1,
138
+ maximum: HISTORY_MAX,
139
+ description: `How many of the latest shifts to show, default ${HISTORY_DEFAULT}.`,
140
+ },
141
+ },
142
+ }
143
+
144
+ export const TOOL_SCHEMA = {
145
+ type: 'object',
146
+ properties: {
147
+ letter: {
148
+ type: 'string',
149
+ description: `The path to the letter to yourself, usually ${LETTER}.`,
150
+ },
151
+ after: {
152
+ type: 'string',
153
+ enum: [...AFTER],
154
+ description: 'continue — you go on right after the shift; wait — you wait for the owner.',
155
+ },
156
+ about: {
157
+ type: 'string',
158
+ description: `One line up to ${ABOUT_MAX} characters: what the stretch did and where you stand. The line of the shift history, shown after later shifts too; the work only, not whether you continue or wait.`,
159
+ },
160
+ },
161
+ required: ['letter', 'after', 'about'],
162
+ }
163
+
164
+ export const ARCHIVE_SCHEMA = {
165
+ type: 'object',
166
+ properties: {
167
+ name: { type: 'string', description: `The task's folder name in ${TASKS}/.` },
168
+ outcome: {
169
+ type: 'string',
170
+ enum: [...OUTCOMES],
171
+ description: 'done — every track item is done or dropped; dropped — the task is abandoned, the reason goes into about.',
172
+ },
173
+ about: {
174
+ type: 'string',
175
+ description: `One line up to ${ABOUT_MAX} characters: what the task was and how it ended. The line of the archive index.`,
176
+ },
177
+ },
178
+ required: ['name', 'outcome', 'about'],
179
+ }
180
+
181
+ // What the model and the owner read of each tool: the label a harness shows, the description, the line of the
182
+ // doctrine's tool list, and the schema of its arguments.
183
+ export type ToolText = { label: string; description: string; brief: string; schema: Record<string, unknown> }
184
+
185
+ export const TOOL_TEXTS: Record<string, ToolText> = {
186
+ [GUIDE_TOOL]: {
187
+ label: 'Shift guide',
188
+ description: GUIDE_DESCRIPTION,
189
+ brief:
190
+ 'how to shift properly and how the files are laid out. Read it once, before your first shift in a project; after that only when a refusal sends you to it — the steps do not change between shifts.',
191
+ schema: GUIDE_SCHEMA,
192
+ },
193
+ [TOOL]: { label: 'Shift', description: TOOL_DESCRIPTION, brief: 'make a shift.', schema: TOOL_SCHEMA },
194
+ [OPEN_TOOL]: {
195
+ label: 'Open a task',
196
+ description: OPEN_DESCRIPTION,
197
+ brief: `open a task: its folder, task.md, track.md and its line in \`${TASK_LIST}\`, checked before anything is written.`,
198
+ schema: OPEN_SCHEMA,
199
+ },
200
+ [ARCHIVE_TOOL]: {
201
+ label: 'Archive a task',
202
+ description: ARCHIVE_DESCRIPTION,
203
+ brief: 'archive a finished or dropped task.',
204
+ schema: ARCHIVE_SCHEMA,
205
+ },
206
+ [TRACK_TOOL]: {
207
+ label: 'Task status',
208
+ description: TRACK_DESCRIPTION,
209
+ brief: `set a track item's status by its id or add an item, several at once with items; without either, the task's own status in \`${TASK_LIST}\`.`,
210
+ schema: TRACK_SCHEMA,
211
+ },
212
+ [HISTORY_TOOL]: {
213
+ label: 'Shift history',
214
+ description: HISTORY_DESCRIPTION,
215
+ brief: 'what happened in past shifts, briefly.',
216
+ schema: HISTORY_SCHEMA,
217
+ },
218
+ [STATUS_TOOL]: {
219
+ label: 'Shift status',
220
+ description: STATUS_DESCRIPTION,
221
+ brief: 'how full the history is, when the next hints come, and what it grew from.',
222
+ schema: STATUS_SCHEMA,
223
+ },
224
+ [SETUP_TOOL]: {
225
+ label: 'Shift setup',
226
+ description: SETUP_DESCRIPTION,
227
+ brief:
228
+ "how the mod is set up here: the settings with their values and the version each came in, the session's files and whether they changed since the session read them, the documents with remarks.",
229
+ schema: SETUP_SCHEMA,
230
+ },
231
+ [OUTLINE_TOOL]: {
232
+ label: 'Document outline',
233
+ description: OUTLINE_DESCRIPTION,
234
+ brief: "a document's description and sections with line numbers: read only the section you need.",
235
+ schema: OUTLINE_SCHEMA,
236
+ },
237
+ [MENTIONS_TOOL]: {
238
+ label: 'Documents mentioning a file',
239
+ description: MENTIONS_DESCRIPTION,
240
+ brief: 'which documents mention a file: call it after changing code, before calling the work done.',
241
+ schema: MENTIONS_SCHEMA,
242
+ },
243
+ }
package/core/tools.ts ADDED
@@ -0,0 +1,193 @@
1
+ // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
+ import { docOutline, docsMentioning } from './docs'
3
+ import { acceptShift, archiveTask, keepRecordsOut, openTask, shiftHistory, staleLayout } from './flows'
4
+ import { parseArchiveInput, parseHistoryCount, parseOpenInput, parsePath, parseShiftInput, parseTrackInput } from './input'
5
+ import {
6
+ ARCHIVE_TOOL,
7
+ atPlaces,
8
+ DIR,
9
+ GUIDE_TOOL,
10
+ HISTORY_TOOL,
11
+ MENTIONS_TOOL,
12
+ MOD,
13
+ OPEN_TOOL,
14
+ OUTLINE_TOOL,
15
+ SETUP_TOOL,
16
+ STATUS_TOOL,
17
+ TOOL,
18
+ TRACK_TOOL,
19
+ } from './layout'
20
+ import { holdShift, type Loop } from './loop'
21
+ import type { Project } from './project'
22
+ import type { Settings } from './settings'
23
+ import { setupReport } from './setup'
24
+ import { doctrine, doctrineBody, GUIDE } from './texts/doctrine'
25
+ import { EXCLUDED, SHIFT_TOO_EARLY } from './texts/prompts'
26
+ import { TOOL_TEXTS, type ToolText } from './texts/tools'
27
+ import { updateTrack } from './track'
28
+
29
+ // The mod's tools as one table: an adapter registers every row the project shows and hands each call to its `run`.
30
+ // A new tool is a name in layout, its texts and a row here; no adapter changes.
31
+
32
+ // What a call knows beyond its arguments; the adapter fills it from the harness. What costs a read is asked for
33
+ // only by the tool that needs it: the guide loads no project, the status reads no files.
34
+ export type ToolCall = {
35
+ project: () => Promise<Project>
36
+ sessionId: () => Promise<string>
37
+ now: () => Promise<number>
38
+ // A subagent's call: only the main agent shifts.
39
+ subagent: boolean
40
+ // The shift loop: a shift accepted is held in it until the turn ends, and only one a turn.
41
+ loop: Loop
42
+ // The session's block as this session holds it; null when the harness reads it anew before every run.
43
+ loaded: () => Promise<string | null>
44
+ // How full the history is: the harness measures it.
45
+ status: () => Promise<string>
46
+ // Why the harness cannot let this history go now — too small to let go of; null when it can.
47
+ cannotLetGo: () => Promise<string | null>
48
+ }
49
+
50
+ // A refusal, or the result.
51
+ export type ToolDone = { deny: string } | { result: string }
52
+
53
+ export type Tool = ToolText & {
54
+ name: string
55
+ // Writes the records: a harness that runs tools side by side runs these one at a time.
56
+ writes: boolean
57
+ // Shown only where the mod keeps the project's docs.
58
+ docs: boolean
59
+ run: (raw: Record<string, unknown>, call: ToolCall) => Promise<ToolDone>
60
+ }
61
+
62
+ type Row = Omit<Tool, keyof ToolText | 'writes' | 'docs'> & { writes?: boolean; docs?: boolean }
63
+
64
+ const ROWS: readonly Row[] = [
65
+ { name: GUIDE_TOOL, run: async (_raw, call) => ({ result: atPlaces(GUIDE, (await call.project()).settings.files) }) },
66
+ {
67
+ name: TOOL,
68
+ writes: true,
69
+ run: async (raw, call) => {
70
+ if (call.subagent) return { deny: 'Only the main agent shifts, not a subagent.' }
71
+ if ((await call.loop.read()).pending !== null) return { deny: 'The shift is already accepted: end the turn as its result said.' }
72
+ const input = parseShiftInput(raw)
73
+ if (typeof input === 'string') return { deny: input }
74
+ const cannot = await call.cannotLetGo()
75
+ if (cannot !== null) return { deny: SHIFT_TOO_EARLY(cannot) }
76
+ const accepted = await acceptShift(await call.project(), { input, at: await call.now(), sessionId: await call.sessionId() })
77
+ if ('deny' in accepted) return accepted
78
+ await holdShift(call.loop, accepted.shift)
79
+
80
+ return { result: accepted.result }
81
+ },
82
+ },
83
+ {
84
+ name: OPEN_TOOL,
85
+ writes: true,
86
+ run: async (raw, call) => {
87
+ const input = parseOpenInput(raw)
88
+
89
+ return typeof input === 'string' ? { deny: input } : openTask(await call.project(), input)
90
+ },
91
+ },
92
+ {
93
+ name: ARCHIVE_TOOL,
94
+ writes: true,
95
+ run: async (raw, call) => {
96
+ const input = parseArchiveInput(raw)
97
+
98
+ return typeof input === 'string' ? { deny: input } : archiveTask(await call.project(), input)
99
+ },
100
+ },
101
+ {
102
+ name: TRACK_TOOL,
103
+ writes: true,
104
+ run: async (raw, call) => {
105
+ const input = parseTrackInput(raw)
106
+
107
+ return typeof input === 'string' ? { deny: input } : updateTrack(await call.project(), input)
108
+ },
109
+ },
110
+ {
111
+ name: HISTORY_TOOL,
112
+ run: async (raw, call) => {
113
+ const count = parseHistoryCount(raw)
114
+
115
+ return typeof count === 'string' ? { deny: count } : { result: await shiftHistory(await call.project(), count) }
116
+ },
117
+ },
118
+ { name: STATUS_TOOL, run: async (_raw, call) => ({ result: await call.status() }) },
119
+ { name: SETUP_TOOL, run: async (_raw, call) => ({ result: await setupReport(await call.project(), await call.loaded()) }) },
120
+ {
121
+ name: OUTLINE_TOOL,
122
+ docs: true,
123
+ run: async (raw, call) => {
124
+ const path = parsePath(raw, 'path')
125
+
126
+ return path === null
127
+ ? { deny: "path is the document, from the project's root." }
128
+ : { result: await docOutline(await call.project(), path) }
129
+ },
130
+ },
131
+ {
132
+ name: MENTIONS_TOOL,
133
+ docs: true,
134
+ run: async (raw, call) => {
135
+ const file = parsePath(raw, 'file')
136
+
137
+ return file === null
138
+ ? { deny: 'file is the file whose name to look for.' }
139
+ : { result: await docsMentioning(await call.project(), file) }
140
+ },
141
+ },
142
+ ]
143
+
144
+ export const TOOLS: readonly Tool[] = ROWS.map(row => {
145
+ const text = TOOL_TEXTS[row.name]
146
+ if (text === undefined) throw new Error(`No texts for the tool ${row.name}.`)
147
+
148
+ return { ...text, writes: false, docs: false, ...row }
149
+ })
150
+
151
+ // The tools a project with these settings shows: none where the mod is off, no docs tools where it keeps no docs.
152
+ export function shownTools(settings: Settings): Tool[] {
153
+ if (!settings.enabled) return []
154
+
155
+ return TOOLS.filter(tool => !tool.docs || settings.docs.dirs.length > 0)
156
+ }
157
+
158
+ // What a session starts with: whether the mod is on, the rows for the owner, the tools to register and the doctrine.
159
+ export type SessionStart = {
160
+ enabled: boolean
161
+ rows: { text: string; level: 'info' | 'warning' }[]
162
+ tools: Tool[]
163
+ // The doctrine for the system prompt, with and without its tag.
164
+ doctrine: string
165
+ doctrineBody: string
166
+ }
167
+
168
+ // A broken settings file is told and leaves the mod on; records in an older layout are named; records the project's
169
+ // git would take in are kept out before the first shift too.
170
+ // The doctrine with the tools the project shows, at the places its settings give: in its tag, and the body alone for a
171
+ // harness that puts it under a heading of its own. An adapter that has none kept yet builds it here, not from the table.
172
+ export function sessionDoctrine(settings: Settings): { doctrine: string; doctrineBody: string } {
173
+ const names = shownTools(settings).map(tool => tool.name)
174
+
175
+ return { doctrine: atPlaces(doctrine(names), settings.files), doctrineBody: atPlaces(doctrineBody(names), settings.files) }
176
+ }
177
+
178
+ export async function startSession(project: Project): Promise<SessionStart> {
179
+ const { settings, problem } = project
180
+ const rows: SessionStart['rows'] = []
181
+ if (problem !== null) rows.push({ text: `${MOD}: ${problem} The mod stays on.`, level: 'warning' })
182
+ const start = { enabled: settings.enabled, rows, tools: shownTools(settings), ...sessionDoctrine(settings) }
183
+ if (!settings.enabled) return start
184
+
185
+ const stale = await staleLayout(project)
186
+ if (stale !== null) rows.push({ text: `${MOD}: ${stale}`, level: 'warning' })
187
+ if (await project.store.exists(`${project.root}/${DIR}`)) {
188
+ const kept = await keepRecordsOut(project)
189
+ if ('excluded' in kept && kept.excluded !== null) rows.push({ text: EXCLUDED(kept.excluded), level: 'info' })
190
+ }
191
+
192
+ return start
193
+ }
package/core/track.ts ADDED
@@ -0,0 +1,129 @@
1
+ // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
+ import { ARCHIVE_TOOL, CLOSED, DIR, TASK_LIST, TASKS, taskFile } from './layout'
3
+ import { formatItem, itemsOf } from './markdown'
4
+ import type { Project } from './project'
5
+ import type { Store } from './store'
6
+ import { formatTaskLine, taskLine } from './tasks'
7
+ import type { Item, ItemChange, TrackInput } from './types'
8
+
9
+ // Statuses set by a tool instead of an edit by hand: a track item found by its id, or a task's own line in TASKS.md.
10
+ // An id is the item's `#<n>`, given by the mod when the item is added and never reused in the track: a call names an
11
+ // item in a few characters, not by the words of its name.
12
+
13
+ export async function updateTrack(project: Project, input: TrackInput): Promise<{ deny: string } | { result: string }> {
14
+ const { store, root } = project
15
+ const done: string[] = []
16
+ if (input.items.length > 0) {
17
+ const items = await setItems(store, root, input.task, input.items)
18
+ if ('deny' in items) return items
19
+ done.push(items.result)
20
+ }
21
+ if (input.own !== null) {
22
+ const own = await setTaskStatus(store, root, input.task, input.own)
23
+ if ('deny' in own)
24
+ return done.length === 0 ? own : { deny: `${done.join('\n')}\n\nThe items are set, the task's line is not: ${own.deny}` }
25
+ done.push(own.result)
26
+ }
27
+
28
+ return { result: done.join('\n') }
29
+ }
30
+
31
+ async function setTaskStatus(
32
+ store: Store,
33
+ root: string,
34
+ task: string,
35
+ own: { status: string; note: string | null },
36
+ ): Promise<{ deny: string } | { result: string }> {
37
+ const path = `${root}/${TASK_LIST}`
38
+ const lines = ((await store.read(path)) ?? '').split('\n')
39
+ const at = lines.findIndex(line => taskLine(line)?.name === task)
40
+ const found = taskLine(lines[at] ?? '')
41
+ if (found === null) return { deny: `No line for ${task} in ${TASK_LIST}: open the task there first.` }
42
+ lines[at] = formatTaskLine(own.status, found.label, found.name, own.note ?? found.about)
43
+ await store.write(path, lines.join('\n'))
44
+
45
+ return { result: `${TASK_LIST}: ${lines[at]}` }
46
+ }
47
+
48
+ // Every change applied to the track in order, then written once: one that finds no item writes nothing.
49
+ async function setItems(
50
+ store: Store,
51
+ root: string,
52
+ task: string,
53
+ changes: readonly ItemChange[],
54
+ ): Promise<{ deny: string } | { result: string }> {
55
+ const path = taskFile(`${root}/${DIR}`, task, 'track')
56
+ const read = await store.read(path)
57
+ if (read === null) return { deny: `No ${TASKS}/${task}/track.md: the task is not open.` }
58
+ let text = numberItems(read)
59
+ const lines: string[] = []
60
+ for (const [n, change] of changes.entries()) {
61
+ const applied = applyItem(text, task, change)
62
+ if ('deny' in applied) return { deny: changes.length === 1 ? applied.deny : `items[${n}]: ${applied.deny}\nNothing was written.` }
63
+ text = applied.text
64
+ lines.push(`${task}/track.md: ${applied.line}`)
65
+ }
66
+ await store.write(path, text)
67
+ const closed = itemsOf(text).every(each => each.status === '' || CLOSED.has(each.status))
68
+ if (closed) lines.push(`Every item of ${task} is closed: archive it with ${ARCHIVE_TOOL} when the task is over.`)
69
+
70
+ return { result: lines.join('\n') }
71
+ }
72
+
73
+ function applyItem(text: string, task: string, change: ItemChange): { deny: string } | { text: string; line: string } {
74
+ const lines = text.split('\n')
75
+ const items = itemsOf(text).filter(item => item.status !== '')
76
+
77
+ if ('item' in change) {
78
+ const wanted = change.item.toLowerCase()
79
+ const same = items.find(each => each.name.toLowerCase() === wanted)
80
+ if (same !== undefined) return { deny: `"${change.item}" is already an item of ${task}: #${same.id}.` }
81
+ const line = formatItem(change.status, nextId(items), change.item, change.note)
82
+ const body = text.trimEnd()
83
+
84
+ return { text: `${body === '' ? '' : `${body}\n`}${line}\n`, line }
85
+ }
86
+
87
+ const found = items.find(each => each.id === change.id)
88
+ if (found === undefined) {
89
+ return { deny: `No item #${change.id} in ${task}. Its items:\n${items.map(each => each.line).join('\n')}` }
90
+ }
91
+ lines[found.index] = formatItem(change.status, change.id, found.name, change.note ?? found.note)
92
+
93
+ return { text: lines.join('\n'), line: lines[found.index] ?? '' }
94
+ }
95
+
96
+ // Ids for the track items without one, or with one an earlier item took — added by hand, or written before items had
97
+ // ids — numbered on from the highest; the text as it was when every item has its own.
98
+ export function numberItems(text: string): string {
99
+ const items = itemsOf(text).filter(item => item.status !== '')
100
+ let next = nextId(items)
101
+ const lines = text.split('\n')
102
+ const seen = new Set<number>()
103
+ for (const item of items) {
104
+ if (item.id !== null && !seen.has(item.id)) {
105
+ seen.add(item.id)
106
+ continue
107
+ }
108
+ lines[item.index] = formatItem(item.status, next++, item.name, item.note)
109
+ }
110
+
111
+ return lines.join('\n')
112
+ }
113
+
114
+ // Every open task's track numbered where it has items without ids: done at a shift, so the tracks it hands back
115
+ // carry an id on every item.
116
+ export async function numberTracks(project: Project): Promise<void> {
117
+ const { store, root } = project
118
+ for (const task of await store.list(`${root}/${TASKS}`, 'dir')) {
119
+ const path = taskFile(`${root}/${DIR}`, task, 'track')
120
+ const text = await store.read(path)
121
+ if (text === null) continue
122
+ const numbered = numberItems(text)
123
+ if (numbered !== text) await store.write(path, numbered)
124
+ }
125
+ }
126
+
127
+ function nextId(items: readonly Item[]): number {
128
+ return Math.max(0, ...items.map(item => item.id ?? 0)) + 1
129
+ }