@astrosheep/keiyaku 4.5.5 → 4.5.6

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,178 @@
1
+ import { parseTaskId } from "./identity.js";
2
+ function diagnostic(line, reason, token) {
3
+ return { line, reason, token };
4
+ }
5
+ function sourceLines(source) {
6
+ const lines = [];
7
+ let start = 0;
8
+ let number = 1;
9
+ while (start < source.length) {
10
+ let cursor = start;
11
+ while (cursor < source.length && source[cursor] !== "\n" && source[cursor] !== "\r")
12
+ cursor += 1;
13
+ let end = cursor;
14
+ if (source[cursor] === "\r" && source[cursor + 1] === "\n")
15
+ end += 2;
16
+ else if (cursor < source.length)
17
+ end += 1;
18
+ lines.push({ number, start, end, text: source.slice(start, cursor) });
19
+ start = end;
20
+ number += 1;
21
+ }
22
+ if (source.length === 0 || source.endsWith("\n") || source.endsWith("\r")) {
23
+ lines.push({ number, start: source.length, end: source.length, text: "" });
24
+ }
25
+ return lines;
26
+ }
27
+ function withoutFenceSeparator(value) {
28
+ if (value.endsWith("\r\n"))
29
+ return value.slice(0, -2);
30
+ if (value.endsWith("\n") || value.endsWith("\r"))
31
+ return value.slice(0, -1);
32
+ return value;
33
+ }
34
+ function parseNamespace(value) {
35
+ if (value === "")
36
+ return [];
37
+ return parseTaskId(`task/${value}/placeholder`).namespace;
38
+ }
39
+ function parseAssignment(text, line) {
40
+ const matched = /^(as|parent|pri|needs|supersedes|relates)\s*(=|\+=|-=)\s*(.*)$/u.exec(text);
41
+ if (matched === null)
42
+ return null;
43
+ return {
44
+ field: matched[1],
45
+ operator: matched[2],
46
+ value: matched[3],
47
+ line,
48
+ token: text,
49
+ };
50
+ }
51
+ function parseNode(text, line, index) {
52
+ if (text.startsWith("+ ")) {
53
+ const title = text.slice(2);
54
+ return title.trim().length === 0
55
+ ? diagnostic(line, "new task title must be nonblank", text)
56
+ : { index, line, kind: "new", title, assignments: [] };
57
+ }
58
+ if (!text.startsWith("@task/"))
59
+ return diagnostic(line, "node must begin with + or @task/", text);
60
+ try {
61
+ const id = text.slice(1);
62
+ parseTaskId(id);
63
+ return { index, line, kind: "existing", id, assignments: [] };
64
+ }
65
+ catch (error) {
66
+ return diagnostic(line, error instanceof Error ? error.message : String(error), text);
67
+ }
68
+ }
69
+ function withAssignment(node, assignment) {
70
+ return { ...node, assignments: [...node.assignments, assignment] };
71
+ }
72
+ function withBody(node, body) {
73
+ return { ...node, body };
74
+ }
75
+ function replaceNode(nodes, node) {
76
+ nodes[node.index] = node;
77
+ }
78
+ function parseBodyAssignment(input, diagnostics) {
79
+ const fence = /^body\s+<<(.+)$/u.exec(input.text);
80
+ if (fence !== null) {
81
+ const token = fence[1];
82
+ if (!/^[A-Z][A-Z0-9_]{2,31}$/u.test(token)) {
83
+ diagnostics.push(diagnostic(input.line.number, "body token must match [A-Z][A-Z0-9_]* with length 3..32", token));
84
+ return { handled: true };
85
+ }
86
+ const close = input.lines.findIndex((candidate, candidateIndex) => candidateIndex > input.index && candidate.text === token);
87
+ if (close < 0) {
88
+ diagnostics.push(diagnostic(input.line.number, "body fence is not closed", token));
89
+ return { handled: true, stop: true };
90
+ }
91
+ const body = withoutFenceSeparator(input.source.slice(input.line.end, input.lines[close].start));
92
+ if (input.current.body !== undefined) {
93
+ diagnostics.push(diagnostic(input.line.number, "body is assigned more than once", input.text));
94
+ return { handled: true, close };
95
+ }
96
+ return {
97
+ handled: true,
98
+ node: withBody(input.current, { kind: "replace", value: body, line: input.line.number, token }),
99
+ close,
100
+ };
101
+ }
102
+ if (!/^body\s*=\s*$/u.test(input.text))
103
+ return { handled: false };
104
+ if (input.current.body !== undefined) {
105
+ diagnostics.push(diagnostic(input.line.number, "body is assigned more than once", input.text));
106
+ return { handled: true };
107
+ }
108
+ return {
109
+ handled: true,
110
+ node: withBody(input.current, { kind: "clear", value: "", line: input.line.number, token: input.text }),
111
+ };
112
+ }
113
+ export function parseTaskComposition(source) {
114
+ const lines = sourceLines(source);
115
+ const diagnostics = [];
116
+ const nodes = [];
117
+ let namespace;
118
+ let current;
119
+ let sawNode = false;
120
+ let sawNamespace = false;
121
+ for (let index = 0; index < lines.length; index += 1) {
122
+ const line = lines[index];
123
+ const text = line.text.trimStart();
124
+ if (text.trim().length === 0)
125
+ continue;
126
+ if (text.startsWith("ns=")) {
127
+ if (sawNode || sawNamespace)
128
+ diagnostics.push(diagnostic(line.number, "namespace must be the first nonblank line", text));
129
+ else {
130
+ try {
131
+ namespace = parseNamespace(text.slice(3));
132
+ }
133
+ catch (error) {
134
+ diagnostics.push(diagnostic(line.number, error instanceof Error ? error.message : String(error), text));
135
+ }
136
+ }
137
+ sawNamespace = true;
138
+ continue;
139
+ }
140
+ if (text.startsWith("+ ") || text.startsWith("@task/")) {
141
+ const parsed = parseNode(text, line.number, nodes.length);
142
+ if ("reason" in parsed) {
143
+ diagnostics.push(parsed);
144
+ current = undefined;
145
+ }
146
+ else {
147
+ nodes.push(parsed);
148
+ current = parsed;
149
+ }
150
+ sawNode = true;
151
+ continue;
152
+ }
153
+ if (current === undefined) {
154
+ diagnostics.push(diagnostic(line.number, "property must follow a task node", text));
155
+ continue;
156
+ }
157
+ const body = parseBodyAssignment({ text, line, index, lines, source, current }, diagnostics);
158
+ if (body.handled) {
159
+ if (body.node !== undefined) {
160
+ current = body.node;
161
+ replaceNode(nodes, current);
162
+ }
163
+ if (body.close !== undefined)
164
+ index = body.close;
165
+ if (body.stop === true)
166
+ break;
167
+ continue;
168
+ }
169
+ const assignment = parseAssignment(text, line.number);
170
+ if (assignment === null)
171
+ diagnostics.push(diagnostic(line.number, "unknown compose property", text));
172
+ else {
173
+ current = withAssignment(current, assignment);
174
+ replaceNode(nodes, current);
175
+ }
176
+ }
177
+ return { ...(namespace === undefined ? {} : { namespace }), nodes, diagnostics };
178
+ }
@@ -1,18 +1,31 @@
1
- import { type TaskId } from "./identity.js";
2
1
  import type { WorldRoot } from "../world.js";
