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,895 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * The `.case/` **structural** validator — the canonical executable ruleset for the
5
+ * Fito profile of Case Structure Spec v0.3 (`specs_and_tasks/SPEC.md` §Case Structure,
6
+ * the narrative spec). It enforces every `.case/` rule that is a pure function of the
7
+ * repo bytes; it does **not** resolve `knowledge_component` references against the
8
+ * backend — reference *existence* is the Case Registry's job (Task 3.3). Branch/tag
9
+ * existence is confirmed by the backend reachability ping (Task 3.3), not here.
10
+ *
11
+ * Per ADR-005 (Hybrid-H0) this runs against a **local checkout only**. It emits a
12
+ * structural attestation (stamped with `RULESET_VERSION`) plus the extracted, deduped
13
+ * `(componentId, bloomLevel)` reference set, both consumed by the backend publish
14
+ * contract (Tasks 9.2/9.3 → 3.3) and re-run as the consumption-time backstop (Task 5.2).
15
+ *
16
+ * This module is pure (no filesystem access). `case-loader.ts` reads + parses the
17
+ * `.case/` files on disk and feeds the parsed content here.
18
+ */
19
+
20
+ /** Stamped into every attestation; bump when the validator implementation changes. */
21
+ export const VALIDATOR_VERSION = "0.1.8";
22
+ /** Stamped into every attestation; bump when the ruleset (the rules below) changes (ADR-005 §4). */
23
+ export const RULESET_VERSION = "1.8.0";
24
+
25
+ // ── Shared building blocks ────────────────────────────────────────────────────
26
+
27
+ /**
28
+ * 3-level Fito Bloom taxonomy (SPEC deviation #4) — used in rubric/learning_objectives/prerequisites/quiz.
29
+ * Declared lowest to highest, and the order is load-bearing: the reachability rule in
30
+ * `validateCaseContent` compares levels by their position here.
31
+ */
32
+ export const BLOOM_LEVELS = ["KNOWLEDGE", "COMPREHENSION", "APPLICATION"] as const;
33
+ export const bloomLevelSchema = z.enum(BLOOM_LEVELS);
34
+ export type BloomLevel = z.infer<typeof bloomLevelSchema>;
35
+
36
+ /** A lowercased, dash-joined slug segment (e.g. `git`, `requires-known-good-commit`). */
37
+ const SLUG = "[a-z0-9]+(?:-[a-z0-9]+)*";
38
+
39
+ /**
40
+ * A single, well-formed knowledge-component reference: a `concept:`/`execution-fact:`/
41
+ * `usage-scenario:` prefix followed by `<tech-slug>.<component-slug>` (>= 2 dot-joined
42
+ * slug segments; the component slug may itself contain dots). Existence and type are
43
+ * resolved on the backend, never here.
44
+ */
45
+ export const KNOWLEDGE_COMPONENT_REF = new RegExp(
46
+ `^(?:concept|execution-fact|usage-scenario):${SLUG}(?:\\.${SLUG})+$`,
47
+ );
48
+ export const knowledgeComponentRefSchema = z
49
+ .string()
50
+ .regex(
51
+ KNOWLEDGE_COMPONENT_REF,
52
+ "must be a single well-formed knowledge-component reference, e.g. concept:git.bisect",
53
+ );
54
+
55
+ /**
56
+ * **The topic-not-move rule** (`SPEC.md` §What a readable case file may say). The `description`
57
+ * fields below are prose a learner reads: the tutor is briefed from these files, and the public
58
+ * storefront pitch is drafted from `learning_objectives.yaml`. Such a description may state what is broken
59
+ * and what the goal is; it must not state the move that repairs it. The test is one question —
60
+ * *could a learner who read only this description, and nothing else from the case, apply the fix?*
61
+ * `tutorial` cases are exempt: their `task/steps.md` *is* the method, so there is no repair to
62
+ * withhold. `rubric.yaml` is exempt too — it is never served to a briefing, and a scoring level
63
+ * cannot describe an exemplary answer without naming what that answer does.
64
+ *
65
+ * **Zod cannot enforce this**, and every field the rule binds stays `z.string().optional()`: a case
66
+ * that violates it validates clean. Two things keep the check out of this file, and neither is
67
+ * "the bytes are not there" — a checkout carries `solution/notes.md`, and `validateCaseContent`
68
+ * already runs cross-file rules over it. **A mechanical comparison flags; it does not decide.**
69
+ * Overlap against the solution's wording catches a real leak and also fires on a title and tags
70
+ * that name the topic on purpose, so its output is a candidate list for an author, not a verdict.
71
+ * **And this function is the learner's backstop** — `skills/fito-case-runner/open.ts` runs
72
+ * `validateCaseDir` on every `/fito-case-open` — so a leak warning raised here would tell a learner
73
+ * that their case gives away its own answer, and where. The author-side checker is registered as
74
+ * `DI6` in the plan; until it exists the rule is carried by the authoring prompts and by review.
75
+ */
76
+
77
+ /** The three case types — validated on `manifest.type`. */
78
+ export const CASE_TYPES = ["diagnostic", "implementation", "tutorial"] as const;
79
+ export const caseTypeSchema = z.enum(CASE_TYPES);
80
+
81
+ /** SemVer 2.0.0 grammar (matches the backend `CaseProject` version check). */
82
+ const SEMVER =
83
+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
84
+
85
+ // ── Per-file schemas ──────────────────────────────────────────────────────────
86
+
87
+ /**
88
+ * `manifest.yaml` — classification/presentation. The case identity is the backend-assigned id
89
+ * (a UUID), not carried in the `.case/` repo; `taxonomy_version` is dropped (deviation #1).
90
+ */
91
+ export const manifestSchema = z
92
+ .object({
93
+ title: z.string().min(1),
94
+ type: caseTypeSchema,
95
+ version: z.string().regex(SEMVER, "manifest.version must be a valid semantic version"),
96
+ status: z.enum(["draft", "review", "published", "deprecated"]),
97
+ estimated_duration_minutes: z.number().int().positive(),
98
+ language: z.string().min(2),
99
+ tags: z.array(z.string()),
100
+ authors: z
101
+ .array(z.object({ name: z.string().min(1), email: z.string().min(1), role: z.string().optional() }))
102
+ .min(1),
103
+ created_at: z.union([z.string(), z.date()]).optional(),
104
+ updated_at: z.union([z.string(), z.date()]).optional(),
105
+ submission: z.object({
106
+ method: z.literal("pull_request"),
107
+ target_branch: z.string().min(1),
108
+ student_branch: z.string().min(1),
109
+ }),
110
+ deprecated_reason: z.string().optional(),
111
+ })
112
+ .superRefine((m, ctx) => {
113
+ if (m.status === "deprecated" && !m.deprecated_reason) {
114
+ ctx.addIssue({
115
+ code: "custom",
116
+ path: ["deprecated_reason"],
117
+ message: "deprecated_reason is required when status is deprecated",
118
+ });
119
+ }
120
+ });
121
+
122
+ export const artifactRoleSchema = z.enum(["evidence", "target", "reference", "scaffold", "do-not-touch"]);
123
+ /**
124
+ * `artifacts.yaml` — annotated map of relevant repo files. Each `description` is bound by the
125
+ * topic-not-move rule above, which nothing here can check.
126
+ */
127
+ export const artifactsSchema = z.object({
128
+ artifacts: z.array(
129
+ z.object({ path: z.string().min(1), role: artifactRoleSchema, description: z.string().optional() }),
130
+ ),
131
+ });
132
+
133
+ export const learningObjectiveWeightSchema = z.enum(["primary", "secondary"]);
134
+ /**
135
+ * `learning_objectives.yaml` — skills the case develops; >= 1 must be `primary`. Each `description` is
136
+ * bound by the topic-not-move rule above, which nothing here can check — and this file's prose
137
+ * travels furthest, since the public storefront pitch is drafted from it.
138
+ */
139
+ export const learningObjectivesSchema = z
140
+ .object({
141
+ learning_objectives: z
142
+ .array(
143
+ z.object({
144
+ knowledge_component: knowledgeComponentRefSchema,
145
+ bloom_level: bloomLevelSchema,
146
+ description: z.string().optional(),
147
+ weight: learningObjectiveWeightSchema,
148
+ }),
149
+ )
150
+ .min(1),
151
+ })
152
+ .superRefine((c, ctx) => {
153
+ if (!c.learning_objectives.some((entry) => entry.weight === "primary")) {
154
+ ctx.addIssue({
155
+ code: "custom",
156
+ path: ["learning_objectives"],
157
+ message: "at least one learning objective must have weight: primary",
158
+ });
159
+ }
160
+ });
161
+
162
+ /**
163
+ * `prerequisites.yaml` — skills the student must already have (Fito uses `knowledge_component`,
164
+ * deviation #1). Each `description` is bound by the topic-not-move rule above, which nothing here
165
+ * can check.
166
+ */
167
+ export const prerequisitesSchema = z.object({
168
+ prerequisites: z.array(
169
+ z.object({
170
+ knowledge_component: knowledgeComponentRefSchema,
171
+ bloom_level: bloomLevelSchema,
172
+ description: z.string().optional(),
173
+ mandatory: z.boolean(),
174
+ }),
175
+ ),
176
+ });
177
+
178
+ /** `rubric.yaml` evaluation methods (automated/ai/human/hybrid). */
179
+ export const evaluationMethodSchema = z.discriminatedUnion("type", [
180
+ z.object({ type: z.literal("automated"), command: z.string().min(1), passing_condition: z.string().min(1) }),
181
+ z.object({ type: z.literal("ai"), prompt_hint: z.string().min(1) }),
182
+ z.object({ type: z.literal("human"), guidance: z.string().optional() }),
183
+ z.object({
184
+ type: z.literal("hybrid"),
185
+ automated: z.object({ command: z.string().min(1), passing_condition: z.string().min(1) }),
186
+ on_pass: z.string().min(1),
187
+ on_fail: z.enum(["ai", "human"]),
188
+ fallback_prompt_hint: z.string().optional(),
189
+ }),
190
+ ]);
191
+
192
+ export const rubricLevelSchema = z.object({
193
+ score: z.number().int(),
194
+ label: z.string().min(1),
195
+ description: z.string().min(1),
196
+ });
197
+
198
+ /** `rubric.yaml` — criterion weights sum to exactly 100; each criterion's levels cover {0,1,2,3}. */
199
+ export const rubricSchema = z
200
+ .object({
201
+ criteria: z
202
+ .array(
203
+ z.object({
204
+ id: z.string().min(1),
205
+ title: z.string().min(1),
206
+ knowledge_component: knowledgeComponentRefSchema,
207
+ bloom_level: bloomLevelSchema,
208
+ weight: z.number().int().positive("rubric criterion weight must be a positive integer"),
209
+ levels: z.array(rubricLevelSchema),
210
+ evaluation_method: evaluationMethodSchema,
211
+ }),
212
+ )
213
+ .min(1),
214
+ })
215
+ .superRefine((r, ctx) => {
216
+ const total = r.criteria.reduce((sum, c) => sum + c.weight, 0);
217
+ if (total !== 100) {
218
+ ctx.addIssue({
219
+ code: "custom",
220
+ path: ["criteria"],
221
+ message: `rubric criterion weights must sum to exactly 100 (got ${total})`,
222
+ });
223
+ }
224
+ r.criteria.forEach((c, i) => {
225
+ const scores = new Set(c.levels.map((l) => l.score));
226
+ if (![0, 1, 2, 3].every((s) => scores.has(s))) {
227
+ ctx.addIssue({
228
+ code: "custom",
229
+ path: ["criteria", i, "levels"],
230
+ message: `criterion "${c.id}" levels must cover scores 0, 1, 2, and 3`,
231
+ });
232
+ }
233
+ });
234
+ });
235
+
236
+ /** `solution.yaml` — exemplar branch reference + visibility. */
237
+ export const solutionSchema = z.object({
238
+ branch: z.string().min(1),
239
+ visibility: z.enum(["never", "post_completion", "always"]),
240
+ notes: z.string().min(1),
241
+ acceptable_solutions: z
242
+ .array(z.object({ id: z.string().min(1), branch: z.string().min(1), description: z.string().optional() }))
243
+ .optional(),
244
+ });
245
+
246
+ /** `situation/situation.yaml` — document manifest. */
247
+ export const situationFormatSchema = z.enum([
248
+ "prose",
249
+ "ticket",
250
+ "email",
251
+ "pull_request_description",
252
+ "chat_thread",
253
+ "log_output",
254
+ ]);
255
+ export const situationSchema = z.object({
256
+ documents: z
257
+ .array(z.object({ file: z.string().min(1), title: z.string().min(1), format: situationFormatSchema }))
258
+ .min(1),
259
+ });
260
+
261
+ export const deliverableTypeSchema = z.enum([
262
+ "code_change",
263
+ "new_file",
264
+ "tests_passing",
265
+ "written_explanation",
266
+ "configuration_change",
267
+ "test_written",
268
+ "refactoring",
269
+ "documentation",
270
+ "dependency_change",
271
+ ]);
272
+ /**
273
+ * `task/deliverables.yaml` — expected outputs. Each `description` is bound by the topic-not-move
274
+ * rule above, which nothing here can check.
275
+ */
276
+ export const deliverablesSchema = z.object({
277
+ deliverables: z
278
+ .array(
279
+ z.object({
280
+ type: deliverableTypeSchema,
281
+ description: z.string().optional(),
282
+ path: z.string().optional(),
283
+ target: z.string().optional(),
284
+ }),
285
+ )
286
+ .min(1),
287
+ });
288
+
289
+ /**
290
+ * `starter_state/known_state.yaml` — machine-readable baseline (all fields optional; case-type
291
+ * rules read it). No `branch` field (SPEC deviation #5): under the `.case/` parity invariant the
292
+ * same file describes the case on every ref, so a branch value cannot be per-branch-correct.
293
+ * Deliberately non-strict — frozen refs published before the removal still carry `branch`, and
294
+ * unknown keys are stripped, never rejected.
295
+ */
296
+ export const knownStateSchema = z.object({
297
+ failing_tests: z.array(z.string()).optional(),
298
+ missing_implementations: z
299
+ .array(z.object({ path: z.string(), description: z.string().optional() }))
300
+ .optional(),
301
+ known_errors: z.array(z.object({ type: z.string(), description: z.string() })).optional(),
302
+ build_status: z.enum(["passing", "failing", "not_applicable"]).optional(),
303
+ lint_errors: z.boolean().optional(),
304
+ coverage_baseline: z.object({ path: z.string(), percentage: z.number() }).optional(),
305
+ });
306
+
307
+ /** `quiz.yaml` (OPTIONAL, Fito addition #2) — each question references >= 1 component + a Bloom level + type-specific fields. */
308
+ export const quizQuestionTypeSchema = z.enum(["multiple_choice", "short_answer", "code_snippet"]);
309
+ export const quizSchema = z
310
+ .object({
311
+ questions: z
312
+ .array(
313
+ z.object({
314
+ id: z.string().min(1),
315
+ type: quizQuestionTypeSchema,
316
+ prompt: z.string().min(1),
317
+ knowledge_components: z.array(knowledgeComponentRefSchema).min(1),
318
+ bloom_level: bloomLevelSchema,
319
+ weight: z.number().int().positive("quiz question weight must be a positive integer").optional(),
320
+ choices: z.array(z.object({ id: z.string().min(1), text: z.string().min(1) })).optional(),
321
+ // MVP: a multiple_choice answer is a single choice id. Multi-select (array) answers
322
+ // are rejected — the SPEC says the answer references "one of its choices", and the
323
+ // backend `QuestionDto.answer` / domain `Question.answer` are a single string.
324
+ answer: z
325
+ .string("a multiple_choice answer must be a single choice id; multiple answers are not supported for MVP")
326
+ .optional(),
327
+ evaluation: z
328
+ .object({ method: z.enum(["ai", "human"]), prompt_hint: z.string().optional() })
329
+ .optional(),
330
+ }),
331
+ )
332
+ .min(1),
333
+ })
334
+ .superRefine((q, ctx) => {
335
+ q.questions.forEach((question, i) => {
336
+ if (question.type === "multiple_choice") {
337
+ if (!question.choices || question.choices.length === 0) {
338
+ ctx.addIssue({
339
+ code: "custom",
340
+ path: ["questions", i, "choices"],
341
+ message: `multiple_choice question "${question.id}" must define choices`,
342
+ });
343
+ }
344
+ if (question.answer === undefined) {
345
+ ctx.addIssue({
346
+ code: "custom",
347
+ path: ["questions", i, "answer"],
348
+ message: `multiple_choice question "${question.id}" must define an answer`,
349
+ });
350
+ } else if (question.choices && question.choices.length > 0) {
351
+ const choiceIds = new Set(question.choices.map((choice) => choice.id));
352
+ if (!choiceIds.has(question.answer)) {
353
+ ctx.addIssue({
354
+ code: "custom",
355
+ path: ["questions", i, "answer"],
356
+ message: `multiple_choice question "${question.id}" answer "${question.answer}" does not match any choice id`,
357
+ });
358
+ }
359
+ }
360
+ } else if (!question.evaluation) {
361
+ ctx.addIssue({
362
+ code: "custom",
363
+ path: ["questions", i, "evaluation"],
364
+ message: `${question.type} question "${question.id}" must define an evaluation (ai or human)`,
365
+ });
366
+ }
367
+ });
368
+ });
369
+
370
+ // ── Always-required `.case/` files (paths relative to `.case/`) ───────────────
371
+
372
+ /**
373
+ * The learning-objectives file and its root key, each beside the name it carried until Tasks 12a.4
374
+ * and 12a.4b renamed it.
375
+ *
376
+ * There is **no fallback read** for either — `loadCaseDir` opens the current file name and nothing
377
+ * else, and the schema knows only the current key. The old names survive here as signposts: a tree
378
+ * still carrying one fails naming the rename, rather than reporting a file missing while its
379
+ * predecessor sits unread beside it, or an array missing while its predecessor sits stripped.
380
+ */
381
+ const LEARNING_OBJECTIVES_FILE = "learning_objectives.yaml";
382
+ const FORMER_LEARNING_OBJECTIVES_FILE = "competencies.yaml";
383
+ const LEARNING_OBJECTIVES_KEY = "learning_objectives";
384
+ const FORMER_LEARNING_OBJECTIVES_KEY = "competencies";
385
+
386
+ /** Files that must always be present; `task/steps.md` is conditionally required for `tutorial` cases. */
387
+ export const REQUIRED_FILES = [
388
+ "manifest.yaml",
389
+ "artifacts.yaml",
390
+ "learning_objectives.yaml",
391
+ "prerequisites.yaml",
392
+ "rubric.yaml",
393
+ "solution.yaml",
394
+ "situation/situation.yaml",
395
+ "situation/01_intro.md",
396
+ "task/objective.md",
397
+ "task/deliverables.yaml",
398
+ "starter_state/description.md",
399
+ "starter_state/known_state.yaml",
400
+ "solution/notes.md",
401
+ "solution/notes-template.md",
402
+ ] as const;
403
+
404
+ // ── Public result shapes ──────────────────────────────────────────────────────
405
+
406
+ /** A single extracted `(componentId, bloomLevel)` reference (the backend resolves existence). */
407
+ export interface ComponentReference {
408
+ componentId: string;
409
+ bloomLevel: BloomLevel;
410
+ }
411
+
412
+ /** Structural attestation emitted on a passing validation (ADR-005 §4). */
413
+ export interface Attestation {
414
+ pass: true;
415
+ validatorVersion: string;
416
+ rulesetVersion: string;
417
+ }
418
+
419
+ /** One structural error, scoped to the file (and field path) that produced it. */
420
+ export interface ValidationError {
421
+ file: string;
422
+ message: string;
423
+ path?: (string | number)[];
424
+ }
425
+
426
+ export type ValidationResult =
427
+ | { ok: true; attestation: Attestation; references: ComponentReference[] }
428
+ | { ok: false; errors: ValidationError[] };
429
+
430
+ /** Parsed `.case/` content, keyed by concern. YAML files absent on disk are `undefined`. */
431
+ export interface CaseContent {
432
+ manifest?: unknown;
433
+ artifacts?: unknown;
434
+ learningObjectives?: unknown;
435
+ prerequisites?: unknown;
436
+ rubric?: unknown;
437
+ solution?: unknown;
438
+ situation?: unknown;
439
+ deliverables?: unknown;
440
+ knownState?: unknown;
441
+ quiz?: unknown;
442
+ }
443
+
444
+ export interface ValidateInput {
445
+ content: CaseContent;
446
+ presentFiles: ReadonlySet<string>;
447
+ }
448
+
449
+ interface ParsedCase {
450
+ manifest?: z.infer<typeof manifestSchema>;
451
+ artifacts?: z.infer<typeof artifactsSchema>;
452
+ learningObjectives?: z.infer<typeof learningObjectivesSchema>;
453
+ prerequisites?: z.infer<typeof prerequisitesSchema>;
454
+ rubric?: z.infer<typeof rubricSchema>;
455
+ solution?: z.infer<typeof solutionSchema>;
456
+ situation?: z.infer<typeof situationSchema>;
457
+ deliverables?: z.infer<typeof deliverablesSchema>;
458
+ knownState?: z.infer<typeof knownStateSchema>;
459
+ quiz?: z.infer<typeof quizSchema>;
460
+ }
461
+
462
+ // ── Validation orchestration ──────────────────────────────────────────────────
463
+
464
+ /**
465
+ * Validate already-parsed `.case/` content against the structural ruleset. Collects
466
+ * *all* errors (never fail-fast) so callers see every rule violation at once. On
467
+ * success, emits the attestation + the deduped reference set.
468
+ */
469
+ export function validateCaseContent(input: ValidateInput): ValidationResult {
470
+ const { content, presentFiles } = input;
471
+ const errors: ValidationError[] = [];
472
+
473
+ // Rule 1 — the learning-objectives file carries its current name (Task 12a.4). Stated before the
474
+ // required-file loop it modifies, so it also heads the error list a human reads. It fires whether
475
+ // or not the new name is also present, catching a migration that copied rather than moved.
476
+ const carriesFormerLearningObjectivesName = presentFiles.has(FORMER_LEARNING_OBJECTIVES_FILE);
477
+ if (carriesFormerLearningObjectivesName) {
478
+ errors.push({
479
+ file: FORMER_LEARNING_OBJECTIVES_FILE,
480
+ message: `${FORMER_LEARNING_OBJECTIVES_FILE} was renamed to ${LEARNING_OBJECTIVES_FILE} — rename .case/${FORMER_LEARNING_OBJECTIVES_FILE} to .case/${LEARNING_OBJECTIVES_FILE}`,
481
+ });
482
+ }
483
+
484
+ // Rule 2 — the learning-objectives file carries its current root key (Task 12a.4b). Beside the
485
+ // file-name rule because they are two halves of one rename family, and it fires whether or not
486
+ // the new key is also present — catching an edit that copied the first line rather than
487
+ // replacing it, which is the mistake Task 12a.5's four hand-edits can make.
488
+ const carriesFormerLearningObjectivesKey =
489
+ isRecord(content.learningObjectives) && FORMER_LEARNING_OBJECTIVES_KEY in content.learningObjectives;
490
+ if (carriesFormerLearningObjectivesKey) {
491
+ errors.push({
492
+ file: LEARNING_OBJECTIVES_FILE,
493
+ message: `the ${FORMER_LEARNING_OBJECTIVES_KEY}: root key was renamed to ${LEARNING_OBJECTIVES_KEY}: — rename it in .case/${LEARNING_OBJECTIVES_FILE}`,
494
+ });
495
+ }
496
+
497
+ // Rule 3 — required files present on disk.
498
+ for (const file of REQUIRED_FILES) {
499
+ // The rename signpost above stands in for this file's missing-file line, rather than
500
+ // doubling it — one rule, one message.
501
+ if (file === LEARNING_OBJECTIVES_FILE && carriesFormerLearningObjectivesName) continue;
502
+ if (!presentFiles.has(file)) {
503
+ errors.push({ file, message: `required file ${file} is missing from .case/` });
504
+ }
505
+ }
506
+
507
+ // Per-file shape (+ per-file cross-field rules live in each schema's superRefine).
508
+ const parsed: ParsedCase = {};
509
+ const runSchema = <T>(
510
+ file: string,
511
+ schema: z.ZodType<T>,
512
+ raw: unknown,
513
+ assign: (value: T) => void,
514
+ ): void => {
515
+ if (raw === undefined) return; // missing required files are reported above; optional files are skipped
516
+ const result = schema.safeParse(raw);
517
+ if (result.success) {
518
+ assign(result.data);
519
+ } else {
520
+ for (const issue of result.error.issues) {
521
+ errors.push({ file, message: issue.message, path: issue.path as (string | number)[] });
522
+ }
523
+ }
524
+ };
525
+
526
+ runSchema("manifest.yaml", manifestSchema, content.manifest, (v) => (parsed.manifest = v));
527
+ runSchema("artifacts.yaml", artifactsSchema, content.artifacts, (v) => (parsed.artifacts = v));
528
+ // The root-key signpost stands in for this file's shape errors rather than doubling them: an
529
+ // old-key file is stripped to `{}` and would otherwise also report a missing array.
530
+ if (!carriesFormerLearningObjectivesKey) {
531
+ runSchema(
532
+ "learning_objectives.yaml",
533
+ learningObjectivesSchema,
534
+ content.learningObjectives,
535
+ (v) => (parsed.learningObjectives = v),
536
+ );
537
+ }
538
+ runSchema("prerequisites.yaml", prerequisitesSchema, content.prerequisites, (v) => (parsed.prerequisites = v));
539
+ runSchema("rubric.yaml", rubricSchema, content.rubric, (v) => (parsed.rubric = v));
540
+ runSchema("solution.yaml", solutionSchema, content.solution, (v) => (parsed.solution = v));
541
+ runSchema("situation/situation.yaml", situationSchema, content.situation, (v) => (parsed.situation = v));
542
+ runSchema("task/deliverables.yaml", deliverablesSchema, content.deliverables, (v) => (parsed.deliverables = v));
543
+ runSchema("starter_state/known_state.yaml", knownStateSchema, content.knownState, (v) => (parsed.knownState = v));
544
+ if (content.quiz !== undefined) {
545
+ runSchema("quiz.yaml", quizSchema, content.quiz, (v) => (parsed.quiz = v));
546
+ }
547
+
548
+ // Referenced situation documents must exist on disk (paths are relative to situation/).
549
+ for (const doc of parsed.situation?.documents ?? []) {
550
+ const rel = `situation/${doc.file}`;
551
+ if (!presentFiles.has(rel)) {
552
+ errors.push({
553
+ file: "situation/situation.yaml",
554
+ message: `situation document "${doc.file}" is missing from .case/ (expected ${rel})`,
555
+ });
556
+ }
557
+ }
558
+
559
+ // Every learning objective carries at least one rubric criterion (Task 17.1). The rubric is what
560
+ // scores the work, so an objective no criterion names can never award a proficiency — while the
561
+ // backend still recommends this case to a learner missing that component, on the strength of the
562
+ // learning-objective edge alone. A quiz question does not satisfy this: the quiz is optional, and
563
+ // its weights sum to nothing in particular. The match is on the component alone; the rule below
564
+ // compares Bloom levels. Stated per uncovered objective rather than once, so an author sees every
565
+ // gap in one run.
566
+ //
567
+ // Every learning objective is reachable at its own level (Task 17.10): at least one criterion on
568
+ // its component declares a `bloom_level` at least as high as the objective's. A score of 2 or 3
569
+ // awards the criterion's declared level and nothing above it, so an objective whose criteria all
570
+ // sit lower can never be certified. An ordering, not an equality — an APPLICATION criterion covers
571
+ // a COMPREHENSION objective. Only a criterion counts, for the reasons above. An objective with no
572
+ // criterion at all is reported by the coverage rule alone — one gap, one message.
573
+ if (parsed.learningObjectives && parsed.rubric) {
574
+ const criteria = parsed.rubric.criteria;
575
+ for (const objective of parsed.learningObjectives.learning_objectives) {
576
+ const onComponent = criteria.filter((c) => c.knowledge_component === objective.knowledge_component);
577
+ if (onComponent.length === 0) {
578
+ errors.push({
579
+ file: LEARNING_OBJECTIVES_FILE,
580
+ message: `learning objective "${objective.knowledge_component}" must have at least one rubric criterion`,
581
+ });
582
+ continue;
583
+ }
584
+ const needed = BLOOM_LEVELS.indexOf(objective.bloom_level);
585
+ if (!onComponent.some((c) => BLOOM_LEVELS.indexOf(c.bloom_level) >= needed)) {
586
+ const reaching = BLOOM_LEVELS.slice(needed).join(" or ");
587
+ errors.push({
588
+ file: LEARNING_OBJECTIVES_FILE,
589
+ message: `learning objective "${objective.knowledge_component}" is ${objective.bloom_level}, so at least one of its rubric criteria must declare bloom_level ${reaching} — a criterion awards no more than the level it declares`,
590
+ });
591
+ }
592
+ }
593
+ }
594
+
595
+ // Cross-file case-type constraints (run only when the manifest type validated).
596
+ const type = parsed.manifest?.type;
597
+ if (type === "diagnostic") {
598
+ const ks = parsed.knownState;
599
+ const hasFailing = (ks?.failing_tests?.length ?? 0) > 0;
600
+ const hasErrors = (ks?.known_errors?.length ?? 0) > 0;
601
+ if (!hasFailing && !hasErrors) {
602
+ errors.push({
603
+ file: "starter_state/known_state.yaml",
604
+ message: "diagnostic cases must declare at least one failing_tests or known_errors entry in known_state.yaml",
605
+ });
606
+ }
607
+ } else if (type === "implementation") {
608
+ const hasCodeChange = (parsed.deliverables?.deliverables ?? []).some((d) => d.type === "code_change");
609
+ if (!hasCodeChange) {
610
+ errors.push({
611
+ file: "task/deliverables.yaml",
612
+ message: "implementation cases must include at least one code_change deliverable",
613
+ });
614
+ }
615
+ } else if (type === "tutorial") {
616
+ if (!presentFiles.has("task/steps.md")) {
617
+ errors.push({ file: "task/steps.md", message: "tutorial cases must include task/steps.md" });
618
+ }
619
+ if ((parsed.knownState?.failing_tests?.length ?? 0) > 0) {
620
+ errors.push({
621
+ file: "starter_state/known_state.yaml",
622
+ message: "tutorial cases must not declare failing_tests in known_state.yaml",
623
+ });
624
+ }
625
+ }
626
+
627
+ if (errors.length > 0) {
628
+ return { ok: false, errors };
629
+ }
630
+ return {
631
+ ok: true,
632
+ attestation: { pass: true, validatorVersion: VALIDATOR_VERSION, rulesetVersion: RULESET_VERSION },
633
+ references: extractReferences(parsed),
634
+ };
635
+ }
636
+
637
+ /**
638
+ * Extract the deduped `(componentId, bloomLevel)` reference set from the four
639
+ * reference-bearing files (learning objectives + prerequisites + rubric + quiz). Only
640
+ * well-formedness has been checked; the backend resolves existence (Task 3.3).
641
+ */
642
+ function extractReferences(parsed: ParsedCase): ComponentReference[] {
643
+ const refs: ComponentReference[] = [];
644
+ for (const c of parsed.learningObjectives?.learning_objectives ?? []) {
645
+ refs.push({ componentId: c.knowledge_component, bloomLevel: c.bloom_level });
646
+ }
647
+ for (const p of parsed.prerequisites?.prerequisites ?? []) {
648
+ refs.push({ componentId: p.knowledge_component, bloomLevel: p.bloom_level });
649
+ }
650
+ for (const cr of parsed.rubric?.criteria ?? []) {
651
+ refs.push({ componentId: cr.knowledge_component, bloomLevel: cr.bloom_level });
652
+ }
653
+ for (const q of parsed.quiz?.questions ?? []) {
654
+ for (const kc of q.knowledge_components) {
655
+ refs.push({ componentId: kc, bloomLevel: q.bloom_level });
656
+ }
657
+ }
658
+ const seen = new Set<string>();
659
+ return refs.filter((r) => {
660
+ const key = `${r.componentId}\0${r.bloomLevel}`;
661
+ if (seen.has(key)) return false;
662
+ seen.add(key);
663
+ return true;
664
+ });
665
+ }
666
+
667
+ // ── The optional-field inventory (Task 11.10) ─────────────────────────────────
668
+
669
+ /**
670
+ * **What the validator can never reject.** Every rejectable rule above teaches its own fix —
671
+ * each enum error lists every legal value, each cross-file rule states itself in English, and
672
+ * every error carries a `path`. But an **optional field is never rejected**, so the ~20 optional
673
+ * fields of the `.case/` contract are invisible to the `/fito-case-generate` loop forever. The
674
+ * inventory closes that hole: the schema-derived list of optional fields a case does not use.
675
+ * Nothing is rejected — an unused optional field stays legal; the author sees it and decides.
676
+ *
677
+ * **It is deliberately not part of `ValidationResult`.** `validateCaseDir` is shared with the
678
+ * learner — `skills/fito-case-runner/open.ts` runs it as the consumption-time backstop on every
679
+ * `/fito-case-open` — so a line in the result type would tell a *learner* opening a case that its
680
+ * `coverage_baseline` is unfilled. The only caller is the authoring CLI,
681
+ * `skills/fito-case-author/validate.ts`, which nothing on the learner path invokes.
682
+ *
683
+ * Unused optional field paths, keyed by their `.case/`-relative file. Files with none are absent.
684
+ */
685
+ export type OptionalFieldInventory = Record<string, string[]>;
686
+
687
+ /**
688
+ * `io: "input"` because the author writes the *input* shape. `unrepresentable: "any"` is
689
+ * **required, not cosmetic**: `manifestSchema` carries `z.union([z.string(), z.date()])` on
690
+ * `created_at`, and the default `"throw"` kills the whole derivation with
691
+ * *"Date cannot be represented in JSON Schema"*.
692
+ */
693
+ const TO_JSON_SCHEMA_OPTIONS = { io: "input", unrepresentable: "any" } as const;
694
+
695
+ /** The subset of JSON Schema the walk below reads. */
696
+ interface JsonSchemaNode {
697
+ type?: string;
698
+ properties?: Record<string, JsonSchemaNode>;
699
+ required?: string[];
700
+ items?: JsonSchemaNode;
701
+ oneOf?: JsonSchemaNode[];
702
+ anyOf?: JsonSchemaNode[];
703
+ const?: unknown;
704
+ }
705
+
706
+ function isRecord(value: unknown): value is Record<string, unknown> {
707
+ return typeof value === "object" && value !== null && !Array.isArray(value);
708
+ }
709
+
710
+ /**
711
+ * The union's discriminator: the one property carrying a `const` in **every** branch, with a
712
+ * distinct value in each. `z.discriminatedUnion` renders exactly that. Resolving the key first
713
+ * — rather than accepting whichever branch happens to hold a matching `const` — keeps the match
714
+ * correct for a union whose branches also carry an unrelated literal field.
715
+ */
716
+ function discriminatorKey(branches: JsonSchemaNode[]): string | undefined {
717
+ const first = branches[0]?.properties;
718
+ if (!first) return undefined;
719
+ return Object.keys(first).find((key) => {
720
+ const consts = branches.map((branch) => branch.properties?.[key]?.const);
721
+ return consts.every((value) => value !== undefined) && new Set(consts).size === branches.length;
722
+ });
723
+ }
724
+
725
+ /**
726
+ * The union branch the value actually uses, labelled by its discriminator value (rule B) —
727
+ * never by array index, which would label a report `evaluation_method.<3>` instead of
728
+ * `evaluation_method(hybrid)`. A union with no discriminator (a plain `z.union`, rendered as
729
+ * `anyOf`) has no branch label to give and is skipped.
730
+ */
731
+ function matchingBranch(
732
+ branches: JsonSchemaNode[],
733
+ value: unknown,
734
+ ): { branch: JsonSchemaNode; label: string } | undefined {
735
+ const key = discriminatorKey(branches);
736
+ if (key === undefined || !isRecord(value)) return undefined;
737
+ for (const branch of branches) {
738
+ const literal = branch.properties?.[key]?.const;
739
+ if (value[key] === literal) return { branch, label: String(literal) };
740
+ }
741
+ return undefined;
742
+ }
743
+
744
+ /**
745
+ * Walk `node` against `value`, appending every optional path to `empty` or to `filled`.
746
+ * Array elements all walk under the same `[]` prefix, so one path can land in both lists —
747
+ * which is what makes an array's verdict a set subtraction rather than a per-element answer.
748
+ */
749
+ function collectOptionalPaths(
750
+ node: JsonSchemaNode,
751
+ value: unknown,
752
+ prefix: string,
753
+ empty: string[],
754
+ filled: string[],
755
+ ): void {
756
+ const branches = node.oneOf ?? node.anyOf;
757
+ if (branches) {
758
+ const used = matchingBranch(branches, value);
759
+ // Rule B — the branches the case does not use contribute nothing.
760
+ if (!used) return;
761
+ const base = prefix.endsWith(".") ? prefix.slice(0, -1) : prefix;
762
+ collectOptionalPaths(used.branch, value, `${base}(${used.label}).`, empty, filled);
763
+ return;
764
+ }
765
+
766
+ if (node.type === "object" && node.properties) {
767
+ const required = new Set(node.required ?? []);
768
+ for (const [key, property] of Object.entries(node.properties)) {
769
+ const child = isRecord(value) ? value[key] : undefined;
770
+ if (child === undefined) {
771
+ // Rule A — an absent optional parent is named once; its children are not walked.
772
+ // A *required* field that is absent is a validation error, never an inventory line.
773
+ if (!required.has(key)) empty.push(`${prefix}${key}`);
774
+ continue;
775
+ }
776
+ if (!required.has(key)) filled.push(`${prefix}${key}`);
777
+ collectOptionalPaths(property, child, `${prefix}${key}.`, empty, filled);
778
+ }
779
+ return;
780
+ }
781
+
782
+ if (node.type === "array" && node.items) {
783
+ if (!Array.isArray(value)) return;
784
+ const base = prefix.endsWith(".") ? prefix.slice(0, -1) : prefix;
785
+ for (const element of value) {
786
+ collectOptionalPaths(node.items, element, `${base}[].`, empty, filled);
787
+ }
788
+ }
789
+ }
790
+
791
+ /**
792
+ * The optional fields of `schema` that `value` leaves empty, as dotted paths — `[]` for an
793
+ * array's elements, `(branch)` for a discriminated-union branch. **Optionality is derived from
794
+ * the schema**, via `z.toJSONSchema`: a field is optional when it appears in `properties` and
795
+ * not in `required`, so a field made optional later surfaces here with no edit. Pure: the
796
+ * schema and the value are the only inputs.
797
+ *
798
+ * **An array's verdict is every-empty minus any-filled, not a per-element intersection.** A
799
+ * field is used the moment one element fills it — three deliverables and one `path` between
800
+ * them is a case that uses `path`. But intersecting the elements' *empty* sets would also
801
+ * silence a field the other elements cannot possibly fill: under rule B an `ai` rubric
802
+ * criterion reports nothing about `evaluation_method(hybrid).fallback_prompt_hint`, and
803
+ * treating that silence as agreement hid the one `hybrid` criterion's empty field entirely
804
+ * (caught by the Task 11.10 mutation sweep). Subtracting the filled paths asks only the
805
+ * elements the field actually reaches.
806
+ */
807
+ export function unusedOptionalPaths(schema: z.ZodType, value: unknown): string[] {
808
+ const root = z.toJSONSchema(schema, TO_JSON_SCHEMA_OPTIONS) as unknown as JsonSchemaNode;
809
+ const empty: string[] = [];
810
+ const filled: string[] = [];
811
+ collectOptionalPaths(root, value, "", empty, filled);
812
+ const used = new Set(filled);
813
+ const unused: string[] = [];
814
+ for (const path of empty) {
815
+ if (used.has(path) || unused.includes(path)) continue;
816
+ unused.push(path);
817
+ }
818
+ return unused;
819
+ }
820
+
821
+ /**
822
+ * The per-file optional-field inventory for one parsed `.case/`. Two of its four suppression
823
+ * rules are derivable from the JSON Schema and live in `collectUnused` above (**A** — children of
824
+ * an absent parent; **B** — unused union branches). The other two are **not** derivable, because
825
+ * they are not properties of the schema at all — they mirror the cross-file `superRefine` rules
826
+ * in `validateCaseContent`, which is why this function lives in this file rather than in a module
827
+ * of its own; a mirror in another file drifts from what it mirrors.
828
+ *
829
+ * - **Rule C** — a field the case's own state makes **illegal**: `manifest.deprecated_reason`
830
+ * unless `status: deprecated` (where the validator makes it *required*), and
831
+ * `known_state.failing_tests` on a `tutorial` case (which the validator rejects outright).
832
+ * - **Rule D** — a field whose OR-group is already satisfied. The schema holds exactly one:
833
+ * `{failing_tests, known_errors}` on a `diagnostic` case, where the validator demands one and
834
+ * accepts either. (`implementation`'s `code_change` rule and `tutorial`'s `steps.md` rule are
835
+ * **not** OR-groups: one requires a value, the other a file, and neither is an optional field.)
836
+ */
837
+ /** One `.case/` YAML file: its `CaseContent` key and the schema defining its author-written shape. */
838
+ export interface CaseFileSchema {
839
+ contentKey: keyof CaseContent;
840
+ file: string;
841
+ schema: z.ZodType;
842
+ }
843
+
844
+ /**
845
+ * The ten `.case/` YAML files the inventory walks. `case-loader.ts` holds the same
846
+ * `key → path` mapping for reading them off disk and cannot be imported here (it imports
847
+ * *this* module), so the two are bound by a test rather than by a shared constant — a file
848
+ * added to one and not the other fails that test instead of silently reporting nothing.
849
+ */
850
+ export const CASE_FILE_SCHEMAS: readonly CaseFileSchema[] = [
851
+ { contentKey: "manifest", file: "manifest.yaml", schema: manifestSchema },
852
+ { contentKey: "artifacts", file: "artifacts.yaml", schema: artifactsSchema },
853
+ { contentKey: "learningObjectives", file: "learning_objectives.yaml", schema: learningObjectivesSchema },
854
+ { contentKey: "prerequisites", file: "prerequisites.yaml", schema: prerequisitesSchema },
855
+ { contentKey: "rubric", file: "rubric.yaml", schema: rubricSchema },
856
+ { contentKey: "solution", file: "solution.yaml", schema: solutionSchema },
857
+ { contentKey: "situation", file: "situation/situation.yaml", schema: situationSchema },
858
+ { contentKey: "deliverables", file: "task/deliverables.yaml", schema: deliverablesSchema },
859
+ { contentKey: "knownState", file: "starter_state/known_state.yaml", schema: knownStateSchema },
860
+ { contentKey: "quiz", file: "quiz.yaml", schema: quizSchema },
861
+ ];
862
+
863
+ export function optionalFieldsNotUsed(input: ValidateInput): OptionalFieldInventory {
864
+ const { content } = input;
865
+ const manifest = isRecord(content.manifest) ? content.manifest : {};
866
+ const knownState = isRecord(content.knownState) ? content.knownState : {};
867
+ const caseType = manifest.type;
868
+ const hasFailingTests = Array.isArray(knownState.failing_tests) && knownState.failing_tests.length > 0;
869
+ const hasKnownErrors = Array.isArray(knownState.known_errors) && knownState.known_errors.length > 0;
870
+
871
+ /** Rules C and D: whether an empty optional field is worth reporting in this case's state. */
872
+ const applies = (file: string, path: string): boolean => {
873
+ if (file === "manifest.yaml" && path === "deprecated_reason") {
874
+ return manifest.status === "deprecated"; // rule C
875
+ }
876
+ if (file === "starter_state/known_state.yaml") {
877
+ if (path === "failing_tests" && caseType === "tutorial") return false; // rule C
878
+ if (caseType === "diagnostic") {
879
+ if (path === "known_errors" && hasFailingTests) return false; // rule D
880
+ if (path === "failing_tests" && hasKnownErrors) return false; // rule D
881
+ }
882
+ }
883
+ return true;
884
+ };
885
+
886
+ const report: OptionalFieldInventory = {};
887
+ for (const { contentKey, file, schema } of CASE_FILE_SCHEMAS) {
888
+ const value = content[contentKey];
889
+ // Rule A at file level: an optional file the case does not carry reports nothing.
890
+ if (value === undefined) continue;
891
+ const paths = unusedOptionalPaths(schema, value).filter((path) => applies(file, path));
892
+ if (paths.length > 0) report[file] = paths;
893
+ }
894
+ return report;
895
+ }