@davidbyoung/software-factory 0.1.7 → 0.1.9

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.
Files changed (63) hide show
  1. package/README.md +2 -0
  2. package/dist/agent/claude-code.mjs +15 -21
  3. package/dist/board.d.mts +20 -3
  4. package/dist/board.mjs +126 -38
  5. package/dist/cli.mjs +75 -9
  6. package/dist/code-host/github-setup.mjs +2 -2
  7. package/dist/code-host/github.mjs +4 -0
  8. package/dist/code-host/types.d.mts +2 -0
  9. package/dist/columns-suggest.d.mts +0 -1
  10. package/dist/columns-suggest.mjs +2 -8
  11. package/dist/commands.d.mts +2 -0
  12. package/dist/commands.mjs +22 -11
  13. package/dist/config.d.mts +12 -0
  14. package/dist/config.mjs +62 -11
  15. package/dist/doctor.d.mts +9 -1
  16. package/dist/doctor.mjs +209 -20
  17. package/dist/explain.d.mts +5 -0
  18. package/dist/explain.mjs +29 -0
  19. package/dist/init.d.mts +2 -0
  20. package/dist/init.mjs +143 -13
  21. package/dist/lib/color.d.mts +11 -0
  22. package/dist/lib/color.mjs +15 -0
  23. package/dist/npmrc.d.mts +29 -0
  24. package/dist/npmrc.mjs +98 -0
  25. package/dist/preset-commands.d.mts +2 -2
  26. package/dist/preset-commands.mjs +20 -24
  27. package/dist/preset.d.mts +4 -0
  28. package/dist/preset.mjs +13 -2
  29. package/dist/runner/github-actions.mjs +47 -10
  30. package/dist/runner/types.d.mts +13 -0
  31. package/dist/setup.d.mts +6 -1
  32. package/dist/site.d.mts +3 -0
  33. package/dist/site.mjs +8 -1
  34. package/dist/status.d.mts +5 -2
  35. package/dist/status.mjs +13 -22
  36. package/dist/sync.d.mts +14 -1
  37. package/dist/sync.mjs +83 -7
  38. package/dist/ticket-fields.d.mts +84 -0
  39. package/dist/ticket-fields.mjs +374 -0
  40. package/dist/ticket.mjs +8 -7
  41. package/dist/tickets/github-setup.mjs +1 -1
  42. package/dist/tickets/github.mjs +69 -0
  43. package/dist/tickets/index.d.mts +8 -1
  44. package/dist/tickets/index.mjs +67 -7
  45. package/dist/tickets/types.d.mts +27 -1
  46. package/dist/tickets/types.mjs +4 -0
  47. package/dist/tools.d.mts +1 -1
  48. package/docs/cli.md +44 -10
  49. package/docs/configuration.md +78 -25
  50. package/docs/design.md +10 -0
  51. package/docs/developing.md +49 -18
  52. package/docs/existing-repo.md +137 -8
  53. package/docs/github/by-hand.md +4 -0
  54. package/docs/github/reference.md +5 -0
  55. package/docs/github/setup.md +146 -8
  56. package/docs/limitations.md +0 -3
  57. package/docs/presets.md +5 -9
  58. package/docs/quick-start.md +3 -3
  59. package/docs/skills.md +3 -1
  60. package/docs/updating.md +3 -3
  61. package/package.json +4 -2
  62. package/settings.schema.json +68 -11
  63. package/skills/factory-deps/SKILL.md +4 -0