3
- import { type TaskRefusal, type TaskRetry } from "./operations.js";
4
- type TaskDocumentChange = Readonly<{
2
+ import { type TaskCompositionAlias, type TaskCompositionBodyPreview } from "./compose-language.js";
3
+ import type { TaskId } from "./identity.js";
4
+ import type { TaskRefusal, TaskRetry } from "./operations.js";
5
+ export type { TaskCompositionAlias, TaskCompositionBodyPreview } from "./compose-language.js";
6
+ export type TaskDocumentChange = Readonly<{
5
7
  taskId: TaskId;
6
8
  kind: "created" | "updated";
7
9
  documentDiff: string;
8
10
  }>;
11
+ export type TaskCompositionFacts = Readonly<{
12
+ aliases: readonly TaskCompositionAlias[];
13
+ admissionOrder: readonly TaskId[];
14
+ }>;
9
15
  export type TaskCompositionResult = Readonly<{
16
+ kind: "planned";
17
+ aliases: readonly TaskCompositionAlias[];
18
+ admissionOrder: readonly TaskId[];
19
+ bodies: readonly TaskCompositionBodyPreview[];
20
+ }> | Readonly<{
10
21
  kind: "accepted";
11
22
  documentChanges: readonly TaskDocumentChange[];
12
- }> | Readonly<{
23
+ } & TaskCompositionFacts> | Readonly<{
13
24
  kind: "refused";
14
- refusal: TaskRefusal;
15
- }> | Readonly<{
25
+ refusal: Extract<TaskRefusal, {
26
+ kind: "invalid-composition";
27
+ }>;
28
+ }> | (Readonly<{
16
29
  kind: "incomplete";
17
30
  documentChanges: readonly TaskDocumentChange[];
18
31
  stopped: TaskRefusal | Readonly<{
@@ -20,6 +33,12 @@ export type TaskCompositionResult = Readonly<{
20
33
  reason: TaskRetry;
21
34
  }>;
22
35
  draft: string;
23
- }>;
24
- export declare function composeTasks(world: WorldRoot, markdown: string, signal?: AbortSignal, actor?: string, defaultNamespace?: readonly string[]): Promise<TaskCompositionResult>;
25
- export {};
36
+ }> & TaskCompositionFacts);
37
+ export declare function composeTasks(input: Readonly<{
38
+ world: WorldRoot;
39
+ markdown: string;
40
+ signal?: AbortSignal;
41
+ actor?: string;
42
+ defaultNamespace?: readonly string[];
43
+ planOnly?: boolean;
44
+ }>): Promise<TaskCompositionResult>;
@@ -1,305 +1,143 @@
1
1
  import { documentDiff } from "../markdown/diff.js";
2
- import { relationProblem } from "./board.js";
2
+ import { planTaskComposition, } from "./compose-language.js";
3
3
  import { serializeTaskDocument } from "./document.js";
4
- import { allocateLocalId, deriveLocalStem, formatTaskId, parseTaskId, sameNamespace } from "./identity.js";
5
4
  import { authorityPath, readBoard, replaceAuthority, withTaskLocks } from "./store.js";
6
- import { advanceTaskTimestamp } from "./operations.js";
7
- function failure(diagnostic) {
8
- return { kind: "invalid-composition", diagnostic };
5
+ function refusal(diagnostics) {
6
+ return { kind: "refused", refusal: { kind: "invalid-composition", diagnostics } };
9
7
  }
10
- function parseNamespace(value) {
11
- if (value === "")
12
- return [];
13
- const coordinate = parseTaskId(`task/${value}/placeholder`);
14
- return coordinate.namespace;
15
- }
16
- function assignment(token) {
17
- const matched = /^(parent|needs|supersedes|relates|pri|body)(\+=|=)(.*)$/u.exec(token);
18
- if (matched === null)
19
- return null;
20
- const field = matched[1], append = matched[2] === "+=", value = matched[3];
21
- if (append && (field === "parent" || field === "pri" || field === "body"))
22
- throw new TypeError(`${field} does not accept +=`);
23
- if (field === "body" && (append || value !== ""))
24
- throw new TypeError("body accepts only bare body=");
25
- return { field, append, value };
26
- }
27
- function parseNode(text, depth, index) {
28
- const tokens = text.split(/ +/u);
29
- if (text.startsWith("+ ")) {
30
- const values = tokens.slice(1);
31
- const at = values.findIndex((token) => assignment(token) !== null);
32
- const title = values.slice(0, at < 0 ? values.length : at).join(" ");
33
- if (title.trim().length === 0)
34
- throw new TypeError("compose + node requires a title");
35
- return {
36
- index,
37
- depth,
38
- kind: "new",
39
- title,
40
- assignments: (at < 0 ? [] : values.slice(at)).map((token) => assignment(token) ??
41
- (() => {
42
- throw new TypeError(`invalid assignment token: ${token}`);
43
- })()),
44
- };
45
- }
46
- const [rawId, ...rest] = tokens;
47
- if (rawId === undefined || !rawId.startsWith("@task/"))
48
- throw new TypeError("compose node must begin with + or @task/");
49
- const id = `task/${rawId.slice(1).slice(5)}`;
50
- parseTaskId(id);
51
- return {
52
- index,
53
- depth,
54
- kind: "existing",
55
- id,
56
- assignments: rest.map((token) => assignment(token) ??
57
- (() => {
58
- throw new TypeError(`invalid assignment token: ${token}`);
59
- })()),
60
- };
8
+ function currentTimestamp() {
9
+ return new Date().toISOString();
61
10
  }
62
- function parseSketch(markdown) {
63
- try {
64
- const lines = markdown.replace(/\r\n?/gu, "\n").split("\n");
65
- let namespace;
66
- let start = 0;
67
- if (lines[0]?.startsWith("ns=")) {
68
- namespace = parseNamespace(lines[0].slice(3));
69
- start = 1;
70
- }
71
- const mutable = [];
72
- for (let line = start; line < lines.length; line += 1) {
73
- const raw = lines[line];
74
- if (line === lines.length - 1 && raw === "")
75
- continue;
76
- const leading = /^(?:\t| )*/u.exec(raw)[0].replace(/\t/gu, " ");
77
- const text = raw.slice(/^(?:\t| )*/u.exec(raw)[0].length);
78
- const nodeLine = text.startsWith("+ ") || text.startsWith("@task/");
79
- if (nodeLine) {
80
- if (leading.length % 2 !== 0)
81
- throw new TypeError(`compose line ${line + 1} has invalid indentation`);
82
- const depth = leading.length / 2;
83
- if (depth > 0 && !mutable.some((entry) => entry.node.depth === depth - 1))
84
- throw new TypeError(`compose line ${line + 1} skips a parent depth`);
85
- mutable.push({ node: parseNode(text, depth, mutable.length), body: [] });
86
- continue;
87
- }
88
- const current = mutable.at(-1);
89
- if (current === undefined) {
90
- if (text.trim() === "")
91
- continue;
92
- throw new TypeError(`compose line ${line + 1} has body before a node`);
93
- }
94
- current.body.push(text.startsWith("\\") ? text.slice(1) : text);
95
- }
96
- const nodes = mutable.map(({ node, body }) => ({
97
- ...node,
98
- ...(body.length === 0 ? {} : { body: body.join("\n") }),
99
- }));
100
- return { ...(namespace === undefined ? {} : { namespace }), nodes };
11
+ function facts(plan) {
12
+ return { aliases: plan.aliases, admissionOrder: plan.admissionOrder };
13
+ }
14
+ function reference(id, remainingAliases) {
15
+ const alias = remainingAliases.get(id);
16
+ return alias === undefined ? `@${id}` : `^${alias}`;
17
+ }
18
+ function bodyToken(body) {
19
+ const lines = new Set(body.split(/\r\n|\n|\r/u));
20
+ for (let suffix = 0; Number.isSafeInteger(suffix); suffix += 1) {
21
+ const token = suffix === 0 ? "END_BODY" : `END_BODY_${suffix}`;
22
+ if (token.length > 32)
23
+ break;
24
+ if (!lines.has(token))
25
+ return token;
101
26
  }
102
- catch (error) {
103
- return failure(error instanceof Error ? error.message : String(error));
27
+ throw new Error("compose recovery body token space exhausted");
28
+ }
29
+ function taskDraft(task, remainingAliases) {
30
+ const document = task.after;
31
+ const lines = [task.kind === "new" ? `+ ${document.title}` : `@${document.id}`];
32
+ if (task.kind === "new" && task.alias !== undefined)
33
+ lines.push(`as = ${task.alias}`);
34
+ lines.push(`pri = ${document.priority}`, `needs = ${document.needs.map((id) => reference(id, remainingAliases)).join(", ")}`, `parent = ${document.parent === null ? "" : reference(document.parent, remainingAliases)}`, `supersedes = ${document.supersedes.map((id) => reference(id, remainingAliases)).join(", ")}`, `relates = ${document.relates.map((id) => reference(id, remainingAliases)).join(", ")}`);
35
+ if (document.body === "")
36
+ lines.push("body =");
37
+ else {
38
+ const token = bodyToken(document.body);
39
+ lines.push(`body <<${token}`, document.body, token);
104
40
  }
41
+ return lines;
105
42
  }
106
- function ids(value) {
107
- if (value === "")
108
- return [];
109
- const parsed = value.split(",").map((raw) => {
110
- if (!raw.startsWith("@task/"))
111
- throw new TypeError("relation values must be @TaskId");
112
- const id = raw.slice(1);
113
- parseTaskId(id);
114
- return id;
115
- });
116
- if (new Set(parsed).size !== parsed.length)
117
- throw new TypeError("relation values must not contain duplicates");
118
- return parsed;
119
- }
120
- function scalarId(value) {
121
- const values = ids(value);
122
- if (values.length > 1)
123
- throw new TypeError("parent accepts at most one TaskId");
124
- return values[0] ?? null;
125
- }
126
- function changed(current, value, append) {
127
- return append ? [...current, ...value.filter((id) => !current.includes(id))] : value;
128
- }
129
- function applyAssignments(document, assignments, body) {
130
- let next = document;
131
- const seen = new Set();
132
- for (const item of assignments) {
133
- const mode = `${item.field}:${item.append}`;
134
- if (seen.has(mode) || [...seen].some((value) => value.startsWith(`${item.field}:`) && value !== mode))
135
- throw new TypeError(`duplicate compose assignment: ${item.field}`);
136
- seen.add(mode);
137
- if (item.field === "pri") {
138
- const priority = Number(item.value);
139
- if (!Number.isInteger(priority) || priority < 0 || priority > 3)
140
- throw new TypeError("pri must be 0..3");
141
- next = { ...next, priority: priority };
142
- }
143
- else if (item.field === "parent")
144
- next = { ...next, parent: scalarId(item.value) };
145
- else if (item.field === "body")
146
- next = { ...next, body: "" };
147
- else
148
- next = { ...next, [item.field]: changed(next[item.field], ids(item.value), item.append) };
43
+ function recoveryDraft(namespace, remaining) {
44
+ const aliases = new Map();
45
+ for (const task of remaining) {
46
+ if (task.kind === "new" && task.alias !== undefined)
47
+ aliases.set(task.after.id, task.alias);
149
48
  }
150
- return body === undefined ? next : { ...next, body };
151
- }
152
- function currentTimestamp() {
153
- return new Date().toISOString();
154
- }
155
- function createdTask(id, title, at, actor) {
156
- return {
157
- id,
158
- title,
159
- state: "open",
160
- priority: 2,
161
- needs: [],
162
- parent: null,
163
- supersedes: [],
164
- relates: [],
165
- note: "",
166
- ...(actor === undefined ? {} : { createdBy: actor }),
167
- createdAt: at,
168
- updatedAt: at,
169
- body: "",
170
- };
49
+ const lines = [`ns=${namespace.join("/")}`];
50
+ for (const task of remaining)
51
+ lines.push("", ...taskDraft(task, aliases));
52
+ return `${lines.join("\n")}\n`;
171
53
  }
172
- function plan(sketch, board, defaultNamespace, at, actor) {
173
- try {
174
- const namespace = sketch.namespace ?? defaultNamespace;
175
- const occupied = new Set([...board.tasks.values()].flatMap((task) => {
176
- const coordinate = parseTaskId(task.id);
177
- return sameNamespace(coordinate.namespace, namespace) ? [coordinate.localId] : [];
178
- }));
179
- const allocations = new Map();
180
- for (const node of sketch.nodes)
181
- if (node.kind === "new") {
182
- const localId = allocateLocalId(deriveLocalStem(node.title), occupied);
183
- occupied.add(localId);
184
- const coordinate = { namespace, localId };
185
- allocations.set(node.index, createdTask(formatTaskId(coordinate), node.title, at, actor));
186
- }
187
- const all = new Map(board.tasks);
188
- for (const allocated of allocations.values())
189
- all.set(allocated.id, allocated);
190
- const byDepth = [], addressed = new Set();
191
- const planned = [];
192
- for (const node of sketch.nodes) {
193
- const before = node.kind === "new" ? null : (board.tasks.get(node.id) ?? null);
194
- let current = node.kind === "new" ? allocations.get(node.index) : all.get(node.id);
195
- if (current === undefined)
196
- throw new TypeError(`compose task does not exist: ${node.id}`);
197
- if (addressed.has(current.id))
198
- throw new TypeError(`compose addresses ${current.id} more than once`);
199
- addressed.add(current.id);
200
- if (node.depth > 0) {
201
- const parent = byDepth[node.depth - 1];
202
- if (parent === undefined)
203
- throw new TypeError("compose parent is unavailable");
204
- if (node.assignments.some((item) => item.field === "parent"))
205
- throw new TypeError("indented node cannot also assign parent");
206
- current = { ...current, parent };
207
- }
208
- current = applyAssignments(current, node.assignments, node.body);
209
- if (before !== null &&
210
- !Buffer.from(serializeTaskDocument(current)).equals(Buffer.from(serializeTaskDocument(before)))) {
211
- current = {
212
- ...current,
213
- updatedAt: advanceTaskTimestamp(before.updatedAt, at),
214
- };
215
- }
216
- byDepth[node.depth] = current.id;
217
- byDepth.length = node.depth + 1;
218
- all.set(current.id, current);
219
- planned.push({ node, before, after: current });
54
+ function plannedResult(plan) {
55
+ return { kind: "planned", ...facts(plan), bodies: plan.bodies };
56
+ }
57
+ function planAgainst(markdown, board, namespace, at, actor) {
58
+ return planTaskComposition({ markdown, board, namespace, at, ...(actor === undefined ? {} : { actor }) });
59
+ }
60
+ async function admitPlan(world, snapshot, plan, signal) {
61
+ const changes = [];
62
+ for (let index = 0; index < plan.tasks.length; index += 1) {
63
+ signal?.throwIfAborted();
64
+ const item = plan.tasks[index];
65
+ const beforeBytes = item.before === null ? null : (snapshot.bytes.get(item.after.id) ?? null);
66
+ const afterBytes = serializeTaskDocument(item.after);
67
+ const before = beforeBytes === null ? "" : Buffer.from(beforeBytes).toString("utf8");
68
+ const after = Buffer.from(afterBytes).toString("utf8");
69
+ const replaced = await replaceAuthority({
70
+ path: authorityPath(world, item.after.id),
71
+ expected: beforeBytes,
72
+ next: afterBytes,
73
+ });
74
+ if (replaced !== "replaced") {
75
+ return {
76
+ kind: "incomplete",
77
+ ...facts(plan),
78
+ documentChanges: changes,
79
+ stopped: { kind: "retry", reason: "concurrent-modification" },
80
+ draft: recoveryDraft(plan.namespace, plan.tasks.slice(index)),
81
+ };
220
82
  }
221
- for (const item of planned) {
222
- const problem = relationProblem({ tasks: all }, item.before, item.after);
223
- if (problem !== null)
224
- return failure(problem);
225
- }
226
- return planned;
227
- }
228
- catch (error) {
229
- return failure(error instanceof Error ? error.message : String(error));
83
+ const label = `${item.after.id}.md`;
84
+ changes.push({
85
+ taskId: item.after.id,
86
+ kind: item.before === null ? "created" : "updated",
87
+ documentDiff: documentDiff(label, label, before, after),
88
+ });
230
89
  }
90
+ return { kind: "accepted", ...facts(plan), documentChanges: changes };
91
+ }
92
+ async function composeUnderLocks(input) {
93
+ const snapshot = await readBoard(input.world);
94
+ const planned = planAgainst(input.markdown, snapshot.board, input.namespace, input.at, input.actor);
95
+ if (planned.kind === "refused")
96
+ return refusal(planned.diagnostics);
97
+ return await withTaskLocks({
98
+ world: input.world,
99
+ allocation: false,
100
+ ids: planned.plan.admissionOrder,
101
+ ...(input.signal === undefined ? {} : { signal: input.signal }),
102
+ }, async () => {
103
+ const fresh = await readBoard(input.world);
104
+ const replanned = planAgainst(input.markdown, fresh.board, input.namespace, input.at, input.actor);
105
+ if (replanned.kind === "refused")
106
+ return refusal(replanned.diagnostics);
107
+ return await admitPlan(input.world, fresh, replanned.plan, input.signal);
108
+ });
231
109
  }
232
- function ref(id) {
233
- return `@${id}`;
234
- }
235
- function bodyLines(body) {
236
- return body.split("\n").map((line) => (/^[\\]|^\+ |^@task\//u.test(line) ? `\\${line}` : line));
237
- }
238
- function draft(namespace, remaining) {
239
- const lines = [`ns=${namespace.join("/")}`];
240
- for (const item of remaining) {
241
- const task = item.after;
242
- const assignments = [
243
- `pri=${task.priority}`,
244
- `needs=${task.needs.map(ref).join(",")}`,
245
- `parent=${task.parent === null ? "" : ref(task.parent)}`,
246
- `supersedes=${task.supersedes.map(ref).join(",")}`,
247
- `relates=${task.relates.map(ref).join(",")}`,
248
- ];
249
- lines.push(`${item.node.kind === "new" ? `+ ${task.title}` : ref(task.id)} ${assignments.join(" ")}${task.body === "" ? " body=" : ""}`);
250
- if (task.body !== "")
251
- lines.push(...bodyLines(task.body));
252
- }
253
- return `${lines.join("\n")}\n`;
110
+ function composeInput(input) {
111
+ return input;
254
112
  }
255
- export async function composeTasks(world, markdown, signal, actor, defaultNamespace) {
256
- const sketch = parseSketch(markdown);
257
- if ("kind" in sketch)
258
- return { kind: "refused", refusal: sketch };
113
+ export async function composeTasks(input) {
114
+ const { world, markdown, signal, actor, defaultNamespace = [], planOnly = false } = input;
259
115
  const at = currentTimestamp();
260
- const namespace = sketch.namespace ?? defaultNamespace ?? [];
261
116
  const initial = await readBoard(world);
262
- const planned = plan(sketch, initial.board, namespace, at, actor);
263
- if ("kind" in planned)
264
- return { kind: "refused", refusal: planned };
265
- const ordered = [...planned].sort((a, b) => Buffer.compare(Buffer.from(a.after.id), Buffer.from(b.after.id)));
266
- const allocation = sketch.nodes.some((node) => node.kind === "new");
267
- const result = await withTaskLocks({ world, allocation, ids: ordered.map((item) => item.after.id), ...(signal === undefined ? {} : { signal }) }, async () => {
268
- const fresh = await readBoard(world);
269
- const replanned = plan(sketch, fresh.board, namespace, at, actor);
270
- if ("kind" in replanned)
271
- return { kind: "refused", refusal: replanned };
272
- const queue = [...replanned].sort((a, b) => Buffer.compare(Buffer.from(a.after.id), Buffer.from(b.after.id))), changes = [];
273
- for (let index = 0; index < queue.length; index += 1) {
274
- signal?.throwIfAborted();
275
- const item = queue[index], path = authorityPath(world, item.after.id);
276
- const beforeBytes = item.before === null ? null : (fresh.bytes.get(item.after.id) ?? null);
277
- const afterBytes = serializeTaskDocument(item.after);
278
- const before = beforeBytes === null ? "" : Buffer.from(beforeBytes).toString("utf8"), after = Buffer.from(afterBytes).toString("utf8");
279
- if (before === after)
280
- continue;
281
- if ((await replaceAuthority({ path, expected: beforeBytes, next: afterBytes })) !== "replaced")
282
- return {
283
- kind: "incomplete",
284
- documentChanges: changes,
285
- stopped: { kind: "retry", reason: "concurrent-modification" },
286
- draft: draft(namespace, queue.slice(index)),
287
- };
288
- const label = `${item.after.id}.md`;
289
- changes.push({
290
- taskId: item.after.id,
291
- kind: item.before === null ? "created" : "updated",
292
- documentDiff: documentDiff(label, label, before, after),
293
- });
294
- }
295
- return { kind: "accepted", documentChanges: changes };
117
+ const initialPlan = planAgainst(markdown, initial.board, defaultNamespace, at, actor);
118
+ if (initialPlan.kind === "refused")
119
+ return refusal(initialPlan.diagnostics);
120
+ if (planOnly)
121
+ return plannedResult(initialPlan.plan);
122
+ const request = composeInput({
123
+ world,
124
+ markdown,
125
+ namespace: defaultNamespace,
126
+ at,
127
+ ...(actor === undefined ? {} : { actor }),
128
+ ...(signal === undefined ? {} : { signal }),
296
129
  });
297
- return result === "busy"
298
- ? {
299
- kind: "incomplete",
300
- documentChanges: [],
301
- stopped: { kind: "retry", reason: "busy" },
302
- draft: draft(namespace, ordered),
303
- }
304
- : result;
130
+ const allocation = initialPlan.plan.tasks.some((task) => task.kind === "new");
131
+ const admitted = allocation
132
+ ? await withTaskLocks({ world, allocation: true, ids: [], ...(signal === undefined ? {} : { signal }) }, async () => await composeUnderLocks(request))
133
+ : await composeUnderLocks(request);
134
+ if (admitted !== "busy")
135
+ return admitted;
136
+ return {
137
+ kind: "incomplete",
138
+ ...facts(initialPlan.plan),
139
+ documentChanges: [],
140
+ stopped: { kind: "retry", reason: "busy" },
141
+ draft: recoveryDraft(initialPlan.plan.namespace, initialPlan.plan.tasks),
142
+ };
305
143
  }