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,234 @@
1
+ /**
2
+ * Pure helpers for the `fito-case-runner` skill's GitHub / git command surface. They parse the
3
+ * case's repository pointer and build the **`{command, args}`** the orchestration spawns (via the
4
+ * `gh` and `git` CLIs) through an injectable executor. Keeping them pure makes the command surface
5
+ * unit-testable while `runner.ts` only sequences them. No shell strings — every argument is a
6
+ * discrete argv element, so nothing is shell-interpolated.
7
+ *
8
+ * GitHub-only at MVP (ADR-005 / SPEC §Submission): {@link assertGithubPlatform} refuses other
9
+ * platforms. Auth is the learner's **local** `gh` credentials (`gh auth login`) — the backend's
10
+ * GitHub OAuth link is identity-only (`read:user user:email`) and cannot fork/push/open PRs.
11
+ */
12
+ import { parseGithubHttpsUrl } from "../../shared/github-url/parse.js";
13
+ /**
14
+ * Parse a case `repositoryUrl` into its `{ owner, repo }` (the shared `github-url` grammar,
15
+ * lesson 46). Only `https://github.com/...` is accepted: ssh remotes are rejected (the backend
16
+ * reachability ping only accepts https), as is any non-GitHub host or a URL missing the
17
+ * repository segment — both hard errors here, because a case pointer that doesn't parse is broken.
18
+ */
19
+ export function parseGithubRepo(repositoryUrl) {
20
+ if (repositoryUrl.startsWith("git@") || repositoryUrl.startsWith("ssh://")) {
21
+ throw new Error(`case repository must be an https GitHub URL, got an ssh remote: ${repositoryUrl}`);
22
+ }
23
+ const parsed = parseGithubHttpsUrl(repositoryUrl);
24
+ if (!parsed) {
25
+ throw new Error(`case repository must be an https github.com URL, got: ${repositoryUrl}`);
26
+ }
27
+ return parsed;
28
+ }
29
+ /** `owner/repo` slug — the form `gh` takes for `--repo` and `repo fork`. */
30
+ export function repoSlug(repo) {
31
+ return `${repo.owner}/${repo.repo}`;
32
+ }
33
+ /**
34
+ * Refuse any non-GitHub platform. At MVP only `GITHUB` is supported; the Case Registry already
35
+ * rejects other platforms at registration (Task 3.3), so this branch is a defensive backstop.
36
+ */
37
+ export function assertGithubPlatform(gitPlatform) {
38
+ if (gitPlatform !== "GITHUB") {
39
+ throw new Error(`case git platform ${gitPlatform} is not supported — non-GitHub platforms are deferred to post-MVP`);
40
+ }
41
+ }
42
+ /** `gh auth status` — the upfront readiness check (gh installed + authenticated). */
43
+ export function ghAuthStatusCommand() {
44
+ return { command: "gh", args: ["auth", "status"] };
45
+ }
46
+ /** `gh repo fork <slug> --clone=false` — create the fork on GitHub; the clone into the case dir is explicit. */
47
+ export function ghForkCommand(slug) {
48
+ return { command: "gh", args: ["repo", "fork", slug, "--clone=false"] };
49
+ }
50
+ /** `gh api user --jq .login` — the authenticated gh login (the fork owner + the learner self-check). */
51
+ export function ghCurrentLoginCommand() {
52
+ return { command: "gh", args: ["api", "user", "--jq", ".login"] };
53
+ }
54
+ /** The https clone URL of the learner's fork (`https://github.com/<login>/<repo>.git`). */
55
+ export function forkCloneUrl(login, repo) {
56
+ return `https://github.com/${login}/${repo}.git`;
57
+ }
58
+ /** `git clone <url> <dir>` — clone the fork into the explicit per-case working directory. */
59
+ export function gitCloneCommand(cloneUrl, targetDir) {
60
+ return { command: "git", args: ["clone", cloneUrl, targetDir] };
61
+ }
62
+ /**
63
+ * `git remote add upstream <case-repo-url>` — wire the upstream case repo into the fork clone
64
+ * (Task 9a.2). The fork is created once and never synced, so a version published after it is
65
+ * absent from `origin`; version refs are therefore always read from upstream's frozen refs, while
66
+ * the fork stays the write side (student branch push, PR head).
67
+ */
68
+ export function gitAddUpstreamRemoteCommand(repo) {
69
+ return {
70
+ command: "git",
71
+ args: ["remote", "add", "upstream", `https://github.com/${repo.owner}/${repo.repo}.git`],
72
+ };
73
+ }
74
+ /**
75
+ * `git fetch upstream refs/heads/<versionRef>:refs/remotes/upstream/<versionRef>` — bring
76
+ * upstream's frozen version branch into the clone (Task 9a.2). The explicit refspec is required:
77
+ * a case repo carries both a `vX.Y.Z` tag and a `vX.Y.Z` branch (lesson 46), and a shorthand
78
+ * `git fetch upstream vX.Y.Z` resolves tag-before-branch — fetching the tag into `FETCH_HEAD`
79
+ * only and leaving `upstream/<ref>` unset, so the subsequent checkout would fail. The refspec
80
+ * fetches the branch unambiguously and guarantees `upstream/<ref>` exists. Never forced: frozen
81
+ * refs are immutable, and the clone is always fresh (open refuses a non-empty dir), so the
82
+ * destination cannot pre-exist.
83
+ */
84
+ export function gitFetchUpstreamRefCommand(versionRef) {
85
+ return {
86
+ command: "git",
87
+ args: ["fetch", "upstream", `refs/heads/${versionRef}:refs/remotes/upstream/${versionRef}`],
88
+ };
89
+ }
90
+ /**
91
+ * `git checkout upstream/<versionRef>` — land (detached) on the upstream's `versionRef` branch tip,
92
+ * fetched moments earlier ({@link gitFetchUpstreamRefCommand}) so it exists regardless of fork
93
+ * staleness (Task 9a.2). The `upstream/` prefix is deliberate: a case repo carries both a `vX.Y.Z`
94
+ * tag and a `vX.Y.Z` branch (lesson 46), so a bare `git checkout vX.Y.Z` is ambiguous.
95
+ */
96
+ export function gitCheckoutRefCommand(versionRef) {
97
+ return { command: "git", args: ["checkout", `upstream/${versionRef}`] };
98
+ }
99
+ /** `git checkout -b <studentBranch>` — create the student branch from the current (versionRef) checkout. */
100
+ export function gitCreateBranchCommand(studentBranch) {
101
+ return { command: "git", args: ["checkout", "-b", studentBranch] };
102
+ }
103
+ /**
104
+ * `git branch --list --remotes origin/<studentBranch>` — probe whether the fork already carries the
105
+ * student branch from a previous attempt (Task 7.6). Runs right after the clone, so the local
106
+ * remote-tracking refs are current — no network round-trip. Non-empty stdout means the branch exists.
107
+ */
108
+ export function gitListRemoteBranchCommand(studentBranch) {
109
+ return { command: "git", args: ["branch", "--list", "--remotes", `origin/${studentBranch}`] };
110
+ }
111
+ /**
112
+ * `git checkout --track origin/<studentBranch>` — the **resume** path (Task 7.6): check out the
113
+ * fork's existing student branch, tracking it, so the previous attempt's commits (and its open PR)
114
+ * carry forward.
115
+ */
116
+ export function gitCheckoutTrackCommand(studentBranch) {
117
+ return { command: "git", args: ["checkout", "--track", `origin/${studentBranch}`] };
118
+ }
119
+ /**
120
+ * `git push origin --delete <studentBranch>` — the **start-over** path (Task 7.6): delete the fork's
121
+ * student branch, which closes its open PR the documented way ("head branch was deleted"). Chosen
122
+ * over force-pushing the branch back to the versionRef, which would empty the PR and trip GitHub's
123
+ * undocumented auto-close anyway — this keeps the whole scripted flow force-push-free. Only ever run
124
+ * after the learner explicitly chose to discard the previous attempt.
125
+ */
126
+ export function gitDeleteRemoteBranchCommand(studentBranch) {
127
+ return { command: "git", args: ["push", "origin", "--delete", studentBranch] };
128
+ }
129
+ /**
130
+ * Whether a failed `git push` message is the **divergence** family — the fork's branch has commits
131
+ * this checkout doesn't (a previous attempt, Task 7.6) — which the submit guard maps to the
132
+ * resume/start-over re-open choice. Git words it `! [rejected] <b> -> <b> (non-fast-forward)` or
133
+ * `(fetch first)`. A server-side `! [remote rejected]` (pre-receive hooks, branch protection,
134
+ * permissions) is **not** a divergence — re-opening cannot fix it — so it must not match here and
135
+ * propagates as-is.
136
+ */
137
+ export function isDivergedPush(message) {
138
+ return /non-fast-forward|fetch first|! \[rejected\]/i.test(message);
139
+ }
140
+ /** `git push -u origin <studentBranch>` — publish the student branch to the fork. */
141
+ export function gitPushCommand(studentBranch) {
142
+ return { command: "git", args: ["push", "-u", "origin", studentBranch] };
143
+ }
144
+ /**
145
+ * `gh pr create --repo <upstream> --base <target> --head <forkOwner>:<student> ...` — open the
146
+ * submission PR. The clone is the fork (no upstream remote), so `--repo` targets the case repo
147
+ * explicitly and `--head <owner>:<branch>` pins the fork branch — neither relies on remote naming.
148
+ */
149
+ export function ghPrCreateCommand(input) {
150
+ return {
151
+ command: "gh",
152
+ args: [
153
+ "pr",
154
+ "create",
155
+ "--repo",
156
+ input.repoSlug,
157
+ "--base",
158
+ input.base,
159
+ "--head",
160
+ `${input.headOwner}:${input.headBranch}`,
161
+ "--title",
162
+ input.title,
163
+ "--body",
164
+ input.body,
165
+ ],
166
+ };
167
+ }
168
+ /**
169
+ * `gh pr list --repo <upstream> --head <student> --base <target> --state open --json
170
+ * url,headRefName,headRepositoryOwner` — list open PRs whose head branch is the student branch against
171
+ * the case's target. The record-aware retry uses it: if a submission PR already exists (a prior submit
172
+ * opened it but failed to record, or the learner re-submits), the runner reuses it instead of letting
173
+ * `gh pr create` fail on a duplicate.
174
+ *
175
+ * `gh`'s `--head` filters by **branch name only** (the GraphQL `headRefName`), not `owner:branch`, so
176
+ * it can return same-named branches from other forks; {@link parseExistingPrUrl} narrows to *this*
177
+ * learner's fork via `headRepositoryOwner`. (At MVP the default 30-result page is ample; a case with
178
+ * 30+ concurrently-open same-branch submissions is out of scope.)
179
+ */
180
+ export function ghPrListCommand(input) {
181
+ return {
182
+ command: "gh",
183
+ args: [
184
+ "pr",
185
+ "list",
186
+ "--repo",
187
+ input.repoSlug,
188
+ "--head",
189
+ input.headBranch,
190
+ "--base",
191
+ input.base,
192
+ "--state",
193
+ "open",
194
+ "--json",
195
+ "url,headRefName,headRepositoryOwner",
196
+ ],
197
+ };
198
+ }
199
+ /**
200
+ * Parse `gh pr list --json url,headRefName,headRepositoryOwner` stdout (a JSON array) → the url of the
201
+ * open PR from `headOwner`'s fork on branch `headBranch`, or null when none matches. Filtering by both
202
+ * the head branch and the fork owner here (rather than trusting `gh --head`, which is branch-name only)
203
+ * makes the reuse precise. Empty/whitespace stdout is "no PR"; malformed JSON throws an actionable
204
+ * error (a real `gh` failure surfaced, not a silent miss that would wrongly route to `gh pr create`).
205
+ */
206
+ export function parseExistingPrUrl(stdout, headOwner, headBranch) {
207
+ const trimmed = stdout.trim();
208
+ if (!trimmed)
209
+ return null;
210
+ let parsed;
211
+ try {
212
+ parsed = JSON.parse(trimmed);
213
+ }
214
+ catch (error) {
215
+ const detail = error instanceof Error ? error.message : String(error);
216
+ throw new Error(`gh pr list returned malformed JSON: ${detail}`);
217
+ }
218
+ if (!Array.isArray(parsed))
219
+ return null;
220
+ for (const entry of parsed) {
221
+ if (typeof entry !== "object" || entry === null)
222
+ continue;
223
+ const record = entry;
224
+ const ownerLogin = record.headRepositoryOwner?.login;
225
+ if (typeof record.url === "string" &&
226
+ record.url.length > 0 &&
227
+ record.headRefName === headBranch &&
228
+ typeof ownerLogin === "string" &&
229
+ ownerLogin.toLowerCase() === headOwner.toLowerCase()) {
230
+ return record.url;
231
+ }
232
+ }
233
+ return null;
234
+ }
@@ -0,0 +1,287 @@
1
+ /**
2
+ * Pure helpers for the `fito-case-runner` skill's GitHub / git command surface. They parse the
3
+ * case's repository pointer and build the **`{command, args}`** the orchestration spawns (via the
4
+ * `gh` and `git` CLIs) through an injectable executor. Keeping them pure makes the command surface
5
+ * unit-testable while `runner.ts` only sequences them. No shell strings — every argument is a
6
+ * discrete argv element, so nothing is shell-interpolated.
7
+ *
8
+ * GitHub-only at MVP (ADR-005 / SPEC §Submission): {@link assertGithubPlatform} refuses other
9
+ * platforms. Auth is the learner's **local** `gh` credentials (`gh auth login`) — the backend's
10
+ * GitHub OAuth link is identity-only (`read:user user:email`) and cannot fork/push/open PRs.
11
+ */
12
+
13
+ import { parseGithubHttpsUrl } from "../../shared/github-url/parse.ts";
14
+ import type { ShellCommand } from "../../shared/shell-exec/exec.ts";
15
+
16
+ /** A command to spawn: the binary plus its discrete argv elements (the shared `shell-exec` contract). */
17
+ export type { ShellCommand };
18
+
19
+ /** An `owner`/`repo` pair parsed from a case's `repositoryUrl`. */
20
+ export interface GithubRepo {
21
+ owner: string;
22
+ repo: string;
23
+ }
24
+
25
+ /**
26
+ * Parse a case `repositoryUrl` into its `{ owner, repo }` (the shared `github-url` grammar,
27
+ * lesson 46). Only `https://github.com/...` is accepted: ssh remotes are rejected (the backend
28
+ * reachability ping only accepts https), as is any non-GitHub host or a URL missing the
29
+ * repository segment — both hard errors here, because a case pointer that doesn't parse is broken.
30
+ */
31
+ export function parseGithubRepo(repositoryUrl: string): GithubRepo {
32
+ if (repositoryUrl.startsWith("git@") || repositoryUrl.startsWith("ssh://")) {
33
+ throw new Error(`case repository must be an https GitHub URL, got an ssh remote: ${repositoryUrl}`);
34
+ }
35
+ const parsed = parseGithubHttpsUrl(repositoryUrl);
36
+ if (!parsed) {
37
+ throw new Error(`case repository must be an https github.com URL, got: ${repositoryUrl}`);
38
+ }
39
+ return parsed;
40
+ }
41
+
42
+ /** `owner/repo` slug — the form `gh` takes for `--repo` and `repo fork`. */
43
+ export function repoSlug(repo: GithubRepo): string {
44
+ return `${repo.owner}/${repo.repo}`;
45
+ }
46
+
47
+ /**
48
+ * Refuse any non-GitHub platform. At MVP only `GITHUB` is supported; the Case Registry already
49
+ * rejects other platforms at registration (Task 3.3), so this branch is a defensive backstop.
50
+ */
51
+ export function assertGithubPlatform(gitPlatform: string): void {
52
+ if (gitPlatform !== "GITHUB") {
53
+ throw new Error(
54
+ `case git platform ${gitPlatform} is not supported — non-GitHub platforms are deferred to post-MVP`,
55
+ );
56
+ }
57
+ }
58
+
59
+ /** `gh auth status` — the upfront readiness check (gh installed + authenticated). */
60
+ export function ghAuthStatusCommand(): ShellCommand {
61
+ return { command: "gh", args: ["auth", "status"] };
62
+ }
63
+
64
+ /** `gh repo fork <slug> --clone=false` — create the fork on GitHub; the clone into the case dir is explicit. */
65
+ export function ghForkCommand(slug: string): ShellCommand {
66
+ return { command: "gh", args: ["repo", "fork", slug, "--clone=false"] };
67
+ }
68
+
69
+ /** `gh api user --jq .login` — the authenticated gh login (the fork owner + the learner self-check). */
70
+ export function ghCurrentLoginCommand(): ShellCommand {
71
+ return { command: "gh", args: ["api", "user", "--jq", ".login"] };
72
+ }
73
+
74
+ /** The https clone URL of the learner's fork (`https://github.com/<login>/<repo>.git`). */
75
+ export function forkCloneUrl(login: string, repo: string): string {
76
+ return `https://github.com/${login}/${repo}.git`;
77
+ }
78
+
79
+ /** `git clone <url> <dir>` — clone the fork into the explicit per-case working directory. */
80
+ export function gitCloneCommand(cloneUrl: string, targetDir: string): ShellCommand {
81
+ return { command: "git", args: ["clone", cloneUrl, targetDir] };
82
+ }
83
+
84
+ /**
85
+ * `git remote add upstream <case-repo-url>` — wire the upstream case repo into the fork clone
86
+ * (Task 9a.2). The fork is created once and never synced, so a version published after it is
87
+ * absent from `origin`; version refs are therefore always read from upstream's frozen refs, while
88
+ * the fork stays the write side (student branch push, PR head).
89
+ */
90
+ export function gitAddUpstreamRemoteCommand(repo: GithubRepo): ShellCommand {
91
+ return {
92
+ command: "git",
93
+ args: ["remote", "add", "upstream", `https://github.com/${repo.owner}/${repo.repo}.git`],
94
+ };
95
+ }
96
+
97
+ /**
98
+ * `git fetch upstream refs/heads/<versionRef>:refs/remotes/upstream/<versionRef>` — bring
99
+ * upstream's frozen version branch into the clone (Task 9a.2). The explicit refspec is required:
100
+ * a case repo carries both a `vX.Y.Z` tag and a `vX.Y.Z` branch (lesson 46), and a shorthand
101
+ * `git fetch upstream vX.Y.Z` resolves tag-before-branch — fetching the tag into `FETCH_HEAD`
102
+ * only and leaving `upstream/<ref>` unset, so the subsequent checkout would fail. The refspec
103
+ * fetches the branch unambiguously and guarantees `upstream/<ref>` exists. Never forced: frozen
104
+ * refs are immutable, and the clone is always fresh (open refuses a non-empty dir), so the
105
+ * destination cannot pre-exist.
106
+ */
107
+ export function gitFetchUpstreamRefCommand(versionRef: string): ShellCommand {
108
+ return {
109
+ command: "git",
110
+ args: ["fetch", "upstream", `refs/heads/${versionRef}:refs/remotes/upstream/${versionRef}`],
111
+ };
112
+ }
113
+
114
+ /**
115
+ * `git checkout upstream/<versionRef>` — land (detached) on the upstream's `versionRef` branch tip,
116
+ * fetched moments earlier ({@link gitFetchUpstreamRefCommand}) so it exists regardless of fork
117
+ * staleness (Task 9a.2). The `upstream/` prefix is deliberate: a case repo carries both a `vX.Y.Z`
118
+ * tag and a `vX.Y.Z` branch (lesson 46), so a bare `git checkout vX.Y.Z` is ambiguous.
119
+ */
120
+ export function gitCheckoutRefCommand(versionRef: string): ShellCommand {
121
+ return { command: "git", args: ["checkout", `upstream/${versionRef}`] };
122
+ }
123
+
124
+ /** `git checkout -b <studentBranch>` — create the student branch from the current (versionRef) checkout. */
125
+ export function gitCreateBranchCommand(studentBranch: string): ShellCommand {
126
+ return { command: "git", args: ["checkout", "-b", studentBranch] };
127
+ }
128
+
129
+ /**
130
+ * `git branch --list --remotes origin/<studentBranch>` — probe whether the fork already carries the
131
+ * student branch from a previous attempt (Task 7.6). Runs right after the clone, so the local
132
+ * remote-tracking refs are current — no network round-trip. Non-empty stdout means the branch exists.
133
+ */
134
+ export function gitListRemoteBranchCommand(studentBranch: string): ShellCommand {
135
+ return { command: "git", args: ["branch", "--list", "--remotes", `origin/${studentBranch}`] };
136
+ }
137
+
138
+ /**
139
+ * `git checkout --track origin/<studentBranch>` — the **resume** path (Task 7.6): check out the
140
+ * fork's existing student branch, tracking it, so the previous attempt's commits (and its open PR)
141
+ * carry forward.
142
+ */
143
+ export function gitCheckoutTrackCommand(studentBranch: string): ShellCommand {
144
+ return { command: "git", args: ["checkout", "--track", `origin/${studentBranch}`] };
145
+ }
146
+
147
+ /**
148
+ * `git push origin --delete <studentBranch>` — the **start-over** path (Task 7.6): delete the fork's
149
+ * student branch, which closes its open PR the documented way ("head branch was deleted"). Chosen
150
+ * over force-pushing the branch back to the versionRef, which would empty the PR and trip GitHub's
151
+ * undocumented auto-close anyway — this keeps the whole scripted flow force-push-free. Only ever run
152
+ * after the learner explicitly chose to discard the previous attempt.
153
+ */
154
+ export function gitDeleteRemoteBranchCommand(studentBranch: string): ShellCommand {
155
+ return { command: "git", args: ["push", "origin", "--delete", studentBranch] };
156
+ }
157
+
158
+ /**
159
+ * Whether a failed `git push` message is the **divergence** family — the fork's branch has commits
160
+ * this checkout doesn't (a previous attempt, Task 7.6) — which the submit guard maps to the
161
+ * resume/start-over re-open choice. Git words it `! [rejected] <b> -> <b> (non-fast-forward)` or
162
+ * `(fetch first)`. A server-side `! [remote rejected]` (pre-receive hooks, branch protection,
163
+ * permissions) is **not** a divergence — re-opening cannot fix it — so it must not match here and
164
+ * propagates as-is.
165
+ */
166
+ export function isDivergedPush(message: string): boolean {
167
+ return /non-fast-forward|fetch first|! \[rejected\]/i.test(message);
168
+ }
169
+
170
+ /** `git push -u origin <studentBranch>` — publish the student branch to the fork. */
171
+ export function gitPushCommand(studentBranch: string): ShellCommand {
172
+ return { command: "git", args: ["push", "-u", "origin", studentBranch] };
173
+ }
174
+
175
+ export interface PrCreateInput {
176
+ /** `owner/repo` of the **upstream** case repo the PR targets. */
177
+ repoSlug: string;
178
+ /** Base branch on the upstream (the case's `submission.target_branch`, e.g. `v1.0.0`). */
179
+ base: string;
180
+ /** The fork owner (the learner's local `gh` login) for the `<owner>:<branch>` head ref. */
181
+ headOwner: string;
182
+ /** The student branch pushed to the fork. */
183
+ headBranch: string;
184
+ title: string;
185
+ body: string;
186
+ }
187
+
188
+ /**
189
+ * `gh pr create --repo <upstream> --base <target> --head <forkOwner>:<student> ...` — open the
190
+ * submission PR. The clone is the fork (no upstream remote), so `--repo` targets the case repo
191
+ * explicitly and `--head <owner>:<branch>` pins the fork branch — neither relies on remote naming.
192
+ */
193
+ export function ghPrCreateCommand(input: PrCreateInput): ShellCommand {
194
+ return {
195
+ command: "gh",
196
+ args: [
197
+ "pr",
198
+ "create",
199
+ "--repo",
200
+ input.repoSlug,
201
+ "--base",
202
+ input.base,
203
+ "--head",
204
+ `${input.headOwner}:${input.headBranch}`,
205
+ "--title",
206
+ input.title,
207
+ "--body",
208
+ input.body,
209
+ ],
210
+ };
211
+ }
212
+
213
+ export interface PrListInput {
214
+ /** `owner/repo` of the **upstream** case repo. */
215
+ repoSlug: string;
216
+ /** Base branch on the upstream (the case's `submission.target_branch`). */
217
+ base: string;
218
+ /** The student branch pushed to the fork. */
219
+ headBranch: string;
220
+ }
221
+
222
+ /**
223
+ * `gh pr list --repo <upstream> --head <student> --base <target> --state open --json
224
+ * url,headRefName,headRepositoryOwner` — list open PRs whose head branch is the student branch against
225
+ * the case's target. The record-aware retry uses it: if a submission PR already exists (a prior submit
226
+ * opened it but failed to record, or the learner re-submits), the runner reuses it instead of letting
227
+ * `gh pr create` fail on a duplicate.
228
+ *
229
+ * `gh`'s `--head` filters by **branch name only** (the GraphQL `headRefName`), not `owner:branch`, so
230
+ * it can return same-named branches from other forks; {@link parseExistingPrUrl} narrows to *this*
231
+ * learner's fork via `headRepositoryOwner`. (At MVP the default 30-result page is ample; a case with
232
+ * 30+ concurrently-open same-branch submissions is out of scope.)
233
+ */
234
+ export function ghPrListCommand(input: PrListInput): ShellCommand {
235
+ return {
236
+ command: "gh",
237
+ args: [
238
+ "pr",
239
+ "list",
240
+ "--repo",
241
+ input.repoSlug,
242
+ "--head",
243
+ input.headBranch,
244
+ "--base",
245
+ input.base,
246
+ "--state",
247
+ "open",
248
+ "--json",
249
+ "url,headRefName,headRepositoryOwner",
250
+ ],
251
+ };
252
+ }
253
+
254
+ /**
255
+ * Parse `gh pr list --json url,headRefName,headRepositoryOwner` stdout (a JSON array) → the url of the
256
+ * open PR from `headOwner`'s fork on branch `headBranch`, or null when none matches. Filtering by both
257
+ * the head branch and the fork owner here (rather than trusting `gh --head`, which is branch-name only)
258
+ * makes the reuse precise. Empty/whitespace stdout is "no PR"; malformed JSON throws an actionable
259
+ * error (a real `gh` failure surfaced, not a silent miss that would wrongly route to `gh pr create`).
260
+ */
261
+ export function parseExistingPrUrl(stdout: string, headOwner: string, headBranch: string): string | null {
262
+ const trimmed = stdout.trim();
263
+ if (!trimmed) return null;
264
+ let parsed: unknown;
265
+ try {
266
+ parsed = JSON.parse(trimmed);
267
+ } catch (error) {
268
+ const detail = error instanceof Error ? error.message : String(error);
269
+ throw new Error(`gh pr list returned malformed JSON: ${detail}`);
270
+ }
271
+ if (!Array.isArray(parsed)) return null;
272
+ for (const entry of parsed) {
273
+ if (typeof entry !== "object" || entry === null) continue;
274
+ const record = entry as { url?: unknown; headRefName?: unknown; headRepositoryOwner?: { login?: unknown } };
275
+ const ownerLogin = record.headRepositoryOwner?.login;
276
+ if (
277
+ typeof record.url === "string" &&
278
+ record.url.length > 0 &&
279
+ record.headRefName === headBranch &&
280
+ typeof ownerLogin === "string" &&
281
+ ownerLogin.toLowerCase() === headOwner.toLowerCase()
282
+ ) {
283
+ return record.url;
284
+ }
285
+ }
286
+ return null;
287
+ }
@@ -0,0 +1,56 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { parse as parseYaml } from "yaml";
4
+ import { z } from "zod";
5
+ /**
6
+ * Reads what the runner needs from a case's parsed `.case/manifest.yaml`: the submission branch
7
+ * configuration (`submission.target_branch`, the PR base, and `submission.student_branch`, the
8
+ * branch the learner works on) and the checkout's `version` (from which the submission's version
9
+ * pin derives, Task 9.4) — not the whole manifest — so this uses minimal local schemas rather than
10
+ * the full `shared/case-validation` `manifestSchema`: at submit time the case has already passed
11
+ * the open-time structural backstop, and an unrelated manifest field shouldn't block a submission.
12
+ * The structural validator remains the authority for full `.case/` correctness.
13
+ *
14
+ * Pure: the caller reads + YAML-parses the file and passes the parsed object here.
15
+ */
16
+ const submissionConfigSchema = z.object({
17
+ submission: z.object({
18
+ target_branch: z.string().min(1),
19
+ student_branch: z.string().min(1),
20
+ }),
21
+ });
22
+ /** Extract `{ targetBranch, studentBranch }` from a parsed manifest; throws if the submission block is missing/invalid. */
23
+ export function submissionBranches(parsedManifest) {
24
+ const result = submissionConfigSchema.safeParse(parsedManifest);
25
+ if (!result.success) {
26
+ throw new Error("could not read submission.target_branch / submission.student_branch from .case/manifest.yaml");
27
+ }
28
+ return {
29
+ targetBranch: result.data.submission.target_branch,
30
+ studentBranch: result.data.submission.student_branch,
31
+ };
32
+ }
33
+ /** Read + YAML-parse `<repoRoot>/.case/manifest.yaml` and extract the submission branches. */
34
+ export function readSubmissionBranches(repoRoot) {
35
+ const parsed = parseYaml(readFileSync(join(repoRoot, ".case", "manifest.yaml"), "utf8"));
36
+ return submissionBranches(parsed);
37
+ }
38
+ const versionSchema = z.object({ version: z.string().min(1) });
39
+ /**
40
+ * The checkout's frozen version ref, derived from `manifest.version` by the publish convention
41
+ * (`versionRef = "v" + version` — the same derivation `fito-case-author/publish-payload.ts` mints,
42
+ * so the ref names exactly the version the backend registered). The submission record pins the
43
+ * version the learner actually solved through it (Task 9.4), which is why it reads the *local
44
+ * tree*: after a case update, the backend's current version is newer than this checkout.
45
+ */
46
+ export function checkoutVersionRef(parsedManifest) {
47
+ const result = versionSchema.safeParse(parsedManifest);
48
+ if (!result.success) {
49
+ throw new Error("could not read version from .case/manifest.yaml");
50
+ }
51
+ return `v${result.data.version}`;
52
+ }
53
+ /** Read + YAML-parse `<repoRoot>/.case/manifest.yaml` and derive the checkout's version ref. */
54
+ export function readCheckoutVersionRef(repoRoot) {
55
+ return checkoutVersionRef(parseYaml(readFileSync(join(repoRoot, ".case", "manifest.yaml"), "utf8")));
56
+ }
@@ -0,0 +1,73 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ import { parse as parseYaml } from "yaml";
5
+ import { z } from "zod";
6
+
7
+ /**
8
+ * Reads what the runner needs from a case's parsed `.case/manifest.yaml`: the submission branch
9
+ * configuration (`submission.target_branch`, the PR base, and `submission.student_branch`, the
10
+ * branch the learner works on) and the checkout's `version` (from which the submission's version
11
+ * pin derives, Task 9.4) — not the whole manifest — so this uses minimal local schemas rather than
12
+ * the full `shared/case-validation` `manifestSchema`: at submit time the case has already passed
13
+ * the open-time structural backstop, and an unrelated manifest field shouldn't block a submission.
14
+ * The structural validator remains the authority for full `.case/` correctness.
15
+ *
16
+ * Pure: the caller reads + YAML-parses the file and passes the parsed object here.
17
+ */
18
+
19
+ const submissionConfigSchema = z.object({
20
+ submission: z.object({
21
+ target_branch: z.string().min(1),
22
+ student_branch: z.string().min(1),
23
+ }),
24
+ });
25
+
26
+ export interface SubmissionBranches {
27
+ /** The upstream branch the PR targets (`submission.target_branch`, e.g. `v1.0.0`). */
28
+ targetBranch: string;
29
+ /** The branch the learner works on and pushes (`submission.student_branch`, e.g. `solution`). */
30
+ studentBranch: string;
31
+ }
32
+
33
+ /** Extract `{ targetBranch, studentBranch }` from a parsed manifest; throws if the submission block is missing/invalid. */
34
+ export function submissionBranches(parsedManifest: unknown): SubmissionBranches {
35
+ const result = submissionConfigSchema.safeParse(parsedManifest);
36
+ if (!result.success) {
37
+ throw new Error(
38
+ "could not read submission.target_branch / submission.student_branch from .case/manifest.yaml",
39
+ );
40
+ }
41
+ return {
42
+ targetBranch: result.data.submission.target_branch,
43
+ studentBranch: result.data.submission.student_branch,
44
+ };
45
+ }
46
+
47
+ /** Read + YAML-parse `<repoRoot>/.case/manifest.yaml` and extract the submission branches. */
48
+ export function readSubmissionBranches(repoRoot: string): SubmissionBranches {
49
+ const parsed = parseYaml(readFileSync(join(repoRoot, ".case", "manifest.yaml"), "utf8"));
50
+ return submissionBranches(parsed);
51
+ }
52
+
53
+ const versionSchema = z.object({ version: z.string().min(1) });
54
+
55
+ /**
56
+ * The checkout's frozen version ref, derived from `manifest.version` by the publish convention
57
+ * (`versionRef = "v" + version` — the same derivation `fito-case-author/publish-payload.ts` mints,
58
+ * so the ref names exactly the version the backend registered). The submission record pins the
59
+ * version the learner actually solved through it (Task 9.4), which is why it reads the *local
60
+ * tree*: after a case update, the backend's current version is newer than this checkout.
61
+ */
62
+ export function checkoutVersionRef(parsedManifest: unknown): string {
63
+ const result = versionSchema.safeParse(parsedManifest);
64
+ if (!result.success) {
65
+ throw new Error("could not read version from .case/manifest.yaml");
66
+ }
67
+ return `v${result.data.version}`;
68
+ }
69
+
70
+ /** Read + YAML-parse `<repoRoot>/.case/manifest.yaml` and derive the checkout's version ref. */
71
+ export function readCheckoutVersionRef(repoRoot: string): string {
72
+ return checkoutVersionRef(parseYaml(readFileSync(join(repoRoot, ".case", "manifest.yaml"), "utf8")));
73
+ }