@aigile/engine 0.2.3 → 0.4.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.
Files changed (198) hide show
  1. package/dist/action-item-features.d.ts +33 -0
  2. package/dist/action-item-features.d.ts.map +1 -0
  3. package/dist/action-item-features.js +113 -0
  4. package/dist/action-item-features.js.map +1 -0
  5. package/dist/action-items.d.ts +234 -0
  6. package/dist/action-items.d.ts.map +1 -0
  7. package/dist/action-items.js +722 -0
  8. package/dist/action-items.js.map +1 -0
  9. package/dist/action-sources.d.ts +44 -0
  10. package/dist/action-sources.d.ts.map +1 -0
  11. package/dist/action-sources.js +141 -0
  12. package/dist/action-sources.js.map +1 -0
  13. package/dist/agent-roles.d.ts +9 -0
  14. package/dist/agent-roles.d.ts.map +1 -0
  15. package/dist/agent-roles.js +18 -0
  16. package/dist/agent-roles.js.map +1 -0
  17. package/dist/agent-tasks.d.ts +36 -0
  18. package/dist/agent-tasks.d.ts.map +1 -0
  19. package/dist/agent-tasks.js +151 -0
  20. package/dist/agent-tasks.js.map +1 -0
  21. package/dist/agents/orchestrator.d.ts +26 -6
  22. package/dist/agents/orchestrator.d.ts.map +1 -1
  23. package/dist/agents/orchestrator.js +95 -45
  24. package/dist/agents/orchestrator.js.map +1 -1
  25. package/dist/agents/spec-analyst.d.ts +81 -13
  26. package/dist/agents/spec-analyst.d.ts.map +1 -1
  27. package/dist/agents/spec-analyst.js +350 -89
  28. package/dist/agents/spec-analyst.js.map +1 -1
  29. package/dist/ai-service.d.ts +40 -0
  30. package/dist/ai-service.d.ts.map +1 -1
  31. package/dist/ai-service.js +94 -9
  32. package/dist/ai-service.js.map +1 -1
  33. package/dist/api-tokens.d.ts +67 -0
  34. package/dist/api-tokens.d.ts.map +1 -0
  35. package/dist/api-tokens.js +89 -0
  36. package/dist/api-tokens.js.map +1 -0
  37. package/dist/attachments/extract.d.ts +26 -0
  38. package/dist/attachments/extract.d.ts.map +1 -0
  39. package/dist/attachments/extract.js +160 -0
  40. package/dist/attachments/extract.js.map +1 -0
  41. package/dist/attachments/fixtures.d.ts +9 -0
  42. package/dist/attachments/fixtures.d.ts.map +1 -0
  43. package/dist/attachments/fixtures.js +58 -0
  44. package/dist/attachments/fixtures.js.map +1 -0
  45. package/dist/attachments/service.d.ts +71 -0
  46. package/dist/attachments/service.d.ts.map +1 -0
  47. package/dist/attachments/service.js +220 -0
  48. package/dist/attachments/service.js.map +1 -0
  49. package/dist/build-service.d.ts +1 -1
  50. package/dist/build-service.d.ts.map +1 -1
  51. package/dist/build-service.js +9 -4
  52. package/dist/build-service.js.map +1 -1
  53. package/dist/change-events.d.ts +110 -0
  54. package/dist/change-events.d.ts.map +1 -0
  55. package/dist/change-events.js +238 -0
  56. package/dist/change-events.js.map +1 -0
  57. package/dist/change-sets.d.ts +110 -0
  58. package/dist/change-sets.d.ts.map +1 -0
  59. package/dist/change-sets.js +188 -0
  60. package/dist/change-sets.js.map +1 -0
  61. package/dist/command-runner.d.ts.map +1 -1
  62. package/dist/command-runner.js +2 -1
  63. package/dist/command-runner.js.map +1 -1
  64. package/dist/conversations.d.ts +2 -1
  65. package/dist/conversations.d.ts.map +1 -1
  66. package/dist/conversations.js +1 -1
  67. package/dist/conversations.js.map +1 -1
  68. package/dist/data-access.d.ts +9 -2
  69. package/dist/data-access.d.ts.map +1 -1
  70. package/dist/data-access.js +38 -6
  71. package/dist/data-access.js.map +1 -1
  72. package/dist/decisions.d.ts +56 -0
  73. package/dist/decisions.d.ts.map +1 -0
  74. package/dist/decisions.js +76 -0
  75. package/dist/decisions.js.map +1 -0
  76. package/dist/deliverables.d.ts +96 -0
  77. package/dist/deliverables.d.ts.map +1 -0
  78. package/dist/deliverables.js +344 -0
  79. package/dist/deliverables.js.map +1 -0
  80. package/dist/designs.d.ts +30 -0
  81. package/dist/designs.d.ts.map +1 -0
  82. package/dist/designs.js +154 -0
  83. package/dist/designs.js.map +1 -0
  84. package/dist/git-host.d.ts +10 -0
  85. package/dist/git-host.d.ts.map +1 -1
  86. package/dist/git-host.js +30 -2
  87. package/dist/git-host.js.map +1 -1
  88. package/dist/grounding.d.ts +9 -0
  89. package/dist/grounding.d.ts.map +1 -0
  90. package/dist/grounding.js +12 -0
  91. package/dist/grounding.js.map +1 -0
  92. package/dist/index.d.ts +35 -12
  93. package/dist/index.d.ts.map +1 -1
  94. package/dist/index.js +33 -10
  95. package/dist/index.js.map +1 -1
  96. package/dist/jira-features.d.ts +142 -0
  97. package/dist/jira-features.d.ts.map +1 -0
  98. package/dist/jira-features.js +366 -0
  99. package/dist/jira-features.js.map +1 -0
  100. package/dist/milestones.js +1 -1
  101. package/dist/milestones.js.map +1 -1
  102. package/dist/pull-request-sync.d.ts.map +1 -1
  103. package/dist/pull-request-sync.js +10 -6
  104. package/dist/pull-request-sync.js.map +1 -1
  105. package/dist/questions.d.ts +100 -10
  106. package/dist/questions.d.ts.map +1 -1
  107. package/dist/questions.js +211 -22
  108. package/dist/questions.js.map +1 -1
  109. package/dist/related.d.ts +26 -0
  110. package/dist/related.d.ts.map +1 -0
  111. package/dist/related.js +64 -0
  112. package/dist/related.js.map +1 -0
  113. package/dist/release-gates.d.ts +16 -0
  114. package/dist/release-gates.d.ts.map +1 -0
  115. package/dist/release-gates.js +47 -0
  116. package/dist/release-gates.js.map +1 -0
  117. package/dist/reviews.d.ts.map +1 -1
  118. package/dist/reviews.js +4 -3
  119. package/dist/reviews.js.map +1 -1
  120. package/dist/router.d.ts +2 -2
  121. package/dist/router.d.ts.map +1 -1
  122. package/dist/router.js.map +1 -1
  123. package/dist/scheduler.d.ts +41 -5
  124. package/dist/scheduler.d.ts.map +1 -1
  125. package/dist/scheduler.js +109 -7
  126. package/dist/scheduler.js.map +1 -1
  127. package/dist/services.d.ts +760 -15
  128. package/dist/services.d.ts.map +1 -1
  129. package/dist/services.js +402 -20
  130. package/dist/services.js.map +1 -1
  131. package/dist/source-sync.d.ts +136 -0
  132. package/dist/source-sync.d.ts.map +1 -0
  133. package/dist/source-sync.js +370 -0
  134. package/dist/source-sync.js.map +1 -0
  135. package/dist/sources/front-matter.d.ts +20 -0
  136. package/dist/sources/front-matter.d.ts.map +1 -0
  137. package/dist/sources/front-matter.js +57 -0
  138. package/dist/sources/front-matter.js.map +1 -0
  139. package/dist/sources/git.d.ts +80 -0
  140. package/dist/sources/git.d.ts.map +1 -0
  141. package/dist/sources/git.js +338 -0
  142. package/dist/sources/git.js.map +1 -0
  143. package/dist/sources/http.d.ts +54 -0
  144. package/dist/sources/http.d.ts.map +1 -0
  145. package/dist/sources/http.js +79 -0
  146. package/dist/sources/http.js.map +1 -0
  147. package/dist/spec-cache.d.ts +54 -0
  148. package/dist/spec-cache.d.ts.map +1 -0
  149. package/dist/spec-cache.js +133 -0
  150. package/dist/spec-cache.js.map +1 -0
  151. package/dist/spec-links.d.ts +68 -0
  152. package/dist/spec-links.d.ts.map +1 -0
  153. package/dist/spec-links.js +144 -0
  154. package/dist/spec-links.js.map +1 -0
  155. package/dist/spec-reader.d.ts +44 -0
  156. package/dist/spec-reader.d.ts.map +1 -0
  157. package/dist/spec-reader.js +81 -0
  158. package/dist/spec-reader.js.map +1 -0
  159. package/dist/spec-resolver.d.ts +13 -1
  160. package/dist/spec-resolver.d.ts.map +1 -1
  161. package/dist/spec-resolver.js +45 -8
  162. package/dist/spec-resolver.js.map +1 -1
  163. package/dist/spec-tools.d.ts +10 -0
  164. package/dist/spec-tools.d.ts.map +1 -0
  165. package/dist/spec-tools.js +103 -0
  166. package/dist/spec-tools.js.map +1 -0
  167. package/dist/task-scope.d.ts +11 -0
  168. package/dist/task-scope.d.ts.map +1 -0
  169. package/dist/task-scope.js +11 -0
  170. package/dist/task-scope.js.map +1 -0
  171. package/dist/telemetry.d.ts +34 -0
  172. package/dist/telemetry.d.ts.map +1 -0
  173. package/dist/telemetry.js +72 -0
  174. package/dist/telemetry.js.map +1 -0
  175. package/dist/template.d.ts +341 -0
  176. package/dist/template.d.ts.map +1 -0
  177. package/dist/template.js +142 -0
  178. package/dist/template.js.map +1 -0
  179. package/dist/tool-sandbox.d.ts.map +1 -1
  180. package/dist/tool-sandbox.js +2 -2
  181. package/dist/tool-sandbox.js.map +1 -1
  182. package/dist/tracks.d.ts +3 -3
  183. package/dist/tracks.js +1 -1
  184. package/dist/tracks.js.map +1 -1
  185. package/dist/verifier.d.ts.map +1 -1
  186. package/dist/verifier.js +8 -7
  187. package/dist/verifier.js.map +1 -1
  188. package/dist/vscode-connect.d.ts +48 -0
  189. package/dist/vscode-connect.d.ts.map +1 -0
  190. package/dist/vscode-connect.js +105 -0
  191. package/dist/vscode-connect.js.map +1 -0
  192. package/package.json +14 -3
  193. package/prompts/agent-task.contract.md +9 -0
  194. package/prompts/orchestrator.brief.md +17 -0
  195. package/prompts/orchestrator.contract.md +7 -0
  196. package/prompts/spec-analyst.brief.md +19 -0
  197. package/prompts/spec-analyst.contract.md +5 -0
  198. package/prompts/spec-analyst.sweep.md +2 -0