@@ -0,0 +1,374 @@
1
+ import { listed } from "./lib/listed.mjs";
2
+ /** The factory fields a refined ticket has, in the order its body has them. */
3
+ export const FACTORY_FIELDS = [
4
+ {
5
+ key: "decisions",
6
+ heading: "Decisions",
7
+ holds: "the questions refinement settled, and what was chosen",
8
+ },
9
+ {
10
+ key: "spec",
11
+ heading: "Spec",
12
+ holds: "what a change users will notice must do, line by line",
13
+ },
14
+ {
15
+ key: "acceptance-criteria",
16
+ heading: "Acceptance criteria",
17
+ holds: "what must be true for any other ticket to be done",
18
+ },
19
+ {
20
+ key: "for-the-builder",
21
+ heading: "For the builder",
22
+ holds: "how to build it, as a design and a list of tasks",
23
+ },
24
+ ];
25
+ const MOCKUPS = "mockups";
26
+ /** Spec and Acceptance criteria may share a ticket field: a ticket has one. */
27
+ const SHARED = ["spec", "acceptance-criteria"];
28
+ /** The heading a key stands for: the factory's own, or the key with its
29
+ * hyphens as spaces and its first letter capitalized. */
30
+ export function headingOf(key) {
31
+ const own = FACTORY_FIELDS.find((f) => f.key === key);
32
+ if (own)
33
+ return own.heading;
34
+ const words = key.replace(/-/g, " ");
35
+ return words.charAt(0).toUpperCase() + words.slice(1);
36
+ }
37
+ /** The key a heading stands for: lowercase, with hyphens for spaces. */
38
+ export const keyOf = (heading) => heading.trim().toLowerCase().replace(/\s+/g, "-");
39
+ /** Each line, with the key of the level-two heading it is, outside fenced
40
+ * code, or null. */
41
+ function headings(lines) {
42
+ let fence = null;
43
+ return lines.map((line) => {
44
+ const mark = /^\s*(```+|~~~+)/.exec(line)?.[1];
45
+ if (fence === null && mark) {
46
+ fence = mark;
47
+ return null;
48
+ }
49
+ if (fence !== null) {
50
+ if (mark?.[0] === fence[0] && mark.length >= fence.length)
51
+ fence = null;
52
+ return null;
53
+ }
54
+ const h = /^## (.+?)\s*$/.exec(line);
55
+ return h ? keyOf(h[1]) : null;
56
+ });
57
+ }
58
+ /** Lines with the blank ones at either end taken off. */
59
+ function trimmed(lines) {
60
+ let a = 0;
61
+ let b = lines.length;
62
+ while (a < b && !lines[a].trim())
63
+ a++;
64
+ while (b > a && !lines[b - 1].trim())
65
+ b--;
66
+ return lines.slice(a, b);
67
+ }
68
+ /** Pieces of text as a document: separated by one blank line, ending in
69
+ * a newline. */
70
+ const document = (pieces) => pieces
71
+ .map(trimmed)
72
+ .filter((p) => p.length)
73
+ .map((p) => p.join("\n"))
74
+ .join("\n\n") + "\n";
75
+ const named = (mapping) => Object.entries(mapping).filter((e) => e[1] !== null && e[1] !== undefined);
76
+ /** A ticket's document taken apart: the description, and each named ticket
77
+ * field's text, or null to clear it. */
78
+ export function split(body, mapping) {
79
+ const lines = body.split(/\r?\n/);
80
+ const keys = headings(lines);
81
+ const fieldOf = new Map(named(mapping));
82
+ const enders = new Set([
83
+ ...FACTORY_FIELDS.map((f) => f.key),
84
+ MOCKUPS,
85
+ ...Object.keys(mapping),
86
+ ]);
87
+ const kept = [[]];
88
+ const sections = new Map();
89
+ let into = null;
90
+ for (const [i, line] of lines.entries()) {
91
+ const key = keys[i];
92
+ if (key !== null && key !== undefined && enders.has(key)) {
93
+ if (fieldOf.has(key)) {
94
+ into = key;
95
+ sections.set(key, [...(sections.get(key) ?? []), ""]);
96
+ continue;
97
+ }
98
+ into = null;
99
+ kept.push([]);
100
+ }
101
+ if (into === null)
102
+ kept.at(-1).push(line);
103
+ else
104
+ sections.get(into).push(line);
105
+ }
106
+ const shared = fieldOf.get(SHARED[0]);
107
+ if (shared !== undefined &&
108
+ shared === fieldOf.get(SHARED[1]) &&
109
+ SHARED.every((k) => sections.has(k)))
110
+ return {
111
+ error: `Spec and Acceptance criteria both go in ${shared}, and the file has both: keep one.`,
112
+ };
113
+ const values = {};
114
+ for (const [key, field] of fieldOf) {
115
+ const text = sections.get(key);
116
+ if (text !== undefined)
117
+ values[field] = trimmed(text).join("\n");
118
+ else if (!(field in values))
119
+ values[field] = null;
120
+ }
121
+ const description = document(kept);
122
+ return { description: body.trim() ? description : body, values };
123
+ }
124
+ /** The order of the sections a body has: a heading of the repository's own
125
+ * first, in settings order, then the factory's. */
126
+ const ORDER = [
127
+ "decisions",
128
+ "spec",
129
+ "acceptance-criteria",
130
+ MOCKUPS,
131
+ "for-the-builder",
132
+ ];
133
+ /** A ticket's document: its description with each ticket field's text under
134
+ * its key's heading, before the first later heading the description has. */
135
+ export function join(description, values, mapping, labels) {
136
+ const order = [
137
+ ...Object.keys(mapping).filter((k) => !ORDER.includes(k)),
138
+ ...ORDER,
139
+ ];
140
+ const pairs = named(mapping);
141
+ const shared = pairs.filter(([k]) => SHARED.includes(k)).length === 2 &&
142
+ mapping.spec === mapping["acceptance-criteria"];
143
+ const reads = shared
144
+ ? labels.includes("spec")
145
+ ? "spec"
146
+ : "acceptance-criteria"
147
+ : null;
148
+ let lines = description.replace(/\n+$/, "").split("\n");
149
+ const add = pairs
150
+ .filter(([k]) => !(shared && SHARED.includes(k) && k !== reads))
151
+ .map(([k, field]) => [k, values[field] ?? ""])
152
+ .filter(([, text]) => text.trim())
153
+ .sort(([a], [b]) => order.indexOf(a) - order.indexOf(b));
154
+ for (const [key, text] of add) {
155
+ const rank = order.indexOf(key);
156
+ const at = headings(lines).findIndex((k) => k !== null && order.indexOf(k) > rank);
157
+ const section = [`## ${headingOf(key)}`, "", ...trimmed(text.split("\n"))];
158
+ lines =
159
+ at === -1
160
+ ? [...lines, "", ...section]
161
+ : [...lines.slice(0, at), ...section, "", ...lines.slice(at)];
162
+ }
163
+ return document([lines]);
164
+ }
165
+ /** The agent's answer for a factory field no ticket field fits. A token,
166
+ * so a ticket field called "Description" stays usable. */
167
+ export const DESCRIPTION = "__description__";
168
+ export const TIMEOUT_MS = 60_000;
169
+ const KEYS = FACTORY_FIELDS.map((f) => f.key);
170
+ const HEADING = Object.fromEntries(FACTORY_FIELDS.map((f) => [f.key, f.heading]));
171
+ export function prompt(fields) {
172
+ return [
173
+ "A software factory refines each ticket into parts, each under its own heading:",
174
+ ...FACTORY_FIELDS.map((f) => `- ${f.key} (${f.heading}): ${f.holds}`),
175
+ "",
176
+ "The tickets have these text fields:",
177
+ ...fields.map((f) => `- ${f.name}${f.description ? `: ${f.description}` : ""}`),
178
+ "",
179
+ "For each part, say which one of the text fields should hold it.",
180
+ `Answer ${DESCRIPTION} for a part no field clearly fits: it then stays in the ticket's description. Don't pick the nearest field when none fits.`,
181
+ "Give each field to at most one part, except that spec and acceptance-criteria may share one, since a ticket has only one of them.",
182
+ "Answer with a JSON object with each of the four parts as a key.",
183
+ ].join("\n");
184
+ }
185
+ export function schema(fields) {
186
+ const one = {
187
+ type: "string",
188
+ enum: [...fields.map((f) => f.name), DESCRIPTION],
189
+ };
190
+ return {
191
+ type: "object",
192
+ properties: Object.fromEntries(KEYS.map((k) => [k, one])),
193
+ required: KEYS,
194
+ };
195
+ }
196
+ /** Whether two factory fields may hold one ticket field. */
197
+ const mayShare = (a, b) => SHARED.includes(a) && SHARED.includes(b) && a !== b;
198
+ /** The suggestion the agent's answer gives, or the reason it can't be
199
+ * used, the first that applies in the order the issue lists them. */
200
+ export function check(answer, fields, repository) {
201
+ const form = { reason: "it did not answer in the form asked for" };
202
+ if (typeof answer !== "object" || answer === null || Array.isArray(answer))
203
+ return form;
204
+ const raw = answer;
205
+ const given = KEYS.filter((k) => typeof raw[k] === "string");
206
+ for (const k of given) {
207
+ const v = raw[k];
208
+ if (v !== DESCRIPTION && !fields.some((f) => f.name === v))
209
+ return {
210
+ reason: `it named ${v}, which ${repository}'s tickets don't have`,
211
+ };
212
+ }
213
+ for (const [i, a] of given.entries())
214
+ for (const b of given.slice(i + 1))
215
+ if (raw[a] !== DESCRIPTION && raw[a] === raw[b] && !mayShare(a, b))
216
+ return {
217
+ reason: `it put ${raw[a]} in both ${HEADING[a]} and ${HEADING[b]}`,
218
+ };
219
+ const missing = KEYS.find((k) => raw[k] === undefined);
220
+ if (missing)
221
+ return { reason: `it left out ${HEADING[missing]}` };
222
+ if (given.length < KEYS.length)
223
+ return form;
224
+ return {
225
+ suggestion: Object.fromEntries(KEYS.map((k) => [k, raw[k] === DESCRIPTION ? null : raw[k]])),
226
+ };
227
+ }
228
+ const shownIn = (field) => field ?? "the description";
229
+ /** The table of each factory field's ticket field. */
230
+ export function table(suggestion) {
231
+ const pad = (label) => ` ${label.padEnd(22)}`;
232
+ return [
233
+ `${pad("Factory field")}Ticket field`,
234
+ ...KEYS.map((k) => pad(HEADING[k]) + shownIn(suggestion[k])),
235
+ ];
236
+ }
237
+ /** The factory field that already holds `field`, other than `key` and the
238
+ * one it may share with, or null. */
239
+ function holding(field, key, s) {
240
+ return (KEYS.find((k) => k !== key && s[k] === field && !mayShare(k, key)) ?? null);
241
+ }
242
+ /** "Change some": the factory fields you pick, then a ticket field for
243
+ * each, until no two share one they may not. */
244
+ async function changeSome(d, suggestion, fields) {
245
+ const s = { ...suggestion };
246
+ let picked = [];
247
+ for (;;) {
248
+ picked = await d.ask.checkbox("Which factory fields do you want to change?", KEYS.map((k) => ({
249
+ name: `${HEADING[k]}: ${shownIn(s[k])}`,
250
+ value: k,
251
+ checked: picked.includes(k),
252
+ })));
253
+ let clash = false;
254
+ for (const key of KEYS.filter((k) => picked.includes(k))) {
255
+ const v = await d.ask.select(`Where does ${HEADING[key]} go?`, [
256
+ { name: "The description", value: DESCRIPTION },
257
+ ...fields.map((f) => ({ name: f.name, value: `field:${f.name}` })),
258
+ ], s[key] === null ? DESCRIPTION : `field:${s[key]}`);
259
+ const field = v === DESCRIPTION ? null : v.slice(6);
260
+ const other = field === null ? null : holding(field, key, s);
261
+ if (other) {
262
+ d.out(`${field} already holds ${HEADING[other]}. Pick another ticket field for ${HEADING[key]}.`);
263
+ clash = true;
264
+ break;
265
+ }
266
+ s[key] = field;
267
+ }
268
+ if (!clash)
269
+ return s;
270
+ }
271
+ }
272
+ /** The field step: the four factory fields' lines to write under
273
+ * `tickets.fields`, or 1 when init stops. */
274
+ export async function suggestFields(d, o) {
275
+ d.out("");
276
+ d.out(`${o.repository}'s tickets have the text fields ${listed(o.fields.map((f) => f.name))}.`);
277
+ d.out(`Asking ${d.label} which of them should hold each of the factory's fields...`);
278
+ const got = await d.agent.answer({
279
+ prompt: prompt(o.fields),
280
+ schema: schema(o.fields),
281
+ timeoutMs: TIMEOUT_MS,
282
+ });
283
+ const checked = "timedOut" in got
284
+ ? { reason: `it took longer than ${TIMEOUT_MS / 1000} seconds` }
285
+ : "failed" in got
286
+ ? {
287
+ reason: got.failed.error === null
288
+ ? `it failed with exit code ${got.failed.code}`
289
+ : `it failed: ${got.failed.error}`,
290
+ }
291
+ : check(got.answer, o.fields, o.repository);
292
+ if ("reason" in checked) {
293
+ d.out(`${d.label}'s answer could not be used: ${checked.reason}.`);
294
+ d.out("Run factory init again, or write tickets.fields in .claude/factory.yaml yourself.");
295
+ d.out("Nothing changed.");
296
+ return 1;
297
+ }
298
+ let suggestion = checked.suggestion;
299
+ for (;;) {
300
+ d.out("");
301
+ for (const line of table(suggestion))
302
+ d.out(line);
303
+ d.out("");
304
+ d.out("Your own text stays in the description.");
305
+ if (o.plainText)
306
+ d.out(`${o.plainText} shows a field's text as typed, without Markdown formatting.`);
307
+ d.out("");
308
+ const use = await d.ask.select("Use these ticket fields?", [
309
+ { name: "Yes", value: "yes" },
310
+ { name: "Change some", value: "change" },
311
+ { name: "No: keep everything in the description", value: "no" },
312
+ ], "yes");
313
+ if (use === "no")
314
+ return KEYS.map((k) => [k, "none"]);
315
+ if (use === "yes")
316
+ return KEYS.map((k) => [k, suggestion[k] ?? "none"]);
317
+ suggestion = await changeSome(d, suggestion, o.fields);
318
+ }
319
+ }
320
+ const FIX = "Create the field, or change tickets.fields in .claude/factory.yaml";
321
+ /** The checks `factory doctor` and `init` end with: that each ticket field
322
+ * the settings name exists and holds text. None when they name none. */
323
+ export async function fieldChecks(tickets, mapping, repository,
324
+ /** The ticket system's registered label. */
325
+ label) {
326
+ const wanted = named(mapping);
327
+ if (!wanted.length)
328
+ return [];
329
+ if (!tickets.fields)
330
+ return [
331
+ {
332
+ state: "fail",
333
+ text: `${label} has no ticket fields, which tickets.fields names`,
334
+ fix: FIX,
335
+ },
336
+ ];
337
+ let known;
338
+ try {
339
+ known = await tickets.fields.list();
340
+ }
341
+ catch (e) {
342
+ return [
343
+ {
344
+ state: "fail",
345
+ text: `${repository}'s ticket fields can be read`,
346
+ fix: (e instanceof Error ? e.message : String(e)).split("\n")[0],
347
+ },
348
+ ];
349
+ }
350
+ const failed = [];
351
+ for (const [key, name] of wanted) {
352
+ const field = known.find((f) => f.name === name);
353
+ if (!field)
354
+ failed.push({
355
+ state: "fail",
356
+ text: `${repository}'s tickets have no field called ${name}, which tickets.fields.${key} names`,
357
+ fix: FIX,
358
+ });
359
+ else if (!field.text)
360
+ failed.push({
361
+ state: "fail",
362
+ text: `${name}, which tickets.fields.${key} names, doesn't hold text`,
363
+ fix: FIX,
364
+ });
365
+ }
366
+ return failed.length
367
+ ? failed
368
+ : [
369
+ {
370
+ state: "pass",
371
+ text: `${repository}'s tickets have every field the settings name`,
372
+ },
373
+ ];
374
+ }
package/dist/ticket.mjs CHANGED
@@ -347,25 +347,26 @@ async function ticketCommand(command, args, d) {
347
347
  throw new Error(USAGE);
348
348
  if (!file && options(args, "--attach").length)
349
349
  throw new Error(USAGE);
350
- if (newTitle !== undefined) {
350
+ if (newTitle !== undefined)
351
351
  refuseBareTags(newTitle);
352
+ if (!file) {
352
353
  await t.writeTitle(ticket, newTitle);
353
- if (!file) {
354
- d.out("edited");
355
- return 0;
356
- }
354
+ d.out("edited");
355
+ return 0;
357
356
  }
358
- if (!file)
359
- throw new Error(USAGE);
360
357
  const attach = options(args, "--attach");
361
358
  const body = d.readFile(file);
362
359
  refuseBareTags(body);
363
360
  const files = attach.length ? need(t, "attachments") : null;
364
361
  if (command === "edit") {
362
+ // The body first: a body refused, as by a missing ticket field,
363
+ // leaves the title as it was.
365
364
  if (files)
366
365
  await files.writeBody(ticket, body, attach);
367
366
  else
368
367
  await t.writeBody(ticket, body);
368
+ if (newTitle !== undefined)
369
+ await t.writeTitle(ticket, newTitle);
369
370
  d.out("edited");
370
371
  }
371
372
  else
@@ -3,7 +3,7 @@
3
3
  import { boardConfigOf, inspectBoard } from "../board.mjs";
4
4
  import { fieldNamesOf } from "../config.mjs";
5
5
  import { listed } from "../lib/listed.mjs";
6
- const INIT = "Run npx --no-install factory init";
6
+ const INIT = "Run factory init";
7
7
  export const githubTicketsSetup = {
8
8
  checks: async (c) => {
9
9
  const s = c.settings;
@@ -209,6 +209,34 @@ export function commentIdFromUrl(url) {
209
209
  throw new Error(`gh printed no comment address: ${url.trim()}`);
210
210
  return Number(match[1]);
211
211
  }
212
+ const ISSUE_FIELDS = `query IssueFields($owner: String!, $name: String!) {
213
+ repository(owner: $owner, name: $name) {
214
+ issueFields(first: 100) {
215
+ nodes {
216
+ __typename
217
+ ... on IssueFieldText { id name description }
218
+ ... on IssueFieldSingleSelect { id name description }
219
+ ... on IssueFieldNumber { id name description }
220
+ ... on IssueFieldDate { id name description }
221
+ }
222
+ }
223
+ }
224
+ }`;
225
+ const FIELD_VALUES = `query IssueFieldValues($owner: String!, $name: String!, $number: Int!) {
226
+ repository(owner: $owner, name: $name) {
227
+ issue(number: $number) {
228
+ issueFieldValues(first: 50) {
229
+ nodes { ... on IssueFieldTextValue { value field { ... on IssueFieldText { name } } } }
230
+ }
231
+ }
232
+ }
233
+ }`;
234
+ const SET_ISSUE_FIELD = `mutation SetIssueField($issue: ID!, $field: ID!, $text: String!) {
235
+ setIssueFieldValue(input: { issueId: $issue, issueFields: [{ fieldId: $field, textValue: $text }] }) { clientMutationId }
236
+ }`;
237
+ const CLEAR_ISSUE_FIELD = `mutation ClearIssueField($issue: ID!, $field: ID!) {
238
+ setIssueFieldValue(input: { issueId: $issue, issueFields: [{ fieldId: $field, delete: true }] }) { clientMutationId }
239
+ }`;
212
240
  export function githubTickets(o) {
213
241
  const API = `repos/${o.repository}`;
214
242
  const [repoOwner, repoName] = o.repository.split("/");
@@ -220,6 +248,11 @@ export function githubTickets(o) {
220
248
  const answer = await t.graphql(STATUS_FIELD, { owner: o.boardOwner ?? repoOwner, number });
221
249
  return answer.data.owner?.projectV2?.field ?? null;
222
250
  };
251
+ /** The repository's issue fields, each with its type. */
252
+ const issueFields = async () => {
253
+ const answer = await t.graphql(ISSUE_FIELDS, { owner: repoOwner, name: repoName });
254
+ return answer.data.repository.issueFields.nodes.filter((f) => f !== null);
255
+ };
223
256
  const readBoard = async () => {
224
257
  if (o.board === null)
225
258
  return { projectId: "", fields: [], items: new Map() };
@@ -403,6 +436,42 @@ export function githubTickets(o) {
403
436
  return missing.map((f) => f.name);
404
437
  },
405
438
  },
439
+ fields: {
440
+ plainText: true,
441
+ async list() {
442
+ return (await issueFields()).map((f) => ({
443
+ name: f.name,
444
+ description: f.description ?? null,
445
+ text: f.__typename === "IssueFieldText",
446
+ }));
447
+ },
448
+ async holds() {
449
+ return { max: null };
450
+ },
451
+ async read(n) {
452
+ const answer = await t.graphql(FIELD_VALUES, { owner: repoOwner, name: repoName, number: n });
453
+ const found = answer.data.repository.issue;
454
+ if (!found)
455
+ throw new NotFoundError(`#${n}`);
456
+ const values = {};
457
+ for (const v of found.issueFieldValues.nodes)
458
+ if (v?.field?.name)
459
+ values[v.field.name] = v.value ?? "";
460
+ return values;
461
+ },
462
+ async write(n, values) {
463
+ const fields = await issueFields();
464
+ const { node_id } = await issue(n);
465
+ for (const [name, value] of Object.entries(values)) {
466
+ const field = fields.find((f) => f.name === name);
467
+ if (!field)
468
+ throw new Error(`No issue field called ${name}.`);
469
+ await t.graphql(value === null ? CLEAR_ISSUE_FIELD : SET_ISSUE_FIELD, value === null
470
+ ? { issue: node_id, field: field.id }
471
+ : { issue: node_id, field: field.id, text: value });
472
+ }
473
+ },
474
+ },
406
475
  blockers: {
407
476
  async list(n) {
408
477
  const list = await found(`#${n}`, t.rest("GET", `${API}/issues/${n}/dependencies/blocked_by`, { paginate: true }));
@@ -1,6 +1,7 @@
1
1
  import { type Gh } from "../lib/gh.mts";
2
2
  import { type Settings } from "../config.mts";
3
- import type { Tickets } from "./types.mts";
3
+ import { type Tickets } from "./types.mts";
4
+ import { type FieldMapping } from "../ticket-fields.mts";
4
5
  export * from "./types.mts";
5
6
  /** The ticket system's message for a type that is not built. */
6
7
  export declare const unsupportedType: (type: string) => string;
@@ -13,3 +14,9 @@ export declare function openTickets(settings: Settings, target: {
13
14
  repository: string;
14
15
  board: number | null;
15
16
  }, run?: Gh): Promise<Opened>;
17
+ /** The adapter with each ticket read as one document and written back
18
+ * split: the description, and each ticket field `tickets.fields` names.
19
+ * The follow-ups ticket stays whole. `readAll` is the adapter's, since its
20
+ * callers read comments, labels, and cards, never a refined ticket's
21
+ * sections. */
22
+ export declare function withTicketFields(inner: Tickets, mapping: FieldMapping, repository: string): Tickets;
@@ -5,6 +5,8 @@ import { gh } from "../lib/gh.mjs";
5
5
  import { fieldNamesOf } from "../config.mjs";
6
6
  import { githubTickets } from "./github.mjs";
7
7
  import { ghTransport } from "./transport.mjs";
8
+ import { need } from "./types.mjs";
9
+ import { join, split } from "../ticket-fields.mjs";
8
10
  import { BUILT, unsupported } from "../tool-names.mjs";
9
11
  export * from "./types.mjs";
10
12
  /** The ticket system's message for a type that is not built. */
@@ -16,13 +18,71 @@ export async function openTickets(settings, target, run = gh) {
16
18
  if (type !== "github")
17
19
  throw new Error(unsupportedType(type));
18
20
  const transport = ghTransport(run);
21
+ const tickets = githubTickets({
22
+ transport,
23
+ repository: target.repository,
24
+ board: target.board,
25
+ cli: run,
26
+ fieldNames: fieldNamesOf(settings),
27
+ });
28
+ const mapping = settings.tickets.ticketFields;
19
29
  return {
20
- tickets: githubTickets({
21
- transport,
22
- repository: target.repository,
23
- board: target.board,
24
- cli: run,
25
- fieldNames: fieldNamesOf(settings),
26
- }),
30
+ tickets: Object.values(mapping).some((v) => v !== null)
31
+ ? withTicketFields(tickets, mapping, target.repository)
32
+ : tickets,
27
33
  };
28
34
  }
35
+ /** The adapter with each ticket read as one document and written back
36
+ * split: the description, and each ticket field `tickets.fields` names.
37
+ * The follow-ups ticket stays whole. `readAll` is the adapter's, since its
38
+ * callers read comments, labels, and cards, never a refined ticket's
39
+ * sections. */
40
+ export function withTicketFields(inner, mapping, repository) {
41
+ const fields = () => need(inner, "fields");
42
+ const whole = (labels) => labels.includes("follow-up");
43
+ /** The description to write, once every named field is checked and
44
+ * written. */
45
+ const written = async (n, body) => {
46
+ const { labels } = await inner.read(n);
47
+ if (whole(labels))
48
+ return body;
49
+ const ops = fields();
50
+ const known = await ops.list();
51
+ for (const [key, name] of Object.entries(mapping)) {
52
+ if (name === null)
53
+ continue;
54
+ const field = known.find((f) => f.name === name);
55
+ if (!field)
56
+ throw new Error(`${repository}'s tickets have no field called ${name}, which tickets.fields.${key} names.`);
57
+ if (!field.text)
58
+ throw new Error(`${name}, which tickets.fields.${key} names, doesn't hold text.`);
59
+ }
60
+ const parts = split(body, mapping);
61
+ if ("error" in parts)
62
+ throw new Error(parts.error);
63
+ await ops.write(n, parts.values);
64
+ return parts.description;
65
+ };
66
+ const tickets = {
67
+ ...inner,
68
+ async read(n) {
69
+ const ticket = await inner.read(n);
70
+ if (whole(ticket.labels))
71
+ return ticket;
72
+ const values = await fields().read(n);
73
+ return {
74
+ ...ticket,
75
+ body: join(ticket.body, values, mapping, ticket.labels),
76
+ };
77
+ },
78
+ async writeBody(n, body) {
79
+ await inner.writeBody(n, await written(n, body));
80
+ },
81
+ };
82
+ if (inner.attachments)
83
+ tickets.attachments = {
84
+ ...inner.attachments,
85
+ writeBody: async (n, body, files) => inner.attachments.writeBody(n, await written(n, body), files),
86
+ };
87
+ return tickets;
88
+ }
@@ -123,7 +123,31 @@ export type AttachmentOps = {
123
123
  /** Replaces the body with the images attached. */
124
124
  writeBody(ticket: number, body: string, files: string[]): Promise<void>;
125
125
  };
126
- export declare const GROUPS: readonly ["board", "blockers", "label-history", "attachments"];
126
+ /** A field tickets can have, set on the ticket itself. */
127
+ export type TicketField = {
128
+ name: string;
129
+ /** The field's own description, for the coding agent; null with none. */
130
+ description: string | null;
131
+ /** Whether it holds text, so it can hold a factory field. */
132
+ text: boolean;
133
+ };
134
+ export type FieldOps = {
135
+ /** Whether a field shows its text as typed, without formatting. */
136
+ plainText: boolean;
137
+ /** The fields tickets can have, in the system's order. */
138
+ list(): Promise<TicketField[]>;
139
+ /** Whether the ticket can hold the field, and how many characters. */
140
+ holds(ticket: number, field: string): Promise<{
141
+ max: number | null;
142
+ } | {
143
+ reason: string;
144
+ }>;
145
+ /** The ticket's text field values, by field name. */
146
+ read(ticket: number): Promise<Record<string, string>>;
147
+ /** Sets each field by name; null clears it. */
148
+ write(ticket: number, values: Record<string, string | null>): Promise<void>;
149
+ };
150
+ export declare const GROUPS: readonly ["board", "blockers", "label-history", "attachments", "fields"];
127
151
  export type Group = (typeof GROUPS)[number];
128
152
  export type NewTicket = {
129
153
  title: string;
@@ -162,6 +186,7 @@ export type Tickets = {
162
186
  blockers?: BlockerOps;
163
187
  labelHistory?: LabelHistoryOps;
164
188
  attachments?: AttachmentOps;
189
+ fields?: FieldOps;
165
190
  };
166
191
  /** A ticket or comment that does not exist, told apart from any other
167
192
  * failure. Every adapter throws this one. */
@@ -181,6 +206,7 @@ declare const GROUP_KEYS: {
181
206
  readonly blockers: "blockers";
182
207
  readonly "label-history": "labelHistory";
183
208
  readonly attachments: "attachments";
209
+ readonly fields: "fields";
184
210
  };
185
211
  type GroupKey<G extends Group> = (typeof GROUP_KEYS)[G];
186
212
  /** "Read everything at once" from the list and the single reads, for an
@@ -8,6 +8,7 @@ export const GROUPS = [
8
8
  "blockers",
9
9
  "label-history",
10
10
  "attachments",
11
+ "fields",
11
12
  ];
12
13
  /** A ticket or comment that does not exist, told apart from any other
13
14
  * failure. Every adapter throws this one. */
@@ -35,6 +36,8 @@ export function supports(tickets, group) {
35
36
  return tickets.labelHistory !== undefined;
36
37
  case "attachments":
37
38
  return tickets.attachments !== undefined;
39
+ case "fields":
40
+ return tickets.fields !== undefined;
38
41
  }
39
42
  }
40
43
  /** The group's operations, or UnsupportedError naming it. */
@@ -50,6 +53,7 @@ const GROUP_KEYS = {
50
53
  blockers: "blockers",
51
54
  "label-history": "labelHistory",
52
55
  attachments: "attachments",
56
+ fields: "fields",
53
57
  };
54
58
  /** "Read everything at once" from the list and the single reads, for an
55
59
  * adapter that does not override it. It returns the open tickets: a list of