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,120 @@
1
+ ---
2
+ description: Ask the Fito tutor about the case you have open — one question or a whole conversation, scoped to that case
3
+ argument-hint: '[<case-id>] [question]'
4
+ ---
5
+ The learner wants the Fito tutor: case-scoped help while they work, from a
6
+ worker that can read the case and the knowledge components it references, but
7
+ not its solution, quiz answers or rubric key. Drive the flow below. Throughout
8
+ it you are the **relay** — the tutor answers, you carry its words across.
9
+
10
+ Parse `$ARGUMENTS`:
11
+
12
+ - **case-id** (optional): the leading token, but only when it is **UUID-shaped**
13
+ — the `<id>` from the case's `/cases/<id>` URL. Anything else belongs to the
14
+ question, so `/fito-tutor why does this test fail?` reads as a question with
15
+ no case id.
16
+ - **question** (optional): everything after that.
17
+
18
+ ## 1. Resolve which case
19
+
20
+ Take the first of these that settles it:
21
+
22
+ 1. the UUID-shaped argument, when one was given;
23
+ 2. the case opened earlier in this conversation — by `/fito-case-open <id>`, or
24
+ by a previous `/fito-tutor` turn;
25
+ 3. the checkout this session is standing in, when the working directory sits
26
+ inside `~/.fito/cases/<id>/`;
27
+ 4. the single open checkout, when `~/.fito/cases/` holds exactly one.
28
+
29
+ When none of them settles it, list what is open and ask the learner which case
30
+ they mean — never guess. A confident answer about the wrong case is worse than
31
+ a question left unanswered, because nothing in it looks wrong.
32
+
33
+ Name each candidate so the learner can tell them apart. Fetch its manifest —
34
+
35
+ ```
36
+ fito_case_partial_fetch({ caseId: "<id>", key: "manifest" })
37
+ ```
38
+
39
+ — and offer the case's `title` and `type` alongside its id, one line each:
40
+ `<title> — <type> (<id>)`. A manifest that does not come back costs that
41
+ candidate its label and nothing else: offer its bare id and keep the list
42
+ whole. A checkout that has moved is still a case the learner may mean, and a
43
+ picker that fails to draw leaves them no way to reach the tutor at all.
44
+
45
+ **Done when** you hold exactly one case id.
46
+
47
+ ## 2. Confirm the case is open
48
+
49
+ `~/.fito/cases/<id>/.case/` must exist. If it does not, the case was never
50
+ opened or its checkout has moved — point the learner at `/fito-case-open <id>`
51
+ and stop.
52
+
53
+ Confirm the directory is there and do not read what is inside it. The case's
54
+ contents are the tutor's to fetch; this flow opening them is the leak its gating
55
+ exists to prevent. The one thing you may take from the case is what §1's
56
+ picker labels with — the `manifest` key, allow-listed and served by the same
57
+ tool the tutor reads through, so it adds no reach.
58
+
59
+ **Done when** the checkout is confirmed present.
60
+
61
+ ## 3. Put the question to the tutor
62
+
63
+ If the learner gave no question, ask what they would like to ask before running
64
+ anything.
65
+
66
+ **The first question for this case in this session** opens the thread:
67
+
68
+ ```
69
+ fito_delegate({ agent: "fito-tutor", thread: true, task: "Case id: <id>\n\nThe learner asks:\n<question>" })
70
+ ```
71
+
72
+ The tutor's reply comes back as that tool's own result, and its last line carries
73
+ the handle for this conversation:
74
+
75
+ ```
76
+ Fito thread id: <thread-id>
77
+ ```
78
+
79
+ **Every later question about the same case** goes back to the same worker, which
80
+ still remembers everything said so far:
81
+
82
+ ```
83
+ fito_delegate({ agent: "fito-tutor", thread: "<thread id for this case>", task: "<question>" })
84
+ ```
85
+
86
+ Every turn answers with a `Fito thread id:` line of its own, and a continued turn
87
+ can name a new id — so carry the most recent one into the next question. That
88
+ line is yours to keep: the learner reads the tutor's words and nothing of the
89
+ machinery underneath them.
90
+
91
+ If a turn comes back as an error — the thread has aged out, or belongs to another
92
+ session — say so in one line and open a fresh one with `thread: true`. A new
93
+ thread does not remember the conversation, and the learner should hear that from
94
+ you rather than infer it from a tutor that has forgotten where they were.
95
+
96
+ **Done when** the tutor's reply to this question is in hand.
97
+
98
+ ## 4. Relay what the tutor said
99
+
100
+ Pass the tutor's reply through as the tutor's, in full. Never answer on its
101
+ behalf, and never top its answer up with case content of your own: you can read
102
+ `.case/` and it cannot, so anything you add is unscoped by construction — it
103
+ skipped the allow-list the tutor's every read goes through.
104
+
105
+ - It **answered** — relay it, keeping the component ids and `.case/` files it
106
+ cited so the learner can follow them.
107
+ - It **handed back** — the question sits outside the case's purpose. Tell the
108
+ learner they can put it to this session directly and carry on, and that the
109
+ tutor thread is still there when they come back to the case.
110
+ - It **refused** — the exemplar solution, the quiz answers, the rubric key.
111
+ Relay the refusal as it stands: do not soften it, argue with it, or supply any
112
+ part of what it withheld.
113
+
114
+ **Done when** the learner has the tutor's reply and nothing you wrote yourself.
115
+
116
+ ## 5. Carry on
117
+
118
+ Close with how to keep going — `/fito-tutor <question>`, no case id needed while
119
+ this session knows the case — and with the one limit worth stating: the thread
120
+ lives as long as this pi session does, so a new session starts a fresh one.
@@ -0,0 +1,221 @@
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { parse as parseYaml } from "yaml";
5
+ /**
6
+ * The **briefable** surface of a local `.case/` checkout — the read the `fito-tutor` worker
7
+ * persona is given in place of filesystem access (Success Criterion #9). A caller names a case
8
+ * id and one of an enumerated set of document **keys**; it never names a path.
9
+ *
10
+ * **Why keys, not paths.** A path parameter — however filtered — rests the containment claim on
11
+ * a string check applied to caller input. An enumerated key makes the served set a closed
12
+ * constant in this file (`BRIEFING_KEYS` + `KEY_DOCUMENTS`), so what a tutor can reach is a
13
+ * property of the code rather than of the sanitiser, and its test can assert the denied
14
+ * artifacts by name across *every* key — including keys added later.
15
+ *
16
+ * **Never served, by construction:** `solution/**`, `solution.yaml`, `rubric.yaml`, `quiz.yaml`
17
+ * (`DENIED_PATHS`). Those hold the exemplar, the scoring key, and the quiz answers; a tutor that
18
+ * could read them would answer the case instead of teaching it. They are not merely filtered out
19
+ * of the result — no code path opens them, and the single read seam re-checks the resolved path
20
+ * before touching disk.
21
+ *
22
+ * This is domain logic over the local checkout rather than an HTTP call, so it lives in
23
+ * `shared/<subject>/` beside `case-validation/` (ADR-003 / ADR-006 placement rule). It also
24
+ * deliberately does **not** reuse `case-validation`'s `loadCaseDir`, which eagerly parses every
25
+ * `.case/` YAML file — including the three denied ones — for the validator's benefit.
26
+ *
27
+ * Every failure is a plain `Error` carrying one clear line: the `fito_case_partial_fetch` tool
28
+ * (Task 11.2) lets it propagate so pi marks the call an error, and a raw `ENOENT` stack would tell
29
+ * the learner nothing.
30
+ */
31
+ /** The closed set of briefable document keys. Anything outside it is rejected. */
32
+ export const BRIEFING_KEYS = [
33
+ "manifest",
34
+ "situation",
35
+ "task",
36
+ "artifacts",
37
+ "starter_state",
38
+ "knowledge_refs",
39
+ ];
40
+ /**
41
+ * `.case/`-relative paths that no key may ever serve — the exemplar solution (directory and
42
+ * manifest), the scoring key, and the quiz answers. A trailing `/` marks a directory prefix.
43
+ */
44
+ export const DENIED_PATHS = ["solution/", "solution.yaml", "rubric.yaml", "quiz.yaml"];
45
+ /**
46
+ * What each key serves, in the order it should be briefed. `situation` lists only its manifest —
47
+ * its documents are appended from what that manifest declares (see `readSituation`).
48
+ *
49
+ * Adding a key here is what makes it reachable; the containment test iterates `BRIEFING_KEYS`, so
50
+ * a new key that reaches a denied artifact fails that test rather than shipping quietly.
51
+ */
52
+ const KEY_DOCUMENTS = {
53
+ manifest: [{ file: "manifest.yaml", kind: "yaml" }],
54
+ situation: [{ file: "situation/situation.yaml", kind: "yaml" }],
55
+ task: [
56
+ { file: "task/objective.md", kind: "markdown" },
57
+ { file: "task/constraints.md", kind: "markdown" },
58
+ { file: "task/steps.md", kind: "markdown" },
59
+ { file: "task/deliverables.yaml", kind: "yaml" },
60
+ ],
61
+ artifacts: [{ file: "artifacts.yaml", kind: "yaml" }],
62
+ starter_state: [
63
+ { file: "starter_state/description.md", kind: "markdown" },
64
+ { file: "starter_state/known_state.yaml", kind: "yaml" },
65
+ ],
66
+ knowledge_refs: [
67
+ { file: "learning_objectives.yaml", kind: "yaml" },
68
+ { file: "prerequisites.yaml", kind: "yaml" },
69
+ ],
70
+ };
71
+ /**
72
+ * The manifest fields a learner may see. The rest of `manifest.yaml` — `authors`, the
73
+ * `submission` config, `status`, the timestamps — is authoring and publication metadata that
74
+ * says nothing about the case as a learning object, so it is projected away rather than served.
75
+ */
76
+ const MANIFEST_FIELDS = ["title", "type", "version", "estimated_duration_minutes", "language", "tags"];
77
+ /**
78
+ * A case id is a single path segment (the backend mints UUIDs), so anything that could steer the
79
+ * resolution out of `~/.fito/cases/` is rejected before a path is built from it.
80
+ */
81
+ const CASE_ID = /^[A-Za-z0-9._-]+$/;
82
+ /**
83
+ * The per-case checkout, `~/.fito/cases/<caseId>/`. The convention's authority is
84
+ * `skills/fito-case-runner/workdir.ts`, which `/fito-case-open` writes through; it is re-derived
85
+ * here rather than imported because `shared/` does not depend on `skills/`.
86
+ */
87
+ function caseCheckoutDir(caseId, home) {
88
+ return join(home, ".fito", "cases", caseId);
89
+ }
90
+ /** Collapse a thrown library message to one line, so every surfaced error stays single-line. */
91
+ function oneLine(error) {
92
+ const message = error instanceof Error ? error.message : String(error);
93
+ return message.replace(/\s+/g, " ").trim();
94
+ }
95
+ /**
96
+ * The single read seam — every byte a briefing serves is opened here, and nowhere else.
97
+ *
98
+ * It re-checks the **resolved** `.case/`-relative path against `DENIED_PATHS` and against escape
99
+ * from `.case/` itself, then fails closed. Neither throw is reachable today: the key tables above
100
+ * name no denied file, and `readSituation` already drops an entry that leaves `situation/`. That
101
+ * is the point — this is the guard that keeps the containment claim true for the *next* key or
102
+ * the next selection rule, rather than only for the ones written here.
103
+ */
104
+ function readDocument(caseDir, entry) {
105
+ // Check the *resolved* path, not the requested string: `situation/../solution/notes.md`
106
+ // starts with none of the denied prefixes but lands on one of them.
107
+ const abs = resolve(caseDir, entry.file);
108
+ const normalized = relative(caseDir, abs).split(sep).join("/");
109
+ for (const denied of DENIED_PATHS) {
110
+ if (normalized === denied || normalized.startsWith(denied)) {
111
+ throw new Error(`Refusing to serve .case/${normalized}: it is withheld from every case briefing.`);
112
+ }
113
+ }
114
+ if (normalized.startsWith("../") || normalized === "..") {
115
+ throw new Error(`Refusing to serve ${entry.file}: it resolves outside the case's .case/ directory.`);
116
+ }
117
+ if (!existsSync(abs) || !statSync(abs).isFile())
118
+ return undefined;
119
+ // Report the normalized path, so what a tutor cites is where the bytes actually came from.
120
+ const text = readFileSync(abs, "utf8");
121
+ if (entry.kind === "markdown") {
122
+ return { file: normalized, text };
123
+ }
124
+ try {
125
+ // An empty / comment-only `.case/` YAML map parses to undefined — treat it as `{}`.
126
+ return { file: normalized, data: parseYaml(text) ?? {} };
127
+ }
128
+ catch (error) {
129
+ throw new Error(`Could not parse .case/${normalized} as YAML: ${oneLine(error)}`);
130
+ }
131
+ }
132
+ /** Keep only the briefable manifest fields the case actually declares. */
133
+ function projectManifest(document) {
134
+ const raw = document.data;
135
+ const projected = {};
136
+ if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) {
137
+ for (const field of MANIFEST_FIELDS) {
138
+ const value = raw[field];
139
+ if (value !== undefined)
140
+ projected[field] = value;
141
+ }
142
+ }
143
+ return { file: document.file, data: projected };
144
+ }
145
+ /**
146
+ * The situation manifest plus the documents it declares, in declared order.
147
+ *
148
+ * Each document is selected by **matching the manifest's own list** — the declared `file` is
149
+ * never used as a path directly. A case repo could declare `../solution/notes.md` or an absolute
150
+ * path and turn an allowed key into a leak, so an entry that does not resolve inside
151
+ * `.case/situation/` yields nothing at all rather than escaping the checkout.
152
+ */
153
+ function readSituation(caseDir) {
154
+ const manifest = readDocument(caseDir, KEY_DOCUMENTS.situation[0]);
155
+ if (!manifest)
156
+ return [];
157
+ const documents = [manifest];
158
+ const situationDir = resolve(caseDir, "situation");
159
+ const declared = manifest.data?.documents;
160
+ if (!Array.isArray(declared))
161
+ return documents;
162
+ for (const entry of declared) {
163
+ if (entry === null || typeof entry !== "object")
164
+ continue;
165
+ const { file, title, format } = entry;
166
+ if (typeof file !== "string" || file.length === 0 || isAbsolute(file))
167
+ continue;
168
+ const abs = resolve(situationDir, file);
169
+ if (!abs.startsWith(situationDir + sep))
170
+ continue;
171
+ const document = readDocument(caseDir, { file: `situation/${file}`, kind: "markdown" });
172
+ if (!document)
173
+ continue;
174
+ if (typeof title === "string")
175
+ document.title = title;
176
+ if (typeof format === "string")
177
+ document.format = format;
178
+ documents.push(document);
179
+ }
180
+ return documents;
181
+ }
182
+ /**
183
+ * Read one key's worth of a case's briefable documents from the learner's local checkout.
184
+ *
185
+ * Throws a single-line `Error` when the key is unknown or the case id is not a single path
186
+ * segment (both **before** any filesystem access), when the case is not open, when the checkout
187
+ * carries no `.case/`, when the key's documents are all absent, or when a served YAML file does
188
+ * not parse. `options.home` is injectable so tests can point at a throwaway HOME.
189
+ */
190
+ export function readCaseBriefing(caseId, key, options = {}) {
191
+ if (!BRIEFING_KEYS.includes(key)) {
192
+ throw new Error(`Unknown case document key "${key}". Served keys: ${BRIEFING_KEYS.join(", ")}.`);
193
+ }
194
+ if (!CASE_ID.test(caseId) || caseId === "." || caseId === "..") {
195
+ throw new Error(`Invalid case id "${caseId}" — a case id is a single path segment, as minted by the backend.`);
196
+ }
197
+ const briefingKey = key;
198
+ const checkoutDir = caseCheckoutDir(caseId, options.home ?? homedir());
199
+ if (!existsSync(checkoutDir)) {
200
+ throw new Error(`No open case checkout at ${checkoutDir} — open it first with /fito-case-open ${caseId}.`);
201
+ }
202
+ const caseDir = join(checkoutDir, ".case");
203
+ if (!existsSync(caseDir)) {
204
+ throw new Error(`The checkout at ${checkoutDir} has no .case/ directory — reopen the case with /fito-case-open ${caseId}.`);
205
+ }
206
+ let documents;
207
+ if (briefingKey === "situation") {
208
+ documents = readSituation(caseDir);
209
+ }
210
+ else {
211
+ documents = KEY_DOCUMENTS[briefingKey]
212
+ .map((entry) => readDocument(caseDir, entry))
213
+ .filter((document) => document !== undefined);
214
+ if (briefingKey === "manifest")
215
+ documents = documents.map(projectManifest);
216
+ }
217
+ if (documents.length === 0) {
218
+ throw new Error(`No ${briefingKey} documents in the case checkout at ${caseDir}.`);
219
+ }
220
+ return { caseId, key: briefingKey, documents };
221
+ }
@@ -0,0 +1,261 @@
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
4
+
5
+ import { parse as parseYaml } from "yaml";
6
+
7
+ /**
8
+ * The **briefable** surface of a local `.case/` checkout — the read the `fito-tutor` worker
9
+ * persona is given in place of filesystem access (Success Criterion #9). A caller names a case
10
+ * id and one of an enumerated set of document **keys**; it never names a path.
11
+ *
12
+ * **Why keys, not paths.** A path parameter — however filtered — rests the containment claim on
13
+ * a string check applied to caller input. An enumerated key makes the served set a closed
14
+ * constant in this file (`BRIEFING_KEYS` + `KEY_DOCUMENTS`), so what a tutor can reach is a
15
+ * property of the code rather than of the sanitiser, and its test can assert the denied
16
+ * artifacts by name across *every* key — including keys added later.
17
+ *
18
+ * **Never served, by construction:** `solution/**`, `solution.yaml`, `rubric.yaml`, `quiz.yaml`
19
+ * (`DENIED_PATHS`). Those hold the exemplar, the scoring key, and the quiz answers; a tutor that
20
+ * could read them would answer the case instead of teaching it. They are not merely filtered out
21
+ * of the result — no code path opens them, and the single read seam re-checks the resolved path
22
+ * before touching disk.
23
+ *
24
+ * This is domain logic over the local checkout rather than an HTTP call, so it lives in
25
+ * `shared/<subject>/` beside `case-validation/` (ADR-003 / ADR-006 placement rule). It also
26
+ * deliberately does **not** reuse `case-validation`'s `loadCaseDir`, which eagerly parses every
27
+ * `.case/` YAML file — including the three denied ones — for the validator's benefit.
28
+ *
29
+ * Every failure is a plain `Error` carrying one clear line: the `fito_case_partial_fetch` tool
30
+ * (Task 11.2) lets it propagate so pi marks the call an error, and a raw `ENOENT` stack would tell
31
+ * the learner nothing.
32
+ */
33
+
34
+ /** The closed set of briefable document keys. Anything outside it is rejected. */
35
+ export const BRIEFING_KEYS = [
36
+ "manifest",
37
+ "situation",
38
+ "task",
39
+ "artifacts",
40
+ "starter_state",
41
+ "knowledge_refs",
42
+ ] as const;
43
+
44
+ export type BriefingKey = (typeof BRIEFING_KEYS)[number];
45
+
46
+ /**
47
+ * `.case/`-relative paths that no key may ever serve — the exemplar solution (directory and
48
+ * manifest), the scoring key, and the quiz answers. A trailing `/` marks a directory prefix.
49
+ */
50
+ export const DENIED_PATHS = ["solution/", "solution.yaml", "rubric.yaml", "quiz.yaml"] as const;
51
+
52
+ /** One document of a briefing: either markdown (`text`) or parsed YAML (`data`), never both. */
53
+ export interface BriefingDocument {
54
+ /** Path relative to `.case/`, e.g. `task/objective.md` — so the tutor can cite its source. */
55
+ file: string;
56
+ /** The title the case declares for a situation document. */
57
+ title?: string;
58
+ /** The situation document's declared format (`ticket`, `email`, `log_output`, …). */
59
+ format?: string;
60
+ /** A markdown document's text, verbatim. */
61
+ text?: string;
62
+ /** A YAML document's parsed content (field-projected for the manifest). */
63
+ data?: unknown;
64
+ }
65
+
66
+ export interface CaseBriefing {
67
+ caseId: string;
68
+ key: BriefingKey;
69
+ /** The key's documents, in briefing order. Absent optional files are omitted. */
70
+ documents: BriefingDocument[];
71
+ }
72
+
73
+ /** A `.case/`-relative file one key serves, and how to read it. */
74
+ interface DocumentEntry {
75
+ file: string;
76
+ kind: "markdown" | "yaml";
77
+ }
78
+
79
+ /**
80
+ * What each key serves, in the order it should be briefed. `situation` lists only its manifest —
81
+ * its documents are appended from what that manifest declares (see `readSituation`).
82
+ *
83
+ * Adding a key here is what makes it reachable; the containment test iterates `BRIEFING_KEYS`, so
84
+ * a new key that reaches a denied artifact fails that test rather than shipping quietly.
85
+ */
86
+ const KEY_DOCUMENTS: Record<BriefingKey, readonly DocumentEntry[]> = {
87
+ manifest: [{ file: "manifest.yaml", kind: "yaml" }],
88
+ situation: [{ file: "situation/situation.yaml", kind: "yaml" }],
89
+ task: [
90
+ { file: "task/objective.md", kind: "markdown" },
91
+ { file: "task/constraints.md", kind: "markdown" },
92
+ { file: "task/steps.md", kind: "markdown" },
93
+ { file: "task/deliverables.yaml", kind: "yaml" },
94
+ ],
95
+ artifacts: [{ file: "artifacts.yaml", kind: "yaml" }],
96
+ starter_state: [
97
+ { file: "starter_state/description.md", kind: "markdown" },
98
+ { file: "starter_state/known_state.yaml", kind: "yaml" },
99
+ ],
100
+ knowledge_refs: [
101
+ { file: "learning_objectives.yaml", kind: "yaml" },
102
+ { file: "prerequisites.yaml", kind: "yaml" },
103
+ ],
104
+ };
105
+
106
+ /**
107
+ * The manifest fields a learner may see. The rest of `manifest.yaml` — `authors`, the
108
+ * `submission` config, `status`, the timestamps — is authoring and publication metadata that
109
+ * says nothing about the case as a learning object, so it is projected away rather than served.
110
+ */
111
+ const MANIFEST_FIELDS = ["title", "type", "version", "estimated_duration_minutes", "language", "tags"] as const;
112
+
113
+ /**
114
+ * A case id is a single path segment (the backend mints UUIDs), so anything that could steer the
115
+ * resolution out of `~/.fito/cases/` is rejected before a path is built from it.
116
+ */
117
+ const CASE_ID = /^[A-Za-z0-9._-]+$/;
118
+
119
+ /**
120
+ * The per-case checkout, `~/.fito/cases/<caseId>/`. The convention's authority is
121
+ * `skills/fito-case-runner/workdir.ts`, which `/fito-case-open` writes through; it is re-derived
122
+ * here rather than imported because `shared/` does not depend on `skills/`.
123
+ */
124
+ function caseCheckoutDir(caseId: string, home: string): string {
125
+ return join(home, ".fito", "cases", caseId);
126
+ }
127
+
128
+ /** Collapse a thrown library message to one line, so every surfaced error stays single-line. */
129
+ function oneLine(error: unknown): string {
130
+ const message = error instanceof Error ? error.message : String(error);
131
+ return message.replace(/\s+/g, " ").trim();
132
+ }
133
+
134
+ /**
135
+ * The single read seam — every byte a briefing serves is opened here, and nowhere else.
136
+ *
137
+ * It re-checks the **resolved** `.case/`-relative path against `DENIED_PATHS` and against escape
138
+ * from `.case/` itself, then fails closed. Neither throw is reachable today: the key tables above
139
+ * name no denied file, and `readSituation` already drops an entry that leaves `situation/`. That
140
+ * is the point — this is the guard that keeps the containment claim true for the *next* key or
141
+ * the next selection rule, rather than only for the ones written here.
142
+ */
143
+ function readDocument(caseDir: string, entry: DocumentEntry): BriefingDocument | undefined {
144
+ // Check the *resolved* path, not the requested string: `situation/../solution/notes.md`
145
+ // starts with none of the denied prefixes but lands on one of them.
146
+ const abs = resolve(caseDir, entry.file);
147
+ const normalized = relative(caseDir, abs).split(sep).join("/");
148
+ for (const denied of DENIED_PATHS) {
149
+ if (normalized === denied || normalized.startsWith(denied)) {
150
+ throw new Error(`Refusing to serve .case/${normalized}: it is withheld from every case briefing.`);
151
+ }
152
+ }
153
+ if (normalized.startsWith("../") || normalized === "..") {
154
+ throw new Error(`Refusing to serve ${entry.file}: it resolves outside the case's .case/ directory.`);
155
+ }
156
+
157
+ if (!existsSync(abs) || !statSync(abs).isFile()) return undefined;
158
+
159
+ // Report the normalized path, so what a tutor cites is where the bytes actually came from.
160
+ const text = readFileSync(abs, "utf8");
161
+ if (entry.kind === "markdown") {
162
+ return { file: normalized, text };
163
+ }
164
+ try {
165
+ // An empty / comment-only `.case/` YAML map parses to undefined — treat it as `{}`.
166
+ return { file: normalized, data: parseYaml(text) ?? {} };
167
+ } catch (error) {
168
+ throw new Error(`Could not parse .case/${normalized} as YAML: ${oneLine(error)}`);
169
+ }
170
+ }
171
+
172
+ /** Keep only the briefable manifest fields the case actually declares. */
173
+ function projectManifest(document: BriefingDocument): BriefingDocument {
174
+ const raw = document.data;
175
+ const projected: Record<string, unknown> = {};
176
+ if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) {
177
+ for (const field of MANIFEST_FIELDS) {
178
+ const value = (raw as Record<string, unknown>)[field];
179
+ if (value !== undefined) projected[field] = value;
180
+ }
181
+ }
182
+ return { file: document.file, data: projected };
183
+ }
184
+
185
+ /**
186
+ * The situation manifest plus the documents it declares, in declared order.
187
+ *
188
+ * Each document is selected by **matching the manifest's own list** — the declared `file` is
189
+ * never used as a path directly. A case repo could declare `../solution/notes.md` or an absolute
190
+ * path and turn an allowed key into a leak, so an entry that does not resolve inside
191
+ * `.case/situation/` yields nothing at all rather than escaping the checkout.
192
+ */
193
+ function readSituation(caseDir: string): BriefingDocument[] {
194
+ const manifest = readDocument(caseDir, KEY_DOCUMENTS.situation[0]);
195
+ if (!manifest) return [];
196
+
197
+ const documents = [manifest];
198
+ const situationDir = resolve(caseDir, "situation");
199
+ const declared = (manifest.data as { documents?: unknown } | undefined)?.documents;
200
+ if (!Array.isArray(declared)) return documents;
201
+
202
+ for (const entry of declared) {
203
+ if (entry === null || typeof entry !== "object") continue;
204
+ const { file, title, format } = entry as { file?: unknown; title?: unknown; format?: unknown };
205
+ if (typeof file !== "string" || file.length === 0 || isAbsolute(file)) continue;
206
+
207
+ const abs = resolve(situationDir, file);
208
+ if (!abs.startsWith(situationDir + sep)) continue;
209
+
210
+ const document = readDocument(caseDir, { file: `situation/${file}`, kind: "markdown" });
211
+ if (!document) continue;
212
+ if (typeof title === "string") document.title = title;
213
+ if (typeof format === "string") document.format = format;
214
+ documents.push(document);
215
+ }
216
+ return documents;
217
+ }
218
+
219
+ /**
220
+ * Read one key's worth of a case's briefable documents from the learner's local checkout.
221
+ *
222
+ * Throws a single-line `Error` when the key is unknown or the case id is not a single path
223
+ * segment (both **before** any filesystem access), when the case is not open, when the checkout
224
+ * carries no `.case/`, when the key's documents are all absent, or when a served YAML file does
225
+ * not parse. `options.home` is injectable so tests can point at a throwaway HOME.
226
+ */
227
+ export function readCaseBriefing(caseId: string, key: string, options: { home?: string } = {}): CaseBriefing {
228
+ if (!(BRIEFING_KEYS as readonly string[]).includes(key)) {
229
+ throw new Error(`Unknown case document key "${key}". Served keys: ${BRIEFING_KEYS.join(", ")}.`);
230
+ }
231
+ if (!CASE_ID.test(caseId) || caseId === "." || caseId === "..") {
232
+ throw new Error(`Invalid case id "${caseId}" — a case id is a single path segment, as minted by the backend.`);
233
+ }
234
+ const briefingKey = key as BriefingKey;
235
+
236
+ const checkoutDir = caseCheckoutDir(caseId, options.home ?? homedir());
237
+ if (!existsSync(checkoutDir)) {
238
+ throw new Error(`No open case checkout at ${checkoutDir} — open it first with /fito-case-open ${caseId}.`);
239
+ }
240
+ const caseDir = join(checkoutDir, ".case");
241
+ if (!existsSync(caseDir)) {
242
+ throw new Error(
243
+ `The checkout at ${checkoutDir} has no .case/ directory — reopen the case with /fito-case-open ${caseId}.`,
244
+ );
245
+ }
246
+
247
+ let documents: BriefingDocument[];
248
+ if (briefingKey === "situation") {
249
+ documents = readSituation(caseDir);
250
+ } else {
251
+ documents = KEY_DOCUMENTS[briefingKey]
252
+ .map((entry) => readDocument(caseDir, entry))
253
+ .filter((document): document is BriefingDocument => document !== undefined);
254
+ if (briefingKey === "manifest") documents = documents.map(projectManifest);
255
+ }
256
+
257
+ if (documents.length === 0) {
258
+ throw new Error(`No ${briefingKey} documents in the case checkout at ${caseDir}.`);
259
+ }
260
+ return { caseId, key: briefingKey, documents };
261
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Score a `multiple_choice` [question] from the learner's chosen [learnerChoiceId] (or `undefined`
3
+ * when they skipped it). Correct → 2 (met); incorrect/blank → 0. The result carries the question's id,
4
+ * its declared Bloom level, and its full knowledge-component set (its single score is recorded for
5
+ * each), with a non-leaking justification.
6
+ */
7
+ export function scoreMultipleChoice(question, learnerChoiceId) {
8
+ const correct = learnerChoiceId !== undefined && question.answer !== undefined && learnerChoiceId === question.answer;
9
+ return {
10
+ questionId: question.id,
11
+ knowledgeComponents: [...question.knowledge_components],
12
+ bloomLevel: question.bloom_level,
13
+ score: correct ? 2 : 0,
14
+ justification: correct ? "Correct." : "Incorrect — multiple choice is all-or-nothing (no partial credit).",
15
+ };
16
+ }
@@ -0,0 +1,61 @@
1
+ import type { BloomLevel } from "../case-validation/case-schema.ts";
2
+
3
+ /**
4
+ * Deterministic quiz scoring for the TUI (Task 7.3) — the `multiple_choice` half of quiz
5
+ * administration. `multiple_choice` is a mechanical string-equality of the learner's chosen choice id
6
+ * against the question's correct `answer`, so it is scored **here in code** (unit-tested, deterministic)
7
+ * rather than by the `fito-performance-reviewer` subagent, which scores only the `short_answer` /
8
+ * `code_snippet` questions. This honours AC1 ("multiple-choice scored *automatically*") and keeps the
9
+ * answer key out of any LLM context.
10
+ *
11
+ * **Rule (Task 17.7):** a multiple-choice answer is met or not met — a correct answer scores `2`, an
12
+ * incorrect or blank one `0`, with no partial credit and no `3`. The score says **how well** the
13
+ * answer met the question, the same on every quiz and rubric path; the question's `bloom_level`
14
+ * travels beside it as `bloomLevel`, and the backend awards that level at score 2 or 3 and
15
+ * `NOT_ACHIEVED` below.
16
+ *
17
+ * A pure function with no I/O, so it is unit-tested directly. The justification never names the correct
18
+ * choice id — both branches avoid leaking the answer key.
19
+ */
20
+
21
+ /** The minimal shape of a parsed `multiple_choice` question that [scoreMultipleChoice] reads. */
22
+ export interface MultipleChoiceQuestion {
23
+ readonly id: string;
24
+ readonly bloom_level: BloomLevel;
25
+ /** The correct choice id (`quiz.yaml` `answer`). Optional to match the parsed shape; a missing
26
+ * answer is treated as "no correct match", i.e. any learner choice scores 0. */
27
+ readonly answer?: string;
28
+ readonly knowledge_components: readonly string[];
29
+ }
30
+
31
+ /** One scored quiz question in the wire shape `POST /submissions/{id}/quiz-result` expects. */
32
+ export interface QuizScore {
33
+ readonly questionId: string;
34
+ readonly knowledgeComponents: string[];
35
+ /** The question's declared level — what a met score (2 or 3) awards. */
36
+ readonly bloomLevel: BloomLevel;
37
+ /** 0–3 band: 2 for a correct answer (met), 0 for an incorrect or blank one. */
38
+ readonly score: number;
39
+ readonly justification: string;
40
+ }
41
+
42
+ /**
43
+ * Score a `multiple_choice` [question] from the learner's chosen [learnerChoiceId] (or `undefined`
44
+ * when they skipped it). Correct → 2 (met); incorrect/blank → 0. The result carries the question's id,
45
+ * its declared Bloom level, and its full knowledge-component set (its single score is recorded for
46
+ * each), with a non-leaking justification.
47
+ */
48
+ export function scoreMultipleChoice(
49
+ question: MultipleChoiceQuestion,
50
+ learnerChoiceId: string | undefined,
51
+ ): QuizScore {
52
+ const correct =
53
+ learnerChoiceId !== undefined && question.answer !== undefined && learnerChoiceId === question.answer;
54
+ return {
55
+ questionId: question.id,
56
+ knowledgeComponents: [...question.knowledge_components],
57
+ bloomLevel: question.bloom_level,
58
+ score: correct ? 2 : 0,
59
+ justification: correct ? "Correct." : "Incorrect — multiple choice is all-or-nothing (no partial credit).",
60
+ };
61
+ }