@@ -1,13 +1,18 @@
1
- import { COLLECTIONS, nowIso, parseRole } from '@aigile/core';
1
+ import { COLLECTIONS, ancestorsOf, effectivePlacement, nowIso } from '@aigile/core';
2
2
  import { z } from 'zod';
3
+ import { agentRoleFor } from '../agent-roles.js';
3
4
  import { AiBlockedError } from '../ai-service.js';
4
5
  import { DataAccess } from '../data-access.js';
6
+ import { groundingFor } from '../grounding.js';
5
7
  import { MilestoneService } from '../milestones.js';
6
- import { QueueService } from '../queue.js';
8
+ import { ActionItemService } from '../action-items.js';
7
9
  import { QuestionService } from '../questions.js';
10
+ import { ChangeSetService } from '../change-sets.js';
8
11
  import { ConflictService, MessageService, RoleService } from '../services.js';
9
12
  import { SpecResolver } from '../spec-resolver.js';
10
13
  import { diffLines, formatUnifiedDiff, hasChanges } from '../text-diff.js';
14
+ import { rankRelated, withinBudget } from '../related.js';
15
+ import { readPrompt } from '@aigile/core';
11
16
  /** The key the package knows this agent by, in `ai.roles` and on its Role. */
12
17
  export const SPEC_ANALYST_KEY = 'spec-analyst';
13
18
  /** The role `install` seeds; the name and description are the installation's to change afterwards. */
