@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/store.ts ADDED
@@ -0,0 +1,144 @@
1
+ // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
+ import { DIR, NAMES, RECENT_SHIFTS, SHIFTS, taskFile } from './layout'
3
+ import type { Project } from './project'
4
+ import type { HistoryEntry, KnowledgeFile, Recent, Snapshot, TaskFiles, Work } from './types'
5
+
6
+ // The files the mod works on, as a harness gives them; paths are absolute.
7
+ export type Store = {
8
+ // The file's text; null when it is missing or unreadable.
9
+ read(path: string): Promise<string | null>
10
+ // Names of the folders or files right under `path`, sorted; none when it is missing.
11
+ list(path: string, kind: 'dir' | 'file'): Promise<string[]>
12
+ // The files right under `path`, each with a stamp that changes when the file does (its time and size), from one
13
+ // listing and no reads: what the records' look after every tool can afford.
14
+ stamps(path: string): Promise<Record<string, string>>
15
+ // Writes the file whole, making its folders.
16
+ write(path: string, text: string): Promise<void>
17
+ exists(path: string): Promise<boolean>
18
+ // Moves a folder, making the target's parent; null on success, else what went wrong.
19
+ move(from: string, to: string): Promise<string | null>
20
+ // Runs git with `args` in `root`: its exit code and what it printed; null when there is no git to run.
21
+ git(root: string, args: readonly string[]): Promise<{ code: number; stdout: string } | null>
22
+ }
23
+
24
+ // Where the files loaded into every session are, absolute.
25
+ export type Places = { owner: string; glossary: string; shift: string }
26
+
27
+ // The records under `base` (the project's `.shift/` or a shift's snapshot); null without a board.
28
+ // A snapshot keeps every file under its own name; a project's places come from its settings.
29
+ export async function readWork(store: Store, base: string, places?: Places): Promise<Work | null> {
30
+ const board = await store.read(`${base}/${NAMES.board}`)
31
+ if (board === null) return null
32
+ const at = places ?? { owner: `${base}/${NAMES.owner}`, glossary: `${base}/${NAMES.glossary}`, shift: `${base}/${NAMES.shift}` }
33
+ const tasks: TaskFiles[] = await Promise.all((await store.list(`${base}/${NAMES.tasks}`, 'dir')).map(name => readTask(store, base, name)))
34
+
35
+ const knowledge: KnowledgeFile[] = await Promise.all(
36
+ (await store.list(`${base}/${NAMES.knowledge}`, 'file'))
37
+ .filter(name => name.endsWith('.md'))
38
+ .map(async name => ({ name, text: (await store.read(`${base}/${NAMES.knowledge}/${name}`)) ?? '' })),
39
+ )
40
+ const oldOwner = `${base}/${NAMES.oldOwner}`
41
+ // Snapshots taken before OWNER.md keep owner.md.
42
+ const owner = (await store.read(at.owner)) ?? (places === undefined ? await store.read(oldOwner) : null)
43
+
44
+ return {
45
+ board,
46
+ owner,
47
+ tasks,
48
+ knowledge,
49
+ taskList: await store.read(`${base}/${NAMES.taskList}`),
50
+ glossary: await store.read(at.glossary),
51
+ shift: await store.read(at.shift),
52
+ archived: await store.list(`${base}/${NAMES.archive}`, 'dir'),
53
+ oldOwner: places !== undefined && places.owner !== oldOwner && (await store.exists(oldOwner)),
54
+ }
55
+ }
56
+
57
+ // A task's folder under `base`.
58
+ export async function readTask(store: Store, base: string, name: string): Promise<TaskFiles> {
59
+ const notes = `${base}/${NAMES.tasks}/${name}/${NAMES.notes}`
60
+
61
+ return {
62
+ name,
63
+ task: await store.read(taskFile(base, name, 'task')),
64
+ track: await store.read(taskFile(base, name, 'track')),
65
+ notes: await Promise.all(
66
+ (await store.list(notes, 'file'))
67
+ .filter(file => file.endsWith('.md'))
68
+ .map(async file => ({ name: file, text: (await store.read(`${notes}/${file}`)) ?? '' })),
69
+ ),
70
+ }
71
+ }
72
+
73
+ // A shift's folder: the records as they are, each under its own name — the inverse of `readWork` over a snapshot —
74
+ // and the letter, the archive's index and the settings beside them.
75
+ export async function writeSnapshot(
76
+ store: Store,
77
+ dir: string,
78
+ snapshot: { work: Work; letter: string; index: string | null; settings: string | null },
79
+ ): Promise<void> {
80
+ const { work } = snapshot
81
+ const files: [string, string | null][] = [
82
+ [NAMES.letter, snapshot.letter],
83
+ [NAMES.board, work.board],
84
+ [NAMES.index, snapshot.index],
85
+ [NAMES.owner, work.owner],
86
+ [NAMES.taskList, work.taskList],
87
+ [NAMES.glossary, work.glossary],
88
+ [NAMES.shift, work.shift],
89
+ [NAMES.settings, snapshot.settings],
90
+ ...work.knowledge.map((file): [string, string] => [`${NAMES.knowledge}/${file.name}`, file.text]),
91
+ ]
92
+ for (const [name, text] of files) if (text !== null) await store.write(`${dir}/${name}`, text)
93
+ for (const task of work.tasks) {
94
+ if (task.task !== null) await store.write(taskFile(dir, task.name, 'task'), task.task)
95
+ if (task.track !== null) await store.write(taskFile(dir, task.name, 'track'), task.track)
96
+ for (const note of task.notes) await store.write(`${dir}/${NAMES.tasks}/${task.name}/${NAMES.notes}/${note.name}`, note.text)
97
+ }
98
+ }
99
+
100
+ // The project's records at the places its settings give.
101
+ export function readRecords(project: Project): Promise<Work | null> {
102
+ const { root, settings } = project
103
+
104
+ return readWork(project.store, `${root}/${DIR}`, {
105
+ owner: `${root}/${settings.files.owner}`,
106
+ glossary: `${root}/${settings.files.glossary}`,
107
+ shift: `${root}/${settings.files.shift}`,
108
+ })
109
+ }
110
+
111
+ export async function readSnapshot(store: Store, base: string, index: string): Promise<Snapshot | null> {
112
+ const work = await readWork(store, base)
113
+
114
+ return work === null ? null : { work, index: await store.read(index) }
115
+ }
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)
126
+
127
+ return last === undefined ? null : `${root}/${SHIFTS}/${last}`
128
+ }
129
+
130
+ // The last `count` shifts' about.md, oldest first, and how many shifts the project has in all.
131
+ export async function lastShifts(project: Project, count: number): Promise<Recent> {
132
+ const { store, root } = project
133
+ const names = await shiftNames(project)
134
+ const entries: HistoryEntry[] = await Promise.all(
135
+ names.slice(-count).map(async name => ({ name, about: await store.read(`${root}/${SHIFTS}/${name}/${NAMES.about}`) })),
136
+ )
137
+
138
+ return { entries, total: names.length }
139
+ }
140
+
141
+ // The shifts the message after a shift recalls.
142
+ export function recentShifts(project: Project): Promise<Recent> {
143
+ return lastShifts(project, RECENT_SHIFTS)
144
+ }
package/core/tasks.ts ADDED
@@ -0,0 +1,172 @@
1
+ // Generated from core/src by scripts/sync-core.ts — edit the source, not this copy.
2
+ import { ARCHIVE_TOOL, FOCUS, NAME, NAME_RULE, TASK_LIST, TASKS, TASKS_MAX_LINES } from './layout'
3
+ import { dated, overLimit, quote } from './markdown'
4
+ import type { OpenInput } from './types'
5
+
6
+ // TASKS.md: every open task, one line each, and under it the links to other tasks and archived ones.
7
+ //
8
+ // - [in progress] [adapters](tasks/adapters/) — the shift in pi and opencode on the shared core
9
+ // - needs: [core-port](tasks/core-port/) — the port comes first
10
+ // - after: [settings](archive/settings/)
11
+ // - continues: [old-adapters](archive/old-adapters/)
12
+
13
+ export const LINKS = ['needs', 'after', 'continues'] as const
14
+ export type LinkKind = (typeof LINKS)[number]
15
+ export type Link = { kind: LinkKind; place: 'tasks' | 'archive'; name: string; line: string }
16
+ export type ListedTask = { status: string; name: string; about: string; line: string; links: Link[] }
17
+
18
+ const TASK_LINE = /^- \[([^\]]+)\] \[([^\]]+)\]\(tasks\/([^)/]+)\/?\) — (.+)$/
19
+
20
+ export function formatTaskLine(status: string, label: string, name: string, about: string): string {
21
+ return `- [${status}] [${label}](tasks/${name}/) — ${about}`
22
+ }
23
+
24
+ // One line of TASKS.md as `- [status] [label](tasks/name/) — about`; null when it is not a task line.
25
+ export function taskLine(line: string): { status: string; label: string; name: string; about: string } | null {
26
+ const [, status = '', label = '', name = '', about = ''] = TASK_LINE.exec(line.trimEnd()) ?? []
27
+
28
+ return name === '' ? null : { status, label, name, about }
29
+ }
30
+ const LINK_LINE = /^\s+- ([a-z]+): (.+)$/
31
+ const TARGET = /\[([^\]]+)\]\((tasks|archive)\/([^)/]+)\/?\)/g
32
+
33
+ // The tasks as listed, or what is wrong with a line; "none" stands for an empty list.
34
+ export function parseTaskList(text: string): ListedTask[] | string {
35
+ const tasks: ListedTask[] = []
36
+ for (const raw of text.split('\n')) {
37
+ const line = raw.trimEnd()
38
+ if (line.trim() === '' || line.startsWith('#') || line.trim() === 'none') continue
39
+ const task = taskLine(line)
40
+ if (task !== null) {
41
+ const { status, label, name, about } = task
42
+ if (label !== name) return `${TASK_LIST}: the link text and the folder differ in "${line}": write [${name}](tasks/${name}/).`
43
+ tasks.push({ status, name, about, line, links: [] })
44
+ continue
45
+ }
46
+ const link = LINK_LINE.exec(line)
47
+ const owner = tasks.at(-1)
48
+ if (link === null || owner === undefined) {
49
+ return `${TASK_LIST}: "${line.trim()}" is neither a task line \`- [status] [name](tasks/name/) — what it is\` nor a link under one.`
50
+ }
51
+ const kind = link[1] as LinkKind
52
+ if (!(LINKS as readonly string[]).includes(kind))
53
+ return `${TASK_LIST}: unknown link "${kind}:" in "${line.trim()}"; links are ${LINKS.join(', ')}.`
54
+ const targets = [...((link[2] ?? '').split(' — ')[0]?.matchAll(TARGET) ?? [])]
55
+ if (targets.length === 0) return `${TASK_LIST}: "${line.trim()}" links nothing; write [name](tasks/name/) or [name](archive/name/).`
56
+ for (const [, , place = 'tasks', name = ''] of targets)
57
+ owner.links.push({ kind, place: place as Link['place'], name, line: line.trim() })
58
+ }
59
+
60
+ return tasks
61
+ }
62
+
63
+ // TASKS.md against the task folders and the archive.
64
+ export function checkTaskList(text: string | null, folders: readonly string[], archived: readonly string[]): string | null {
65
+ if (text === null) return `No ${TASK_LIST}: list every task folder there, one line each, or write "none".`
66
+ const size =
67
+ overLimit(TASK_LIST, text, TASKS_MAX_LINES, 'archive finished tasks, keep one short line each.') ??
68
+ dated(TASK_LIST, text, 'Tasks have no dates.')
69
+ if (size !== null) return size
70
+ const tasks = parseTaskList(text)
71
+ if (typeof tasks === 'string') return tasks
72
+
73
+ const badStatus = tasks.filter(t => !(FOCUS as readonly string[]).includes(t.status))
74
+ if (badStatus.length > 0) {
75
+ return `Tasks without a status (${FOCUS.join(', ')}) in ${TASK_LIST}: ${quote(
76
+ badStatus.map(t => t.line),
77
+ '; ',
78
+ )}. A finished task is archived with ${ARCHIVE_TOOL}, not marked.`
79
+ }
80
+ const badName = tasks.filter(t => !NAME.test(t.name))
81
+ if (badName.length > 0) return `Task names are ${NAME_RULE}: ${quote(badName.map(t => t.name))}.`
82
+
83
+ const listed = new Set(tasks.map(t => t.name))
84
+ const unlisted = folders.filter(name => !listed.has(name))
85
+ if (unlisted.length > 0)
86
+ return `Task folders missing from ${TASK_LIST}: ${unlisted.join(', ')}. List each with its status, or archive it.`
87
+ const homeless = [...listed].filter(name => !folders.includes(name))
88
+ if (homeless.length > 0)
89
+ return `Tasks in ${TASK_LIST} without a folder in ${TASKS}/: ${homeless.join(', ')}. Create the folder, or remove the line.`
90
+
91
+ for (const task of tasks) {
92
+ for (const link of task.links) {
93
+ const exists = link.place === 'tasks' ? listed.has(link.name) : archived.includes(link.name)
94
+ if (!exists) return `${TASK_LIST}: "${link.line}" under ${task.name} points at ${link.place}/${link.name}/, which is not there.`
95
+ if (link.kind === 'needs' && link.place !== 'tasks') {
96
+ return `${TASK_LIST}: ${task.name} needs ${link.name}, which is archived: what it gave is done — write "after:".`
97
+ }
98
+ if (link.kind === 'continues' && link.place !== 'archive')
99
+ return `${TASK_LIST}: ${task.name} continues ${link.name}, which is not archived: only an archived task is continued.`
100
+ if (link.place === 'tasks' && link.name === task.name) return `${TASK_LIST}: ${task.name} links itself.`
101
+ }
102
+ }
103
+ const cycle = needsCycle(tasks)
104
+ if (cycle !== null)
105
+ return `${TASK_LIST}: tasks need each other in a circle: ${cycle.join(' → ')}. One of them does not really need the next.`
106
+
107
+ return null
108
+ }
109
+
110
+ function needsCycle(tasks: readonly ListedTask[]): string[] | null {
111
+ const needs = new Map(tasks.map(t => [t.name, t.links.filter(l => l.kind === 'needs').map(l => l.name)]))
112
+ const done = new Set<string>()
113
+ const walk = (name: string, path: string[]): string[] | null => {
114
+ if (path.includes(name)) return [...path.slice(path.indexOf(name)), name]
115
+ if (done.has(name)) return null
116
+ for (const next of needs.get(name) ?? []) {
117
+ const found = walk(next, [...path, name])
118
+ if (found !== null) return found
119
+ }
120
+ done.add(name)
121
+
122
+ return null
123
+ }
124
+ for (const task of tasks) {
125
+ const found = walk(task.name, [])
126
+ if (found !== null) return found
127
+ }
128
+
129
+ return null
130
+ }
131
+
132
+ // TASKS.md with a new task's line and its links appended; a link points into the archive when the task is archived.
133
+ // A list that said "none" says it no more.
134
+ export function withTask(text: string | null, input: OpenInput, archived: readonly string[]): string {
135
+ const lines = [
136
+ formatTaskLine(input.status, input.name, input.name, input.about),
137
+ ...input.links.map(link => {
138
+ const place = archived.includes(link.name) ? 'archive' : 'tasks'
139
+ return ` - ${link.kind}: [${link.name}](${place}/${link.name}/)${link.why === null ? '' : ` — ${link.why}`}`
140
+ }),
141
+ ]
142
+ if (text === null) return `# Tasks\n\n${lines.join('\n')}\n`
143
+ const kept = text
144
+ .split('\n')
145
+ .filter(line => line.trim() !== 'none')
146
+ .join('\n')
147
+ .trimEnd()
148
+
149
+ return `${kept}\n${/^- \[/m.test(kept) ? '' : '\n'}${lines.join('\n')}\n`
150
+ }
151
+
152
+ // After archiving `name`: its line and links leave, and the links of others point into the archive; what was needed is
153
+ // now behind them.
154
+ export function archiveInList(text: string, name: string): string {
155
+ const out: string[] = []
156
+ let skipping = false
157
+ for (const line of text.split('\n')) {
158
+ const task = taskLine(line)
159
+ 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)
164
+ }
165
+ const kept = out.join('\n')
166
+ const left = parseTaskList(kept)
167
+ const isEmpty = Array.isArray(left) && left.length === 0 && !/^none$/m.test(kept)
168
+
169
+ if (!isEmpty) return kept
170
+
171
+ return kept.trim() === '' ? 'none\n' : `${kept.trimEnd()}\n\nnone\n`
172
+ }