fito-tui 0.2.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 (179) hide show
  1. package/README.md +88 -0
  2. package/agents/fito-case-source-planner.md +265 -0
  3. package/agents/fito-performance-reviewer.md +231 -0
  4. package/agents/fito-practice-concept-content-generator.md +318 -0
  5. package/agents/fito-practice-concept-identifier.md +482 -0
  6. package/agents/fito-practice-execution-fact-content-generator.md +299 -0
  7. package/agents/fito-practice-execution-fact-identifier.md +367 -0
  8. package/agents/fito-practice-usage-scenario-content-generator.md +331 -0
  9. package/agents/fito-practice-usage-scenario-identifier.md +397 -0
  10. package/agents/fito-subagent-selftest.md +27 -0
  11. package/agents/fito-technology-generator.md +207 -0
  12. package/agents/fito-tool-concept-content-generator.md +282 -0
  13. package/agents/fito-tool-concept-identifier.md +384 -0
  14. package/agents/fito-tool-execution-fact-content-generator.md +382 -0
  15. package/agents/fito-tool-execution-fact-identifier.md +360 -0
  16. package/agents/fito-tool-usage-scenario-content-generator.md +381 -0
  17. package/agents/fito-tool-usage-scenario-identifier.md +432 -0
  18. package/agents/fito-tutor.md +185 -0
  19. package/extensions/fito-delegate.js +539 -0
  20. package/extensions/fito-delegate.ts +691 -0
  21. package/extensions/fito-fetch-tools.js +380 -0
  22. package/extensions/fito-fetch-tools.ts +419 -0
  23. package/extensions/fito-startup.js +166 -0
  24. package/extensions/fito-startup.ts +188 -0
  25. package/package.json +56 -0
  26. package/prompts/fito-auth-refresh.md +15 -0
  27. package/prompts/fito-case-design.md +506 -0
  28. package/prompts/fito-case-edit.md +91 -0
  29. package/prompts/fito-case-generate.md +222 -0
  30. package/prompts/fito-case-open.md +124 -0
  31. package/prompts/fito-case-plan-source.md +114 -0
  32. package/prompts/fito-create-or-update-competence.md +261 -0
  33. package/prompts/fito-create-or-update-technology.md +199 -0
  34. package/prompts/fito-delete-competence.md +147 -0
  35. package/prompts/fito-evaluate.md +148 -0
  36. package/prompts/fito-fetch-urls-content.md +35 -0
  37. package/prompts/fito-generate-domain-concepts.md +85 -0
  38. package/prompts/fito-generate-execution-facts.md +85 -0
  39. package/prompts/fito-generate-usage-scenarios.md +85 -0
  40. package/prompts/fito-identify-domain-concepts.md +49 -0
  41. package/prompts/fito-identify-execution-facts.md +49 -0
  42. package/prompts/fito-identify-usage-scenarios.md +49 -0
  43. package/prompts/fito-login.md +21 -0
  44. package/prompts/fito-logout.md +14 -0
  45. package/prompts/fito-publish-case.md +266 -0
  46. package/prompts/fito-push-knowledge.md +84 -0
  47. package/prompts/fito-submit.md +208 -0
  48. package/prompts/fito-tutor.md +120 -0
  49. package/shared/case-briefing/briefing.js +221 -0
  50. package/shared/case-briefing/briefing.ts +261 -0
  51. package/shared/case-quiz/scoring.js +16 -0
  52. package/shared/case-quiz/scoring.ts +61 -0
  53. package/shared/case-validation/case-loader.js +88 -0
  54. package/shared/case-validation/case-loader.ts +106 -0
  55. package/shared/case-validation/case-schema.js +716 -0
  56. package/shared/case-validation/case-schema.ts +895 -0
  57. package/shared/competences/competence-list.js +29 -0
  58. package/shared/competences/competence-list.ts +32 -0
  59. package/shared/fito-api/README.md +192 -0
  60. package/shared/fito-api/client.js +731 -0
  61. package/shared/fito-api/client.ts +1426 -0
  62. package/shared/fito-session/credentials.js +79 -0
  63. package/shared/fito-session/credentials.ts +88 -0
  64. package/shared/fito-session/session.js +16 -0
  65. package/shared/fito-session/session.ts +35 -0
  66. package/shared/github-url/parse.js +26 -0
  67. package/shared/github-url/parse.ts +35 -0
  68. package/shared/knowledge-components/component-names.js +35 -0
  69. package/shared/knowledge-components/component-names.ts +39 -0
  70. package/shared/knowledge-components/knowledge-fetch.js +46 -0
  71. package/shared/knowledge-components/knowledge-fetch.ts +57 -0
  72. package/shared/knowledge-components/knowledge-search.js +101 -0
  73. package/shared/knowledge-components/knowledge-search.ts +144 -0
  74. package/shared/knowledge-components/push-payload.js +104 -0
  75. package/shared/knowledge-components/push-payload.ts +129 -0
  76. package/shared/knowledge-components/reference.js +24 -0
  77. package/shared/knowledge-components/reference.ts +43 -0
  78. package/shared/knowledge-components/technology-fetch.js +30 -0
  79. package/shared/knowledge-components/technology-fetch.ts +38 -0
  80. package/shared/shell-exec/exec.js +22 -0
  81. package/shared/shell-exec/exec.ts +46 -0
  82. package/skills/fito-auth/SKILL.md +68 -0
  83. package/skills/fito-auth/auth-refresh.js +23 -0
  84. package/skills/fito-auth/auth-refresh.ts +25 -0
  85. package/skills/fito-auth/browser.js +35 -0
  86. package/skills/fito-auth/browser.ts +57 -0
  87. package/skills/fito-auth/callback-server.js +152 -0
  88. package/skills/fito-auth/callback-server.ts +189 -0
  89. package/skills/fito-auth/login.js +37 -0
  90. package/skills/fito-auth/login.ts +42 -0
  91. package/skills/fito-auth/logout.js +24 -0
  92. package/skills/fito-auth/logout.ts +25 -0
  93. package/skills/fito-case-author/SKILL.md +179 -0
  94. package/skills/fito-case-author/checkout.js +222 -0
  95. package/skills/fito-case-author/checkout.ts +281 -0
  96. package/skills/fito-case-author/github-publish.js +218 -0
  97. package/skills/fito-case-author/github-publish.ts +251 -0
  98. package/skills/fito-case-author/publish-payload.js +108 -0
  99. package/skills/fito-case-author/publish-payload.ts +186 -0
  100. package/skills/fito-case-author/publish-state.js +72 -0
  101. package/skills/fito-case-author/publish-state.ts +87 -0
  102. package/skills/fito-case-author/publish-version.js +364 -0
  103. package/skills/fito-case-author/publish-version.ts +495 -0
  104. package/skills/fito-case-author/publish.js +284 -0
  105. package/skills/fito-case-author/publish.ts +394 -0
  106. package/skills/fito-case-author/semver.js +55 -0
  107. package/skills/fito-case-author/semver.ts +63 -0
  108. package/skills/fito-case-author/status-gate.js +34 -0
  109. package/skills/fito-case-author/status-gate.ts +54 -0
  110. package/skills/fito-case-author/validate.js +62 -0
  111. package/skills/fito-case-author/validate.ts +64 -0
  112. package/skills/fito-case-runner/SKILL.md +119 -0
  113. package/skills/fito-case-runner/case-component-names.js +45 -0
  114. package/skills/fito-case-runner/case-component-names.ts +65 -0
  115. package/skills/fito-case-runner/case-detail.js +20 -0
  116. package/skills/fito-case-runner/case-detail.ts +20 -0
  117. package/skills/fito-case-runner/github.js +234 -0
  118. package/skills/fito-case-runner/github.ts +287 -0
  119. package/skills/fito-case-runner/manifest.js +56 -0
  120. package/skills/fito-case-runner/manifest.ts +73 -0
  121. package/skills/fito-case-runner/open.js +175 -0
  122. package/skills/fito-case-runner/open.ts +241 -0
  123. package/skills/fito-case-runner/report.js +22 -0
  124. package/skills/fito-case-runner/report.ts +24 -0
  125. package/skills/fito-case-runner/runner.js +158 -0
  126. package/skills/fito-case-runner/runner.ts +304 -0
  127. package/skills/fito-case-runner/score-quiz-mc.js +85 -0
  128. package/skills/fito-case-runner/score-quiz-mc.ts +99 -0
  129. package/skills/fito-case-runner/submit-evaluation.js +73 -0
  130. package/skills/fito-case-runner/submit-evaluation.ts +98 -0
  131. package/skills/fito-case-runner/submit-quiz-result.js +75 -0
  132. package/skills/fito-case-runner/submit-quiz-result.ts +100 -0
  133. package/skills/fito-case-runner/submit.js +85 -0
  134. package/skills/fito-case-runner/submit.ts +111 -0
  135. package/skills/fito-case-runner/workdir.js +10 -0
  136. package/skills/fito-case-runner/workdir.ts +11 -0
  137. package/skills/fito-competence-write/SKILL.md +155 -0
  138. package/skills/fito-competence-write/create.js +64 -0
  139. package/skills/fito-competence-write/create.ts +80 -0
  140. package/skills/fito-competence-write/delete.js +136 -0
  141. package/skills/fito-competence-write/delete.ts +166 -0
  142. package/skills/fito-competence-write/display.js +20 -0
  143. package/skills/fito-competence-write/display.ts +21 -0
  144. package/skills/fito-competence-write/payload.js +96 -0
  145. package/skills/fito-competence-write/payload.ts +115 -0
  146. package/skills/fito-competence-write/update.js +155 -0
  147. package/skills/fito-competence-write/update.ts +206 -0
  148. package/skills/fito-evaluator/SKILL.md +73 -0
  149. package/skills/fito-evaluator/criterion-exec.js +64 -0
  150. package/skills/fito-evaluator/criterion-exec.ts +73 -0
  151. package/skills/fito-evaluator/evaluate-automated.js +57 -0
  152. package/skills/fito-evaluator/evaluate-automated.ts +84 -0
  153. package/skills/fito-evaluator/evaluate.js +28 -0
  154. package/skills/fito-evaluator/evaluate.ts +86 -0
  155. package/skills/fito-evaluator/report.js +112 -0
  156. package/skills/fito-evaluator/report.ts +128 -0
  157. package/skills/fito-evaluator/rubric.js +90 -0
  158. package/skills/fito-evaluator/rubric.ts +170 -0
  159. package/skills/fito-knowledge-push/SKILL.md +114 -0
  160. package/skills/fito-knowledge-push/push.js +282 -0
  161. package/skills/fito-knowledge-push/push.ts +360 -0
  162. package/skills/fito-source-ingestion/SKILL.md +77 -0
  163. package/skills/fito-source-ingestion/authoring-check.js +128 -0
  164. package/skills/fito-source-ingestion/authoring-check.ts +155 -0
  165. package/skills/fito-source-ingestion/bundle.js +198 -0
  166. package/skills/fito-source-ingestion/bundle.ts +246 -0
  167. package/skills/fito-technology-write/SKILL.md +108 -0
  168. package/skills/fito-technology-write/create.js +134 -0
  169. package/skills/fito-technology-write/create.ts +161 -0
  170. package/skills/fito-technology-write/payload.js +64 -0
  171. package/skills/fito-technology-write/payload.ts +70 -0
  172. package/skills/fito-technology-write/update.js +122 -0
  173. package/skills/fito-technology-write/update.ts +171 -0
  174. package/skills/fito-url-content-fetcher/SKILL.md +213 -0
  175. package/templates/concept-practice-content-template.md +281 -0
  176. package/templates/concept-tool-content-template.md +207 -0
  177. package/templates/execution-fact-practice-content-template.md +372 -0
  178. package/templates/execution-fact-tool-content-template.md +307 -0
  179. package/templates/usage-scenario-content-template.md +248 -0