@@ -23,36 +28,52 @@ export const SPEC_ANALYST_ROLE = {
23
28
  * brief can change (documentation/templates.md, "What is not a spec"): what
24
29
  * the agent is, what counts as a conflict, how it answers.
25
30
  */
26
- export const SPEC_ANALYST_CONTRACT = `You are the Spec Analyst of aigile, a system in which people write specs (statements of intent in Markdown) that AI agents turn into work. Specs are mapped to organizations and projects; every project resolves to a ranked set of specs, and the specs with the highest-ranked authors win where they overlap. You never write specs; you read them.
27
-
28
- Your job here: a spec was just revised (or created). Compare the revised spec against the other specs that apply to the same projects, and report every pair that cannot both be satisfied. A conflict is a genuine contradiction: the revised spec requires something another spec forbids, sets a value or limit the other sets differently for the same thing, or imposes a constraint the other spec's requirement cannot meet. Not a conflict: two specs about different things; a more specific spec that refines a general one without contradicting it; the same requirement stated twice; a difference of style or emphasis; something one spec is silent on.
29
-
30
- Be conservative. Report a conflict only when you can quote the passage from each spec that cannot hold with the other. When nothing conflicts, say so with an empty list. Never invent requirements that are not in the text. Answer in the JSON format requested, nothing else.`;
31
+ export const SPEC_ANALYST_CONTRACT = readPrompt(import.meta.url, '../../prompts/spec-analyst.contract.md');
31
32
  /**
32
33
  * The brief the package seeds as a spec mapped to the agent's role; the
33
34
  * installation edits it like any spec, and the resolver adds the organization's
34
35
  * own additions to it.
35
36
  */
36
- export const SPEC_ANALYST_DEFAULT_BRIEF = `# Spec Analyst brief
37
-
38
- How the Spec Analyst reads this installation's specs. Edit this spec to change its judgement; add a spec mapped to the Spec Analyst and to an organization or project to add instructions that apply only there.
39
-
40
- ## What to treat as a conflict
41
-
42
- - Two requirements that cannot both be met for the same project, feature or environment.
43
- - Two different values for the same setting, limit, deadline or name.
44
- - A rule in one spec and an exception in another that does not name itself as the exception.
45
-
46
- ## What not to treat as a conflict
47
-
48
- - A project spec that narrows an organization spec without contradicting it.
49
- - Specs about different areas that merely sound alike.
50
- - Wording, tone or formatting differences.
51
-
52
- ## How to explain one
53
-
54
- Two short paragraphs for the authors: what each spec requires, quoting the passages, and why both cannot hold. Suggest how they might be reconciled when it is obvious; otherwise leave the decision to them.
55
- `;
37
+ export const SPEC_ANALYST_DEFAULT_BRIEF = readPrompt(import.meta.url, '../../prompts/spec-analyst.brief.md');
38
+ /** What a sweep asks (every spec of a project at once); Markdown under prompts/, edited like the other briefs. */
39
+ export const SPEC_ANALYST_SWEEP_CONTRACT = readPrompt(import.meta.url, '../../prompts/spec-analyst.sweep.md');
40
+ /** What a sweep's answer must be. */
41
+ const sweepSchema = z.object({
42
+ conflicts: z
43
+ .array(z.object({
44
+ leftSpecId: z.string().min(1),
45
+ rightSpecId: z.string().min(1),
46
+ summary: z.string().min(1),
47
+ explanation: z.string().min(1),
48
+ leftPassage: z.string().default(''),
49
+ rightPassage: z.string().default(''),
50
+ }))
51
+ .default([]),
52
+ });
53
+ const SWEEP_JSON_SCHEMA = {
54
+ type: 'object',
55
+ properties: {
56
+ conflicts: {
57
+ type: 'array',
58
+ description: 'One entry per pair of specs that contradict each other; empty when none do.',
59
+ items: {
60
+ type: 'object',
61
+ properties: {
62
+ leftSpecId: { type: 'string', description: 'The id of one spec, exactly as given.' },
63
+ rightSpecId: { type: 'string', description: 'The id of the other spec, exactly as given.' },
64
+ summary: { type: 'string', description: 'One line naming the contradiction.' },
65
+ explanation: { type: 'string', description: 'Why the two cannot both hold, in two or three sentences.' },
66
+ leftPassage: { type: 'string', description: 'The passage of the first spec that shows it, quoted.' },
67
+ rightPassage: { type: 'string', description: 'The passage of the second spec that shows it, quoted.' },
68
+ },
69
+ required: ['leftSpecId', 'rightSpecId', 'summary', 'explanation', 'leftPassage', 'rightPassage'],
70
+ additionalProperties: false,
71
+ },
72
+ },
73
+ },
74
+ required: ['conflicts'],
75
+ additionalProperties: false,
76
+ };
56
77
  /** What the model is asked for. */
57
78
  const verdictSchema = z.object({
58
79
  conflicts: z
@@ -89,6 +110,32 @@ const VERDICT_JSON_SCHEMA = {
89
110
  required: ['conflicts'],
90
111
  additionalProperties: false,
91
112
  };
113
+ /** The extra rules for carrying an answer into the specs. */
114
+ const EDITS_CONTRACT = `\n\nWhen given a question and the answer a person decided, propose the edits that put that knowledge into the specs so nobody has to ask again: edit the spec where it belongs (a new section, a changed sentence, a rule made explicit) and return that spec's whole content with the edit made and nothing else changed; propose a new spec only when no existing spec is the right home, and then say where it applies. Keep the authors' voice and structure. Say in one sentence per item why that spec and why there. Never remove a spec. If the answer changes nothing the specs should say, return no items.`;
115
+ const editsVerdictSchema = z.object({
116
+ items: z.array(z.object({ specId: z.string().min(1).nullable(), title: z.string(), content: z.string().min(1), rationale: z.string() })),
117
+ });
118
+ const EDITS_JSON_SCHEMA = {
119
+ type: 'object',
120
+ properties: {
121
+ items: {
122
+ type: 'array',
123
+ items: {
124
+ type: 'object',
125
+ properties: {
126
+ specId: { type: ['string', 'null'], description: 'The spec to edit, or null for a new spec.' },
127
+ title: { type: 'string', description: "The spec's title (unchanged for an edit unless the answer renames it)." },
128
+ content: { type: 'string', description: 'The whole content after the edit, Markdown.' },
129
+ rationale: { type: 'string', description: 'Why this spec and why there, one sentence.' },
130
+ },
131
+ required: ['specId', 'title', 'content', 'rationale'],
132
+ additionalProperties: false,
133
+ },
134
+ },
135
+ },
136
+ required: ['items'],
137
+ additionalProperties: false,
138
+ };
92
139
  /** The extra rules for answering a question (the same voice as the conflict contract). */
93
140
  const ANSWER_CONTRACT = `\n\nWhen asked a question, answer from the specs and grade your answer: "documented" when a spec says it (cite the spec and quote the passage), "inferred" when it follows from what the specs say (cite each spec you reasoned from), "undecided" when no spec decides it; then say what the question is and, if you can tell, what would have to be decided. Never guess at what the authors want. Keep the answer short and in the asker's terms.`;
94
141
  const answerVerdictSchema = z.object({
@@ -115,35 +162,42 @@ const ANSWER_JSON_SCHEMA = {
115
162
  additionalProperties: false,
116
163
  };
117
164
  /** Keep the prompt within a sane size: counterparts beyond this many characters are left out, best-ranked first. */
118
- const MAX_COUNTERPART_CHARS = 400_000;
119
165
  /**
120
166
  * The Spec Analyst's conflict detection (documentation/agents.md §2.2). On a
121
167
  * spec revision it gathers the resolved specs of every project the spec
122
168
  * applies to (for a role definition or brief, the role's resolved specs),
123
169
  * asks the provider for a verdict with the package contract plus its own
124
170
  * resolved brief as the system prompt, and opens a Conflict with a first
125
- * Message for each contradiction, plus a queue item for each author involved.
171
+ * Message for each contradiction, plus a action item for each author involved.
126
172
  * Every outcome is a report; nothing here throws into the author's save.
127
173
  */
128
174
  export class SpecAnalyst {
129
175
  store;
130
176
  ai;
177
+ /** Why no review can run now (no key, the stub, the cost cap), or null: the clock skips the analyst then rather than record a blocked call per spec per tick. */
178
+ unavailable() {
179
+ return this.ai.blocked();
180
+ }
131
181
  data;
132
182
  resolver;
133
183
  conflicts;
134
184
  messages;
135
- queue;
185
+ actionItems;
136
186
  roles;
137
187
  milestones;
138
- constructor(store, ai, queue) {
188
+ reviewChars;
189
+ sweepChars;
190
+ constructor(store, ai, actionItems, limits = {}) {
139
191
  this.store = store;
140
192
  this.ai = ai;
193
+ this.reviewChars = limits.reviewChars ?? 80_000;
194
+ this.sweepChars = limits.sweepChars ?? 2_000_000;
141
195
  this.milestones = new MilestoneService(store);
142
196
  this.data = new DataAccess(store);
143
197
  this.resolver = new SpecResolver(this.data);
144
198
  this.conflicts = new ConflictService(store);
145
199
  this.messages = new MessageService(store);
146
- this.queue = queue ?? new QueueService(store);
200
+ this.actionItems = actionItems ?? new ActionItemService(store);
147
201
  this.roles = new RoleService(store);
148
202
  }
149
203
  /**
@@ -153,7 +207,7 @@ export class SpecAnalyst {
153
207
  * project's specs) through the Questions queue; the asker hears either way.
154
208
  */
155
209
  async answer(questionId) {
156
- const questions = new QuestionService(this.store, this.queue);
210
+ const questions = new QuestionService(this.store, this.actionItems);
157
211
  const question = await questions.get(questionId);
158
212
  const role = await this.role();
159
213
  const actor = { userId: `agent:${SPEC_ANALYST_KEY}`, author: { name: role?.name ?? 'Spec Analyst', email: `${SPEC_ANALYST_KEY}@aigile.local` } };
@@ -165,18 +219,14 @@ export class SpecAnalyst {
165
219
  if (specs.length === 0)
166
220
  return fail('No spec applies here, so nothing decides this; a person must.');
167
221
  const brief = await this.resolver.resolveRole(role.id, question.projectId);
168
- const system = [SPEC_ANALYST_CONTRACT, ANSWER_CONTRACT, ...brief.map((b) => `\n\n---\n\n${b.content}`)].join('');
169
- let budget = MAX_COUNTERPART_CHARS;
170
- const listed = specs
171
- .filter((r) => {
172
- budget -= r.content.length;
173
- return budget >= 0;
174
- })
175
- .map((r) => `### Spec ${r.specId}: ${r.title}\nRevision ${r.revision}; author ranking ${r.ranking ?? 'none'}\n\n${r.content}`)
222
+ const system = [await groundingFor(this.resolver, question.projectId), SPEC_ANALYST_CONTRACT, ANSWER_CONTRACT, ...brief.map((b) => `\n\n---\n\n${b.content}`)].join('');
223
+ // The specs most related to the question, within twice a review's budget (documentation/agents.md "Conflict detection").
224
+ const listed = withinBudget(rankRelated({ id: '', title: question.body.slice(0, 200), content: question.body, family: new Set() }, specs.map((s) => ({ ...s, specId: s.specId }))), this.reviewChars * 2)
225
+ .map((r) => `### Spec ${r.specId}: ${r.title}\n${r.path.length ? `Under: ${r.path.join(' › ')}\n` : ''}Revision ${r.revision}; author ranking ${r.ranking ?? 'none'}\n\n${r.content}`)
176
226
  .join('\n\n');
177
227
  const user = `## The question\n\n${question.body}${question.area ? `\n\nAbout: ${question.area}` : ''}${question.projectId ? `\n\nProject ${question.projectId}` : ''}\n\n## The specs that apply, strongest first (${specs.length})\n\n${listed}\n\n## Your task\n\nAnswer from the specs, graded, as JSON.`;
178
228
  try {
179
- const result = await this.ai.complete({ system, messages: [{ role: 'user', content: user }], format: { name: 'graded_answer', schema: ANSWER_JSON_SCHEMA } }, { roleId: role.id, agentKey: SPEC_ANALYST_KEY, purpose: `answer: ${question.body.slice(0, 60)}`, subject: null, briefRevisions: brief.map((b) => ({ specId: b.specId, revision: b.revision })) });
229
+ const result = await this.ai.complete({ system, messages: [{ role: 'user', content: user }], format: { name: 'graded_answer', schema: ANSWER_JSON_SCHEMA } }, { roleId: role.id, agentKey: SPEC_ANALYST_KEY, purpose: `answer: ${question.body.slice(0, 60)}`, job: { ref: { kind: 'question', id: questionId }, projectIds: question.projectId ? [question.projectId] : [] }, subject: null, briefRevisions: brief.map((b) => ({ specId: b.specId, revision: b.revision })) });
180
230
  if (result.stopReason === 'refusal')
181
231
  return fail(`The model declined: ${result.refusal ?? ''}`);
182
232
  const parsed = answerVerdictSchema.safeParse(result.json);
@@ -199,6 +249,54 @@ export class SpecAnalyst {
199
249
  return fail(err instanceof AiBlockedError ? `Blocked: ${err.message}` : err instanceof Error ? err.message : String(err));
200
250
  }
201
251
  }
252
+ /**
253
+ * Answer into the specs (documentation/agents.md §2.2): once a person has
254
+ * answered a question, propose where that knowledge belongs as a change
255
+ * set of edits to the specs that apply (a new section, a changed rule; a
256
+ * new spec only when nothing fits), for the person to review and save.
257
+ * The answer itself stays on the question; the set's summary carries it
258
+ * into the commit. Nothing is written to any source here.
259
+ */
260
+ async proposeEdits(questionId, reviewerUserId) {
261
+ const questions = new QuestionService(this.store, this.actionItems);
262
+ const question = await questions.get(questionId);
263
+ const answer = question.answer;
264
+ if (!answer || answer.grade !== 'decided')
265
+ return null;
266
+ const role = await this.role();
267
+ if (!role)
268
+ return null;
269
+ const actor = { userId: `agent:${SPEC_ANALYST_KEY}`, author: { name: role.name, email: `${SPEC_ANALYST_KEY}@aigile.local` } };
270
+ const specs = question.projectId ? (await this.resolver.resolveProject(question.projectId)).resolved : await this.allSpecs();
271
+ const brief = await this.resolver.resolveRole(role.id, question.projectId);
272
+ const system = [await groundingFor(this.resolver, question.projectId), SPEC_ANALYST_CONTRACT, EDITS_CONTRACT, ...brief.map((b) => `\n\n---\n\n${b.content}`)].join('');
273
+ // The specs most related to the question and its decided answer, within twice a review's budget.
274
+ const asked = `${question.body}\n\n${question.answer?.body ?? ''}`;
275
+ const listed = withinBudget(rankRelated({ id: '', title: question.body.slice(0, 200), content: asked, family: new Set() }, specs), this.reviewChars * 2)
276
+ .map((r) => `### Spec ${r.specId}: ${r.title}\n${r.path.length ? `Under: ${r.path.join(' › ')}\n` : ''}Revision ${r.revision}\n\n${r.content}`)
277
+ .join('\n\n');
278
+ const user = `## The question\n\n${question.body}${question.area ? `\n\nAbout: ${question.area}` : ''}\n\n## The answer a person gave\n\n${answer.body}\n\n## The specs that apply (${specs.length})\n\n${listed || '(none)'}\n\n## Your task\n\nPropose the edits that put this answer into the specs, as JSON.`;
279
+ try {
280
+ const result = await this.ai.complete({ system, messages: [{ role: 'user', content: user }], format: { name: 'spec_edits', schema: EDITS_JSON_SCHEMA } }, { roleId: role.id, agentKey: SPEC_ANALYST_KEY, purpose: `edits for: ${question.body.slice(0, 60)}`, job: { ref: { kind: 'question', id: questionId }, projectIds: question.projectId ? [question.projectId] : [] }, subject: null, briefRevisions: brief.map((b) => ({ specId: b.specId, revision: b.revision })) });
281
+ if (result.stopReason === 'refusal')
282
+ return null;
283
+ const parsed = editsVerdictSchema.safeParse(result.json);
284
+ if (!parsed.success || parsed.data.items.length === 0)
285
+ return null;
286
+ const known = new Map(specs.map((r) => [r.specId, r]));
287
+ const items = parsed.data.items
288
+ .filter((i) => i.specId === null || known.has(i.specId))
289
+ .map((i) => (i.specId ? { specId: i.specId, action: 'revise', title: i.title || known.get(i.specId).title, content: i.content, rationale: i.rationale, baseRevision: known.get(i.specId).revision } : { specId: null, action: 'create', title: i.title, content: i.content, rationale: i.rationale, projectIds: question.projectId ? [question.projectId] : [] }));
290
+ if (items.length === 0)
291
+ return null;
292
+ return new ChangeSetService(this.store, this.actionItems).propose({ title: `Answer into the specs: ${question.body.slice(0, 60)}`, summary: `**Question:** ${question.body}\n\n**Answer (${answer.by.kind === 'user' ? 'a person' : 'the analyst'}):** ${answer.body}`, questionId, reviewerUserId, items }, { kind: 'agent', id: role.id }, actor);
293
+ }
294
+ catch (err) {
295
+ if (err instanceof AiBlockedError)
296
+ return null;
297
+ throw err;
298
+ }
299
+ }
202
300
  /** Every spec at its usable revision, for a question about the installation as a whole. */
203
301
  async allSpecs() {
204
302
  const projects = await this.data.projects();
@@ -211,10 +309,35 @@ export class SpecAnalyst {
211
309
  }
212
310
  /** The installed Spec Analyst role, or null before `aigile install` seeded it. */
213
311
  async role() {
214
- const raw = await this.store.list(COLLECTIONS.roles);
215
- return raw.map((r) => parseRole(r)).find((r) => r.agentKey === SPEC_ANALYST_KEY) ?? null;
312
+ return agentRoleFor(this.store, SPEC_ANALYST_KEY);
216
313
  }
314
+ /**
315
+ * One review of one revision, recorded in `spec-reviews` so the clock never
316
+ * reviews the same revision twice; except when it could not run (blocked by
317
+ * the cost cap or a missing key, or an error), which leaves the revision
318
+ * unreviewed for a later tick.
319
+ */
217
320
  async reviewRevision(specId, revision) {
321
+ const report = await this.review(specId, revision);
322
+ if (report.status === 'blocked' || report.status === 'error')
323
+ return report;
324
+ const record = { specId, revision, status: report.status, at: nowIso() };
325
+ await this.store.put(COLLECTIONS.specReviews, specId, record, { message: `Spec Analyst reviewed spec ${specId} @ ${revision.slice(0, 8)}: ${report.status}` });
326
+ return report;
327
+ }
328
+ /** The specs whose newest revision the analyst has not reviewed (the clock's work; `aigile analyze` and the web's save queue cover the rest). */
329
+ async unreviewed() {
330
+ // A mark left by a review that could not run (recorded before blocked reviews stopped leaving marks) does not count.
331
+ const reviews = new Map((await this.store.list(COLLECTIONS.specReviews)).filter((r) => r.status !== 'blocked' && r.status !== 'error').map((r) => [r.specId, r.revision]));
332
+ const out = [];
333
+ for (const spec of await this.data.specs()) {
334
+ const newest = await this.data.specCurrentRevision(spec.id);
335
+ if (newest && reviews.get(spec.id) !== newest)
336
+ out.push({ specId: spec.id, revision: newest });
337
+ }
338
+ return out;
339
+ }
340
+ async review(specId, revision) {
218
341
  const report = { specId, revision, status: 'reviewed', detail: '', counterparts: 0, conflictsOpened: [], alreadyOpen: 0 };
219
342
  const done = (status, detail) => ({ ...report, status, detail });
220
343
  const role = await this.role();
@@ -228,19 +351,23 @@ export class SpecAnalyst {
228
351
  const spec = await this.data.specAtRevision(specId, revision);
229
352
  if (!spec)
230
353
  return done('error', `spec ${specId} has no revision ${revision}`);
231
- const { counterparts, projectIds } = await this.counterpartsFor(spec);
354
+ // An outline heading (a folder, an index page) says nothing to contradict.
355
+ if (!spec.content.trim())
356
+ return done('nothing-to-compare', 'no text (an outline heading)');
357
+ const { counterparts, projectIds, considered } = await this.counterpartsFor(spec);
232
358
  report.counterparts = counterparts.length;
233
359
  if (counterparts.length === 0)
234
360
  return done('nothing-to-compare', 'no other spec applies where this one does');
235
361
  const brief = await this.resolver.resolveRole(role.id, projectIds[0] ?? null);
236
- const system = [SPEC_ANALYST_CONTRACT, ...brief.map((b) => `\n\n---\n\n${b.content}`)].join('');
237
- const user = await this.prompt(spec, revision, counterparts);
362
+ const system = [await groundingFor(this.resolver, projectIds[0] ?? null), SPEC_ANALYST_CONTRACT, ...brief.map((b) => `\n\n---\n\n${b.content}`)].join('');
363
+ const user = await this.prompt(spec, revision, counterparts, considered);
238
364
  let verdict;
239
365
  try {
240
366
  const result = await this.ai.complete({ system, messages: [{ role: 'user', content: user }], format: { name: 'conflict_verdict', schema: VERDICT_JSON_SCHEMA } }, {
241
367
  roleId: role.id,
242
368
  agentKey: SPEC_ANALYST_KEY,
243
369
  purpose: `review spec revision: ${spec.title}`,
370
+ job: { ref: { kind: 'spec', id: specId } },
244
371
  subject: { specId, revision },
245
372
  briefRevisions: brief.map((b) => ({ specId: b.specId, revision: b.revision })),
246
373
  });
@@ -261,33 +388,13 @@ export class SpecAnalyst {
261
388
  const other = byId.get(found.specId);
262
389
  if (!other || other.specId === specId)
263
390
  continue;
264
- if (await this.conflicts.activeBetween(specId, other.specId)) {
391
+ const opened = await this.openConflict({ specId, revision, title: spec.title, authorUserId: spec.authorUserId }, other, { summary: found.summary, explanation: found.explanation, leftPassage: found.revisedPassage, rightPassage: found.otherPassage }, role, actor, projectIds);
392
+ if (opened)
393
+ report.conflictsOpened.push(opened);
394
+ else
265
395
  report.alreadyOpen++;
266
- continue;
267
- }
268
- const conflict = await this.conflicts.open({ left: { specId, revision }, right: { specId: other.specId, revision: other.revision }, detectedBy: 'agent' }, actor);
269
- const quotes = [
270
- found.revisedPassage ? `> ${spec.title}: “${found.revisedPassage}”` : '',
271
- found.otherPassage ? `> ${other.title}: “${found.otherPassage}”` : '',
272
- ].filter(Boolean);
273
- const body = [`**${found.summary}**`, found.explanation, ...(quotes.length ? [quotes.join('\n>\n')] : [])].join('\n\n');
274
- await this.messages.post(conflict.id, body, { kind: 'agent', id: role.id }, actor);
275
- for (const userId of new Set([spec.authorUserId, other.authorUserId])) {
276
- if (userId.startsWith('agent:') || userId === 'aigile')
277
- continue;
278
- await this.queue.open({
279
- kind: 'conflict',
280
- assigneeUserId: userId,
281
- title: `${spec.title} ↔ ${other.title}`,
282
- summary: found.summary,
283
- ref: { kind: 'conflict', id: conflict.id },
284
- waitingOnRoleId: role.id,
285
- projectIds,
286
- }, actor);
287
- }
288
- report.conflictsOpened.push(conflict);
289
396
  }
290
- report.detail = report.conflictsOpened.length === 0 ? `no conflict with ${counterparts.length} other spec(s)` : `${report.conflictsOpened.length} conflict(s) opened`;
397
+ report.detail = report.conflictsOpened.length === 0 ? `no conflict with the ${counterparts.length} most related of ${considered} other spec(s)` : `${report.conflictsOpened.length} conflict(s) opened`;
291
398
  for (const conflict of report.conflictsOpened) {
292
399
  await this.milestones.post({ kind: 'finding', roleId: role.id, agentKey: SPEC_ANALYST_KEY, about: { kind: 'conflict', id: conflict.id }, projectIds, summary: `Conflict: ${spec.title} ↔ ${byId.get(conflict.right.specId)?.title ?? conflict.right.specId}`, needs: 'the authors resolve or revise' }, actor);
293
400
  }
@@ -297,11 +404,13 @@ export class SpecAnalyst {
297
404
  return report;
298
405
  }
299
406
  /**
300
- * The specs the revised one is compared against: for a spec mapped to
301
- * organizations or projects, the resolved set of every project it applies
302
- * to; for a role definition or brief, the role's resolved specs; nothing for
303
- * a spec mapped only to users or to nothing. Each counterpart once, at its
304
- * resolved revision, best-ranked first.
407
+ * The specs the revised one is compared against (documentation/agents.md
408
+ * "Conflict detection"): of everything that applies where it does (the
409
+ * resolved set of every project it applies to, its own placement or its
410
+ * outline ancestor's; for a role definition or brief, the role's resolved
411
+ * specs), its outline family first and then the most similar, within
412
+ * `reviewChars`. A sweep reads the whole set; a revision's review reads what
413
+ * it could contradict.
305
414
  */
306
415
  async counterpartsFor(spec) {
307
416
  const seen = new Map();
@@ -315,9 +424,12 @@ export class SpecAnalyst {
315
424
  existing.projectIds.push(projectId);
316
425
  return;
317
426
  }
318
- seen.set(r.specId, { specId: r.specId, title: r.title, authorUserId: r.authorUserId, revision: r.revision, content: r.content, ranking: r.ranking, projectIds: projectId ? [projectId] : [] });
427
+ seen.set(r.specId, { specId: r.specId, title: r.title, authorUserId: r.authorUserId, revision: r.revision, content: r.content, ranking: r.ranking, projectIds: projectId ? [projectId] : [], path: r.path });
319
428
  };
320
- if (spec.organizationIds.length + spec.projectIds.length > 0) {
429
+ const all = await this.data.specs();
430
+ const byId = new Map(all.map((s) => [s.id, s]));
431
+ const placement = effectivePlacement(spec, byId);
432
+ if (placement.organizationIds.length + placement.projectIds.length > 0) {
321
433
  for (const resolution of await this.resolver.projectsAffectedBy(spec.id)) {
322
434
  projectIds.push(resolution.projectId);
323
435
  for (const r of resolution.resolved)
@@ -328,15 +440,124 @@ export class SpecAnalyst {
328
440
  for (const r of await this.resolver.resolveRole(roleId, null))
329
441
  add(r, null);
330
442
  }
331
- const counterparts = [...seen.values()].sort((a, b) => (b.ranking ?? Number.NEGATIVE_INFINITY) - (a.ranking ?? Number.NEGATIVE_INFINITY) || a.specId.localeCompare(b.specId));
332
- let budget = MAX_COUNTERPART_CHARS;
333
- const kept = counterparts.filter((c) => {
334
- budget -= c.content.length;
335
- return budget >= 0;
336
- });
337
- return { counterparts: kept, projectIds };
443
+ const candidates = [...seen.values()];
444
+ const current = byId.get(spec.id);
445
+ const ancestors = current ? ancestorsOf(current, byId).map((a) => a.id) : [];
446
+ const family = new Set([...ancestors, ...all.filter((s) => s.parentId === spec.id || (spec.parentId && s.parentId === spec.parentId)).map((s) => s.id)]);
447
+ const ranked = rankRelated({ id: spec.id, title: spec.title, content: spec.content, family }, candidates);
448
+ return { counterparts: withinBudget(ranked, this.reviewChars), projectIds, considered: candidates.length };
338
449
  }
339
- async prompt(spec, revision, counterparts) {
450
+ /**
451
+ * Read every spec of a project at once and open a Conflict for each pair
452
+ * that contradicts (documentation/agents.md "Conflict detection"): the
453
+ * thorough check, run on request or every `sweepDays`. Projects that share
454
+ * one set (children that only inherit) are swept once; a set bigger than
455
+ * `sweepChars` is read in parts, one outline branch never split across two
456
+ * unless it alone is too big. Stops at the first blocked call.
457
+ */
458
+ async sweep(projectId) {
459
+ const role = await this.role();
460
+ if (!role)
461
+ return [{ projectIds: projectId ? [projectId] : [], status: 'blocked', specs: 0, parts: 0, conflictsOpened: [], alreadyOpen: 0, detail: 'the Spec Analyst role is not installed; run `aigile install`' }];
462
+ const actor = { userId: `agent:${SPEC_ANALYST_KEY}`, author: { name: role.name, email: `${SPEC_ANALYST_KEY}@aigile.local` } };
463
+ const resolutions = projectId ? [await this.resolver.resolveProject(projectId)] : await this.resolver.resolveAll();
464
+ const groups = new Map();
465
+ for (const r of resolutions) {
466
+ const key = r.resolved
467
+ .map((s) => `${s.specId}@${s.revision}`)
468
+ .sort()
469
+ .join(',');
470
+ const group = groups.get(key) ?? { projectIds: [], specs: r.resolved };
471
+ group.projectIds.push(r.projectId);
472
+ groups.set(key, group);
473
+ }
474
+ const reports = [];
475
+ for (const { projectIds, specs } of groups.values()) {
476
+ const report = { projectIds, status: 'swept', specs: specs.length, parts: 0, conflictsOpened: [], alreadyOpen: 0, detail: '' };
477
+ reports.push(report);
478
+ if (specs.length < 2) {
479
+ report.status = 'nothing-to-compare';
480
+ report.detail = 'fewer than two specs with text';
481
+ await this.recordSweep(report);
482
+ continue;
483
+ }
484
+ const brief = await this.resolver.resolveRole(role.id, projectIds[0] ?? null);
485
+ const system = [await groundingFor(this.resolver, projectIds[0] ?? null), SPEC_ANALYST_CONTRACT, SPEC_ANALYST_SWEEP_CONTRACT, ...brief.map((b) => `\n\n---\n\n${b.content}`)].join('');
486
+ const names = (await this.data.projects()).filter((p) => projectIds.includes(p.id)).map((p) => p.name);
487
+ for (const part of sweepParts(specs, this.sweepChars)) {
488
+ report.parts++;
489
+ const byId = new Map(part.map((s) => [s.specId, s]));
490
+ const listing = part.map((s) => `### Spec ${s.specId}: ${s.title}\n${s.path.length ? `Under: ${s.path.join(' › ')}\n` : ''}Revision ${s.revision}; author ranking ${s.ranking ?? 'none'}\n\n${s.content}`).join('\n\n');
491
+ const user = `## Every spec that applies to ${names.join(', ') || 'the project'} (${part.length}${report.parts > 1 || part.length < specs.length ? ` of ${specs.length}, part ${report.parts}` : ''})\n\n${listing}\n\n## Your task\n\nList every pair of these specs that contradict each other, as JSON; an empty list when none do.`;
492
+ let found;
493
+ try {
494
+ const result = await this.ai.complete({ system, messages: [{ role: 'user', content: user }], format: { name: 'conflict_sweep', schema: SWEEP_JSON_SCHEMA } }, { roleId: role.id, agentKey: SPEC_ANALYST_KEY, purpose: `sweep specs: ${names.join(', ') || projectIds.join(', ')}${report.parts > 1 ? ` (part ${report.parts})` : ''}`, job: { title: `Sweep the specs of ${names.join(', ') || projectIds.join(', ')}`, projectIds }, subject: null, briefRevisions: brief.map((b) => ({ specId: b.specId, revision: b.revision })) });
495
+ if (result.stopReason === 'refusal') {
496
+ report.status = 'refused';
497
+ report.detail = result.refusal ?? 'the model declined';
498
+ break;
499
+ }
500
+ const parsed = sweepSchema.safeParse(result.json);
501
+ if (!parsed.success) {
502
+ report.status = 'error';
503
+ report.detail = `the model's answer was not a list of conflicts: ${result.text.slice(0, 200)}`;
504
+ break;
505
+ }
506
+ found = parsed.data;
507
+ }
508
+ catch (err) {
509
+ report.status = err instanceof AiBlockedError ? 'blocked' : 'error';
510
+ report.detail = err instanceof Error ? err.message : String(err);
511
+ break;
512
+ }
513
+ for (const pair of found.conflicts) {
514
+ const left = byId.get(pair.leftSpecId);
515
+ const right = byId.get(pair.rightSpecId);
516
+ if (!left || !right || left.specId === right.specId)
517
+ continue;
518
+ const opened = await this.openConflict(left, { ...right, projectIds }, { summary: pair.summary, explanation: pair.explanation, leftPassage: pair.leftPassage, rightPassage: pair.rightPassage }, role, actor, projectIds);
519
+ if (opened)
520
+ report.conflictsOpened.push(opened);
521
+ else
522
+ report.alreadyOpen++;
523
+ }
524
+ }
525
+ if (report.status === 'swept')
526
+ report.detail = `${report.conflictsOpened.length} conflict(s) opened among ${specs.length} spec(s)${report.parts > 1 ? ` in ${report.parts} parts` : ''}${report.alreadyOpen ? `; ${report.alreadyOpen} already open` : ''}`;
527
+ await this.recordSweep(report);
528
+ await this.milestones.post({ kind: report.status === 'swept' ? 'finished' : 'blocked', roleId: role.id, agentKey: SPEC_ANALYST_KEY, about: { kind: 'project', id: projectIds[0] ?? '' }, projectIds, summary: `Swept ${names.join(', ') || 'the specs'}: ${report.detail}` }, actor);
529
+ if (report.status === 'blocked')
530
+ break;
531
+ }
532
+ return reports;
533
+ }
534
+ /** When each project was last swept (its newest sweep), for the clock. */
535
+ async lastSweepAt() {
536
+ const sweeps = await this.store.list(COLLECTIONS.specSweeps);
537
+ return sweeps.map((s) => s.at).sort().at(-1) ?? null;
538
+ }
539
+ async recordSweep(report) {
540
+ if (report.status === 'blocked' || report.status === 'error')
541
+ return;
542
+ const id = report.projectIds[0] ?? 'installation';
543
+ await this.store.put(COLLECTIONS.specSweeps, id, { id, projectIds: report.projectIds, status: report.status, specs: report.specs, parts: report.parts, conflictsOpened: report.conflictsOpened.map((c) => c.id), alreadyOpen: report.alreadyOpen, at: nowIso() }, { message: `Spec Analyst swept ${report.specs} spec(s): ${report.detail}` });
544
+ }
545
+ /** Open a Conflict between two specs with its first message and an action item per author, unless one is already open between them (null). */
546
+ async openConflict(left, right, found, role, actor, projectIds) {
547
+ if (await this.conflicts.activeBetween(left.specId, right.specId))
548
+ return null;
549
+ const conflict = await this.conflicts.open({ left: { specId: left.specId, revision: left.revision }, right: { specId: right.specId, revision: right.revision }, detectedBy: 'agent' }, actor);
550
+ const quotes = [found.leftPassage ? `> ${left.title}: “${found.leftPassage}”` : '', found.rightPassage ? `> ${right.title}: “${found.rightPassage}”` : ''].filter(Boolean);
551
+ const body = [`**${found.summary}**`, found.explanation, ...(quotes.length ? [quotes.join('\n>\n')] : [])].join('\n\n');
552
+ await this.messages.post(conflict.id, body, { kind: 'agent', id: role.id }, actor);
553
+ for (const userId of new Set([left.authorUserId, right.authorUserId])) {
554
+ if (userId.startsWith('agent:') || userId === 'aigile')
555
+ continue;
556
+ await this.actionItems.open({ kind: 'conflict', assigneeUserId: userId, title: `${left.title} ↔ ${right.title}`, summary: found.summary, ref: { kind: 'conflict', id: conflict.id }, waitingOnRoleId: role.id, projectIds }, actor);
557
+ }
558
+ return conflict;
559
+ }
560
+ async prompt(spec, revision, counterparts, considered) {
340
561
  const history = await this.data.specHistory(spec.id);
341
562
  const at = history.findIndex((h) => h.revision === revision);
342
563
  const previous = at >= 0 ? history[at + 1] : undefined;
@@ -355,10 +576,50 @@ export class SpecAnalyst {
355
576
  .filter(Boolean)
356
577
  .join('; ');
357
578
  const others = counterparts
358
- .map((c) => `### Spec ${c.specId}: ${c.title}\nRevision ${c.revision}; author ranking ${c.ranking ?? 'none'}${c.projectIds.length ? `; applies to projects ${c.projectIds.join(', ')}` : ''}\n\n${c.content}`)
579
+ .map((c) => `### Spec ${c.specId}: ${c.title}\n${c.path.length ? `Under: ${c.path.join(' › ')}\n` : ''}Revision ${c.revision}; author ranking ${c.ranking ?? 'none'}${c.projectIds.length ? `; applies to projects ${c.projectIds.join(', ')}` : ''}\n\n${c.content}`)
359
580
  .join('\n\n');
360
- return `## The revised spec\n\nSpec ${spec.id}: ${spec.title}\nRevision ${revision}${previous ? ` (${history.length - at - 1} earlier revision(s))` : ' (new)'}; mapped to ${scope || 'nothing'}.\n\n${spec.content}${diff}\n\n## The other specs that apply to the same projects (${counterparts.length})\n\n${others}\n\n## Your task\n\nList every spec among the others that the revised spec conflicts with, as JSON; an empty list when none does.`;
581
+ return `## The revised spec\n\nSpec ${spec.id}: ${spec.title}\nRevision ${revision}${previous ? ` (${history.length - at - 1} earlier revision(s))` : ' (new)'}; mapped to ${scope || 'nothing'}.\n\n${spec.content}${diff}\n\n## The other specs most related to it (${counterparts.length} of the ${considered} that apply where it does)\n\n${others}\n\n## Your task\n\nList every spec among the others that the revised spec conflicts with, as JSON; an empty list when none does.`;
582
+ }
583
+ }
584
+ /** A resolved set in parts of at most `budget` characters, grouped by top outline branch so related specs stay together. */
585
+ export function sweepParts(specs, budget) {
586
+ const total = specs.reduce((n, s) => n + s.content.length, 0);
587
+ if (total <= budget)
588
+ return [[...specs]];
589
+ const branches = new Map();
590
+ for (const s of specs) {
591
+ const key = s.path[0] ?? s.title;
592
+ branches.set(key, [...(branches.get(key) ?? []), s]);
593
+ }
594
+ const parts = [];
595
+ let current = [];
596
+ let size = 0;
597
+ const flush = () => {
598
+ if (current.length)
599
+ parts.push(current);
600
+ current = [];
601
+ size = 0;
602
+ };
603
+ for (const branch of [...branches.values()].sort((a, b) => b.length - a.length)) {
604
+ const branchSize = branch.reduce((n, s) => n + s.content.length, 0);
605
+ if (branchSize > budget) {
606
+ flush();
607
+ for (const s of branch) {
608
+ if (size + s.content.length > budget)
609
+ flush();
610
+ current.push(s);
611
+ size += s.content.length;
612
+ }
613
+ flush();
614
+ continue;
615
+ }
616
+ if (size + branchSize > budget)
617
+ flush();
618
+ current.push(...branch);
619
+ size += branchSize;
361
620
  }
621
+ flush();
622
+ return parts;
362
623
  }
363
624
  /**
364
625
  * One review at a time per process, newest revision of a spec winning: a