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,251 @@
1
+ /**
2
+ * Pure helpers for the publish flow's GitHub / git command surface (Task 9.3). Like the
3
+ * case-runner's `github.ts`, they build **`{command, args}`** values the orchestration spawns
4
+ * through an injectable executor — no shell strings, so nothing is shell-interpolated.
5
+ *
6
+ * Two publish-flow decisions live here: pushes go to an **explicit URL** (never a named remote —
7
+ * a reused project's `origin` is the author's own repo and must not be touched), and the author's
8
+ * current branch lands on the case repo as the canonical **`main`** whatever its local name, so
9
+ * every case repo looks identical to `/fito-case-edit` and the case-runner.
10
+ */
11
+
12
+ import type { ShellCommand } from "../../shared/shell-exec/exec.ts";
13
+
14
+ /** A command to spawn: the binary plus its discrete argv elements (the shared `shell-exec` contract). */
15
+ export type { ShellCommand };
16
+
17
+ /** An `owner`/`name` pair for the case repo; `owner` is absent when the default chain must fill it. */
18
+ export interface RepoArg {
19
+ owner: string | undefined;
20
+ name: string;
21
+ }
22
+
23
+ /** A GitHub owner or repo segment: word chars, dots and dashes — enough to reject slashes/spaces. */
24
+ const REPO_SEGMENT = /^[A-Za-z0-9._-]+$/;
25
+
26
+ /**
27
+ * Parse the `--repo` argument: `owner/name` (owner may be an org) or a bare `name`, whose owner
28
+ * the default chain fills (`FITO_PUBLISH_GITHUB_OWNER` env, else the authenticated `gh` login).
29
+ */
30
+ export function parseRepoArg(arg: string): RepoArg {
31
+ const parts = arg.split("/");
32
+ if (parts.length > 2 || !parts.every((p) => REPO_SEGMENT.test(p))) {
33
+ throw new Error(`--repo must be <owner>/<name> or a bare <name>, got: "${arg}"`);
34
+ }
35
+ if (parts.length === 2) {
36
+ return { owner: parts[0], name: parts[1] };
37
+ }
38
+ return { owner: undefined, name: parts[0] };
39
+ }
40
+
41
+ /**
42
+ * The https URL of the case repo — what `POST /cases` registers and every learner clone uses.
43
+ * Always https (the backend reachability ping rejects ssh remotes, lesson 46), no `.git` suffix.
44
+ */
45
+ export function caseRepoHttpsUrl(owner: string, name: string): string {
46
+ return `https://github.com/${owner}/${name}`;
47
+ }
48
+
49
+ /** `gh auth status` — the upfront readiness check (gh installed + authenticated). */
50
+ export function ghAuthStatusCommand(): ShellCommand {
51
+ return { command: "gh", args: ["auth", "status"] };
52
+ }
53
+
54
+ /** `gh api user --jq .login` — the authenticated gh login (default repo owner + the identity warning). */
55
+ export function ghCurrentLoginCommand(): ShellCommand {
56
+ return { command: "gh", args: ["api", "user", "--jq", ".login"] };
57
+ }
58
+
59
+ /** `gh repo view <slug> --json name` — the existence probe; a re-run must never create a duplicate repo. */
60
+ export function ghRepoViewCommand(slug: string): ShellCommand {
61
+ return { command: "gh", args: ["repo", "view", slug, "--json", "name"] };
62
+ }
63
+
64
+ /** `gh repo create <slug> --public --description <text>` — create the case repo (MVP is public-only), titled for its storefront; no clone, no push. */
65
+ export function ghRepoCreateCommand(slug: string, description: string): ShellCommand {
66
+ return { command: "gh", args: ["repo", "create", slug, "--public", "--description", description] };
67
+ }
68
+
69
+ /** `git status --porcelain` — the clean-tree guard: what was validated must be exactly what is pushed. */
70
+ export function gitStatusPorcelainCommand(): ShellCommand {
71
+ return { command: "git", args: ["status", "--porcelain"] };
72
+ }
73
+
74
+ /**
75
+ * The authoring-harness paths a case working tree legitimately carries, each written **into the case
76
+ * dir** by a designed Fito workflow, none of them ever a case artifact, and none of them avoidable on
77
+ * the route the author is defaulted onto. That last criterion read *"impossible to relocate"* until
78
+ * F31: `.pi/` **can** be relocated, so the bar is now the default route rather than impossibility, and
79
+ * the member admitted under the weaker form says so in its own bullet.
80
+ *
81
+ * Membership is the bar: `.gitignore` is rejected for all three (it would ship a Fito-authoring entry
82
+ * into the learner-facing repo) and so is `.git/info/exclude` (per-clone — it breaks on a machine
83
+ * switch or a second author's `/fito-case-edit` re-clone), which leaves this gate as the one place
84
+ * that can know.
85
+ *
86
+ * - **`.pi-subagents/`** — the **legacy** pi-subagents debug run-store (F23). Every
87
+ * `/fito-case-plan-source` run spawns the `fito-case-source-planner` subagent with the case dir as
88
+ * cwd, and pi-subagents wrote its transcripts there with no config knob to relocate it (read from
89
+ * v0.35.1, the pin shipped until 2026-08-15). The shipped **0.50.0** writes to `.pi/subagents`
90
+ * instead, which `AUTHORING_HARNESS_PATHS` already covers via its `.pi/` entry — so both eras stay
91
+ * filtered and this entry is **kept for authors on an older copy**, not left behind.
92
+ *
93
+ * **Open: the "no config knob" half of this bullet is doubtful on 0.50.0** — see PLAN Open
94
+ * Question 12. That release exposes an `artifactDir` preference (`project` / `session` / `temp`,
95
+ * named in upstream's own packaging warning at `src/shared/artifacts.ts:125`), and Fito sets it
96
+ * nowhere, so what puts the run-store in the case dir is no longer established. **This changes
97
+ * nothing here**: the membership question is whether the path lands on the author's default route,
98
+ * which F23 observed directly and 9b.16 already reworded the bar around. Settle the reason before
99
+ * citing it as precedent for admitting a *new* member.
100
+ * - **`output/`** — the knowledge pipeline's stage workspace (F30). Every step writes its stage to
101
+ * `./output/…` relative to **CWD** — `/fito-fetch-urls-content` and `fito-source-ingestion` into
102
+ * `1-ingest/`, `/fito-identify-*` into `2-identify/`, `/fito-generate-*` into `3-generate/`, which
103
+ * is also where `/fito-push-knowledge` reads its payloads from — and `/fito-identify-*` **offers**
104
+ * `--source .` when the CWD holds `.case/manifest.yaml` and the authoring-context check returns
105
+ * *authoring*, so mining a case's own source is an offered workflow, not misuse, and it necessarily
106
+ * lands `output/` in the case tree. Unlike the run-store it could not be relocated even in
107
+ * principle: the stage convention is shared by every step and is the reuse point ADR-012
108
+ * Decision 3 depends on.
109
+ * - **`.pi/`** — the pi project directory (F31). One writer now: `pi install -l <path>` run from
110
+ * **inside the case dir** writes `<caseDir>/.pi/settings.json`. *(Until 2026-09-17 a second
111
+ * writer chained onto it — `fito-startup.ts` walked up for an existing `.pi/`, found the one the
112
+ * install had just made, and synced the worker personas into `<caseDir>/.pi/agents/`. That sync
113
+ * is gone; personas are read from the package itself, so the directory holds settings alone. The
114
+ * path stays on this list because the install still creates it.)* **Not a pre-release artifact:** Fito
115
+ * ships via `npx skills add`, whose default scope is **project** (`-g` is opt-in) and whose pi
116
+ * project dir is `.pi/skills/` — a case checkout is a project dir, so the default install lands it
117
+ * in every author's case tree. **Admitted on weaker ground than its siblings, deliberately:** they
118
+ * cannot be relocated even in principle, whereas this one can (`-g`, or installing from a parent
119
+ * dir). It is tolerated because preventing it means a behavioural instruction fighting the tool's
120
+ * default on every install — the shape Task 9b.13 rejected in favour of a mechanical guard — not
121
+ * because relocation is impossible.
122
+ *
123
+ * Git collapses any of these untracked dirs into a single `?? <path>` porcelain line.
124
+ */
125
+ const AUTHORING_HARNESS_PATHS: readonly string[] = [".pi-subagents/", "output/", ".pi/"];
126
+
127
+ /**
128
+ * Filter `git status --porcelain` output down to the changes the clean-tree gate must still refuse,
129
+ * dropping only an **untracked** `AUTHORING_HARNESS_PATHS` member so publish is not blocked on pure
130
+ * authoring-harness noise (F23, F30, F31). A porcelain line is `XY<space>path`; a line is dropped iff its
131
+ * status is `??` (untracked) **and** its path is under one of those paths. A **tracked** member (a
132
+ * stray `git add -A` stages each file with status `A `, not `??`) and every other change are kept, so
133
+ * real dirt still blocks — the asymmetry matters because the publish pushes `HEAD` to `main` *and* to
134
+ * the frozen `vX.Y.Z` branch and tag, whose refs are immutable once published.
135
+ *
136
+ * The match is **start-anchored on a path that ends in `/`**, which makes it precise in both
137
+ * directions: `--porcelain` prints paths relative to the **repository root** even when git runs from
138
+ * a subdirectory (unlike the short format's CWD-relative default), so only the case-root workspace
139
+ * matches — a `src/output/` is some build's and still blocks, as do a neighbouring `output-notes/`
140
+ * and a plain file named `output`. The slash carries the most weight for `.pi/`, whose bare form
141
+ * would prefix-match the whole `.pi*` dotfile space (`.pilot-notes/`, `.pi-cache`); with it, only
142
+ * the pi project dir matches and a nested `src/.pi/` still blocks.
143
+ *
144
+ * Returns the surviving porcelain lines joined by newlines (no trailing newline; empty when nothing
145
+ * gates) — the porcelain status field legitimately leads with a space (` M`), so the result is
146
+ * deliberately not trimmed.
147
+ */
148
+ export function withoutAuthoringHarnessPaths(porcelain: string): string {
149
+ return porcelain
150
+ .split("\n")
151
+ .filter((line) => {
152
+ if (line.length === 0) return false;
153
+ const status = line.slice(0, 2);
154
+ const path = line.slice(3);
155
+ const isUntrackedHarnessPath =
156
+ status === "??" && AUTHORING_HARNESS_PATHS.some((harnessPath) => path.startsWith(harnessPath));
157
+ return !isUntrackedHarnessPath;
158
+ })
159
+ .join("\n");
160
+ }
161
+
162
+ /**
163
+ * `git branch --list <branch>` — probe whether the local solution branch exists (empty stdout =
164
+ * missing). Preferred over `rev-parse --verify` because it exits 0 either way, so the throwing
165
+ * executor doesn't conflate "missing branch" with a real git failure.
166
+ */
167
+ export function gitListLocalBranchCommand(branch: string): ShellCommand {
168
+ return { command: "git", args: ["branch", "--list", branch] };
169
+ }
170
+
171
+ /**
172
+ * `git diff --name-only <solutionBranch> HEAD -- .case` — the `.case/` parity probe (Task 9a.7):
173
+ * non-empty stdout = the solution branch's `.case/` diverged from the canonical branch's (F9 —
174
+ * plan-source finalizes `artifacts.yaml` on `main` after the solution branch was cut). Exits 0
175
+ * either way, so the throwing executor doesn't conflate "divergent" with a real git failure.
176
+ */
177
+ export function gitCaseParityDiffCommand(solutionBranch: string): ShellCommand {
178
+ return { command: "git", args: ["diff", "--name-only", solutionBranch, "HEAD", "--", ".case"] };
179
+ }
180
+
181
+ /** `git rev-parse --abbrev-ref HEAD` — the author's current branch: the reconcile's restore source and return point. */
182
+ export function gitCurrentBranchCommand(): ShellCommand {
183
+ return { command: "git", args: ["rev-parse", "--abbrev-ref", "HEAD"] };
184
+ }
185
+
186
+ /** `git checkout <ref>` — switch branches during the reconcile (the case-runner's convention). */
187
+ export function gitCheckoutCommand(ref: string): ShellCommand {
188
+ return { command: "git", args: ["checkout", ref] };
189
+ }
190
+
191
+ /**
192
+ * `git restore --source <ref> --staged --worktree -- .case` — replace `.case/` wholesale from the
193
+ * canonical branch: unlike `git checkout <ref> -- path`, `git restore` also DELETES tracked paths
194
+ * absent in the source, and the pathspec keeps everything outside `.case/` untouched.
195
+ */
196
+ export function gitRestoreCaseDirCommand(sourceRef: string): ShellCommand {
197
+ return { command: "git", args: ["restore", "--source", sourceRef, "--staged", "--worktree", "--", ".case"] };
198
+ }
199
+
200
+ /** `git commit -m …` — the reconcile commit (the restore staged its changes, so no `git add`). */
201
+ export function gitCommitCaseParityCommand(): ShellCommand {
202
+ return {
203
+ command: "git",
204
+ args: ["commit", "-m", "chore: sync .case/ with main — the case description is branch-invariant"],
205
+ };
206
+ }
207
+
208
+ /**
209
+ * The one-shot push of every case ref to the repo URL: the current branch as the canonical
210
+ * `main`, plus the frozen `vX.Y.Z` **branch and tag** (a case repo carries both, which is why
211
+ * every version ref is an explicit refspec — lesson 46) and the `case/solution-vX.Y.Z` exemplar
212
+ * branch. The version refs are `+`-forced so a fix-and-retry can re-cut them: safe pre-publish,
213
+ * and the published-guard stops any post-publish re-run before this command (published refs are
214
+ * immutable — SPEC "Never" boundary).
215
+ */
216
+ export function gitPushCaseRefsCommand(
217
+ repoUrl: string,
218
+ versionRef: string,
219
+ solutionBranch: string,
220
+ ): ShellCommand {
221
+ return {
222
+ command: "git",
223
+ args: [
224
+ "push",
225
+ repoUrl,
226
+ "HEAD:refs/heads/main",
227
+ `+HEAD:refs/heads/${versionRef}`,
228
+ `+HEAD:refs/tags/${versionRef}`,
229
+ `+refs/heads/${solutionBranch}:refs/heads/${solutionBranch}`,
230
+ ],
231
+ };
232
+ }
233
+
234
+ /**
235
+ * `git fetch origin --tags` — the post-publish refresh of the author's **own** bookkeeping (F58).
236
+ * Because the push above goes to an explicit URL and never through a named remote, git updates no
237
+ * remote-tracking ref from it: `git status` reports a false *ahead*, the new tag is absent, and
238
+ * `origin/vX.Y.Z` does not exist locally. A fetch clears all of that **without breaking the rule
239
+ * the push exists to keep** — it reads from the remote and writes only local `refs/remotes/*` and
240
+ * tags, so it neither pushes through `origin` nor edits remote config.
241
+ *
242
+ * `--tags` is **belt-and-braces, not load-bearing** — measured, not assumed (2026-08-27): a bare
243
+ * `git fetch origin` against a real stale checkout brought `v1.2.0` too, because git's default
244
+ * tag auto-following already fetches a tag pointing into the history it fetched, and a case repo's
245
+ * `vX.Y.Z` tag and `main` name the same commit. `--tags` is kept because it also covers a tag that
246
+ * points *outside* that history, and because it is the command the failure warning tells the author
247
+ * to run — the two must not drift apart.
248
+ */
249
+ export function gitFetchOriginTagsCommand(): ShellCommand {
250
+ return { command: "git", args: ["fetch", "origin", "--tags"] };
251
+ }
@@ -0,0 +1,108 @@
1
+ import { learningObjectivesSchema, manifestSchema, prerequisitesSchema, quizSchema, rubricSchema, solutionSchema, } from "../../shared/case-validation/case-schema.js";
2
+ /** Read the publish-flow facts from validated `.case/` content. */
3
+ export function readCasePublishFacts(content) {
4
+ const manifest = manifestSchema.parse(content.manifest);
5
+ const solution = solutionSchema.parse(content.solution);
6
+ return {
7
+ title: manifest.title,
8
+ version: manifest.version,
9
+ versionRef: `v${manifest.version}`,
10
+ solutionBranch: solution.branch,
11
+ };
12
+ }
13
+ /** Build both Case Registry write payloads from one validated `.case/` tree. */
14
+ export function buildCaseWritePayloads(input) {
15
+ const manifest = manifestSchema.parse(input.content.manifest);
16
+ const register = {
17
+ type: manifest.type.toUpperCase(),
18
+ repositoryUrl: input.repositoryUrl,
19
+ gitPlatform: "GITHUB",
20
+ versionRef: `v${manifest.version}`,
21
+ version: manifest.version,
22
+ visibility: "PUBLIC",
23
+ };
24
+ return {
25
+ register,
26
+ publish: buildPublishFields(input.content, input.descriptionOverview, input.attestation),
27
+ };
28
+ }
29
+ /**
30
+ * Build the `POST /cases/{id}/versions` payload from one validated `.case/` tree (Task 9.8): the
31
+ * publish fields plus the new version identity — `manifest.version`, its derived `versionRef`
32
+ * (exactly `"v" + version`, the Task 9.4 contract), and the required `changeDescription`.
33
+ */
34
+ export function buildCaseVersionPayload(input) {
35
+ if (input.changeDescription.trim().length === 0) {
36
+ throw new Error("the change description is blank — every published version must document its correction");
37
+ }
38
+ const manifest = manifestSchema.parse(input.content.manifest);
39
+ return {
40
+ version: manifest.version,
41
+ versionRef: `v${manifest.version}`,
42
+ changeDescription: input.changeDescription,
43
+ ...buildPublishFields(input.content, input.descriptionOverview, input.attestation),
44
+ };
45
+ }
46
+ /** The publish fields shared by `POST /cases/{id}/publish` and `POST /cases/{id}/versions`. */
47
+ function buildPublishFields(content, descriptionOverview, attestation) {
48
+ if (descriptionOverview.trim().length === 0) {
49
+ throw new Error("the description overview is blank — the backend requires a non-blank storefront description");
50
+ }
51
+ const manifest = manifestSchema.parse(content.manifest);
52
+ const learningObjectives = learningObjectivesSchema.parse(content.learningObjectives);
53
+ const prerequisites = prerequisitesSchema.parse(content.prerequisites);
54
+ const rubric = rubricSchema.parse(content.rubric);
55
+ const quiz = content.quiz === undefined ? undefined : quizSchema.parse(content.quiz);
56
+ const publish = {
57
+ title: manifest.title,
58
+ descriptionOverview,
59
+ tags: manifest.tags,
60
+ estimatedDurationMinutes: manifest.estimated_duration_minutes,
61
+ language: manifest.language,
62
+ learningObjectives: learningObjectives.learning_objectives.map((c) => ({
63
+ componentId: c.knowledge_component,
64
+ bloomLevel: c.bloom_level,
65
+ description: c.description,
66
+ weight: c.weight.toUpperCase(),
67
+ })),
68
+ // A prerequisite's `mandatory` has no publish-wire field (ADR-005 §2) — dropped. Its
69
+ // `description` is carried (Task 12a.3): `undefined` when the entry omits it, which
70
+ // `JSON.stringify` drops, so the backend stores null.
71
+ prerequisites: prerequisites.prerequisites.map((p) => ({
72
+ componentId: p.knowledge_component,
73
+ bloomLevel: p.bloom_level,
74
+ description: p.description,
75
+ })),
76
+ rubric: rubric.criteria.map((cr) => ({
77
+ componentId: cr.knowledge_component,
78
+ bloomLevel: cr.bloom_level,
79
+ })),
80
+ attestation,
81
+ };
82
+ if (quiz !== undefined) {
83
+ publish.quiz = { questions: quiz.questions.map(toWireQuestion) };
84
+ }
85
+ return publish;
86
+ }
87
+ /** One quiz question → the wire shape: uppercased type token, snake_case fields renamed. */
88
+ function toWireQuestion(q) {
89
+ const question = {
90
+ id: q.id,
91
+ type: q.type.toUpperCase(),
92
+ prompt: q.prompt,
93
+ knowledgeComponents: q.knowledge_components,
94
+ bloomLevel: q.bloom_level,
95
+ };
96
+ if (q.weight !== undefined)
97
+ question.weight = q.weight;
98
+ if (q.choices !== undefined)
99
+ question.choices = q.choices;
100
+ if (q.answer !== undefined)
101
+ question.answer = q.answer;
102
+ if (q.evaluation !== undefined) {
103
+ question.evaluation = { method: q.evaluation.method };
104
+ if (q.evaluation.prompt_hint !== undefined)
105
+ question.evaluation.promptHint = q.evaluation.prompt_hint;
106
+ }
107
+ return question;
108
+ }
@@ -0,0 +1,186 @@
1
+ import {
2
+ learningObjectivesSchema,
3
+ manifestSchema,
4
+ prerequisitesSchema,
5
+ quizSchema,
6
+ rubricSchema,
7
+ solutionSchema,
8
+ } from "../../shared/case-validation/case-schema.ts";
9
+ import type { Attestation, CaseContent } from "../../shared/case-validation/case-schema.ts";
10
+ import type {
11
+ CasePublishQuizQuestion,
12
+ PublishCaseInput,
13
+ PublishCaseVersionInput,
14
+ RegisterCaseInput,
15
+ } from "../../shared/fito-api/client.ts";
16
+
17
+ /**
18
+ * Maps validated `.case/` content onto the two Case Registry write payloads (Task 9.3):
19
+ * `POST /cases` (the pointer + classification) and `POST /cases/{id}/publish` (S1 presentation +
20
+ * role-grouped references + optional quiz + attestation). Pure — no filesystem, no HTTP.
21
+ *
22
+ * The caller must have run the structural validator over the same content first
23
+ * (`validateCaseContent` — `publish.ts` does); this module re-parses with the shared Zod schemas
24
+ * only to get typed values, so a parse failure here means the content changed since validation.
25
+ */
26
+
27
+ /** What `buildCaseWritePayloads` needs beyond the `.case/` content itself. */
28
+ export interface CaseWritePayloadInput {
29
+ /** Parsed `.case/` content (from `loadCaseDir`), already structurally validated. */
30
+ content: CaseContent;
31
+ /** The https GitHub URL of the case repo (constructed, not parsed — lesson 46: never ssh). */
32
+ repositoryUrl: string;
33
+ /** The author-approved storefront markdown (S1) — the backend requires it non-blank. */
34
+ descriptionOverview: string;
35
+ /** The attestation from the validator run over this same tree. */
36
+ attestation: Attestation;
37
+ }
38
+
39
+ /** The pair of Case Registry write payloads, built from one `.case/` tree. */
40
+ export interface CaseWritePayloads {
41
+ register: RegisterCaseInput;
42
+ publish: PublishCaseInput;
43
+ }
44
+
45
+ /** The `.case/` facts the publish flow needs outside the payloads (refspecs, local-branch guard). */
46
+ export interface CasePublishFacts {
47
+ title: string;
48
+ /** `manifest.version`, e.g. `1.0.0`. */
49
+ version: string;
50
+ /** The frozen ref name derived from it, e.g. `v1.0.0` — the tag, the branch, and the registered `versionRef`. */
51
+ versionRef: string;
52
+ /** The local exemplar branch named by `solution.yaml` (e.g. `case/solution-v1.0.0`). */
53
+ solutionBranch: string;
54
+ }
55
+
56
+ /** Read the publish-flow facts from validated `.case/` content. */
57
+ export function readCasePublishFacts(content: CaseContent): CasePublishFacts {
58
+ const manifest = manifestSchema.parse(content.manifest);
59
+ const solution = solutionSchema.parse(content.solution);
60
+ return {
61
+ title: manifest.title,
62
+ version: manifest.version,
63
+ versionRef: `v${manifest.version}`,
64
+ solutionBranch: solution.branch,
65
+ };
66
+ }
67
+
68
+ /** Build both Case Registry write payloads from one validated `.case/` tree. */
69
+ export function buildCaseWritePayloads(input: CaseWritePayloadInput): CaseWritePayloads {
70
+ const manifest = manifestSchema.parse(input.content.manifest);
71
+ const register: RegisterCaseInput = {
72
+ type: manifest.type.toUpperCase(),
73
+ repositoryUrl: input.repositoryUrl,
74
+ gitPlatform: "GITHUB",
75
+ versionRef: `v${manifest.version}`,
76
+ version: manifest.version,
77
+ visibility: "PUBLIC",
78
+ };
79
+ return {
80
+ register,
81
+ publish: buildPublishFields(input.content, input.descriptionOverview, input.attestation),
82
+ };
83
+ }
84
+
85
+ /** What `buildCaseVersionPayload` needs: the `.case/` content plus the two author-approved texts + attestation. */
86
+ export interface CaseVersionPayloadInput {
87
+ /** Parsed `.case/` content (from `loadCaseDir`), already structurally validated. */
88
+ content: CaseContent;
89
+ /** The author-approved storefront markdown (S1) — the backend requires it non-blank. */
90
+ descriptionOverview: string;
91
+ /** The ADR-009 chain note documenting the correction — the backend requires it non-blank. */
92
+ changeDescription: string;
93
+ /** The attestation from the validator run over this same tree. */
94
+ attestation: Attestation;
95
+ }
96
+
97
+ /**
98
+ * Build the `POST /cases/{id}/versions` payload from one validated `.case/` tree (Task 9.8): the
99
+ * publish fields plus the new version identity — `manifest.version`, its derived `versionRef`
100
+ * (exactly `"v" + version`, the Task 9.4 contract), and the required `changeDescription`.
101
+ */
102
+ export function buildCaseVersionPayload(input: CaseVersionPayloadInput): PublishCaseVersionInput {
103
+ if (input.changeDescription.trim().length === 0) {
104
+ throw new Error(
105
+ "the change description is blank — every published version must document its correction",
106
+ );
107
+ }
108
+ const manifest = manifestSchema.parse(input.content.manifest);
109
+ return {
110
+ version: manifest.version,
111
+ versionRef: `v${manifest.version}`,
112
+ changeDescription: input.changeDescription,
113
+ ...buildPublishFields(input.content, input.descriptionOverview, input.attestation),
114
+ };
115
+ }
116
+
117
+ /** The publish fields shared by `POST /cases/{id}/publish` and `POST /cases/{id}/versions`. */
118
+ function buildPublishFields(
119
+ content: CaseContent,
120
+ descriptionOverview: string,
121
+ attestation: Attestation,
122
+ ): PublishCaseInput {
123
+ if (descriptionOverview.trim().length === 0) {
124
+ throw new Error(
125
+ "the description overview is blank — the backend requires a non-blank storefront description",
126
+ );
127
+ }
128
+
129
+ const manifest = manifestSchema.parse(content.manifest);
130
+ const learningObjectives = learningObjectivesSchema.parse(content.learningObjectives);
131
+ const prerequisites = prerequisitesSchema.parse(content.prerequisites);
132
+ const rubric = rubricSchema.parse(content.rubric);
133
+ const quiz = content.quiz === undefined ? undefined : quizSchema.parse(content.quiz);
134
+
135
+ const publish: PublishCaseInput = {
136
+ title: manifest.title,
137
+ descriptionOverview,
138
+ tags: manifest.tags,
139
+ estimatedDurationMinutes: manifest.estimated_duration_minutes,
140
+ language: manifest.language,
141
+ learningObjectives: learningObjectives.learning_objectives.map((c) => ({
142
+ componentId: c.knowledge_component,
143
+ bloomLevel: c.bloom_level,
144
+ description: c.description,
145
+ weight: c.weight.toUpperCase(),
146
+ })),
147
+ // A prerequisite's `mandatory` has no publish-wire field (ADR-005 §2) — dropped. Its
148
+ // `description` is carried (Task 12a.3): `undefined` when the entry omits it, which
149
+ // `JSON.stringify` drops, so the backend stores null.
150
+ prerequisites: prerequisites.prerequisites.map((p) => ({
151
+ componentId: p.knowledge_component,
152
+ bloomLevel: p.bloom_level,
153
+ description: p.description,
154
+ })),
155
+ rubric: rubric.criteria.map((cr) => ({
156
+ componentId: cr.knowledge_component,
157
+ bloomLevel: cr.bloom_level,
158
+ })),
159
+ attestation,
160
+ };
161
+ if (quiz !== undefined) {
162
+ publish.quiz = { questions: quiz.questions.map(toWireQuestion) };
163
+ }
164
+ return publish;
165
+ }
166
+
167
+ type QuizQuestion = ReturnType<typeof quizSchema.parse>["questions"][number];
168
+
169
+ /** One quiz question → the wire shape: uppercased type token, snake_case fields renamed. */
170
+ function toWireQuestion(q: QuizQuestion): CasePublishQuizQuestion {
171
+ const question: CasePublishQuizQuestion = {
172
+ id: q.id,
173
+ type: q.type.toUpperCase(),
174
+ prompt: q.prompt,
175
+ knowledgeComponents: q.knowledge_components,
176
+ bloomLevel: q.bloom_level,
177
+ };
178
+ if (q.weight !== undefined) question.weight = q.weight;
179
+ if (q.choices !== undefined) question.choices = q.choices;
180
+ if (q.answer !== undefined) question.answer = q.answer;
181
+ if (q.evaluation !== undefined) {
182
+ question.evaluation = { method: q.evaluation.method };
183
+ if (q.evaluation.prompt_hint !== undefined) question.evaluation.promptHint = q.evaluation.prompt_hint;
184
+ }
185
+ return question;
186
+ }
@@ -0,0 +1,72 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { z } from "zod";
5
+ /**
6
+ * Publish retry state at `~/.fito/publish-state.json` (Task 9.3): `POST /cases` is **not**
7
+ * idempotent — a repeat run would mint a second, orphaned draft — so the minted case id is
8
+ * remembered here, keyed by the case's `repositoryUrl`, until the publish succeeds. Kept in
9
+ * `~/.fito` (the TUI's local-state home) and **not** in the case repo, where it would trip the
10
+ * publish flow's own clean-tree guard on every retry.
11
+ *
12
+ * An entry is trusted only when its stored `apiBaseUrl` matches the current backend — a
13
+ * dev-vs-prod switch ignores it (and registers fresh) instead of 404ing on a foreign id.
14
+ */
15
+ const entrySchema = z.object({
16
+ caseId: z.string().min(1),
17
+ apiBaseUrl: z.string().min(1),
18
+ registeredAt: z.string().min(1),
19
+ });
20
+ const stateSchema = z.record(z.string(), entrySchema);
21
+ /** The `~/.fito/publish-state.json` file path. */
22
+ export function publishStatePath(home = os.homedir()) {
23
+ return path.join(home, ".fito", "publish-state.json");
24
+ }
25
+ /**
26
+ * The registered-but-unpublished draft id for `repositoryUrl` against the current backend, or
27
+ * `null` when there is none (never written, cleared, corrupt file, or a different `apiBaseUrl`).
28
+ */
29
+ export function readPublishState(repositoryUrl, apiBaseUrl, home = os.homedir()) {
30
+ const entry = readState(home)[repositoryUrl];
31
+ if (!entry || entry.apiBaseUrl !== apiBaseUrl)
32
+ return null;
33
+ return entry.caseId;
34
+ }
35
+ /** Remember a freshly minted draft id for `repositoryUrl` (overwrites that URL's entry only). */
36
+ export function writePublishState(repositoryUrl, entry, home = os.homedir()) {
37
+ const state = readState(home);
38
+ state[repositoryUrl] = { ...entry, registeredAt: new Date().toISOString() };
39
+ writeState(state, home);
40
+ }
41
+ /** Drop `repositoryUrl`'s entry (the publish succeeded); other repos' entries are kept. */
42
+ export function clearPublishState(repositoryUrl, home = os.homedir()) {
43
+ const state = readState(home);
44
+ if (!(repositoryUrl in state))
45
+ return;
46
+ delete state[repositoryUrl];
47
+ writeState(state, home);
48
+ }
49
+ /** Read + validate the state file; absent or corrupt reads as empty (a write recovers it). */
50
+ function readState(home) {
51
+ let raw;
52
+ try {
53
+ raw = fs.readFileSync(publishStatePath(home), "utf8");
54
+ }
55
+ catch {
56
+ return {};
57
+ }
58
+ let parsed;
59
+ try {
60
+ parsed = JSON.parse(raw);
61
+ }
62
+ catch {
63
+ return {};
64
+ }
65
+ const result = stateSchema.safeParse(parsed);
66
+ return result.success ? result.data : {};
67
+ }
68
+ function writeState(state, home) {
69
+ const file = publishStatePath(home);
70
+ fs.mkdirSync(path.dirname(file), { recursive: true });
71
+ fs.writeFileSync(file, `${JSON.stringify(state, null, 2)}\n`);
72
+ }