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,304 @@
1
+ import { dirname } from "node:path";
2
+
3
+ import type { ValidationResult } from "../../shared/case-validation/case-schema.ts";
4
+ import type { Executor } from "../../shared/shell-exec/exec.ts";
5
+ import {
6
+ assertGithubPlatform,
7
+ forkCloneUrl,
8
+ ghAuthStatusCommand,
9
+ ghCurrentLoginCommand,
10
+ ghForkCommand,
11
+ ghPrCreateCommand,
12
+ ghPrListCommand,
13
+ gitAddUpstreamRemoteCommand,
14
+ gitCheckoutRefCommand,
15
+ gitCheckoutTrackCommand,
16
+ gitCloneCommand,
17
+ gitCreateBranchCommand,
18
+ gitDeleteRemoteBranchCommand,
19
+ gitFetchUpstreamRefCommand,
20
+ gitListRemoteBranchCommand,
21
+ gitPushCommand,
22
+ isDivergedPush,
23
+ parseExistingPrUrl,
24
+ parseGithubRepo,
25
+ repoSlug,
26
+ } from "./github.ts";
27
+ import type { SubmissionBranches } from "./manifest.ts";
28
+ import { formatValidationFailure } from "./report.ts";
29
+
30
+ /**
31
+ * The case-runner orchestration (Task 5.2): fork → clone → upstream fetch → checkout → structural
32
+ * re-validation → branch, and on submit, push → PR. Pure sequencing over an injectable `exec` (the real `git`/`gh`
33
+ * spawner is wired by the entrypoints `open.ts`/`submit.ts`); `validate` is the Task 3.2
34
+ * consumption-time backstop and `readBranches` reads the case's declared `submission` branches. This
35
+ * module does no filesystem or process work itself, so the command sequence, ordering, and error
36
+ * handling are unit-tested against fakes — no git/gh install, no disk.
37
+ *
38
+ * GitHub-only at MVP; auth is the learner's local `gh` (Fito stores no GitHub secret).
39
+ */
40
+
41
+ /** The repo-pointer slice of a case detail the runner needs. */
42
+ export interface CaseRepoPointer {
43
+ repositoryUrl: string;
44
+ versionRef: string;
45
+ gitPlatform: string;
46
+ }
47
+
48
+ /** Runs a command in `cwd`, returning its stdout; rejects on a non-zero exit (the shared `shell-exec` contract). */
49
+ export type { Executor };
50
+ /** Consumption-time structural backstop (Task 3.2 `validateCaseDir`). */
51
+ export type CaseValidator = (repoRoot: string) => ValidationResult;
52
+ /** Reads the case's `submission.target_branch` / `student_branch` from the checkout (Task 3.2 manifest). */
53
+ export type BranchReader = (repoRoot: string) => SubmissionBranches;
54
+
55
+ /** Upfront readiness: fail fast with an actionable message when `gh` is missing or unauthenticated. */
56
+ export async function ensureGhReady(exec: Executor, cwd: string): Promise<void> {
57
+ try {
58
+ await exec(ghAuthStatusCommand(), { cwd });
59
+ } catch (error) {
60
+ const detail = error instanceof Error ? error.message : String(error);
61
+ throw new Error(`GitHub CLI is not ready — install gh and run 'gh auth login'.\n (${detail})`);
62
+ }
63
+ }
64
+
65
+ /**
66
+ * How to reconcile a fork that already carries the student branch from a previous attempt
67
+ * (Task 7.6): `resume` continues it (tracking checkout — the open PR and its history carry
68
+ * forward); `start-over` discards it (delete the fork branch, closing its PR, then branch fresh
69
+ * from the versionRef). No mode = fresh open, which stops for the learner's choice when the
70
+ * branch exists.
71
+ */
72
+ export type OpenMode = "resume" | "start-over";
73
+
74
+ /**
75
+ * The fork already has the student branch from a previous attempt and no {@link OpenMode} was
76
+ * given. The resume-vs-start-over call is the learner's, never the agent's — the caller relays
77
+ * the choice and re-runs with the chosen mode.
78
+ */
79
+ export class StudentBranchExistsError extends Error {
80
+ readonly branch: string;
81
+
82
+ constructor(branch: string) {
83
+ super(`your fork already has a '${branch}' branch from a previous attempt`);
84
+ this.name = "StudentBranchExistsError";
85
+ this.branch = branch;
86
+ }
87
+ }
88
+
89
+ export interface OpenCaseOptions {
90
+ pointer: CaseRepoPointer;
91
+ targetDir: string;
92
+ exec: Executor;
93
+ validate: CaseValidator;
94
+ readBranches: BranchReader;
95
+ mode?: OpenMode;
96
+ }
97
+
98
+ export interface OpenCaseResult {
99
+ workDir: string;
100
+ branch: string;
101
+ /** The local `gh` login that owns the fork — surfaced so the learner can confirm the account. */
102
+ login: string;
103
+ /** How the student branch came to be: freshly created, resumed from the fork, or reset after start-over. */
104
+ opened: "fresh" | "resumed" | "reset";
105
+ }
106
+
107
+ /**
108
+ * Open a case for work: fork it on GitHub, clone the fork into `targetDir`, fetch the immutable
109
+ * `versionRef` from the upstream case repo and check it out (the fork is never synced, so version
110
+ * reads must come from upstream's frozen refs — Task 9a.2), structurally re-validate the checkout's
111
+ * `.case/` (the Hybrid-H0 consumption backstop, ADR-005), then create the case's declared student
112
+ * branch and hand control back. On a malformed `.case/`, stops *before* branching and throws a
113
+ * clear "case source malformed" report.
114
+ *
115
+ * When the fork already carries the student branch from a previous attempt (Task 7.6), the branch
116
+ * step is the learner's call: with no `mode` it throws {@link StudentBranchExistsError} (the caller
117
+ * relays the choice), `resume` checks the fork branch out tracking it, and `start-over` deletes the
118
+ * fork branch (closing its PR) before branching fresh. A mode with no fork branch to act on is a
119
+ * stale choice and fails rather than silently falling back.
120
+ */
121
+ export async function openCase(options: OpenCaseOptions): Promise<OpenCaseResult> {
122
+ const { pointer, targetDir, exec, validate, readBranches, mode } = options;
123
+ assertGithubPlatform(pointer.gitPlatform);
124
+ const repo = parseGithubRepo(pointer.repositoryUrl);
125
+ const parentDir = dirname(targetDir);
126
+
127
+ await ensureGhReady(exec, parentDir);
128
+
129
+ // 1. Fork on GitHub (gh waits for the fork to be ready), then clone the fork into the case dir.
130
+ await exec(ghForkCommand(repoSlug(repo)), { cwd: parentDir });
131
+ const login = (await exec(ghCurrentLoginCommand(), { cwd: parentDir })).trim();
132
+ await exec(gitCloneCommand(forkCloneUrl(login, repo.repo), targetDir), { cwd: parentDir });
133
+
134
+ // 2. Check out the immutable version ref, read from the UPSTREAM case repo — never the fork
135
+ // (Task 9a.2): the fork is created once and never synced, so a version published after it is
136
+ // absent from origin (upstream/<ref> also dodges the tag/branch ambiguity, lesson 46).
137
+ await exec(gitAddUpstreamRemoteCommand(repo), { cwd: targetDir });
138
+ await exec(gitFetchUpstreamRefCommand(pointer.versionRef), { cwd: targetDir });
139
+ await exec(gitCheckoutRefCommand(pointer.versionRef), { cwd: targetDir });
140
+
141
+ // 3. Consumption-time structural backstop (ADR-005 §6): independently re-check the actual bytes.
142
+ const validation = validate(targetDir);
143
+ if (!validation.ok) {
144
+ throw new Error(formatValidationFailure(`${pointer.repositoryUrl} (${pointer.versionRef})`, validation.errors));
145
+ }
146
+
147
+ // 4. Reconcile with the fork: does it already carry the student branch the case DECLARES (from
148
+ // the manifest — not a hardcoded name) from a previous attempt? The probe reads the clone's
149
+ // remote-tracking refs, current as of the clone moments ago.
150
+ const { studentBranch } = readBranches(targetDir);
151
+ const forkHasBranch =
152
+ (await exec(gitListRemoteBranchCommand(studentBranch), { cwd: targetDir })).trim().length > 0;
153
+
154
+ if (forkHasBranch && mode === undefined) {
155
+ throw new StudentBranchExistsError(studentBranch);
156
+ }
157
+ if (!forkHasBranch && mode !== undefined) {
158
+ throw new Error(
159
+ `nothing to ${mode === "resume" ? "resume" : "start over"}: your fork has no '${studentBranch}' branch.\n` +
160
+ `Re-run the open without the flag for a fresh start.`,
161
+ );
162
+ }
163
+
164
+ // 5. Land on the student branch per the learner's (implicit or explicit) choice.
165
+ if (forkHasBranch && mode === "resume") {
166
+ await exec(gitCheckoutTrackCommand(studentBranch), { cwd: targetDir });
167
+ return { workDir: targetDir, branch: studentBranch, login, opened: "resumed" };
168
+ }
169
+ if (forkHasBranch && mode === "start-over") {
170
+ await exec(gitDeleteRemoteBranchCommand(studentBranch), { cwd: targetDir });
171
+ await exec(gitCreateBranchCommand(studentBranch), { cwd: targetDir });
172
+ return { workDir: targetDir, branch: studentBranch, login, opened: "reset" };
173
+ }
174
+ await exec(gitCreateBranchCommand(studentBranch), { cwd: targetDir });
175
+ return { workDir: targetDir, branch: studentBranch, login, opened: "fresh" };
176
+ }
177
+
178
+ export interface SubmitSolutionOptions {
179
+ pointer: CaseRepoPointer;
180
+ targetDir: string;
181
+ exec: Executor;
182
+ readBranches: BranchReader;
183
+ /**
184
+ * Resolves the GitHub login linked to the learner's Fito account, or null when none is linked
185
+ * (Task 5.4). The submission is associated server-side by the Fito-linked identity, so before
186
+ * opening the PR the runner confirms the local `gh` account matches it — and that a link exists at
187
+ * all (SPEC §327 / Decision #8). Injected so the runner stays free of credential/HTTP work; the
188
+ * real `/me`-backed resolver is wired in `submit.ts`.
189
+ */
190
+ resolveLinkedGithubLogin: () => Promise<string | null>;
191
+ /**
192
+ * Records the opened PR as a submission with the backend (`POST /submissions`), idempotent on the
193
+ * PR (Task 5.4), returning the recorded submission's id. Called *after* the PR is opened — the PR URL
194
+ * is what gets recorded. Injected so the runner stays free of credential/HTTP work; `submit.ts` wires
195
+ * it to the `fito-api` client using the session token it already resolved for the identity match.
196
+ */
197
+ recordSubmission: (prUrl: string) => Promise<string>;
198
+ title?: string;
199
+ body?: string;
200
+ }
201
+
202
+ export interface SubmitSolutionResult {
203
+ prUrl: string;
204
+ login: string;
205
+ /** The backend submission id recorded for this PR (`GET /submissions/{id}`). */
206
+ submissionId: string;
207
+ }
208
+
209
+ /**
210
+ * Submit the worked solution: push the case's declared student branch to the fork, open (or reuse) a
211
+ * PR against the case's declared target branch, then record the submission with the backend. Returns
212
+ * the PR URL.
213
+ */
214
+ export async function submitSolution(options: SubmitSolutionOptions): Promise<SubmitSolutionResult> {
215
+ const { pointer, targetDir, exec, readBranches, resolveLinkedGithubLogin, recordSubmission } = options;
216
+ assertGithubPlatform(pointer.gitPlatform);
217
+ const repo = parseGithubRepo(pointer.repositoryUrl);
218
+
219
+ await ensureGhReady(exec, targetDir);
220
+
221
+ // The local gh account that will own the fork branch + the PR.
222
+ const login = (await exec(ghCurrentLoginCommand(), { cwd: targetDir })).trim();
223
+
224
+ // Authoritative "Fito-linked ↔ gh-authenticated" match (Task 5.4): the backend associates a
225
+ // submission by the learner's Fito-linked GitHub identity, so require a link and confirm the local
226
+ // gh account matches it BEFORE pushing anything (SPEC §327 / Decision #8). Refuse, don't silently
227
+ // open a PR that would be recorded under a different account than the one that authored it.
228
+ const linkedLogin = await resolveLinkedGithubLogin();
229
+ if (linkedLogin === null) {
230
+ throw new Error(
231
+ "Your Fito account has no linked GitHub identity, which is required to submit.\n" +
232
+ "Link your GitHub account to Fito, then submit again.",
233
+ );
234
+ }
235
+ if (linkedLogin.toLowerCase() !== login.toLowerCase()) {
236
+ throw new Error(
237
+ `GitHub account mismatch: your Fito-linked account is @${linkedLogin}, but gh is authenticated as @${login}.\n` +
238
+ `Run 'gh auth login' as @${linkedLogin}, or link @${login} to your Fito account, then submit again.`,
239
+ );
240
+ }
241
+
242
+ const { targetBranch, studentBranch } = readBranches(targetDir);
243
+
244
+ // Publish the working branch (a no-op if already pushed; updates the PR if there are new commits).
245
+ // A non-fast-forward rejection means the fork's branch diverged (a previous attempt — Task 7.6);
246
+ // the fix is the learner's resume/start-over choice at re-open, never a force-push here.
247
+ try {
248
+ await exec(gitPushCommand(studentBranch), { cwd: targetDir });
249
+ } catch (error) {
250
+ const detail = error instanceof Error ? error.message : String(error);
251
+ if (isDivergedPush(detail)) {
252
+ throw new Error(
253
+ `The push was rejected: your fork's '${studentBranch}' branch has diverged from this checkout ` +
254
+ `(it carries a previous attempt).\n` +
255
+ `Do not force-push. Re-open the case with /fito-case-open and choose to resume the previous ` +
256
+ `attempt or start over, then submit again.\n (${detail})`,
257
+ );
258
+ }
259
+ throw error;
260
+ }
261
+
262
+ // Record-aware retry: reuse an already-open PR rather than letting `gh pr create` fail on a
263
+ // duplicate (a prior submit may have opened the PR but failed to record it; or the learner
264
+ // re-submits).
265
+ const existingPr = parseExistingPrUrl(
266
+ await exec(ghPrListCommand({ repoSlug: repoSlug(repo), base: targetBranch, headBranch: studentBranch }), {
267
+ cwd: targetDir,
268
+ }),
269
+ login,
270
+ studentBranch,
271
+ );
272
+ const prUrl =
273
+ existingPr ??
274
+ (
275
+ await exec(
276
+ ghPrCreateCommand({
277
+ repoSlug: repoSlug(repo),
278
+ base: targetBranch,
279
+ headOwner: login,
280
+ headBranch: studentBranch,
281
+ title: options.title ?? "Fito case submission",
282
+ body: options.body ?? "Submitted via the Fito TUI.",
283
+ }),
284
+ { cwd: targetDir },
285
+ )
286
+ ).trim();
287
+
288
+ // Record the submission with Fito (idempotent on the PR — the backend find-or-creates). The PR is
289
+ // the artifact of record (SPEC §Performance Reviewer), so on a record failure surface the PR URL:
290
+ // re-running /fito-submit reuses this PR and retries the record.
291
+ let submissionId: string;
292
+ try {
293
+ submissionId = await recordSubmission(prUrl);
294
+ } catch (error) {
295
+ const detail = error instanceof Error ? error.message : String(error);
296
+ throw new Error(
297
+ `Your pull request is open:\n ${prUrl}\n` +
298
+ `…but recording the submission with Fito failed: ${detail}\n` +
299
+ `Re-run /fito-submit to retry — it reuses this PR.`,
300
+ );
301
+ }
302
+
303
+ return { prUrl, login, submissionId };
304
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * `node score-quiz-mc.js <case-id> <answers-json-path>` — the deterministic half of quiz scoring
3
+ * (Task 7.3). It reads the case's `.case/quiz.yaml` from the local checkout, scores every
4
+ * `multiple_choice` question from the learner's chosen choice ids (correct → 2, else 0, each carrying
5
+ * the question's declared `bloomLevel` — see `shared/case-quiz/scoring.ts`), and prints the
6
+ * per-question `QuizScore`s as a JSON array on stdout. The `short_answer` / `code_snippet` questions
7
+ * are NOT scored here — the `/fito-evaluate` and `/fito-submit` orchestrators hand those to the
8
+ * `fito-performance-reviewer` subagent and merge its results with this output.
9
+ *
10
+ * It never prints the questions' correct answers or prompt hints — only the scores + non-leaking
11
+ * justifications — so the answer key stays out of the orchestrator's context. `runScoreQuizMc` is the
12
+ * testable core (injectable home); `main` is the thin CLI wrapper.
13
+ */
14
+ import { existsSync, readFileSync } from "node:fs";
15
+ import * as os from "node:os";
16
+ import * as path from "node:path";
17
+ import { fileURLToPath } from "node:url";
18
+ import { z } from "zod";
19
+ import { quizSchema } from "../../shared/case-validation/case-schema.js";
20
+ import { loadCaseDir } from "../../shared/case-validation/case-loader.js";
21
+ import { scoreMultipleChoice } from "../../shared/case-quiz/scoring.js";
22
+ import { caseWorkDir } from "./workdir.js";
23
+ /** The learner's `multiple_choice` answers: question id → the chosen choice id. */
24
+ const answersSchema = z.record(z.string(), z.string());
25
+ /** Read the case's quiz + the learner's MC answers, and score every `multiple_choice` question. */
26
+ export async function runScoreQuizMc(options) {
27
+ const home = options.home ?? os.homedir();
28
+ const checkout = caseWorkDir(options.caseId, home);
29
+ const loaded = loadCaseDir(checkout);
30
+ if (loaded.content.quiz === undefined) {
31
+ throw new Error(`Case ${options.caseId} has no quiz — no .case/quiz.yaml under ${checkout}.`);
32
+ }
33
+ const quiz = quizSchema.parse(loaded.content.quiz);
34
+ const answers = readAnswers(options.answersPath);
35
+ return quiz.questions
36
+ .filter((question) => question.type === "multiple_choice")
37
+ .map((question) => scoreMultipleChoice(question, answers[question.id]));
38
+ }
39
+ /** Load the learner's answers file, failing with an actionable message on any malformed input. */
40
+ function readAnswers(answersPath) {
41
+ if (!existsSync(answersPath)) {
42
+ throw new Error(`No quiz answers file at:\n ${answersPath}`);
43
+ }
44
+ let raw;
45
+ try {
46
+ raw = readFileSync(answersPath, "utf8");
47
+ }
48
+ catch (error) {
49
+ const detail = error instanceof Error ? error.message : String(error);
50
+ throw new Error(`Could not read the quiz answers file:\n ${answersPath}\n (${detail})`);
51
+ }
52
+ let parsed;
53
+ try {
54
+ parsed = JSON.parse(raw);
55
+ }
56
+ catch {
57
+ throw new Error(`The quiz answers file is not valid JSON:\n ${answersPath}`);
58
+ }
59
+ const result = answersSchema.safeParse(parsed);
60
+ if (!result.success) {
61
+ throw new Error(`The quiz answers do not match the expected shape (a JSON object of question id → choice id):\n${result.error.message}`);
62
+ }
63
+ return result.data;
64
+ }
65
+ async function main() {
66
+ const caseId = process.argv[2];
67
+ const answersPath = process.argv[3];
68
+ if (!caseId || !answersPath) {
69
+ console.error("Usage: node score-quiz-mc.js <case-id> <answers-json-path>");
70
+ process.exitCode = 1;
71
+ return;
72
+ }
73
+ // Pure JSON on stdout — the orchestrator captures it and merges it with the AI-scored questions.
74
+ const scores = await runScoreQuizMc({ caseId, answersPath });
75
+ process.stdout.write(`${JSON.stringify(scores)}\n`);
76
+ }
77
+ /** Only auto-invoke the CLI when run directly (`node score-quiz-mc.js …`), not when imported. */
78
+ const entry = process.argv[1];
79
+ const isMainModule = !!entry && path.resolve(entry) === fileURLToPath(import.meta.url);
80
+ if (isMainModule) {
81
+ main().catch((error) => {
82
+ console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
83
+ process.exitCode = 1;
84
+ });
85
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * `node score-quiz-mc.js <case-id> <answers-json-path>` — the deterministic half of quiz scoring
3
+ * (Task 7.3). It reads the case's `.case/quiz.yaml` from the local checkout, scores every
4
+ * `multiple_choice` question from the learner's chosen choice ids (correct → 2, else 0, each carrying
5
+ * the question's declared `bloomLevel` — see `shared/case-quiz/scoring.ts`), and prints the
6
+ * per-question `QuizScore`s as a JSON array on stdout. The `short_answer` / `code_snippet` questions
7
+ * are NOT scored here — the `/fito-evaluate` and `/fito-submit` orchestrators hand those to the
8
+ * `fito-performance-reviewer` subagent and merge its results with this output.
9
+ *
10
+ * It never prints the questions' correct answers or prompt hints — only the scores + non-leaking
11
+ * justifications — so the answer key stays out of the orchestrator's context. `runScoreQuizMc` is the
12
+ * testable core (injectable home); `main` is the thin CLI wrapper.
13
+ */
14
+ import { existsSync, readFileSync } from "node:fs";
15
+ import * as os from "node:os";
16
+ import * as path from "node:path";
17
+ import { fileURLToPath } from "node:url";
18
+
19
+ import { z } from "zod";
20
+
21
+ import { quizSchema } from "../../shared/case-validation/case-schema.ts";
22
+ import { loadCaseDir } from "../../shared/case-validation/case-loader.ts";
23
+ import { scoreMultipleChoice, type QuizScore } from "../../shared/case-quiz/scoring.ts";
24
+ import { caseWorkDir } from "./workdir.ts";
25
+
26
+ /** The learner's `multiple_choice` answers: question id → the chosen choice id. */
27
+ const answersSchema = z.record(z.string(), z.string());
28
+
29
+ export interface RunScoreQuizMcOptions {
30
+ caseId: string;
31
+ /** Path to a JSON file mapping multiple_choice question id → the learner's chosen choice id. */
32
+ answersPath: string;
33
+ home?: string;
34
+ }
35
+
36
+ /** Read the case's quiz + the learner's MC answers, and score every `multiple_choice` question. */
37
+ export async function runScoreQuizMc(options: RunScoreQuizMcOptions): Promise<QuizScore[]> {
38
+ const home = options.home ?? os.homedir();
39
+ const checkout = caseWorkDir(options.caseId, home);
40
+ const loaded = loadCaseDir(checkout);
41
+ if (loaded.content.quiz === undefined) {
42
+ throw new Error(`Case ${options.caseId} has no quiz — no .case/quiz.yaml under ${checkout}.`);
43
+ }
44
+ const quiz = quizSchema.parse(loaded.content.quiz);
45
+ const answers = readAnswers(options.answersPath);
46
+ return quiz.questions
47
+ .filter((question) => question.type === "multiple_choice")
48
+ .map((question) => scoreMultipleChoice(question, answers[question.id]));
49
+ }
50
+
51
+ /** Load the learner's answers file, failing with an actionable message on any malformed input. */
52
+ function readAnswers(answersPath: string): Record<string, string> {
53
+ if (!existsSync(answersPath)) {
54
+ throw new Error(`No quiz answers file at:\n ${answersPath}`);
55
+ }
56
+ let raw: string;
57
+ try {
58
+ raw = readFileSync(answersPath, "utf8");
59
+ } catch (error) {
60
+ const detail = error instanceof Error ? error.message : String(error);
61
+ throw new Error(`Could not read the quiz answers file:\n ${answersPath}\n (${detail})`);
62
+ }
63
+ let parsed: unknown;
64
+ try {
65
+ parsed = JSON.parse(raw);
66
+ } catch {
67
+ throw new Error(`The quiz answers file is not valid JSON:\n ${answersPath}`);
68
+ }
69
+ const result = answersSchema.safeParse(parsed);
70
+ if (!result.success) {
71
+ throw new Error(
72
+ `The quiz answers do not match the expected shape (a JSON object of question id → choice id):\n${result.error.message}`,
73
+ );
74
+ }
75
+ return result.data;
76
+ }
77
+
78
+ async function main(): Promise<void> {
79
+ const caseId = process.argv[2];
80
+ const answersPath = process.argv[3];
81
+ if (!caseId || !answersPath) {
82
+ console.error("Usage: node score-quiz-mc.js <case-id> <answers-json-path>");
83
+ process.exitCode = 1;
84
+ return;
85
+ }
86
+ // Pure JSON on stdout — the orchestrator captures it and merges it with the AI-scored questions.
87
+ const scores = await runScoreQuizMc({ caseId, answersPath });
88
+ process.stdout.write(`${JSON.stringify(scores)}\n`);
89
+ }
90
+
91
+ /** Only auto-invoke the CLI when run directly (`node score-quiz-mc.js …`), not when imported. */
92
+ const entry = process.argv[1];
93
+ const isMainModule = !!entry && path.resolve(entry) === fileURLToPath(import.meta.url);
94
+ if (isMainModule) {
95
+ main().catch((error: unknown) => {
96
+ console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
97
+ process.exitCode = 1;
98
+ });
99
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * `node submit-evaluation.js <submission-id> <results-json-path>` — the second half of the Phase 6
3
+ * round-trip (Task 6.3). After `submit.ts` has recorded the submission and the `fito-performance-reviewer`
4
+ * subagent has scored the rubric, the `/fito-submit` orchestrator writes the reviewer's JSON array to a
5
+ * file and runs this to POST it to `POST /submissions/{id}/results`. The reviewer never touches the
6
+ * backend (its persona is network-free); this is where the recorded scores reach Fito.
7
+ *
8
+ * `runSubmitEvaluation` is the testable core (injectable client/home); `main` is the thin CLI wrapper.
9
+ * Re-runnable: the backend replaces a submission's results, so a retried `/fito-submit` re-POSTs safely.
10
+ */
11
+ import { existsSync, readFileSync } from "node:fs";
12
+ import * as os from "node:os";
13
+ import * as path from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ import { z } from "zod";
16
+ import { createFitoApiClient, criterionEvaluationResultSchema, } from "../../shared/fito-api/client.js";
17
+ import { resolveFitoSession } from "../../shared/fito-session/session.js";
18
+ /** The reviewer hands its scores as a JSON array of per-criterion results. */
19
+ const resultsFileSchema = z.array(criterionEvaluationResultSchema);
20
+ /** Read + validate the reviewer's results file, resolve the Fito session, and POST the results. */
21
+ export async function runSubmitEvaluation(options) {
22
+ const home = options.home ?? os.homedir();
23
+ const client = options.client ?? createFitoApiClient();
24
+ const results = readResults(options.resultsPath);
25
+ const { tokens } = await resolveFitoSession(client, home);
26
+ return client.submitEvaluationResults(tokens.accessToken, options.submissionId, results);
27
+ }
28
+ /** Load the reviewer's JSON results file, failing with an actionable message on any malformed input. */
29
+ function readResults(resultsPath) {
30
+ if (!existsSync(resultsPath)) {
31
+ throw new Error(`No evaluation results file at:\n ${resultsPath}`);
32
+ }
33
+ let raw;
34
+ try {
35
+ raw = readFileSync(resultsPath, "utf8");
36
+ }
37
+ catch (error) {
38
+ const detail = error instanceof Error ? error.message : String(error);
39
+ throw new Error(`Could not read the evaluation results file:\n ${resultsPath}\n (${detail})`);
40
+ }
41
+ let parsed;
42
+ try {
43
+ parsed = JSON.parse(raw);
44
+ }
45
+ catch {
46
+ throw new Error(`The evaluation results file is not valid JSON:\n ${resultsPath}`);
47
+ }
48
+ const result = resultsFileSchema.safeParse(parsed);
49
+ if (!result.success) {
50
+ throw new Error(`The evaluation results do not match the expected shape (a JSON array of per-criterion results):\n${result.error.message}`);
51
+ }
52
+ return result.data;
53
+ }
54
+ async function main() {
55
+ const submissionId = process.argv[2];
56
+ const resultsPath = process.argv[3];
57
+ if (!submissionId || !resultsPath) {
58
+ console.error("Usage: node submit-evaluation.js <submission-id> <results-json-path>");
59
+ process.exitCode = 1;
60
+ return;
61
+ }
62
+ const submission = await runSubmitEvaluation({ submissionId, resultsPath });
63
+ console.log(`✓ Evaluation recorded for submission ${submission.id} (status: ${submission.status}).`);
64
+ }
65
+ /** Only auto-invoke the CLI when run directly (`node submit-evaluation.js …`), not when imported. */
66
+ const entry = process.argv[1];
67
+ const isMainModule = !!entry && path.resolve(entry) === fileURLToPath(import.meta.url);
68
+ if (isMainModule) {
69
+ main().catch((error) => {
70
+ console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
71
+ process.exitCode = 1;
72
+ });
73
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * `node submit-evaluation.js <submission-id> <results-json-path>` — the second half of the Phase 6
3
+ * round-trip (Task 6.3). After `submit.ts` has recorded the submission and the `fito-performance-reviewer`
4
+ * subagent has scored the rubric, the `/fito-submit` orchestrator writes the reviewer's JSON array to a
5
+ * file and runs this to POST it to `POST /submissions/{id}/results`. The reviewer never touches the
6
+ * backend (its persona is network-free); this is where the recorded scores reach Fito.
7
+ *
8
+ * `runSubmitEvaluation` is the testable core (injectable client/home); `main` is the thin CLI wrapper.
9
+ * Re-runnable: the backend replaces a submission's results, so a retried `/fito-submit` re-POSTs safely.
10
+ */
11
+ import { existsSync, readFileSync } from "node:fs";
12
+ import * as os from "node:os";
13
+ import * as path from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+
16
+ import { z } from "zod";
17
+
18
+ import {
19
+ type CriterionEvaluationResult,
20
+ type FitoApiClient,
21
+ type SubmissionResponse,
22
+ createFitoApiClient,
23
+ criterionEvaluationResultSchema,
24
+ } from "../../shared/fito-api/client.ts";
25
+ import { resolveFitoSession } from "../../shared/fito-session/session.ts";
26
+
27
+ /** The fito-api surface this flow needs: the authenticated session lookup + the results POST. */
28
+ type SubmitEvaluationClient = Pick<FitoApiClient, "meWithRefresh" | "submitEvaluationResults">;
29
+
30
+ /** The reviewer hands its scores as a JSON array of per-criterion results. */
31
+ const resultsFileSchema = z.array(criterionEvaluationResultSchema);
32
+
33
+ export interface RunSubmitEvaluationOptions {
34
+ submissionId: string;
35
+ /** Path to the JSON file holding the reviewer's per-criterion results array. */
36
+ resultsPath: string;
37
+ home?: string;
38
+ client?: SubmitEvaluationClient;
39
+ }
40
+
41
+ /** Read + validate the reviewer's results file, resolve the Fito session, and POST the results. */
42
+ export async function runSubmitEvaluation(options: RunSubmitEvaluationOptions): Promise<SubmissionResponse> {
43
+ const home = options.home ?? os.homedir();
44
+ const client = options.client ?? createFitoApiClient();
45
+
46
+ const results = readResults(options.resultsPath);
47
+ const { tokens } = await resolveFitoSession(client, home);
48
+ return client.submitEvaluationResults(tokens.accessToken, options.submissionId, results);
49
+ }
50
+
51
+ /** Load the reviewer's JSON results file, failing with an actionable message on any malformed input. */
52
+ function readResults(resultsPath: string): CriterionEvaluationResult[] {
53
+ if (!existsSync(resultsPath)) {
54
+ throw new Error(`No evaluation results file at:\n ${resultsPath}`);
55
+ }
56
+ let raw: string;
57
+ try {
58
+ raw = readFileSync(resultsPath, "utf8");
59
+ } catch (error) {
60
+ const detail = error instanceof Error ? error.message : String(error);
61
+ throw new Error(`Could not read the evaluation results file:\n ${resultsPath}\n (${detail})`);
62
+ }
63
+ let parsed: unknown;
64
+ try {
65
+ parsed = JSON.parse(raw);
66
+ } catch {
67
+ throw new Error(`The evaluation results file is not valid JSON:\n ${resultsPath}`);
68
+ }
69
+ const result = resultsFileSchema.safeParse(parsed);
70
+ if (!result.success) {
71
+ throw new Error(
72
+ `The evaluation results do not match the expected shape (a JSON array of per-criterion results):\n${result.error.message}`,
73
+ );
74
+ }
75
+ return result.data;
76
+ }
77
+
78
+ async function main(): Promise<void> {
79
+ const submissionId = process.argv[2];
80
+ const resultsPath = process.argv[3];
81
+ if (!submissionId || !resultsPath) {
82
+ console.error("Usage: node submit-evaluation.js <submission-id> <results-json-path>");
83
+ process.exitCode = 1;
84
+ return;
85
+ }
86
+ const submission = await runSubmitEvaluation({ submissionId, resultsPath });
87
+ console.log(`✓ Evaluation recorded for submission ${submission.id} (status: ${submission.status}).`);
88
+ }
89
+
90
+ /** Only auto-invoke the CLI when run directly (`node submit-evaluation.js …`), not when imported. */
91
+ const entry = process.argv[1];
92
+ const isMainModule = !!entry && path.resolve(entry) === fileURLToPath(import.meta.url);
93
+ if (isMainModule) {
94
+ main().catch((error: unknown) => {
95
+ console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
96
+ process.exitCode = 1;
97
+ });
98
+ }