@@ -0,0 +1,1426 @@
1
+ import { z } from "zod";
2
+
3
+ import packageJson from "../../package.json" with { type: "json" };
4
+
5
+ /**
6
+ * The TUI's backend HTTP **transport boundary** (ADR-003): a thin client that mirrors backend
7
+ * REST endpoints one method per endpoint, attaches auth, validates every response with Zod, and
8
+ * normalises errors into `FitoApiError`. It is the only place raw `fetch` lives — no ad-hoc
9
+ * `fetch`, no axios. That, and only that, is what "single seam" means.
10
+ *
11
+ * It carries no domain logic: parsing identifiers, composing calls, or shaping responses for a
12
+ * use case belong in a `shared/<subject>/` module that imports this client (e.g.
13
+ * `shared/knowledge-components/`). New endpoints are added here as typed, Zod-validated functions;
14
+ * it grows per phase. At Task 1.5 it mapped only `refresh`, `logout`, `me`, plus the
15
+ * `401 → /auth/refresh → retry` helper `meWithRefresh`.
16
+ */
17
+
18
+ /** Default backend origin; overridable via `FITO_API_BASE_URL`. */
19
+ export const DEFAULT_BASE_URL = process.env.FITO_API_BASE_URL ?? "http://localhost:8080";
20
+
21
+ /**
22
+ * Sent on every request, so the backend can refuse a TUI older than the minimum version it serves,
23
+ * with a message that says how to update (Task 15d.7a). Without it, Node's `fetch` sends `node`,
24
+ * which the backend always lets through.
25
+ */
26
+ const USER_AGENT = `fito-tui/${packageJson.version}`;
27
+
28
+ export const tokenResponseSchema = z.object({
29
+ accessToken: z.string().min(1),
30
+ refreshToken: z.string().min(1),
31
+ expiresIn: z.number(),
32
+ tokenType: z.string().default("Bearer"),
33
+ });
34
+ export type TokenResponse = z.infer<typeof tokenResponseSchema>;
35
+
36
+ export const meResponseSchema = z.object({
37
+ userId: z.string(),
38
+ email: z.string(),
39
+ username: z.string(),
40
+ // The learner's linked GitHub identity (Task 5.4) — null/absent when none is linked. The TUI
41
+ // matches these against the locally `gh`-authenticated account before a case submission.
42
+ githubLogin: z.string().nullable().optional(),
43
+ githubUserId: z.number().nullable().optional(),
44
+ });
45
+ export type SessionUser = z.infer<typeof meResponseSchema>;
46
+
47
+ /** The backend's health answer (`GET /actuator/health`); `status` is `UP` or `DOWN`. */
48
+ export const healthSchema = z.object({ status: z.string() });
49
+ export type Health = z.infer<typeof healthSchema>;
50
+
51
+ /** The component-type wire tokens, identical to the URL path segments. Mirrors `web/src/lib/api/knowledge.ts`. */
52
+ export const componentTypeSchema = z.enum(["concept", "execution-fact", "usage-scenario"]);
53
+ export type ComponentType = z.infer<typeof componentTypeSchema>;
54
+ export const COMPONENT_TYPES: readonly ComponentType[] = componentTypeSchema.options;
55
+
56
+ /** The technology a knowledge component belongs to, embedded in every component response. */
57
+ export const componentTechnologySchema = z.object({
58
+ id: z.string(),
59
+ kind: z.string(),
60
+ name: z.string(),
61
+ slug: z.string(),
62
+ });
63
+
64
+ /**
65
+ * One renderable content section. `value` is a string or a list of strings, mirroring the
66
+ * backend's structured-content field types (`KnowledgeDtos.ContentSectionResponse`).
67
+ */
68
+ export const contentSectionSchema = z.object({
69
+ key: z.string(),
70
+ label: z.string(),
71
+ value: z.union([z.string(), z.array(z.string())]),
72
+ });
73
+ export type ContentSection = z.infer<typeof contentSectionSchema>;
74
+
75
+ /**
76
+ * One knowledge component on the wire (`KnowledgeDtos.KnowledgeComponentResponse`). `id` is the
77
+ * canonical reference (`concept:git.bisect`); `slug` is the full dotted value (`git.bisect`). The
78
+ * shapes match `web/src/lib/api/knowledge.ts` so the TUI and web share one contract.
79
+ *
80
+ * `supersededById` is the forward version link (Task 11.4a6-4): the **newest** member of this
81
+ * component's version chain when something has replaced it — what a caller should be reading
82
+ * instead — mirroring the backward `previousVersionId`, which names the immediate predecessor.
83
+ *
84
+ * It is `nullish` because the backend sends the key only when the answer is a component: anything
85
+ * still in force has nothing to name. That is now true on **every** endpoint returning this shape
86
+ * (Task 11.14) — an absent key means "nothing replaced it", full stop. Until then listings did not
87
+ * carry the field at all, on the grounds that resolving it walks the chain per row, so an absent
88
+ * key meant "nothing replaced it" on the point read and "nobody computed it" in a listing: the same
89
+ * bytes, opposite facts. Postgres resolves a whole listing's chains in one recursive query, which
90
+ * is what closed the gap.
91
+ */
92
+ export const knowledgeComponentSchema = z.object({
93
+ id: z.string(),
94
+ type: componentTypeSchema,
95
+ technology: componentTechnologySchema,
96
+ slug: z.string(),
97
+ name: z.string(),
98
+ sections: z.array(contentSectionSchema),
99
+ version: z.string(),
100
+ previousVersionId: z.string().nullable(),
101
+ alternativeDefinitionOfId: z.string().nullable(),
102
+ templateId: z.string(),
103
+ supersededById: z.string().nullish(),
104
+ });
105
+ export type KnowledgeComponent = z.infer<typeof knowledgeComponentSchema>;
106
+
107
+ /**
108
+ * A field's requirement on the template wire (`KnowledgeDtos.FieldRequirementResponse`). The
109
+ * trigger fields are non-null only for `OPTIONAL_WITH_TRIGGER`.
110
+ */
111
+ export const templateFieldRequirementSchema = z.object({
112
+ kind: z.string(),
113
+ controllingField: z.string().nullable().optional(),
114
+ triggerValue: z.string().nullable().optional(),
115
+ });
116
+
117
+ /** One field descriptor on the template wire (`KnowledgeDtos.TemplateFieldResponse`); `type` is `TEXT` or `LIST`. */
118
+ export const templateFieldSchema = z.object({
119
+ key: z.string(),
120
+ label: z.string(),
121
+ type: z.string(),
122
+ requirement: templateFieldRequirementSchema,
123
+ includedInEmbedding: z.boolean(),
124
+ metadata: z.boolean(),
125
+ });
126
+
127
+ /**
128
+ * The technology kind a registered template is written for (`KnowledgeDtos.TemplateAppliesToKind`'s
129
+ * wire tokens). `tool` and `practice` match `TechnologySummary.kind` — which is exactly what a
130
+ * caller matches them against — while `any` is the shared row a component type keeps when its
131
+ * fields do not differ by kind.
132
+ */
133
+ export const templateAppliesToKindSchema = z.enum(["tool", "practice", "any"]);
134
+ export type TemplateAppliesToKind = z.infer<typeof templateAppliesToKindSchema>;
135
+
136
+ /**
137
+ * One registered template on the wire (`KnowledgeDtos.TemplateResponse` from
138
+ * `GET /knowledge/templates/{type}`): the `templateId` a knowledge write must name, plus the
139
+ * field-schema the write's `content` must conform to.
140
+ *
141
+ * `appliesToKind` is **required** — no `.nullable()`, no `.optional()`. A component type may carry
142
+ * several templates along two independent axes (the kind variant and the version lineage), and an
143
+ * optional marker would let an omitted value read as "matches nothing" while parsing cleanly; a
144
+ * required one turns a backend that forgot the field into a loud parse failure.
145
+ */
146
+ export const knowledgeTemplateSchema = z.object({
147
+ id: z.string(),
148
+ componentType: componentTypeSchema,
149
+ version: z.string(),
150
+ previousVersionId: z.string().nullable(),
151
+ appliesToKind: templateAppliesToKindSchema,
152
+ schema: z.object({ fields: z.array(templateFieldSchema) }),
153
+ });
154
+ export type KnowledgeTemplate = z.infer<typeof knowledgeTemplateSchema>;
155
+
156
+ const templateListSchema = z.object({ items: z.array(knowledgeTemplateSchema) });
157
+
158
+ /**
159
+ * The create-and-publish payload every knowledge write POSTs (the backend's
160
+ * `CreateKnowledgeComponentRequest`): `content` maps the registered template's field keys to
161
+ * markdown-fragment values — a string for a TEXT field, a string array for a LIST field.
162
+ * `technologyVersions` names the slugs of the technology versions the component applies to (≥1,
163
+ * ADR-011); the backend resolves them and rejects an unknown slug with a 422. `version` defaults
164
+ * to `1.0.0` server-side when absent (a distinct axis from `technologyVersions` — the component's
165
+ * own content revision). `overrideAcknowledging` is the structural confirmation for the
166
+ * near-duplicate 409: the exact duplicate reference the 409 reported, sent only after the author
167
+ * explicitly confirmed coexistence.
168
+ */
169
+ export interface CreateKnowledgeComponentInput {
170
+ technology: string;
171
+ technologyVersions: string[];
172
+ templateId: string;
173
+ name: string;
174
+ version?: string;
175
+ content: Record<string, string | string[]>;
176
+ overrideAcknowledging?: string;
177
+ }
178
+
179
+ /** A technology's major release line on the wire (ADR-011), as the backend's `TechnologyVersionResponse`. */
180
+ export const technologyVersionSchema = z.object({
181
+ id: z.string(),
182
+ label: z.string(),
183
+ slug: z.string(),
184
+ description: z.string().nullable(),
185
+ });
186
+ export type TechnologyVersion = z.infer<typeof technologyVersionSchema>;
187
+
188
+ /**
189
+ * One technology with its major release lines on the wire (`GET /technologies/{slug}`, the
190
+ * backend's `TechnologySummaryResponse`). `description` is the version-agnostic overview; the
191
+ * per-version compatibility prose (ADR-011 F7 — "Javalin 7 requires Java 17+, runs on Jetty 12")
192
+ * lives on each `technologyVersions[].description`, the toolchain cross-check's source (9a.6a).
193
+ * `componentCounts` keys are the component-type wire tokens. Mirrors `web/src/lib/api/technologies.ts`.
194
+ */
195
+ export const technologySummarySchema = z.object({
196
+ id: z.string(),
197
+ kind: z.string(),
198
+ name: z.string(),
199
+ slug: z.string(),
200
+ description: z.string().nullable(),
201
+ technologyVersions: z.array(technologyVersionSchema),
202
+ componentCounts: z.record(z.string(), z.number()),
203
+ });
204
+ export type TechnologySummary = z.infer<typeof technologySummarySchema>;
205
+
206
+ /**
207
+ * One item of the `GET /knowledge` listing (Task 9c.11). The endpoint returns the **same** records
208
+ * the point read does — `sections` and all — so this is [knowledgeComponentSchema] plus
209
+ * `technologyVersions`, the major lines the component is bound to.
210
+ *
211
+ * **Why the extra field is here and not on [knowledgeComponentSchema] itself.** The wire carries
212
+ * `technologyVersions` on every component response, and the point-read schema has always dropped it
213
+ * (Zod strips unknown keys). Adding it there would change what `fito_knowledge_fetch` hands every
214
+ * caller, which is a different decision from this one. Here it is load-bearing: it is what each
215
+ * listing entry's `versions` is projected from in
216
+ * `shared/knowledge-components/knowledge-search.ts`, so a reader can tell a component bound to one
217
+ * major line from one shared across several. **Scoping the listing to a line is no longer its job**
218
+ * — `GET /knowledge` filters on `technologyVersion` server-side (Task 11.4a6-1) — but the field is
219
+ * still what the reader is shown, so dropping it would empty every entry's `versions`.
220
+ *
221
+ * Declared here, after [technologyVersionSchema], rather than beside its base schema: it composes
222
+ * both, and the version schema is defined further down the file.
223
+ */
224
+ export const knowledgeSearchItemSchema = knowledgeComponentSchema.extend({
225
+ technologyVersions: z.array(technologyVersionSchema),
226
+ });
227
+ export type KnowledgeSearchItem = z.infer<typeof knowledgeSearchItemSchema>;
228
+
229
+ const knowledgeSearchListSchema = z.object({ items: z.array(knowledgeSearchItemSchema) });
230
+
231
+ /**
232
+ * The technology a write resolved to (`TechnologyWriteDtos.WrittenTechnology`, Task 9b.2b/9b.4):
233
+ * the same identity fields the read carries, without the versions and component counts. On a
234
+ * **reuse** the `description` is the *stored* overview, not the submitted one — the backend persists
235
+ * a submitted overview only when it creates the row — so the caller reads back what actually exists.
236
+ */
237
+ export const writtenTechnologySchema = z.object({
238
+ id: z.string(),
239
+ kind: z.string(),
240
+ name: z.string(),
241
+ slug: z.string(),
242
+ description: z.string().nullable(),
243
+ });
244
+ export type WrittenTechnology = z.infer<typeof writtenTechnologySchema>;
245
+
246
+ /**
247
+ * Which branch a create-or-resolve took: `created` (201 — a brand-new technology), `reused` (200 —
248
+ * exact-slug hit, the major line already existed), or `version-added` (200 — the technology existed
249
+ * and the major line was added). A **closed** set, so it is an enum rather than a forward-compat
250
+ * string: the three exhaust the endpoint's logical branches (technology absent / present-with-line /
251
+ * present-without-line), and a fourth would be new resolution semantics the 9b.7 command has to
252
+ * handle anyway. Unlike the case enums — which ADR-005 explicitly declares open, hence
253
+ * [caseDetailSchema]'s strings — nothing declares this one open, and the narrowed union is what lets
254
+ * that command's three-way branch be checked exhaustively at build time.
255
+ */
256
+ export const technologyWriteOutcomeSchema = z.enum(["created", "reused", "version-added"]);
257
+ export type TechnologyWriteOutcome = z.infer<typeof technologyWriteOutcomeSchema>;
258
+
259
+ /**
260
+ * The `POST /technologies` response (`TechnologyWriteDtos.TechnologyWriteResponse`, Task 9b.2b):
261
+ * what the create-or-resolve did, plus the resolved technology and the single major line it landed
262
+ * on. The major line reuses [technologyVersionSchema] because `WrittenTechnologyVersion` and the
263
+ * read's `TechnologyVersionResponse` are the same wire shape.
264
+ */
265
+ export const technologyWriteResponseSchema = z.object({
266
+ outcome: technologyWriteOutcomeSchema,
267
+ technology: writtenTechnologySchema,
268
+ version: technologyVersionSchema,
269
+ });
270
+ export type TechnologyWriteResponse = z.infer<typeof technologyWriteResponseSchema>;
271
+
272
+ /**
273
+ * One near-duplicate the technology create guard flagged (Task 9b.2b/9b.3, ADR-012), carried on the
274
+ * `409`'s problem detail under `matches`. `reason` names the layer that flagged it — `dedup-key` for
275
+ * the Layer-1 deterministic normalized-slug collision, `trigram` for a Layer-2 fuzzy `pg_trgm`
276
+ * candidate; Layer-1 matches come first. Kept a string for forward-compat, like the enums above.
277
+ */
278
+ export const technologyNearDuplicateMatchSchema = z.object({
279
+ slug: z.string(),
280
+ name: z.string(),
281
+ reason: z.string(),
282
+ });
283
+ export type TechnologyNearDuplicateMatch = z.infer<typeof technologyNearDuplicateMatchSchema>;
284
+
285
+ /**
286
+ * The two technology kinds a write may declare (ADR-012). Deliberately a **type only** — the
287
+ * write's `kind` is narrowed for the caller's benefit, while `writtenTechnologySchema.kind` stays
288
+ * `z.string()`: a response must keep parsing if the taxonomy grows, and Task 9b.9 is actively
289
+ * re-examining whether Tool/Practice are subclasses or a field. A request has no such exposure —
290
+ * the caller must pick one of the two the backend accepts today, or get a 400.
291
+ */
292
+ export type TechnologyKind = "tool" | "practice";
293
+
294
+ /**
295
+ * The `POST /technologies` payload (the backend's `CreateTechnologyRequest`, Task 9b.2b): the
296
+ * declared technology plus the single major line the command's `@version` names. `technology.kind`
297
+ * is narrowed to the two wire tokens the backend accepts, so a wrong one is a build error rather
298
+ * than a 400 round-trip — a *type*, not a runtime check: nothing here validates the payload, which
299
+ * would put the backend's constraints in this file as a second source of truth (ADR-003/006 —
300
+ * transport only). A non-canonical slug is still a 400. Either `description`
301
+ * is optional and blank-normalises to null server-side (`null` means "unknown", ADR-012), and the
302
+ * technology-level one — the **version-agnostic** overview (ADR-011 Decision 2), distinct from the
303
+ * major line's prose — is persisted only when the technology row is created. `override: true` forces
304
+ * creation past the near-duplicate matches; it is set only after the author explicitly resolved the
305
+ * `409`, never automatically (ADR-012 Decision 4).
306
+ */
307
+ export interface CreateTechnologyInput {
308
+ technology: { name: string; kind: TechnologyKind; slug: string; description?: string | null };
309
+ version: { label: string; slug: string; description?: string | null };
310
+ override?: boolean;
311
+ }
312
+
313
+ /** A technology that demands a competence (`CompetenceDtos.CompetenceTechnologyResponse`): identity only, no kind or versions. */
314
+ export const competenceTechnologySchema = z.object({
315
+ id: z.string(),
316
+ name: z.string(),
317
+ slug: z.string(),
318
+ });
319
+ export type CompetenceTechnology = z.infer<typeof competenceTechnologySchema>;
320
+
321
+ /**
322
+ * One element of a competence (`CompetenceDtos.CompetenceElementResponse`): the knowledge-component
323
+ * reference (`concept:javalin.handler`) and its type token. It carries no component name or content —
324
+ * those are a `getKnowledgeComponent` read away.
325
+ */
326
+ export const competenceElementSchema = z.object({
327
+ knowledgeComponent: z.string(),
328
+ type: componentTypeSchema,
329
+ });
330
+ export type CompetenceElement = z.infer<typeof competenceElementSchema>;
331
+
332
+ /**
333
+ * One competence on the wire (`CompetenceDtos.CompetenceResponse`, Task 4.2) — the shape the listing,
334
+ * the create and the edit all return. `technologies` are the technologies that demand it, `elements`
335
+ * its knowledge-component references in order, and `components` its sub-competences, each the same
336
+ * shape (the getter is Zod's recursive-object form). The wire carries **no owner**: whether a caller
337
+ * may edit or delete a competence is answered by the write itself, as a 403.
338
+ */
339
+ export const competenceSchema = z.object({
340
+ id: z.string(),
341
+ name: z.string(),
342
+ description: z.string().nullable(),
343
+ technologies: z.array(competenceTechnologySchema),
344
+ elements: z.array(competenceElementSchema),
345
+ get components() {
346
+ return z.array(competenceSchema);
347
+ },
348
+ });
349
+ export type Competence = z.infer<typeof competenceSchema>;
350
+
351
+ const competenceListSchema = z.object({ items: z.array(competenceSchema) });
352
+
353
+ /**
354
+ * The `POST /competences` payload (the backend's `CreateCompetenceRequest`, Task 15b.3): the demanding
355
+ * technology, the prose, and the element references. There is no parent field — a created competence
356
+ * is always top-level. The backend refuses an empty `elements` (400), a duplicate element (400), and
357
+ * any reference naming no component (422, every one listed in the problem detail).
358
+ */
359
+ export interface CreateCompetenceInput {
360
+ technologySlug: string;
361
+ name: string;
362
+ description?: string | null;
363
+ elements: string[];
364
+ }
365
+
366
+ /**
367
+ * The `PATCH /competences/{id}` payload (the backend's `UpdateCompetenceRequest`, Task 15b.4): the two
368
+ * prose fields and nothing else, because elements are frozen once written. A field left out keeps its
369
+ * stored value; there is no way to clear a description, and a body with neither field is a 400.
370
+ */
371
+ export interface UpdateCompetenceInput {
372
+ name?: string;
373
+ description?: string;
374
+ }
375
+
376
+ /**
377
+ * One advisory-probe hit (`POST /knowledge/{type}/near-duplicate-probe`, Task 8.7): an existing
378
+ * component's reference identity plus its cosine `similarity` against the probed candidate.
379
+ * Both dedup thresholds — the soft reporting floor and the hard 409 bar — live server-side
380
+ * (`PublishKnowledgeComponentUseCase`); the client only relays what the probe reports.
381
+ *
382
+ * `technologyVersions` are the major lines the match applies to (Task 9a.5e). The probe, unlike
383
+ * the hard gate, still reports a match whose version scope is disjoint from the candidate's — the
384
+ * gate would admit it — so the author needs the scope to judge it. Two distinct axes: `version` is
385
+ * the match's own content revision, `technologyVersions` is what it applies to.
386
+ *
387
+ * `sameVersionScope` is the server's own reading of that scope against the probed candidate: true
388
+ * when they share a line (the gate would 409), false when disjoint (the gate would admit). It
389
+ * decides which of link / supersede / skip / proceed even applies, so it is relayed rather than
390
+ * re-derived here.
391
+ */
392
+ export const nearDuplicateMatchSchema = z.object({
393
+ id: z.string(),
394
+ name: z.string(),
395
+ version: z.string(),
396
+ technologyVersions: z.array(technologyVersionSchema),
397
+ sameVersionScope: z.boolean(),
398
+ urlPath: z.string(),
399
+ similarity: z.number(),
400
+ });
401
+ export type NearDuplicateMatch = z.infer<typeof nearDuplicateMatchSchema>;
402
+
403
+ const nearDuplicateProbeSchema = z.object({ nearMatches: z.array(nearDuplicateMatchSchema) });
404
+
405
+ /**
406
+ * One role-tagged case→component reference resolved to its knowledge-component name
407
+ * (`CaseDtos.ResolvedReferenceResponse`). `description` carries the author's note on what the
408
+ * reference means for this case — present on learning-objective and prerequisite references
409
+ * (Task 12a.3), null on rubric ones, whose source file has none. `weight` is learning-objective-only.
410
+ */
411
+ export const resolvedCaseReferenceSchema = z.object({
412
+ componentId: z.string(),
413
+ name: z.string(),
414
+ bloomLevel: z.string(),
415
+ description: z.string().nullable(),
416
+ weight: z.string().nullable(),
417
+ });
418
+ export type ResolvedCaseReference = z.infer<typeof resolvedCaseReferenceSchema>;
419
+
420
+ /**
421
+ * One structured reference view (`CaseDtos.ReferenceListResponse` from
422
+ * `GET /cases/{id}/learning-objectives`, `/prerequisite-components`, or `/rubric`): the case's
423
+ * references of that role, resolved to knowledge-component names.
424
+ */
425
+ const caseReferenceListSchema = z.object({ items: z.array(resolvedCaseReferenceSchema) });
426
+
427
+ /**
428
+ * One case on the wire (`CaseDtos.CaseDetailResponse` from `GET /cases/{id}`): the S1 presentation
429
+ * metadata, the external-repo pointer (`repositoryUrl` / `versionRef` / `gitPlatform` — what the
430
+ * case-runner needs to fork + check out), and the resolved learning-objective / prerequisite references.
431
+ * `version` is the current SemVer (`versionRef` minus the `v`); `changeDescription` is the current
432
+ * version's chain-row correction note (ADR-009) — null on an initial version; `/fito-case-edit`'s
433
+ * orientation brief shows both (Task 9.7). The `type` / `status` / `gitPlatform` / `visibility`
434
+ * enums are kept as strings so a new forward-compat enum value (ADR-005) does not break parsing;
435
+ * the consumer validates the platform.
436
+ */
437
+ export const caseDetailSchema = z.object({
438
+ id: z.string(),
439
+ type: z.string(),
440
+ status: z.string(),
441
+ title: z.string().nullable(),
442
+ descriptionOverview: z.string().nullable(),
443
+ tags: z.array(z.string()),
444
+ estimatedDurationMinutes: z.number().nullable(),
445
+ language: z.string().nullable(),
446
+ repositoryUrl: z.string(),
447
+ versionRef: z.string(),
448
+ version: z.string(),
449
+ changeDescription: z.string().nullable(),
450
+ gitPlatform: z.string(),
451
+ visibility: z.string(),
452
+ learningObjectives: z.array(resolvedCaseReferenceSchema),
453
+ prerequisites: z.array(resolvedCaseReferenceSchema),
454
+ });
455
+ export type CaseDetail = z.infer<typeof caseDetailSchema>;
456
+
457
+ /**
458
+ * One published case in the discovery listing (`CaseDtos.CaseSummaryResponse` from `GET /cases`):
459
+ * the S1 presentation metadata plus identity and type — no external-repo pointer (that's the
460
+ * detail view). `type` stays a string for forward-compat, mirroring [caseDetailSchema].
461
+ */
462
+ export const caseSummarySchema = z.object({
463
+ id: z.string(),
464
+ type: z.string(),
465
+ title: z.string().nullable(),
466
+ descriptionOverview: z.string().nullable(),
467
+ tags: z.array(z.string()),
468
+ estimatedDurationMinutes: z.number().nullable(),
469
+ language: z.string().nullable(),
470
+ });
471
+ export type CaseSummary = z.infer<typeof caseSummarySchema>;
472
+
473
+ /** One page of the discovery listing (`CaseDtos.CaseListResponse`); `total` counts every match, not the window. */
474
+ export const caseListSchema = z.object({
475
+ items: z.array(caseSummarySchema),
476
+ page: z.number(),
477
+ size: z.number(),
478
+ total: z.number(),
479
+ });
480
+ export type CaseList = z.infer<typeof caseListSchema>;
481
+
482
+ /**
483
+ * Returned by both Case Registry writes (`CaseDtos.RegisterCaseResponse` / `PublishCaseResponse`):
484
+ * the backend case id (a UUID) and its lifecycle status (`DRAFT` after register, `PUBLISHED` after
485
+ * publish). `status` stays a string for forward-compat, mirroring [caseDetailSchema].
486
+ */
487
+ export const caseWriteResponseSchema = z.object({
488
+ id: z.string(),
489
+ status: z.string(),
490
+ });
491
+ export type CaseWriteResponse = z.infer<typeof caseWriteResponseSchema>;
492
+
493
+ /**
494
+ * Returned by `POST /cases/{id}/versions` (`CaseDtos.PublishCaseVersionResponse`, Task 9.4): the
495
+ * case id, its lifecycle status (stays `PUBLISHED`), and the new current version identity — the
496
+ * caller's confirmation of what the backend now serves. `status` stays a string for
497
+ * forward-compat, mirroring [caseWriteResponseSchema].
498
+ */
499
+ export const caseVersionResponseSchema = z.object({
500
+ id: z.string(),
501
+ status: z.string(),
502
+ versionRef: z.string(),
503
+ version: z.string(),
504
+ });
505
+ export type CaseVersionResponse = z.infer<typeof caseVersionResponseSchema>;
506
+
507
+ /**
508
+ * The `POST /cases` payload (the backend's `RegisterCaseRequest`): the case classification plus the
509
+ * external-repo pointer. Enum-valued fields carry the wire tokens (`DIAGNOSTIC`/`IMPLEMENTATION`/
510
+ * `TUTORIAL`, `GITHUB`, `PUBLIC`) as strings — building correct values from `.case/` content is the
511
+ * caller's job (`skills/fito-case-author/publish-payload.ts`). The publishing user comes from the
512
+ * bearer token, never the body.
513
+ */
514
+ export interface RegisterCaseInput {
515
+ type: string;
516
+ repositoryUrl: string;
517
+ gitPlatform: string;
518
+ versionRef: string;
519
+ version: string;
520
+ visibility: string;
521
+ }
522
+
523
+ /**
524
+ * A `prerequisites`/`rubric` reference on the publish wire: a component reference + Bloom level +
525
+ * the author's optional description — what the reference means for this case specifically
526
+ * (Task 12a.3). Only `prerequisites.yaml` supplies one: `rubric.yaml` has no criterion-level
527
+ * description, so a rubric entry's is always absent.
528
+ */
529
+ export interface CasePublishComponentRef {
530
+ componentId: string;
531
+ bloomLevel: string;
532
+ description?: string | null;
533
+ }
534
+
535
+ /** A `learningObjectives` reference on the publish wire: a [CasePublishComponentRef] plus the author's description + weight (`PRIMARY`/`SECONDARY`). */
536
+ export interface CasePublishLearningObjectiveRef extends CasePublishComponentRef {
537
+ description?: string | null;
538
+ weight: string;
539
+ }
540
+
541
+ /** One quiz question on the publish wire (`CaseDtos.QuestionDto`); `type` carries `MULTIPLE_CHOICE`/`SHORT_ANSWER`/`CODE_SNIPPET`. */
542
+ export interface CasePublishQuizQuestion {
543
+ id: string;
544
+ type: string;
545
+ prompt: string;
546
+ knowledgeComponents: string[];
547
+ bloomLevel: string;
548
+ weight?: number | null;
549
+ choices?: Array<{ id: string; text: string }> | null;
550
+ answer?: string | null;
551
+ evaluation?: { method: string; promptHint?: string | null } | null;
552
+ }
553
+
554
+ /**
555
+ * The `POST /cases/{id}/publish` payload (the backend's `PublishCaseRequest`, Task 3.3b): the S1
556
+ * presentation metadata, the role-grouped knowledge-component references, the optional full quiz,
557
+ * and the structural attestation the validator emitted (ADR-005 — it must come from the *last*
558
+ * validator run over the finished tree; the backend rejects a missing or non-passing one with a 422).
559
+ */
560
+ export interface PublishCaseInput {
561
+ title: string;
562
+ descriptionOverview: string;
563
+ tags: string[];
564
+ estimatedDurationMinutes: number;
565
+ language: string;
566
+ learningObjectives: CasePublishLearningObjectiveRef[];
567
+ prerequisites: CasePublishComponentRef[];
568
+ rubric: CasePublishComponentRef[];
569
+ quiz?: { questions: CasePublishQuizQuestion[] } | null;
570
+ attestation: { pass: boolean; validatorVersion: string; rulesetVersion: string };
571
+ }
572
+
573
+ /**
574
+ * The `POST /cases/{id}/versions` payload (the backend's `PublishCaseVersionRequest`, Task 9.4,
575
+ * ADR-009): a correction/perfection version of an already-published case — the new version
576
+ * identity (`version`, its frozen ref `versionRef` — exactly `"v" + version` — and the required
577
+ * `changeDescription` documenting the correction) on top of the same S1 presentation,
578
+ * role-grouped references, optional quiz, and attestation as a publish. The reference set must
579
+ * equal the stored one on `(componentId, bloomLevel, role)` — the backend 422s otherwise
580
+ * (reference changes require a new case); only descriptions/weights and the quiz may change.
581
+ */
582
+ export interface PublishCaseVersionInput extends PublishCaseInput {
583
+ version: string;
584
+ versionRef: string;
585
+ changeDescription: string;
586
+ }
587
+
588
+ /**
589
+ * A recorded case enrollment on the wire (`CaseDtos.CaseEnrollmentResponse` from
590
+ * `POST /cases/{id}/enrollments`, Task 9.5): the enrollment id, the case, the `versionRef` of the
591
+ * case version it pinned (the current one at the open), and the recorded open moment.
592
+ */
593
+ export const caseEnrollmentSchema = z.object({
594
+ id: z.string(),
595
+ caseId: z.string(),
596
+ versionRef: z.string(),
597
+ openedAt: z.string(),
598
+ });
599
+ export type CaseEnrollment = z.infer<typeof caseEnrollmentSchema>;
600
+
601
+ /**
602
+ * The learner's participant status on the wire (`CaseDtos.ParticipantStatusResponse` from
603
+ * `GET /cases/{id}/enrollments/me`, Task 9.6): whether the authenticated learner participates in
604
+ * the case — an enrollment **or** a recorded submission exists. Learner-scoped; an unknown case
605
+ * reads as `false` (existence never leaks).
606
+ */
607
+ export const caseParticipationSchema = z.object({
608
+ participant: z.boolean(),
609
+ });
610
+ export type CaseParticipation = z.infer<typeof caseParticipationSchema>;
611
+
612
+ /**
613
+ * A recorded submission on the wire (`SubmissionDtos.SubmissionResponse` from `POST /submissions` and
614
+ * `GET /submissions/{id}`). All fields are strings; `status` is kept as a string (forward-compat with
615
+ * new lifecycle values) — the TUI only needs the round-trip confirmation, not to branch on it.
616
+ */
617
+ export const submissionResponseSchema = z.object({
618
+ id: z.string(),
619
+ caseId: z.string(),
620
+ learnerId: z.string(),
621
+ prUrl: z.string(),
622
+ submittedAt: z.string(),
623
+ status: z.string(),
624
+ });
625
+ export type SubmissionResponse = z.infer<typeof submissionResponseSchema>;
626
+
627
+ /**
628
+ * One rubric criterion's evaluation outcome the TUI `fito-performance-reviewer` produces and the
629
+ * `/fito-submit` round-trip POSTs to `POST /submissions/{id}/results` (Task 6.3) — the wire shape of
630
+ * the backend's `CriterionResultDto`. `score` is the reviewer's 0–3 band, or `null` for a `human`
631
+ * criterion still awaiting a human reviewer. This schema is the contract used to validate the
632
+ * reviewer's JSON before it is sent (see `fito-case-runner/submit-evaluation.ts`).
633
+ */
634
+ export const criterionEvaluationResultSchema = z.object({
635
+ criterionId: z.string().min(1),
636
+ knowledgeComponent: z.string().min(1),
637
+ // One of the three declared levels, for the reason the quiz schema below checks its own: the
638
+ // reviewer's JSON template spells this field as all three at once, and since Task 17.6 the level
639
+ // decides the proficiency awarded, so a copied placeholder must fail here, not on the backend 400.
640
+ bloomLevel: z.enum(["KNOWLEDGE", "COMPREHENSION", "APPLICATION"]),
641
+ evaluationType: z.string().min(1),
642
+ // 0–3 rubric band, or null for a `human` criterion needing review. Bounded here so a reviewer
643
+ // (LLM) emitting an out-of-band score fails fast at the file-parse boundary rather than on the
644
+ // backend 400 round-trip (the schema also validates the reviewer's results file in submit-evaluation.ts).
645
+ score: z.number().int().min(0).max(3).nullable(),
646
+ label: z.string().min(1),
647
+ justification: z.string().min(1),
648
+ });
649
+ export type CriterionEvaluationResult = z.infer<typeof criterionEvaluationResultSchema>;
650
+
651
+ /**
652
+ * One quiz question's scored outcome the TUI `fito-performance-reviewer` produces and the
653
+ * `/fito-submit` round-trip POSTs to `POST /submissions/{id}/quiz-result` (Task 7.3) — the wire shape
654
+ * of the backend's `QuestionScoreDto`. `score` is the reviewer's 0–3 band (multiple-choice scored
655
+ * deterministically as met (2) or not (0), `short_answer` / `code_snippet` scored by the local LLM), or
656
+ * `null` for a question awaiting human review. `bloomLevel` is the question's declared level, which the
657
+ * backend awards at score 2 or 3 (Task 17.7) to each of the question's `knowledgeComponents`. This
658
+ * schema validates the reviewer's JSON before it is sent (see `fito-case-runner/submit-quiz-result.ts`).
659
+ */
660
+ export const questionScoreResultSchema = z.object({
661
+ questionId: z.string().min(1),
662
+ knowledgeComponents: z.array(z.string().min(1)).min(1),
663
+ // One of the three declared levels, checked here for the reason the score is bounded below: the
664
+ // reviewer's JSON template spells this field as a placeholder listing all three, so a model that
665
+ // copies it verbatim fails at the file-parse boundary rather than on the backend 400 round-trip.
666
+ bloomLevel: z.enum(["KNOWLEDGE", "COMPREHENSION", "APPLICATION"]),
667
+ // 0–3 band, or null for a question needing human review. Bounded here so a reviewer (LLM) emitting
668
+ // an out-of-band score fails fast at the file-parse boundary rather than on the backend 400 round-trip.
669
+ score: z.number().int().min(0).max(3).nullable(),
670
+ justification: z.string().nullable(),
671
+ });
672
+ export type QuestionScoreResult = z.infer<typeof questionScoreResultSchema>;
673
+
674
+ /**
675
+ * Carries the backend's RFC 9457 problem-detail message and HTTP status, plus each write API's 409
676
+ * resolution properties when present: [duplicateId] (knowledge near-duplicate on create — the most
677
+ * similar component's canonical reference), [supersededBy] (new-version target already superseded —
678
+ * the existing successor's reference), and [matches] (the technology create guard's flagged rows,
679
+ * Task 9b.2b/9b.3). All are `undefined` on every other error; consumers branch on them to drive the
680
+ * flow's human resolution (PLAN Task 8.5 / 9b.7), never resolving a duplicate automatically.
681
+ *
682
+ * [type] is the problem's `type`, which names the kind of error where the backend sets one: the
683
+ * refusal of a TUI older than the backend's minimum is `/problems/tui-too-old` (Task 15d.7a), which
684
+ * the startup check recognises (Task 15d.7b). It is `undefined` when the body carries none.
685
+ */
686
+ export class FitoApiError extends Error {
687
+ readonly status: number;
688
+ readonly type?: string;
689
+ readonly duplicateId?: string;
690
+ readonly supersededBy?: string;
691
+ readonly matches?: TechnologyNearDuplicateMatch[];
692
+
693
+ constructor(
694
+ message: string,
695
+ status: number,
696
+ properties: { type?: string; duplicateId?: string; supersededBy?: string; matches?: TechnologyNearDuplicateMatch[] } = {},
697
+ ) {
698
+ super(message);
699
+ this.name = "FitoApiError";
700
+ this.status = status;
701
+ this.type = properties.type;
702
+ this.duplicateId = properties.duplicateId;
703
+ this.supersededBy = properties.supersededBy;
704
+ this.matches = properties.matches;
705
+ }
706
+ }
707
+
708
+ const problemDetailSchema = z.object({
709
+ type: z.string().optional(),
710
+ detail: z.string().optional(),
711
+ title: z.string().optional(),
712
+ duplicateId: z.string().optional(),
713
+ supersededBy: z.string().optional(),
714
+ // `matches` is a shared problem-detail namespace, so a body carrying one of an unexpected shape
715
+ // degrades to "no matches" rather than failing the whole parse — which would drop the `detail`
716
+ // the author is shown back to the bare status fallback.
717
+ matches: z.array(technologyNearDuplicateMatchSchema).optional().catch(undefined),
718
+ });
719
+
720
+ export interface FitoApiClientOptions {
721
+ baseUrl?: string;
722
+ fetch?: typeof fetch;
723
+ }
724
+
725
+ export interface FitoApiClient {
726
+ /** `POST /auth/refresh` — exchange a refresh token for a fresh token pair. */
727
+ refresh(refreshToken: string): Promise<TokenResponse>;
728
+ /** `POST /auth/logout` — revoke a refresh token server-side. */
729
+ logout(refreshToken: string): Promise<void>;
730
+ /** `GET /me` — the authenticated user for an access token. */
731
+ me(accessToken: string): Promise<SessionUser>;
732
+ /**
733
+ * `GET /me`, transparently refreshing on a 401 and retrying once. Returns both
734
+ * the user and the (possibly refreshed) token pair so the caller can persist it.
735
+ */
736
+ meWithRefresh(tokens: TokenResponse): Promise<{ user: SessionUser; tokens: TokenResponse }>;
737
+ /**
738
+ * `GET /actuator/health` — whether the backend is up. No login. The startup check calls it for
739
+ * the backend's answer to this TUI's version (Task 15d.7b), and bounds the wait with `signal`.
740
+ */
741
+ getHealth(options?: { signal?: AbortSignal }): Promise<Health>;
742
+ /**
743
+ * `GET /knowledge/{type}/{slug}` — fetch one knowledge component by its type and its
744
+ * `<tech-slug>.<component-slug>` value. The read is public, so no token is sent.
745
+ * Mirrors the web `getComponent(type, slug)` signature; parsing a canonical reference
746
+ * (`concept:git.bisect`) into these parts is the caller's job
747
+ * (`shared/knowledge-components/reference.ts`'s `parseKnowledgeReference`). An unknown
748
+ * component surfaces as a 404 `FitoApiError`. `params.technologyVersion`, when present, scopes
749
+ * the read to one technology-version slug (9a.5d): a component live only for another major line
750
+ * then reads as a 404, so the version-aware existence check never accepts it as live. An options
751
+ * bag keeps future read filters additive.
752
+ *
753
+ * The parameter was called `version` at the wire until Task 11.4a6-4 — the wrong axis, since the
754
+ * response carries both the major lines a component applies to and its own revision. It now
755
+ * matches [searchKnowledgeComponents]' `technologyVersion`, and the backend keeps **no alias**:
756
+ * a request still spelling it `version` is version-agnostic, not version-scoped.
757
+ *
758
+ * The 404 for a component that exists outside the requested line now carries its own message and
759
+ * a machine-readable `reason` (`technology-version-mismatch`, against `component-not-found` for
760
+ * one nobody wrote — kebab-case, as this API's other `reason` already is). Nothing on this side
761
+ * branches on it yet — that is deferred as DI1, because the branch is a third outcome the
762
+ * identify/design artifacts do not model.
763
+ */
764
+ getKnowledgeComponent(
765
+ type: ComponentType,
766
+ slug: string,
767
+ params?: { technologyVersion?: string },
768
+ ): Promise<KnowledgeComponent>;
769
+ /**
770
+ * `GET /knowledge` — list knowledge components, optionally filtered by `type`, `technology`
771
+ * slug, `technologyVersion` slug, and a free-text `q`. The read is public, so no token is sent;
772
+ * the `{ items: [...] }` envelope is unwrapped, as on [getKnowledgeTemplates]. An unknown
773
+ * technology is **not** an error — it returns an empty list, since this is a search and not an
774
+ * existence check.
775
+ *
776
+ * `excludeSuperseded` is **required**: it states whether components that a newer version has
777
+ * replaced belong in the answer, and the endpoint's callers genuinely disagree — the web's
778
+ * component detail page needs the replaced row to mark the page being read, while every caller
779
+ * on this side wants the version still in force (Task 11.4a6-1). A default would answer that
780
+ * question for a caller who never considered it, and the wrong answer is invisible in the
781
+ * response. It travels on every request, `false` included.
782
+ *
783
+ * The two parameters name **different axes** of "version" and neither is called `version` for
784
+ * that reason: `technologyVersion` is the technology major line a component applies to (picocli
785
+ * `4`), while `excludeSuperseded` acts on the component's own revision (`1.0.0` replaced by
786
+ * `1.0.1`). The response carries both. A component bound to several major lines is kept when any
787
+ * one of them matches — the backend's rule, applied before any projection.
788
+ */
789
+ searchKnowledgeComponents(params: {
790
+ excludeSuperseded: boolean;
791
+ type?: ComponentType;
792
+ technology?: string;
793
+ technologyVersion?: string;
794
+ q?: string;
795
+ }): Promise<KnowledgeSearchItem[]>;
796
+ /**
797
+ * `GET /technologies/{slug}` — fetch one technology by its slug, with its major-line versions
798
+ * and their version-specific prose (ADR-011). The read is public, so no token is sent. Surfaces
799
+ * the `TechnologyVersion.description` compatibility facts the design / plan-source steps read to
800
+ * cross-check the author's declared toolchain (9a.6a, ADR-011 §9). An unknown slug surfaces as a
801
+ * 404 `FitoApiError`; mirrors the web `getTechnology(slug)` signature.
802
+ */
803
+ getTechnology(slug: string): Promise<TechnologySummary>;
804
+ /**
805
+ * `POST /technologies` — create-or-resolve a technology and one major line (Task 9b.2b, ADR-012).
806
+ * Bearer authenticated. Exact-slug hits reuse the existing technology (adding the major line when
807
+ * it is absent); otherwise the two-layer near-duplicate guard may stop the write with a 409
808
+ * `FitoApiError` whose `matches` name the flagged technologies. The author resolves that — reuse,
809
+ * a distinct slug, or `input.override` — never the client (ADR-012 Decision 4). The response's
810
+ * `outcome` reports which branch ran.
811
+ */
812
+ createOrResolveTechnology(accessToken: string, input: CreateTechnologyInput): Promise<TechnologyWriteResponse>;
813
+ /**
814
+ * `PATCH /technologies/{slug}` — replace a technology's **version-agnostic overview** in place
815
+ * (Task 9b.4, the create-or-update tail for ADR-011 Decision 2's technology-level field). Bearer
816
+ * authenticated; an unknown slug is a 404 `FitoApiError`. `description` is required and non-blank
817
+ * — the endpoint is enrichment, and there is no "clear the description" path (a blank or absent
818
+ * one is a 400), so a caller with nothing better to say sends nothing at all.
819
+ */
820
+ updateTechnologyDescription(accessToken: string, slug: string, description: string): Promise<WrittenTechnology>;
821
+ /**
822
+ * `PATCH /technologies/{slug}/versions/{versionSlug}` — replace one **major line's** prose in
823
+ * place (Task 9b.4), the other axis of the same create-or-update tail. Bearer authenticated; an
824
+ * unknown technology *or* major line is a 404 `FitoApiError`. `description` is required and
825
+ * non-blank, exactly as on [updateTechnologyDescription].
826
+ */
827
+ updateTechnologyVersionDescription(
828
+ accessToken: string,
829
+ slug: string,
830
+ versionSlug: string,
831
+ description: string,
832
+ ): Promise<TechnologyVersion>;
833
+ /**
834
+ * `GET /technologies/{slug}/competences` — the competences a technology **directly demands**,
835
+ * name-ordered, each with its sub-competence tree nested in `components`. The read is public, so no
836
+ * token is sent; the `{ items }` envelope is unwrapped. A sub-competence is never a row of its own,
837
+ * and a competence only another technology demands is absent. An unknown slug is a 404
838
+ * `FitoApiError`, not an empty list — unlike [searchKnowledgeComponents], this is an existence check.
839
+ */
840
+ listTechnologyCompetences(slug: string): Promise<Competence[]>;
841
+ /**
842
+ * `GET /competences/{id}` — one competence with its whole sub-competence subtree nested in
843
+ * `components` (Task 4.2). Public, like the listing, so no token is sent. An unknown id is a 404
844
+ * `FitoApiError` and a non-UUID id a 400.
845
+ *
846
+ * It is the read behind the delete's preview (Task 15b.8): `deleteCompetence` removes the subtree,
847
+ * so what will go is counted from `components` here, before the write.
848
+ */
849
+ getCompetence(id: string): Promise<Competence>;
850
+ /**
851
+ * `POST /competences` — create a top-level competence (Task 15b.3). Bearer authenticated; the caller
852
+ * becomes its owner. A curator or an admin may create (else 403), an unknown technology is a 404, and
853
+ * element references naming no component are a 422 whose message lists every one of them — relayed
854
+ * to the author verbatim, since it is their next action.
855
+ */
856
+ createCompetence(accessToken: string, input: CreateCompetenceInput): Promise<Competence>;
857
+ /**
858
+ * `PATCH /competences/{id}` — edit a competence's name, description, or both, in place (Task 15b.4).
859
+ * Bearer authenticated; the owner or an admin may edit (else 403), and an unknown id is a 404.
860
+ * Returns the competence as stored after the write.
861
+ */
862
+ updateCompetence(accessToken: string, id: string, input: UpdateCompetenceInput): Promise<Competence>;
863
+ /**
864
+ * `DELETE /competences/{id}` — delete a competence and every sub-competence beneath it (Task 15b.5).
865
+ * Bearer authenticated; the owner or an admin may delete (else 403), and an unknown id is a 404.
866
+ * The 204 carries no body, so this resolves to nothing; no learner's recorded proficiency is touched.
867
+ */
868
+ deleteCompetence(accessToken: string, id: string): Promise<void>;
869
+ /**
870
+ * `GET /cases/{id}` — fetch one case by its backend id (a UUID). A published case is a public
871
+ * read, so no token is needed; the response carries the external-repo pointer the case-runner
872
+ * forks and checks out. An unknown id surfaces as a 404 `FitoApiError`. The optional
873
+ * `accessToken` mirrors the backend's nullable JWT (Task 9.7): a **draft** is served only to
874
+ * its owner on an authenticated read — `/fito-case-edit` passes the session token best-effort
875
+ * so an author's draft gets its "never published" message instead of a bare 404.
876
+ */
877
+ getCase(id: string, accessToken?: string): Promise<CaseDetail>;
878
+ /**
879
+ * `GET /cases` — the public case-discovery listing, optionally filtered. At MVP the TUI passes
880
+ * only `repositoryUrl` (Task 8.2): the "is this URL a registered case?" lookup (`total >= 1`)
881
+ * used by the authoring-context check and the publish flows' guards/routing. The URL-filtered
882
+ * request matches a **published or deprecated** case (Task 9.6 — deprecation hides a case from
883
+ * browsing, not from this lookup); drafts never match. The backend matches the registered URL
884
+ * ignoring letter case and a trailing `.git` / `/`.
885
+ */
886
+ listCases(params?: { repositoryUrl?: string }): Promise<CaseList>;
887
+ /**
888
+ * `POST /cases` — register a case as a `DRAFT` with its external-repo pointer (Task 3.3a). Bearer
889
+ * authenticated: the case's `ownerCreator` is the JWT subject. The backend mints and returns the
890
+ * case UUID — the id every later call (publish, open) uses. Non-MVP options (`GITLAB`/`BITBUCKET`/
891
+ * `PRIVATE`) are rejected with a 422 `FitoApiError`. Registration is **not** idempotent — a repeat
892
+ * call mints a second draft — so the publish flow persists the minted id and reuses it on retry
893
+ * (`skills/fito-case-author/publish.ts`).
894
+ */
895
+ registerCase(accessToken: string, input: RegisterCaseInput): Promise<CaseWriteResponse>;
896
+ /**
897
+ * `POST /cases/{id}/publish` — run the backend publish pipeline on a registered draft (Task 3.3b):
898
+ * validate the attestation, reachability-ping the repo (tag + solution branch), resolve every
899
+ * knowledge-component reference, persist the S1 presentation + role-tagged edges, and flip the
900
+ * case to `PUBLISHED`. Bearer authenticated; only the case's `ownerCreator` may publish (403).
901
+ * Every rejection (unreachable repo, unresolvable/wrong-type reference, missing or non-passing
902
+ * attestation → 422) surfaces as a `FitoApiError` whose message is the backend's problem detail —
903
+ * relayed to the author verbatim, never paraphrased.
904
+ */
905
+ publishCase(accessToken: string, caseId: string, input: PublishCaseInput): Promise<CaseWriteResponse>;
906
+ /**
907
+ * `POST /cases/{id}/versions` — publish a correction/perfection **version** of an
908
+ * already-published case (Task 9.4, ADR-009; the Task 9.8 update-publish flow). Bearer
909
+ * authenticated; only the case's `ownerCreator` may publish (403). The backend guards the
910
+ * version identity (strictly increasing SemVer whose `versionRef` is exactly `"v" + version`),
911
+ * re-pings the new frozen refs, and enforces the frozen reference set — every rejection is a
912
+ * 422 `FitoApiError` whose message is the backend's problem detail, relayed to the author
913
+ * verbatim, never paraphrased.
914
+ */
915
+ publishCaseVersion(accessToken: string, caseId: string, input: PublishCaseVersionInput): Promise<CaseVersionResponse>;
916
+ /**
917
+ * `GET /cases/{id}/learning-objectives` — the case's `LEARNING_OBJECTIVE` references resolved to
918
+ * knowledge-component names (public read, like every case read). Together with
919
+ * `getCasePrerequisites`/`getCaseRubric` this is the stored reference set the version-publish
920
+ * preflight compares the local `.case/` tree against (Task 9.8).
921
+ */
922
+ getCaseLearningObjectives(caseId: string): Promise<ResolvedCaseReference[]>;
923
+ /**
924
+ * `GET /cases/{id}/prerequisite-components` — the case's `PREREQUISITE` references resolved to
925
+ * names (public read). The path says **components** (renamed at Task 12.5) because
926
+ * `/cases/{id}/prerequisite-cases` is a different endpoint returning cases; this method keeps its
927
+ * name and its shape, so the version-publish preflight is unaffected.
928
+ */
929
+ getCasePrerequisites(caseId: string): Promise<ResolvedCaseReference[]>;
930
+ /** `GET /cases/{id}/rubric` — the case's `RUBRIC` references resolved to names (public read). */
931
+ getCaseRubric(caseId: string): Promise<ResolvedCaseReference[]>;
932
+ /**
933
+ * `POST /cases/{id}/enrollments` — record the learner's case open as an enrollment (Task 9.5),
934
+ * the pre-submission learner↔case trace. Bearer authenticated: the enrollment is associated with
935
+ * the JWT subject. The body is empty — the backend pins the case's **current** version itself.
936
+ * **Idempotent per version**: a repeat open of the same case version returns the existing row
937
+ * (201 fresh vs 200 existing; the client treats both alike), so the case-runner can post it on
938
+ * every successful open. An unknown case is a 404 `FitoApiError`.
939
+ */
940
+ createCaseEnrollment(accessToken: string, caseId: string): Promise<CaseEnrollment>;
941
+ /**
942
+ * `GET /cases/{id}/enrollments/me` — whether the authenticated learner participates in the case:
943
+ * an enrollment **or** a recorded submission exists (Task 9.6). Bearer authenticated and
944
+ * learner-scoped. Never a 404 — an unknown case reads as `participant: false` (existence-hiding,
945
+ * the `submissions/me` precedent). The case-runner's open gates a deprecated case on it: a
946
+ * participant's open proceeds with a warning, everyone else is refused.
947
+ */
948
+ getCaseParticipation(accessToken: string, caseId: string): Promise<CaseParticipation>;
949
+ /**
950
+ * `POST /submissions` — record the learner's opened PR as a submission for `input.caseId`. Bearer
951
+ * authenticated: the submission is associated with the JWT subject (never sent in the body), so the
952
+ * learner must have a linked GitHub identity (else a 422 `FitoApiError`). `input.versionRef` is the
953
+ * checkout's frozen ref read from the local tree (Task 9.4): the backend pins the submission to
954
+ * that exact case version — a ref the case never registered is a 422 `FitoApiError`. **Idempotent
955
+ * on the PR** — re-posting the same `(learner, case, prUrl)` returns the existing row (the backend
956
+ * find-or-creates), so the case-runner's record-aware retry is safe. The caller passes a fresh
957
+ * access token (submit reuses the one from `meWithRefresh`).
958
+ */
959
+ createSubmission(
960
+ accessToken: string,
961
+ input: { caseId: string; prUrl: string; versionRef: string },
962
+ ): Promise<SubmissionResponse>;
963
+ /**
964
+ * `POST /submissions/{id}/results` — record the reviewer's structured per-criterion scores for an
965
+ * already-recorded submission (Task 6.3). Bearer authenticated; the submission must belong to the
966
+ * JWT subject (else a 404 `FitoApiError`, hiding existence). The backend maps each scored criterion
967
+ * to a `Proficiency`, upserts the learner's profile (max-take, never regressing), persists the full
968
+ * result set, and flips the submission to `EVALUATED` — returned here so the caller can confirm it.
969
+ * Idempotent: re-POSTing replaces the submission's results, so a retried `/fito-submit` is safe.
970
+ */
971
+ submitEvaluationResults(
972
+ accessToken: string,
973
+ submissionId: string,
974
+ results: CriterionEvaluationResult[],
975
+ ): Promise<SubmissionResponse>;
976
+ /**
977
+ * `POST /submissions/{id}/quiz-result` — record the reviewer's per-question quiz scores for an
978
+ * already-recorded submission (Task 7.3). Bearer authenticated; the submission must belong to the
979
+ * JWT subject (else a 404 `FitoApiError`, hiding existence). The backend maps each scored question
980
+ * to a `Proficiency`, upserts the learner's profile per knowledge component (max-take, never
981
+ * regressing, coexisting with any rubric result), persists the score set, and flips the submission
982
+ * to `EVALUATED` — returned here so the caller can confirm it. Idempotent: re-POSTing replaces the
983
+ * submission's quiz result, so a retried `/fito-submit` is safe.
984
+ */
985
+ submitQuizResult(
986
+ accessToken: string,
987
+ submissionId: string,
988
+ perQuestionScores: QuestionScoreResult[],
989
+ ): Promise<SubmissionResponse>;
990
+ /**
991
+ * `GET /knowledge/templates/{type}` — the registered templates for a component type, the
992
+ * GENERATE-time field-schema source (Task 8.4). Public like every knowledge read, so no token
993
+ * is sent. Returns the wire list in the backend's order (version ascending); picking "the"
994
+ * registered template is the caller's job (`shared/knowledge-components/push-payload.ts`).
995
+ */
996
+ getKnowledgeTemplates(type: ComponentType): Promise<KnowledgeTemplate[]>;
997
+ /**
998
+ * `POST /knowledge/{type}` — create-and-publish one knowledge component (Task 8.4, no-drafts
999
+ * shape). Bearer authenticated. A near-duplicate is rejected with a 409 `FitoApiError` whose
1000
+ * `duplicateId` names the most similar component — the caller resolves it with a human choice
1001
+ * (link / supersede / skip / override), never automatically (PLAN Task 8.5).
1002
+ */
1003
+ createKnowledgeComponent(
1004
+ accessToken: string,
1005
+ type: ComponentType,
1006
+ input: CreateKnowledgeComponentInput,
1007
+ ): Promise<KnowledgeComponent>;
1008
+ /**
1009
+ * `POST /knowledge/{type}/{slug}/alternative-definitions` — the 409 "link" resolution (or a
1010
+ * proactive alternate framing): create a component linked to the target as an alternative
1011
+ * definition. Bearer authenticated; dedup-exempt (calling it is the acknowledgment). `slug` is
1012
+ * the target's full dotted value (`git.bisect`), as on the reads.
1013
+ */
1014
+ createAlternativeDefinition(
1015
+ accessToken: string,
1016
+ type: ComponentType,
1017
+ slug: string,
1018
+ input: CreateKnowledgeComponentInput,
1019
+ ): Promise<KnowledgeComponent>;
1020
+ /**
1021
+ * `POST /knowledge/{type}/{slug}/new-version` — the revision path (and the 409 "supersede"
1022
+ * resolution): create the target's successor. Bearer authenticated; dedup-exempt. Version
1023
+ * chains are linear — a target that already has a successor is rejected with a 409
1024
+ * `FitoApiError` whose `supersededBy` names the existing successor (the chain head to retarget).
1025
+ */
1026
+ createNewVersion(
1027
+ accessToken: string,
1028
+ type: ComponentType,
1029
+ slug: string,
1030
+ input: CreateKnowledgeComponentInput,
1031
+ ): Promise<KnowledgeComponent>;
1032
+ /**
1033
+ * `POST /knowledge/{type}/near-duplicate-probe` — the advisory dedup probe (Task 8.7):
1034
+ * validates and embeds the create payload server-side **without persisting**, returning the
1035
+ * components above the soft similarity threshold, most similar first — empty when nothing is
1036
+ * close. Bearer authenticated (it runs the embedding model). The push flow probes before every
1037
+ * plain create so a near-duplicate below the hard 409 bar reaches the author while nothing has
1038
+ * been stored yet.
1039
+ */
1040
+ probeNearDuplicates(
1041
+ accessToken: string,
1042
+ type: ComponentType,
1043
+ input: CreateKnowledgeComponentInput,
1044
+ ): Promise<NearDuplicateMatch[]>;
1045
+ }
1046
+
1047
+ export function createFitoApiClient(options: FitoApiClientOptions = {}): FitoApiClient {
1048
+ const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
1049
+ const doFetch = options.fetch ?? fetch;
1050
+
1051
+ async function request<T>(
1052
+ path: string,
1053
+ schema: z.ZodType<T>,
1054
+ init?: RequestInit,
1055
+ ): Promise<T> {
1056
+ const response = await doFetch(`${baseUrl}${path}`, {
1057
+ ...init,
1058
+ headers: { "Content-Type": "application/json", ...init?.headers, "User-Agent": USER_AGENT },
1059
+ });
1060
+ if (!response.ok) {
1061
+ throw await toApiError(response);
1062
+ }
1063
+ return schema.parse(await response.json());
1064
+ }
1065
+
1066
+ const refresh = (refreshToken: string): Promise<TokenResponse> =>
1067
+ request("/auth/refresh", tokenResponseSchema, {
1068
+ method: "POST",
1069
+ body: JSON.stringify({ refreshToken }),
1070
+ });
1071
+
1072
+ const me = (accessToken: string): Promise<SessionUser> =>
1073
+ request("/me", meResponseSchema, {
1074
+ method: "GET",
1075
+ headers: { Authorization: `Bearer ${accessToken}` },
1076
+ });
1077
+
1078
+ async function logout(refreshToken: string): Promise<void> {
1079
+ const response = await doFetch(`${baseUrl}/auth/logout`, {
1080
+ method: "POST",
1081
+ headers: { "Content-Type": "application/json", "User-Agent": USER_AGENT },
1082
+ body: JSON.stringify({ refreshToken }),
1083
+ });
1084
+ if (!response.ok) {
1085
+ throw await toApiError(response);
1086
+ }
1087
+ }
1088
+
1089
+ async function meWithRefresh(
1090
+ tokens: TokenResponse,
1091
+ ): Promise<{ user: SessionUser; tokens: TokenResponse }> {
1092
+ try {
1093
+ return { user: await me(tokens.accessToken), tokens };
1094
+ } catch (error) {
1095
+ if (!(error instanceof FitoApiError) || error.status !== 401) throw error;
1096
+ const fresh = await refresh(tokens.refreshToken);
1097
+ return { user: await me(fresh.accessToken), tokens: fresh };
1098
+ }
1099
+ }
1100
+
1101
+ const getHealth = (options: { signal?: AbortSignal } = {}): Promise<Health> =>
1102
+ request("/actuator/health", healthSchema, { method: "GET", signal: options.signal });
1103
+
1104
+ const getKnowledgeComponent = (
1105
+ type: ComponentType,
1106
+ slug: string,
1107
+ params: { technologyVersion?: string } = {},
1108
+ ): Promise<KnowledgeComponent> => {
1109
+ const query = new URLSearchParams();
1110
+ if (params.technologyVersion !== undefined) {
1111
+ query.set("technologyVersion", params.technologyVersion);
1112
+ }
1113
+ const suffix = query.size > 0 ? `?${query}` : "";
1114
+ return request(`/knowledge/${type}/${encodeURIComponent(slug)}${suffix}`, knowledgeComponentSchema, {
1115
+ method: "GET",
1116
+ });
1117
+ };
1118
+
1119
+ const searchKnowledgeComponents = async (params: {
1120
+ excludeSuperseded: boolean;
1121
+ type?: ComponentType;
1122
+ technology?: string;
1123
+ technologyVersion?: string;
1124
+ q?: string;
1125
+ }): Promise<KnowledgeSearchItem[]> => {
1126
+ const query = new URLSearchParams();
1127
+ if (params.type !== undefined) query.set("type", params.type);
1128
+ if (params.technology !== undefined) query.set("technology", params.technology);
1129
+ if (params.technologyVersion !== undefined) {
1130
+ query.set("technologyVersion", params.technologyVersion);
1131
+ }
1132
+ if (params.q !== undefined) query.set("q", params.q);
1133
+ // Always written, `false` included: the backend still tolerates an absent parameter, but
1134
+ // Task 11.4a6-1c makes it required, and an omission would then read as a 400 rather than as
1135
+ // a `false`. So there is no filter-less `/knowledge` request left to build.
1136
+ query.set("excludeSuperseded", String(params.excludeSuperseded));
1137
+ return (await request(`/knowledge?${query}`, knowledgeSearchListSchema, { method: "GET" })).items;
1138
+ };
1139
+
1140
+ const getTechnology = (slug: string): Promise<TechnologySummary> =>
1141
+ request(`/technologies/${encodeURIComponent(slug)}`, technologySummarySchema, { method: "GET" });
1142
+
1143
+ const createOrResolveTechnology = (
1144
+ accessToken: string,
1145
+ input: CreateTechnologyInput,
1146
+ ): Promise<TechnologyWriteResponse> =>
1147
+ request("/technologies", technologyWriteResponseSchema, {
1148
+ method: "POST",
1149
+ headers: { Authorization: `Bearer ${accessToken}` },
1150
+ body: JSON.stringify(input),
1151
+ });
1152
+
1153
+ const updateTechnologyDescription = (
1154
+ accessToken: string,
1155
+ slug: string,
1156
+ description: string,
1157
+ ): Promise<WrittenTechnology> =>
1158
+ request(`/technologies/${encodeURIComponent(slug)}`, writtenTechnologySchema, {
1159
+ method: "PATCH",
1160
+ headers: { Authorization: `Bearer ${accessToken}` },
1161
+ body: JSON.stringify({ description }),
1162
+ });
1163
+
1164
+ const updateTechnologyVersionDescription = (
1165
+ accessToken: string,
1166
+ slug: string,
1167
+ versionSlug: string,
1168
+ description: string,
1169
+ ): Promise<TechnologyVersion> =>
1170
+ request(
1171
+ `/technologies/${encodeURIComponent(slug)}/versions/${encodeURIComponent(versionSlug)}`,
1172
+ technologyVersionSchema,
1173
+ {
1174
+ method: "PATCH",
1175
+ headers: { Authorization: `Bearer ${accessToken}` },
1176
+ body: JSON.stringify({ description }),
1177
+ },
1178
+ );
1179
+
1180
+ const listTechnologyCompetences = async (slug: string): Promise<Competence[]> =>
1181
+ (await request(`/technologies/${encodeURIComponent(slug)}/competences`, competenceListSchema, { method: "GET" }))
1182
+ .items;
1183
+
1184
+ const getCompetence = (id: string): Promise<Competence> =>
1185
+ request(`/competences/${encodeURIComponent(id)}`, competenceSchema, { method: "GET" });
1186
+
1187
+ const createCompetence = (accessToken: string, input: CreateCompetenceInput): Promise<Competence> =>
1188
+ request("/competences", competenceSchema, {
1189
+ method: "POST",
1190
+ headers: { Authorization: `Bearer ${accessToken}` },
1191
+ body: JSON.stringify(input),
1192
+ });
1193
+
1194
+ const updateCompetence = (accessToken: string, id: string, input: UpdateCompetenceInput): Promise<Competence> =>
1195
+ request(`/competences/${encodeURIComponent(id)}`, competenceSchema, {
1196
+ method: "PATCH",
1197
+ headers: { Authorization: `Bearer ${accessToken}` },
1198
+ body: JSON.stringify(input),
1199
+ });
1200
+
1201
+ async function deleteCompetence(accessToken: string, id: string): Promise<void> {
1202
+ const response = await doFetch(`${baseUrl}/competences/${encodeURIComponent(id)}`, {
1203
+ method: "DELETE",
1204
+ headers: { "Content-Type": "application/json", "User-Agent": USER_AGENT, Authorization: `Bearer ${accessToken}` },
1205
+ });
1206
+ if (!response.ok) {
1207
+ throw await toApiError(response);
1208
+ }
1209
+ }
1210
+
1211
+ const getCase = (id: string, accessToken?: string): Promise<CaseDetail> =>
1212
+ request(`/cases/${encodeURIComponent(id)}`, caseDetailSchema, {
1213
+ method: "GET",
1214
+ ...(accessToken === undefined ? {} : { headers: { Authorization: `Bearer ${accessToken}` } }),
1215
+ });
1216
+
1217
+ const listCases = (params: { repositoryUrl?: string } = {}): Promise<CaseList> => {
1218
+ const query = new URLSearchParams();
1219
+ if (params.repositoryUrl) query.set("repositoryUrl", params.repositoryUrl);
1220
+ const suffix = query.size > 0 ? `?${query}` : "";
1221
+ return request(`/cases${suffix}`, caseListSchema, { method: "GET" });
1222
+ };
1223
+
1224
+ const registerCase = (accessToken: string, input: RegisterCaseInput): Promise<CaseWriteResponse> =>
1225
+ request("/cases", caseWriteResponseSchema, {
1226
+ method: "POST",
1227
+ headers: { Authorization: `Bearer ${accessToken}` },
1228
+ body: JSON.stringify(input),
1229
+ });
1230
+
1231
+ const publishCase = (
1232
+ accessToken: string,
1233
+ caseId: string,
1234
+ input: PublishCaseInput,
1235
+ ): Promise<CaseWriteResponse> =>
1236
+ request(`/cases/${encodeURIComponent(caseId)}/publish`, caseWriteResponseSchema, {
1237
+ method: "POST",
1238
+ headers: { Authorization: `Bearer ${accessToken}` },
1239
+ body: JSON.stringify(input),
1240
+ });
1241
+
1242
+ const publishCaseVersion = (
1243
+ accessToken: string,
1244
+ caseId: string,
1245
+ input: PublishCaseVersionInput,
1246
+ ): Promise<CaseVersionResponse> =>
1247
+ request(`/cases/${encodeURIComponent(caseId)}/versions`, caseVersionResponseSchema, {
1248
+ method: "POST",
1249
+ headers: { Authorization: `Bearer ${accessToken}` },
1250
+ body: JSON.stringify(input),
1251
+ });
1252
+
1253
+ /**
1254
+ * The path segment serving each structured reference view. Only `rubric` doubles as its own path:
1255
+ * `prerequisites` is served at `/prerequisite-components` (Task 12.5), and `learningObjectives` at
1256
+ * the kebab-case `/learning-objectives` (Task 12a.6b), so neither view name can be used as the
1257
+ * path segment directly.
1258
+ */
1259
+ const referenceViewPaths = {
1260
+ learningObjectives: "learning-objectives",
1261
+ prerequisites: "prerequisite-components",
1262
+ rubric: "rubric",
1263
+ } as const;
1264
+
1265
+ const caseReferences = async (
1266
+ caseId: string,
1267
+ view: keyof typeof referenceViewPaths,
1268
+ ): Promise<ResolvedCaseReference[]> =>
1269
+ (
1270
+ await request(`/cases/${encodeURIComponent(caseId)}/${referenceViewPaths[view]}`, caseReferenceListSchema, {
1271
+ method: "GET",
1272
+ })
1273
+ ).items;
1274
+
1275
+ const getCaseLearningObjectives = (caseId: string): Promise<ResolvedCaseReference[]> =>
1276
+ caseReferences(caseId, "learningObjectives");
1277
+
1278
+ const getCasePrerequisites = (caseId: string): Promise<ResolvedCaseReference[]> => caseReferences(caseId, "prerequisites");
1279
+
1280
+ const getCaseRubric = (caseId: string): Promise<ResolvedCaseReference[]> => caseReferences(caseId, "rubric");
1281
+
1282
+ const createCaseEnrollment = (accessToken: string, caseId: string): Promise<CaseEnrollment> =>
1283
+ request(`/cases/${encodeURIComponent(caseId)}/enrollments`, caseEnrollmentSchema, {
1284
+ method: "POST",
1285
+ headers: { Authorization: `Bearer ${accessToken}` },
1286
+ });
1287
+
1288
+ const getCaseParticipation = (accessToken: string, caseId: string): Promise<CaseParticipation> =>
1289
+ request(`/cases/${encodeURIComponent(caseId)}/enrollments/me`, caseParticipationSchema, {
1290
+ method: "GET",
1291
+ headers: { Authorization: `Bearer ${accessToken}` },
1292
+ });
1293
+
1294
+ const createSubmission = (
1295
+ accessToken: string,
1296
+ input: { caseId: string; prUrl: string; versionRef: string },
1297
+ ): Promise<SubmissionResponse> =>
1298
+ request("/submissions", submissionResponseSchema, {
1299
+ method: "POST",
1300
+ headers: { Authorization: `Bearer ${accessToken}` },
1301
+ body: JSON.stringify(input),
1302
+ });
1303
+
1304
+ const submitEvaluationResults = (
1305
+ accessToken: string,
1306
+ submissionId: string,
1307
+ results: CriterionEvaluationResult[],
1308
+ ): Promise<SubmissionResponse> =>
1309
+ request(`/submissions/${encodeURIComponent(submissionId)}/results`, submissionResponseSchema, {
1310
+ method: "POST",
1311
+ headers: { Authorization: `Bearer ${accessToken}` },
1312
+ body: JSON.stringify({ results }),
1313
+ });
1314
+
1315
+ const submitQuizResult = (
1316
+ accessToken: string,
1317
+ submissionId: string,
1318
+ perQuestionScores: QuestionScoreResult[],
1319
+ ): Promise<SubmissionResponse> =>
1320
+ request(`/submissions/${encodeURIComponent(submissionId)}/quiz-result`, submissionResponseSchema, {
1321
+ method: "POST",
1322
+ headers: { Authorization: `Bearer ${accessToken}` },
1323
+ body: JSON.stringify({ perQuestionScores }),
1324
+ });
1325
+
1326
+ const getKnowledgeTemplates = async (type: ComponentType): Promise<KnowledgeTemplate[]> =>
1327
+ (await request(`/knowledge/templates/${type}`, templateListSchema, { method: "GET" })).items;
1328
+
1329
+ const createKnowledgeComponent = (
1330
+ accessToken: string,
1331
+ type: ComponentType,
1332
+ input: CreateKnowledgeComponentInput,
1333
+ ): Promise<KnowledgeComponent> =>
1334
+ request(`/knowledge/${type}`, knowledgeComponentSchema, {
1335
+ method: "POST",
1336
+ headers: { Authorization: `Bearer ${accessToken}` },
1337
+ body: JSON.stringify(input),
1338
+ });
1339
+
1340
+ const createAlternativeDefinition = (
1341
+ accessToken: string,
1342
+ type: ComponentType,
1343
+ slug: string,
1344
+ input: CreateKnowledgeComponentInput,
1345
+ ): Promise<KnowledgeComponent> =>
1346
+ request(`/knowledge/${type}/${encodeURIComponent(slug)}/alternative-definitions`, knowledgeComponentSchema, {
1347
+ method: "POST",
1348
+ headers: { Authorization: `Bearer ${accessToken}` },
1349
+ body: JSON.stringify(input),
1350
+ });
1351
+
1352
+ const createNewVersion = (
1353
+ accessToken: string,
1354
+ type: ComponentType,
1355
+ slug: string,
1356
+ input: CreateKnowledgeComponentInput,
1357
+ ): Promise<KnowledgeComponent> =>
1358
+ request(`/knowledge/${type}/${encodeURIComponent(slug)}/new-version`, knowledgeComponentSchema, {
1359
+ method: "POST",
1360
+ headers: { Authorization: `Bearer ${accessToken}` },
1361
+ body: JSON.stringify(input),
1362
+ });
1363
+
1364
+ const probeNearDuplicates = async (
1365
+ accessToken: string,
1366
+ type: ComponentType,
1367
+ input: CreateKnowledgeComponentInput,
1368
+ ): Promise<NearDuplicateMatch[]> =>
1369
+ (
1370
+ await request(`/knowledge/${type}/near-duplicate-probe`, nearDuplicateProbeSchema, {
1371
+ method: "POST",
1372
+ headers: { Authorization: `Bearer ${accessToken}` },
1373
+ body: JSON.stringify(input),
1374
+ })
1375
+ ).nearMatches;
1376
+
1377
+ return {
1378
+ refresh,
1379
+ logout,
1380
+ me,
1381
+ meWithRefresh,
1382
+ getHealth,
1383
+ getKnowledgeComponent,
1384
+ searchKnowledgeComponents,
1385
+ getTechnology,
1386
+ createOrResolveTechnology,
1387
+ updateTechnologyDescription,
1388
+ updateTechnologyVersionDescription,
1389
+ listTechnologyCompetences,
1390
+ getCompetence,
1391
+ createCompetence,
1392
+ updateCompetence,
1393
+ deleteCompetence,
1394
+ getCase,
1395
+ listCases,
1396
+ registerCase,
1397
+ publishCase,
1398
+ publishCaseVersion,
1399
+ getCaseLearningObjectives,
1400
+ getCasePrerequisites,
1401
+ getCaseRubric,
1402
+ createCaseEnrollment,
1403
+ getCaseParticipation,
1404
+ createSubmission,
1405
+ submitEvaluationResults,
1406
+ submitQuizResult,
1407
+ getKnowledgeTemplates,
1408
+ createKnowledgeComponent,
1409
+ createAlternativeDefinition,
1410
+ createNewVersion,
1411
+ probeNearDuplicates,
1412
+ };
1413
+ }
1414
+
1415
+ async function toApiError(response: Response): Promise<FitoApiError> {
1416
+ let message = `Request failed (${response.status})`;
1417
+ let properties: { type?: string; duplicateId?: string; supersededBy?: string; matches?: TechnologyNearDuplicateMatch[] } = {};
1418
+ try {
1419
+ const body = problemDetailSchema.parse(await response.json());
1420
+ message = body.detail ?? body.title ?? message;
1421
+ properties = { type: body.type, duplicateId: body.duplicateId, supersededBy: body.supersededBy, matches: body.matches };
1422
+ } catch {
1423
+ // Non-JSON or unexpected body — keep the status-based fallback message.
1424
+ }
1425
+ return new FitoApiError(message, response.status, properties);
1426
+ }