- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/worker/project/http.ts?version=201&format=json
630 linesFirst import 94% · engine 3% · candidates 2% · pinch 1% · rename 1% · infra-split 1% · whytrail 1%Last change whytrail in version 193, 7 versions changed it
You're reading version 201. The newest is 318, and 3 versions since then changed this file.
1// The JSON routes of the contract (docs/v2-slice1.md), as a pure function of
2// the project calls, so they can be tested in Node without a Worker.
4import type { EditBody, ProjectCalls, ProjectHistory } from "./project-api.ts";
5import { unseenError } from "./unseen.ts";
7export interface Answer {
8 status: number;
9 body: unknown;
10}
12const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/;
14export function validName(name: string | undefined): name is string {
15 return name !== undefined && NAME.test(name);
16}
18/**
19 * The call's answer, or undefined when `ms` passes or the call fails.
20 * The call keeps running either way: this only bounds how long the caller waits.
21 */
22export function within<T>(work: Promise<T>, ms: number): Promise<T | undefined> {
23 return new Promise((resolve) => {
24 const timer = setTimeout(() => resolve(undefined), ms);
25 work.then(
26 (value) => {
27 clearTimeout(timer);
28 resolve(value);
29 },
30 () => {
31 clearTimeout(timer);
32 resolve(undefined);
33 },
34 );
35 });
36}
38const fail = (status: number, error: string): Answer => ({ status, body: { error } });
40/**
41 * Agents that read everything and record nothing (#37, Reporter). Kept by the
42 * caller outside the log: a refused call writes nothing, so replay never
43 * needs it, and an older Worker can still load the log.
44 */
45export interface Readers {
46 has(agent: string): boolean;
47 set(agent: string, reader: boolean): void;
48 list(): string[];
49}
51/**
52 * What a reader may not do. Edits and records (which old edit mods send on
53 * their own) and publishes answer 200 {ok: false, reason}, so a mod only logs
54 * it; the rest are refused outright.
55 */
56const NOT_FOR_READERS: Record<string, "answer" | "refuse"> = {
57 edit: "answer",
58 record: "answer",
59 publish: "answer",
60 land: "answer",
61 pluck: "answer",
62 "draft-sync": "refuse",
63 drop: "refuse",
64 amend: "refuse",
65 label: "refuse",
66 starting: "refuse",
67 move: "refuse",
68};
70/** A path the project won't hold: .avcs/ is each folder's own settings. */
71/** A path under a folder's state folder (.abso/, or .avcs/ from before the rename), which never leaves it. */
72function localPath(paths: string[]): string | undefined {
73 return paths.find((p) => [".abso", ".avcs"].some((d) => p === d || p.startsWith(`${d}/`) || p.startsWith(`./${d}/`)));
74}
75const LOCAL = (p: string) =>
76 fail(400, `${p} is under ${p.replace(/^\.\//, "").split("/")[0]}/, which stays in the agent's folder`);
78/**
79 * The reader rules (#37, Reporter), for one agent call: the answer to
80 * `reader {reader}`, or the refusal of something a reader may not do, or
81 * undefined when the call goes ahead. An agent holding unpublished work
82 * can't become a reader.
83 */
84export function readerAnswer(
85 project: { status(): unknown },
86 op: string,
87 agent: string,
88 body: unknown,
89 readers: Readers,
90): Answer | undefined {
91 if (op === "reader") {
92 const on = (body as { reader?: unknown } | undefined)?.reader;
93 if (typeof on !== "boolean") return fail(400, "reader needs {reader: true} or {reader: false}");
94 if (on) {
95 const me = (
96 project.status() as { agents?: { agent: string; draftChanges: number; parked?: unknown[] }[] }
97 ).agents?.find((a) => a.agent === agent);
98 if (me && (me.draftChanges > 0 || (me.parked?.length ?? 0) > 0)) {
99 return fail(
100 409,
101 `${agent} has unpushed changes; push or restore them (abso restore --all) before it becomes a reader`,
102 );
103 }
104 }
105 readers.set(agent, on);
106 return { status: 200, body: { agent, reader: on } };
107 }
108 const barred = readers.has(agent) ? NOT_FOR_READERS[op] : undefined;
109 if (!barred) return undefined;
110 const reason = `agent ${agent} is a reader: it records nothing (abso join --reader)`;
111 if (barred === "refuse") return fail(403, reason);
112 return { status: 200, body: { ok: false, reason, ...(op === "edit" || op === "record" ? {} : { collisions: [] }) } };
113}
115/** The status answer with readers marked on their agent entries and listed (#37). */
116export function statusWithReaders(status: unknown, readers: Readers | undefined): unknown {
117 const s = status as { agents?: { agent: string }[] };
118 if (!readers || readers.list().length === 0) return s;
119 return {
120 ...s,
121 agents: (s.agents ?? []).map((a) => (readers.has(a.agent) ? { ...a, reader: true } : a)),
122 readers: readers.list(),
123 };
124}
126/** op is "init", "status", or an agent op ("edit", "record", "publish", "sync"). */
127export function answer(
128 project: ProjectCalls,
129 op: string,
130 agent: string | undefined,
131 body: unknown,
132 readers?: Readers,
133 how?: string,
134): Answer {
135 try {
136 if (op === "init") {
137 const files = (body as { files?: Record<string, string> })?.files;
138 if (!files || typeof files !== "object") return fail(400, "init needs {files: {path: text}}");
139 if (project.exists()) return fail(409, "the project already exists");
140 const bad = localPath(Object.keys(files));
141 if (bad) return LOCAL(bad);
142 const modes = (body as { modes?: unknown })?.modes;
143 if (modes !== undefined && (typeof modes !== "object" || modes === null))
144 return fail(400, "modes must be {path: {exec, link}}");
145 const blobs = (body as { blobs?: unknown })?.blobs;
146 if (blobs !== undefined && (typeof blobs !== "object" || blobs === null))
147 return fail(400, "blobs must be {path: sha256}");
148 if (blobs && localPath(Object.keys(blobs))) return LOCAL(localPath(Object.keys(blobs))!);
149 return {
150 status: 200,
151 body: project.init(
152 files,
153 modes as Record<string, { exec?: boolean; link?: string | null }> | undefined,
154 blobs as Record<string, string> | undefined,
155 ),
156 };
157 }
158 if (!project.exists()) return fail(404, "no such project; run init first");
159 // Readers (#37): marked on their agent entries, and listed even before their first sync.
160 // Reads for the website (#41): ?at=<log position> replays status and where as they stood then.
161 const atOf = (): number | undefined => {
162 const at = (body as { at?: string } | undefined)?.at;
163 return at !== undefined && at !== "" && Number.isInteger(Number(at)) && Number(at) >= 0 ? Number(at) : undefined;
164 };
165 if (op === "status" && agent === undefined) {
166 const at = atOf();
167 const history = project as ProjectCalls & Partial<ProjectHistory>;
168 if (at !== undefined)
169 return history.statusAt
170 ? { status: 200, body: history.statusAt(at) }
171 : fail(501, "status at a log position needs the engine");
172 return { status: 200, body: statusWithReaders(project.status(), readers) };
173 }
174 if (op === "where") {
175 const history = project as ProjectCalls & Partial<ProjectHistory>;
176 if (!history.where) return fail(501, "where needs the engine");
177 const at = atOf();
178 if (at !== undefined)
179 return history.whereAt
180 ? { status: 200, body: history.whereAt(at) }
181 : fail(501, "where at a log position needs the engine");
182 return { status: 200, body: history.where() };
183 }
184 if (op === "changes" || op.startsWith("change/")) {
185 const history = project as ProjectCalls & Partial<ProjectHistory>;
186 if (!history.change || !history.changes) return fail(501, `${op} needs the engine`);
187 const q = (body ?? {}) as Record<string, string | undefined>;
188 if (op !== "changes") return { status: 200, body: history.change(Number(op.slice("change/".length))) };
189 const since = q.since === undefined || q.since === "" ? 0 : Number(q.since);
190 const limit = q.limit === undefined || q.limit === "" ? 50 : Number(q.limit);
191 if (!Number.isInteger(since) || since < 0) return fail(400, "changes needs ?since=<log position>");
192 if (!Number.isInteger(limit) || limit < 1 || limit > 200) return fail(400, "limit is 1-200");
193 const before = q.before === undefined || q.before === "" ? undefined : Number(q.before);
194 if (before !== undefined && (!Number.isInteger(before) || before < 0))
195 return fail(400, "before must be a log position");
196 // ?issue= (#54): the changes whose start note named that issue.
197 if (q.issue !== undefined && q.issue !== "" && !/^[1-9]\d{0,9}$/.test(q.issue))
198 return fail(400, "issue must be an issue number");
199 return { status: 200, body: history.changes(since, limit, before, q.issue ? Number(q.issue) : undefined) };
200 }
201 if (op === "notes") {
202 const history = project as ProjectCalls & Partial<ProjectHistory>;
203 if (!history.notes) return fail(501, "notes needs the engine");
204 const q = (body ?? {}) as Record<string, string | undefined>;
205 if (q.change !== undefined && !/^\d+$/.test(q.change)) return fail(400, "change must be a change id");
206 return {
207 status: 200,
208 body: history.notes({
209 ...(q.file ? { file: q.file } : {}),
210 ...(q.change ? { change: Number(q.change) } : {}),
211 ...(q.open === "1" || q.open === "true" ? { open: true } : {}),
212 }),
213 };
214 }
215 if (op === "position") {
216 const history = project as ProjectCalls & Partial<ProjectHistory>;
217 if (!history.position) return fail(501, "position needs the engine");
218 const q = (body ?? {}) as Record<string, string | undefined>;
219 if (q.version !== undefined && q.version !== "") {
220 if (!/^\d+$/.test(q.version)) return fail(400, "version must be a version number");
221 return { status: 200, body: history.position({ version: Number(q.version) }) };
222 }
223 if (q.time === undefined || q.time === "")
224 return fail(400, "position needs ?time=<ISO time or ms since 1970> or ?version=<n>");
225 const time = /^\d+$/.test(q.time) ? Number(q.time) : Date.parse(q.time);
226 if (!Number.isFinite(time)) return fail(400, "time is an ISO time or ms since 1970");
227 return { status: 200, body: history.position({ time }) };
228 }
229 if (op === "ribbon") {
230 const history = project as ProjectCalls & Partial<ProjectHistory>;
231 if (!history.ribbon) return fail(501, "ribbon needs the engine");
232 return { status: 200, body: history.ribbon() };
233 }
234 if (op === "feed" || op === "drafts" || (op === "diff" && agent === undefined)) {
235 const q = (body ?? {}) as Record<string, string | undefined>;
236 const history = project as ProjectCalls & Partial<ProjectHistory>;
237 if (!history.feed || !history.drafts || !history.diffOf) return fail(501, `${op} needs the engine`);
238 if (op === "drafts") return { status: 200, body: history.drafts() };
239 if (op === "diff") {
240 if (!q.agent) return fail(400, "diff needs ?agent=<name>");
241 return { status: 200, body: history.diffOf(q.agent) };
242 }
243 const from = q.from === undefined || q.from === "" ? 0 : Number(q.from);
244 const limit = q.limit === undefined || q.limit === "" ? 500 : Number(q.limit);
245 if (!Number.isInteger(from) || from < 0) return fail(400, "feed needs ?from=<log position>");
246 if (!Number.isInteger(limit) || limit < 1 || limit > 2000) return fail(400, "limit is 1-2000");
247 return { status: 200, body: history.feed(from, limit) };
248 }
249 if (op === "draft-state") {
250 // A named draft's state in one read (#41, the Drafts page): base, behind, versions, first edit, collisions.
251 const history = project as ProjectCalls & Partial<ProjectHistory>;
252 if (!history.draftState) return fail(501, "draft-state needs the engine");
253 const q = (body ?? {}) as Record<string, string | undefined>;
254 if (!q.name) return fail(400, "draft-state needs ?name=<draft>");
255 return { status: 200, body: history.draftState(q.name) };
256 }
257 if (
258 op === "tree" ||
259 op === "path" ||
260 op === "follow" ||
261 op === "collisions" ||
262 (op === "blame" && (body as { folder?: unknown } | undefined)?.folder !== undefined)
263 ) {
264 // Reads for the Files pages (#41): GETs, the body is the query string.
265 const q = (body ?? {}) as Record<string, string | undefined>;
266 const history = project as ProjectCalls & Partial<ProjectHistory>;
267 if (!history.tree || !history.pathLife || !history.follow || !history.collisions || !history.folderBlame)
268 return fail(501, `${op} needs the engine`);
269 const int = (s: string | undefined): number | undefined | null =>
270 s === undefined || s === "" ? undefined : /^\d+$/.test(s) ? Number(s) : null;
271 const version = int(q.version);
272 if (version === null) return fail(400, "version must be a version number");
273 const draft = q.draft || null;
274 if (op === "blame")
275 return {
276 status: 200,
277 body: history.folderBlame(q.folder ?? "", version, q.draft || undefined, q.agent || undefined),
278 };
279 // agent= (#41, F25): the folder as that agent has it; authors=1 (F33): each entry's authors in the same read.
280 if (op === "tree") {
281 if (q.authors !== undefined && q.authors !== "" && q.authors !== "1")
282 return fail(400, "authors is 1 or left out");
283 return {
284 status: 200,
285 body: history.tree(q.folder ?? "", version, draft, q.agent || undefined, q.authors === "1"),
286 };
287 }
288 if (op === "collisions")
289 return { status: 200, body: history.collisions(q.file || undefined, q.folder || undefined) };
290 if (!q.path) return fail(400, `${op} needs ?path=<path>`);
291 if (op === "path") return { status: 200, body: history.pathLife(q.path, version, draft) };
292 const from = int(q.from);
293 const to = int(q.to) ?? from;
294 const at = int(q.at);
295 if (
296 version === undefined ||
297 from === undefined ||
298 from === null ||
299 to === null ||
300 to === undefined ||
301 at === null
302 )
303 return fail(400, "follow needs ?path=&version=&from=, and ?to= and ?at= if wanted");
304 return { status: 200, body: history.follow(q.path, version, from, to, at, draft) };
305 }
306 if (op === "blame" || op === "why") {
307 // GETs: the body is the query string as {file, from, to, line}.
308 const q = (body ?? {}) as Record<string, string | undefined>;
309 const history = project as ProjectCalls & Partial<ProjectHistory>;
310 if (!q.file) return fail(400, `${op} needs ?file=<path>, or blame ?folder=<path> ("" for the whole project)`);
311 if (!history.blame || !history.why) return fail(501, `${op} needs the engine`);
312 const num = (s: string | undefined) => (s === undefined || s === "" ? undefined : Number(s));
313 const draft = q.draft || undefined;
314 const who = q.agent || undefined;
315 if (op === "blame")
316 return { status: 200, body: history.blame(q.file, num(q.from), num(q.to), num(q.version), draft, who) };
317 const line = num(q.line);
318 if (!line || !Number.isInteger(line)) return fail(400, "why needs ?line=<number>");
319 return { status: 200, body: history.why(q.file, line, draft, who, num(q.version)) };
320 }
321 if (op === "announce" && agent === undefined) {
322 // The sender comes from the route, like every other agent op, not from
323 // a body field anyone can fill in (#31).
324 return fail(400, "announce from your own agent: POST /p/:project/a/<you>/announce {text, to?}");
325 }
326 if (op === "files" && agent === undefined) {
327 // GET ?version=&draft=: the paths in shared (or a named draft) at a version.
328 const q = (body ?? {}) as Record<string, string | undefined>;
329 const history = project as ProjectCalls & Partial<ProjectHistory>;
330 // ?agent=: the files as an agent has them (#41, F25), read only, so an unknown agent is 404.
331 if (q.agent !== undefined) {
332 if (!history.pathsOf) return fail(501, "files?agent= needs the engine");
333 return { status: 200, body: history.pathsOf(q.agent) };
334 }
335 if (!history.pathsAt) return fail(501, "files needs the engine");
336 const version = q.version !== undefined && q.version !== "" ? Number(q.version) : undefined;
337 if (version !== undefined && !Number.isInteger(version)) return fail(400, "version must be a number");
338 return { status: 200, body: history.pathsAt(version, q.draft || null) };
339 }
340 if (op === "labels") {
341 const history = project as ProjectCalls & Partial<ProjectHistory>;
342 if (!history.labels) return fail(501, "labels needs the engine");
343 return { status: 200, body: history.labels() };
344 }
345 if (op === "refusals") {
346 // GET ?agent=<name>&limit=<n>: refused publishes and lands, newest first, and counts.
347 const q = (body ?? {}) as Record<string, string | undefined>;
348 const history = project as ProjectCalls & Partial<ProjectHistory>;
349 if (!history.refusals) return fail(501, "refusals needs the engine");
350 const limit = q.limit !== undefined && Number.isInteger(Number(q.limit)) ? Number(q.limit) : undefined;
351 return { status: 200, body: history.refusals(q.agent || undefined, limit) };
352 }
353 if (op === "without") {
354 // GET ?version=<n>&versions=<n,n>: version n of shared with those versions left out (without.ts).
355 const q = (body ?? {}) as Record<string, string | undefined>;
356 const history = project as ProjectCalls & Partial<ProjectHistory>;
357 if (!history.without) return fail(501, "without needs the engine");
358 const version = q.version !== undefined && /^\d+$/.test(q.version) ? Number(q.version) : undefined;
359 const versions = (q.versions ?? "").split(",").filter((s) => s.trim() !== "");
360 if (version === undefined || versions.length === 0 || versions.some((s) => !/^\s*\d+\s*$/.test(s)))
361 return fail(400, "without needs ?version=<number>&versions=<number,number>");
362 return { status: 200, body: history.without(version, versions.map(Number)) };
363 }
364 if (op === "log" || op === "show" || op === "file" || op === "compare") {
365 // GETs: ?draft=<name> (shared when absent); log ?limit, ?path; show ?version; file ?path, ?version; compare ?from, ?to.
366 const q = (body ?? {}) as Record<string, string | undefined>;
367 const history = project as ProjectCalls & Partial<ProjectHistory>;
368 if (!history.log || !history.show || !history.fileAt || !history.compare)
369 return fail(501, `${op} needs the engine`);
370 const draft = q.draft ? q.draft : null;
371 const int = (s: string | undefined): number | undefined =>
372 s !== undefined && s !== "" && Number.isInteger(Number(s)) ? Number(s) : undefined;
373 const who = q.agent || undefined;
374 if (op === "log")
375 return {
376 status: 200,
377 body: history.log(
378 draft,
379 int(q.limit),
380 q.path || undefined,
381 who,
382 int(q.before),
383 q.follow === "1" || q.follow === "true",
384 ),
385 };
386 if (op === "file") {
387 const version = int(q.version);
388 if (!q.path || version === undefined) return fail(400, "file needs ?path=<path>&version=<number>");
389 return { status: 200, body: history.fileAt(q.path, version, draft, who) };
390 }
391 if (op === "compare") {
392 const from = int(q.from);
393 const to = int(q.to);
394 if (from === undefined || to === undefined) return fail(400, "compare needs ?from=<number>&to=<number>");
395 return { status: 200, body: history.compare(from, to, draft, who) };
396 }
397 const version = Number(q.version);
398 if (q.version === undefined || !Number.isInteger(version)) return fail(400, "show needs ?version=<number>");
399 return { status: 200, body: history.show(version, draft, who) };
400 }
401 if (!validName(agent)) return fail(400, "agent names use letters, digits, '.', '_' and '-'");
402 if (op === "reader" && !readers) return fail(501, "reader needs the Worker");
403 const gated = readers ? readerAnswer(project, op, agent, body, readers) : undefined;
404 if (gated) return gated;
405 switch (op) {
406 case "edit": {
407 const b = body as EditBody;
408 if (!b || typeof b.file !== "string")
409 return fail(400, "edit needs {file, old, new}, {file, content} or {file, edits}");
410 if (localPath([b.file])) return LOCAL(b.file);
411 return { status: 200, body: project.edit(agent, b) };
412 }
413 case "record": {
414 const files = (body as { files?: Record<string, string | null> })?.files;
415 if (!files || typeof files !== "object") return fail(400, "record needs {files: {path: text or null}}");
416 const bad = localPath(Object.keys(files));
417 if (bad) return LOCAL(bad);
418 const modes = (body as { modes?: unknown })?.modes;
419 if (modes !== undefined && (typeof modes !== "object" || modes === null))
420 return fail(400, "modes must be {path: {exec, link}}");
421 const blobs = (body as { blobs?: unknown })?.blobs;
422 if (blobs !== undefined && (typeof blobs !== "object" || blobs === null))
423 return fail(400, "blobs must be {path: sha256}");
424 if (blobs && localPath(Object.keys(blobs))) return LOCAL(localPath(Object.keys(blobs))!);
425 const who = body as { session?: unknown; subagent?: unknown; client?: unknown };
426 const meta = {
427 ...(typeof who.session === "string" ? { session: who.session } : {}),
428 ...(typeof who.subagent === "string" ? { subagent: who.subagent } : {}),
429 ...(typeof who.client === "string" ? { client: who.client } : {}),
430 };
431 return {
432 status: 200,
433 body: project.record(
434 agent,
435 files,
436 modes as Record<string, { exec?: boolean; link?: string | null }> | undefined,
437 blobs as Record<string, string> | undefined,
438 meta,
439 ),
440 };
441 }
442 case "publish": {
443 const message = (body as { message?: string })?.message;
444 if (typeof message !== "string" || !message.trim()) return fail(400, "push needs {message} saying why");
445 const unseen = unseenError("the message", message);
446 if (unseen) return fail(400, unseen);
447 // asIs (#37): publish even with collided lines untouched since the sync, both sides kept.
448 return { status: 200, body: project.publish(agent, message, (body as { asIs?: unknown }).asIs === true) };
449 }
450 case "sync": {
451 // {label}: follow a label (#10), syncing to the newest version of shared that carries it.
452 const label = (body as { label?: unknown } | undefined)?.label;
453 if ((body as { full?: unknown } | undefined)?.full === true) {
454 // {full: true}: every file in the agent's view, as a first sync answers (#37).
455 const history = project as ProjectCalls & Partial<ProjectHistory>;
456 if (!history.syncFull) return fail(501, "a full pull needs the engine");
457 if (label !== undefined && typeof label !== "string") return fail(400, "label must be a label name");
458 return { status: 200, body: history.syncFull(agent, label as string | undefined) };
459 }
460 if (label === undefined) return { status: 200, body: project.sync(agent) };
461 if (typeof label !== "string") return fail(400, "label must be a label name");
462 const history = project as ProjectCalls & Partial<ProjectHistory>;
463 if (!history.syncTo) return fail(501, "following a label needs the engine");
464 return { status: 200, body: history.syncTo(agent, label) };
465 }
466 case "label": {
467 const history = project as ProjectCalls & Partial<ProjectHistory>;
468 if (!history.label) return fail(501, "label needs the engine");
469 const b = (body ?? {}) as { name?: unknown; version?: unknown; remove?: unknown };
470 if (typeof b.name !== "string") return fail(400, "label needs {name}, and {version} unless it's the newest");
471 if (b.version !== undefined && !Number.isInteger(b.version)) return fail(400, "version must be a number");
472 return { status: 200, body: history.label(agent, b.name, b.version as number | undefined, b.remove === true) };
473 }
474 // Named drafts (#10).
475 case "draft": {
476 const name = (body as { name?: unknown })?.name;
477 if (name !== null && typeof name !== "string")
478 return fail(400, "draft needs {name}, or {name: null} for shared");
479 return { status: 200, body: project.switchTo(agent, name, (body as { carry?: unknown }).carry === true) };
480 }
481 case "land": {
482 const message = (body as { message?: string })?.message;
483 if (typeof message !== "string" || !message.trim()) return fail(400, "land needs {message} saying why");
484 const unseen = unseenError("the message", message);
485 if (unseen) return fail(400, unseen);
486 return { status: 200, body: project.land(agent, message) };
487 }
488 case "draft-sync":
489 return { status: 200, body: project.syncDraft(agent) };
490 // The paths in the agent's view (#37): what its folder should hold. A GET; changes nothing.
491 case "files": {
492 const history = project as ProjectCalls & Partial<ProjectHistory>;
493 if (!history.agentPaths) return fail(501, "files needs the engine");
494 return { status: 200, body: history.agentPaths(agent) };
495 }
496 // abso status in one trip (abso issue 80): the project's status and the agent's paths.
497 case "status": {
498 const history = project as ProjectCalls & Partial<ProjectHistory>;
499 if (!history.agentPaths) return fail(501, "status needs the engine");
500 return {
501 status: 200,
502 body: { ...(statusWithReaders(project.status(), readers) as object), files: history.agentPaths(agent) },
503 };
504 }
505 // Amend (#27): correct the message of the agent's newest publish.
506 case "amend": {
507 const history = project as ProjectCalls & Partial<ProjectHistory>;
508 if (!history.amend) return fail(501, "amend needs the engine");
509 const message = (body as { message?: unknown } | undefined)?.message;
510 if (typeof message !== "string" || !message.trim()) return fail(400, "amend needs {message}");
511 const unseen = unseenError("the message", message);
512 if (unseen) return fail(400, unseen);
513 return { status: 200, body: history.amend(agent, message) };
514 }
515 // Pluck (#27): take some versions of a named draft into shared.
516 case "pluck": {
517 const history = project as ProjectCalls & Partial<ProjectHistory>;
518 if (!history.pluck) return fail(501, "pluck needs the engine");
519 const b = (body ?? {}) as {
520 draft?: unknown;
521 versions?: unknown;
522 message?: unknown;
523 withDependencies?: unknown;
524 };
525 if (typeof b.draft !== "string") return fail(400, "pluck needs {draft, versions: [number], message}");
526 if (!Array.isArray(b.versions) || b.versions.length === 0 || !b.versions.every((v) => Number.isInteger(v)))
527 return fail(400, "pluck needs {versions: [number]}");
528 if (typeof b.message !== "string" || !b.message.trim()) return fail(400, "pluck needs {message} saying why");
529 const unseen = unseenError("the message", b.message);
530 if (unseen) return fail(400, unseen);
531 return {
532 status: 200,
533 body: history.pluck(agent, b.draft, b.versions as number[], b.message, b.withDependencies === true),
534 };
535 }
536 // Drop (#10): take published versions out of shared.
537 case "drop": {
538 const history = project as ProjectCalls & Partial<ProjectHistory>;
539 if (!history.drop) return fail(501, "drop needs the engine");
540 const b = (body ?? {}) as { versions?: unknown; message?: unknown; withDependents?: unknown };
541 if (!Array.isArray(b.versions) || b.versions.length === 0 || !b.versions.every((v) => Number.isInteger(v)))
542 return fail(400, "drop needs {versions: [number], message}");
543 if (typeof b.message !== "string" || !b.message.trim()) return fail(400, "drop needs {message} saying why");
544 const unseen = unseenError("the message", b.message);
545 if (unseen) return fail(400, unseen);
546 return { status: 200, body: history.drop(agent, b.versions as number[], b.message, b.withDependents === true) };
547 }
548 // Announcements, and news without an edit.
549 case "move": {
550 const history = project as ProjectCalls & Partial<ProjectHistory>;
551 if (!history.move) return fail(501, "move needs the engine");
552 const b = (body ?? {}) as { from?: unknown; to?: unknown };
553 if (typeof b.from !== "string" || typeof b.to !== "string") return fail(400, "move needs {from, to}");
554 if (localPath([b.from, b.to])) return LOCAL(localPath([b.from, b.to])!);
555 return { status: 200, body: history.move(agent, b.from, b.to) };
556 }
557 case "note":
558 case "note-close": {
559 const history = project as ProjectCalls & Partial<ProjectHistory>;
560 if (!history.note || !history.closeNote) return fail(501, `${op} needs the engine`);
561 const b = (body ?? {}) as Record<string, unknown>;
562 if (op === "note-close") return { status: 200, body: history.closeNote(agent, b.id as number, b.how) };
563 const unseen = unseenError("the note", b.text);
564 if (unseen) return fail(400, unseen);
565 return { status: 200, body: history.note(agent, b) };
566 }
567 case "announce":
568 case "news": {
569 const history = project as ProjectCalls & Partial<ProjectHistory>;
570 if (!history.announce || !history.news) return fail(501, `${op} needs the engine`);
571 if (op === "news") return { status: 200, body: history.news(agent) };
572 const b = (body ?? {}) as { text?: unknown; to?: unknown };
573 if (typeof b.text !== "string" || !b.text.trim()) return fail(400, "announce needs {text}");
574 const unseen = unseenError("the text", b.text);
575 if (unseen) return fail(400, unseen);
576 if (b.to !== undefined && (!Array.isArray(b.to) || !b.to.every((a) => typeof a === "string")))
577 return fail(400, "to must be a list of agent names");
578 return { status: 200, body: history.announce(agent, b.text, b.to as string[] | undefined, how) };
579 }
580 // What the agent is starting on (#37, #13): {text, files?}, or {text: null} to take it back.
581 case "starting": {
582 const history = project as ProjectCalls & Partial<ProjectHistory>;
583 if (!history.starting) return fail(501, "starting needs the engine");
584 const b = (body ?? {}) as { text?: unknown; files?: unknown; issue?: unknown; done?: unknown };
585 if (b.text !== null && (typeof b.text !== "string" || !b.text.trim()))
586 return fail(400, "starting needs {text}, or {text: null} to take it back");
587 const unseen = unseenError("the note", b.text);
588 if (unseen) return fail(400, unseen);
589 if (b.files !== undefined && (!Array.isArray(b.files) || !b.files.every((f) => typeof f === "string")))
590 return fail(400, "files must be a list of paths");
591 // issue (#54): the issue the note works on; done: a take-back because the work is finished, closing it.
592 return {
593 status: 200,
594 body: history.starting(agent, b.text as string | null, b.files as string[] | undefined, {
595 ...(b.issue !== undefined ? { issue: b.issue } : {}),
596 ...(b.done !== undefined ? { done: b.done } : {}),
597 }),
598 };
599 }
600 // Everyday commands (#27).
601 case "diff":
602 case "restore": {
603 const history = project as ProjectCalls & Partial<ProjectHistory>;
604 if (!history.diff || !history.restore) return fail(501, `${op} needs the engine`);
605 if (op === "diff") return { status: 200, body: history.diff(agent) };
606 const b = (body ?? {}) as { files?: unknown; all?: unknown };
607 if (b.all === true) return { status: 200, body: history.restore(agent, null) };
608 if (!Array.isArray(b.files) || !b.files.every((f) => typeof f === "string")) {
609 return fail(400, "restore needs {files: [path]} or {all: true}");
610 }
611 return { status: 200, body: history.restore(agent, b.files as string[]) };
612 }
613 }
614 return fail(404, `no such operation: ${op}`);
615 } catch (e) {
616 // The engine throws ProjectError with a code; anything else is ours.
617 const code = (e as { code?: string }).code;
618 const status =
619 code === "not-implemented"
620 ? 501
621 : code === "not-initialized" || code === "not-found"
622 ? 404
623 : code === "already-initialized" || code === "conflict"
624 ? 409
625 : code === "bad-request" || code === "bad-agent"
626 ? 400
627 : 500;
628 return fail(status, e instanceof Error ? e.message : String(e));
629 }
630}