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,179 @@
1
+ ---
2
+ name: fito-case-author
3
+ description: >
4
+ Validate, publish, version, or check out a Fito case working directory. Use
5
+ when /fito-case-generate's validate loop runs, when /fito-publish-case pushes
6
+ a finished case to GitHub and registers it with the backend — or publishes a
7
+ new version of an edited authoring checkout, routing initial vs update by
8
+ registration state — when /fito-case-edit puts a published case back on the
9
+ author's disk for an update, or when a publish flow needs the fresh
10
+ attestation + reference set the backend consumes.
11
+ allowed-tools: bash
12
+ ---
13
+
14
+ # Fito Case Author
15
+
16
+ The author-side counterpart of `fito-case-runner`: the runnable steps of the case-authoring
17
+ lifecycle (validation — Task 9.2; publish — Task 9.3; authoring checkout — Task 9.7; version
18
+ publish — Task 9.8). Run the scripts from wherever you are — each command below names this
19
+ skill's directory itself.
20
+
21
+ ## Validate a case working directory
22
+
23
+ ```bash
24
+ node <fito-case-author skill dir>/validate.js <case-working-dir>
25
+ ```
26
+
27
+ `<case-working-dir>` is the case repo root (the directory containing `.case/`). Runs the shared
28
+ structural validator (ADR-005 — file presence, per-file schemas, weights sum to 100, case-type
29
+ constraints) and prints the `ValidationResult` as JSON on stdout:
30
+
31
+ - **Failure (exit 1):** `{ "ok": false, "errors": [...] }` — one entry per violation, each scoped
32
+ to the `.case/` file (and field path) that produced it: per-file errors designed for an
33
+ edit → re-run loop over the named files.
34
+ - **Success (exit 0):** `{ "ok": true, "attestation": {...}, "references": [...],
35
+ "optionalFieldsNotUsed": {...} }` — the structural attestation (`pass`, validator + ruleset
36
+ versions), the deduped `(componentId, bloomLevel)` reference set (the pair the backend publish
37
+ contract consumes), and the optional fields this case leaves empty, grouped by `.case/` file.
38
+
39
+ **`optionalFieldsNotUsed` is the one thing the errors can never carry.** An optional field is
40
+ never rejected, so no failure message will ever mention it. Relay it: an empty optional field
41
+ is legal and often right, and the author is the one who decides which to fill. It prints on a
42
+ passing run only — and only here, in the authoring CLI. The same validator runs as the
43
+ learner's backstop on `/fito-case-open`, where the inventory would tell a learner which of a
44
+ case's fields its author left blank.
45
+
46
+ **Nothing is persisted.** The backend must receive the attestation of the *last* run over the
47
+ finished tree, so publish flows re-run the validation at publish time instead of trusting a saved
48
+ file (`publish.js` runs it in-process).
49
+
50
+ **Done when** the run exits 0 and the attestation + references + the unused-optional inventory
51
+ were relayed — or the errors were relayed, scoped to their files, for the author to fix.
52
+
53
+ It validates structure only: knowledge-component reference *existence* is resolved by the backend
54
+ at publish (Task 3.3), and git tag/branch reachability is the backend ping — neither is checked here.
55
+
56
+ ## Publish a case
57
+
58
+ ```bash
59
+ node <fito-case-author skill dir>/publish.js <case-working-dir> --repo <owner>/<name> --overview <file> [--case-id <uuid>] [--accept-gh-mismatch]
60
+ ```
61
+
62
+ Takes a **finished** case tree (source work done, solution branch built, everything committed) and
63
+ makes it a published Fito case in one run: re-validates the tree, pushes `main` + the frozen
64
+ `vX.Y.Z` branch/tag + the `case/solution-vX.Y.Z` branch to the GitHub repo (created if absent,
65
+ public, under the Case Creator's account or a chosen org), then registers (`POST /cases`) and
66
+ publishes (`POST /cases/{id}/publish`) with the backend. Requires an authenticated `gh` **and** a
67
+ Fito login (`/fito-login`).
68
+
69
+ - `--repo` — `<owner>/<name>`, or a bare `<name>`: the owner then comes from
70
+ `FITO_PUBLISH_GITHUB_OWNER`, else the authenticated `gh` login.
71
+ - `--overview` — the author-approved storefront markdown (the case's S1 `descriptionOverview`);
72
+ `/fito-publish-case` drafts it into `.authoring/description-overview.md`.
73
+ - `--case-id` — publish an already-registered draft (skips registration).
74
+ - `--accept-gh-mismatch` — the author's explicit confirmation after the script stopped on a
75
+ gh↔Fito-linked-identity mismatch. **The confirmation is the author's — never yours.**
76
+
77
+ **Safe to re-run after a failure.** The repo is probed before creation (never duplicated), the
78
+ minted draft id is remembered in `~/.fito/publish-state.json` and reused (registration is not
79
+ idempotent), and the local checkout is never modified. Backend rejections print the problem detail
80
+ **verbatim** — relay it unchanged; the fix is the author's call (a missing knowledge component →
81
+ the knowledge pipeline + `/fito-push-knowledge`; a wrong `.case/` value → `/fito-case-generate`).
82
+
83
+ **Done when** it prints the backend case id + `PUBLISHED` and the web URL — or the stop/rejection
84
+ was relayed verbatim with its re-run affordance (`--case-id` / `--accept-gh-mismatch`).
85
+
86
+ It refuses: a dirty tree (what is validated must be exactly what is pushed), a missing local
87
+ solution branch (build it per `/fito-case-plan-source` first), and a URL that is already a
88
+ published case (updating published cases is the version publish below — their refs are immutable).
89
+
90
+ ## Check a published case out for editing
91
+
92
+ ```bash
93
+ node <fito-case-author skill dir>/checkout.js <case-id> [--dir <target>]
94
+ ```
95
+
96
+ The beginning of the update workflow (ADR-009), driven by `/fito-case-edit`: a **direct clone**
97
+ of the case repo — never a fork, so `authoring-check.js` reads the tree as an authoring context —
98
+ checked out on `main` (the development branch, not the frozen ref), into
99
+ `~/.fito/authoring/<case-id>` unless `--dir` says otherwise. No Fito login is needed for a
100
+ published case; with one, the owner's own `DRAFT` resolves to its publish routing instead of a
101
+ bare 404.
102
+
103
+ It prints the orientation brief — the currently published version, the latest change description
104
+ (an initial version has none), the `.case/` summary, and the frozen-reference update rules — and
105
+ it **warns rather than refuses** on: a `gh` account that doesn't own the case repo (editing
106
+ locally is fine; the version-publish push needs write access), and a `.case/` tree that doesn't
107
+ read cleanly (route the fix through `validate.js`).
108
+
109
+ It refuses: a draft (finish the initial publish — `/fito-publish-case`), a deprecated case (a
110
+ correction to a retired case is a **new** case — `/fito-case-design`), an unknown id, and a
111
+ non-empty target directory (it never overwrites).
112
+
113
+ **Done when** the checkout path and branch `main` were printed and the brief was relayed — or the
114
+ refusal was relayed, verbatim, with its named route.
115
+
116
+ ## Publish a new version of a published case
117
+
118
+ ```bash
119
+ node <fito-case-author skill dir>/publish-version.js <case-working-dir> --change-description <file> --overview <file>
120
+ ```
121
+
122
+ The end of the update workflow (ADR-009), driven by `/fito-publish-case` from an **edited,
123
+ committed** authoring checkout (`/fito-case-edit`'s output, on `main`): re-validates the tree
124
+ (fresh attestation), resolves the case from the checkout's `origin` URL via the registry lookup,
125
+ **preflights the frozen reference set** against the backend's structured views, pushes `main` +
126
+ the new `vX.Y.Z` branch/tag + `case/solution-vX.Y.Z` (explicit refspecs), and calls
127
+ `POST /cases/{id}/versions` with the required change description. Requires a Fito login
128
+ (`/fito-login`) and a git credential with write access to the case repo.
129
+
130
+ - `--change-description` — the author-approved ADR-009 correction note; `/fito-publish-case`
131
+ drafts it into `.authoring/change-description.md`.
132
+ - `--overview` — the (possibly revised) storefront markdown, `.authoring/description-overview.md`.
133
+ - `--probe` (alone, no other flags) — resolve the route only: prints `route: update` with the
134
+ case id + currently published version, `route: deprecated` with that same orientation plus the
135
+ ADR-009 successor guidance (a retired case's correction is a **new** case — the probe decides
136
+ this stop, not the prompt), or `route: initial` with the reason. How `/fito-publish-case`
137
+ decides among the initial publish, this flow, and the deprecation stop.
138
+
139
+ **Safe to re-run after a failure.** Nothing is registered until the final call succeeds, the new
140
+ refs are force-re-cut on retry (they are unregistered until then; published refs are protected by
141
+ the strictly-greater guard), and the local checkout is never modified. Backend rejections print
142
+ the problem detail **verbatim** — relay it unchanged.
143
+
144
+ **Done when** it prints the new version (previous → new) and the web URL — or the stop was
145
+ relayed verbatim with its named route.
146
+
147
+ It refuses, before anything is pushed: a stale `submission.target_branch` or `solution.yaml`
148
+ branch (both must name the new version), a dirty tree, a missing local exemplar branch, a version
149
+ not **strictly greater** than the published one (SemVer precedence — a lower or equal version
150
+ could force-move a published frozen ref), a **reference-set change** (itemized added/removed —
151
+ a reference-changing correction is a new case: `/fito-case-design`, deprecate this one), a
152
+ deprecated case, and an origin URL matched by **more than one** registered case (out-of-band
153
+ registrations — it never guesses which case the checkout is).
154
+
155
+ ## Configuration
156
+
157
+ | Env var | Default | Purpose |
158
+ |---|---|---|
159
+ | `FITO_API_BASE_URL` | `http://localhost:8080` | Backend origin (registry writes + session) |
160
+ | `FITO_PUBLISH_GITHUB_OWNER` | *(unset — falls back to the `gh` login)* | Default repo owner (e.g. an org) for a bare `--repo <name>` |
161
+ | `FITO_WEB_ORIGIN` | `http://localhost:5173` | The web origin used in the printed case URL |
162
+
163
+ ## Files
164
+
165
+ | File | Role |
166
+ |---|---|
167
+ | `validate.ts` | CLI entrypoint — argv + JSON stdout over the shared validator, plus the schema-derived inventory of unused optional fields (authoring-only) |
168
+ | `publish.ts` | CLI entrypoint — `runPublish` core: validate → guard → push → register → publish |
169
+ | `checkout.ts` | CLI entrypoint — `runCheckout` core: fetch → status gate → direct clone of `main` → orient |
170
+ | `publish-version.ts` | CLI entrypoint — `runPublishVersion` core: validate → staleness guards → origin route → frozen-set preflight → push → `POST /cases/{id}/versions`; `--probe` resolves initial vs update |
171
+ | `publish-payload.ts` | Pure `.case/` → register/publish/version wire-payload mapping (+ publish facts) |
172
+ | `github-publish.ts` | Pure `gh`/`git` command builders (repo create, explicit-refspec push, guards) |
173
+ | `semver.ts` | SemVer 2.0.0 precedence — the strictly-greater pre-push guard (mirrors the backend `SemVerPrecedence`) |
174
+ | `status-gate.ts` | One home for the case-status policy (ADR-009): the status → allow/refuse/hint mapping behind `checkout.ts`, `runPublishVersion`, and the probe's deprecated route |
175
+ | `publish-state.ts` | `~/.fito/publish-state.json` — the draft-id retry store |
176
+ | — | The real `gh`/`git` executor is the shared `../../shared/shell-exec/exec.ts` (ADR-006) |
177
+
178
+ See [the `.case/` validator](../../shared/case-validation/) for the ruleset itself and
179
+ [the fito-api client](../../shared/fito-api/README.md) for the registry endpoints.
@@ -0,0 +1,222 @@
1
+ /**
2
+ * `node checkout.js <case-id> [--dir <target>]` — the `fito-case-author` authoring-checkout
3
+ * entrypoint (Task 9.7, ADR-009 §6): put a published case's source back on the author's disk in
4
+ * **authoring** shape. A **direct clone** of the case repo — the author's own repo, never a fork —
5
+ * so `authoring-check.ts` classifies the tree `authoring` and the knowledge-pipeline `--source .`
6
+ * offer stays available; checked out on **`main`**, the development branch (every case repo has
7
+ * one — the publish flow lands it), not the frozen `vX.Y.Z` ref.
8
+ *
9
+ * Driven by the `/fito-case-edit` orchestrator; `runCheckout` is the testable core (injectable
10
+ * executor + client — the open.ts pattern), `main` the thin CLI wrapper. The Fito session is
11
+ * resolved **best-effort**: no login is needed to check out a published case, but a logged-in
12
+ * owner's `DRAFT` resolves to its "never published" routing instead of a bare 404. A gh↔repo-owner
13
+ * mismatch **warns and proceeds** — the push would fail later anyway, and warning early is the
14
+ * kindness; refusing is not this script's call.
15
+ */
16
+ import { existsSync, mkdirSync, readdirSync } from "node:fs";
17
+ import * as os from "node:os";
18
+ import * as path from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+ import { loadCaseDir } from "../../shared/case-validation/case-loader.js";
21
+ import { manifestSchema } from "../../shared/case-validation/case-schema.js";
22
+ import { FitoApiError, createFitoApiClient } from "../../shared/fito-api/client.js";
23
+ import { resolveFitoSession } from "../../shared/fito-session/session.js";
24
+ import { parseGithubHttpsUrl } from "../../shared/github-url/parse.js";
25
+ import { ghCurrentLoginCommand } from "./github-publish.js";
26
+ import { gateStatus } from "./status-gate.js";
27
+ /**
28
+ * `git clone --branch main <url> <dir>` — the direct authoring clone. The explicit `--branch main`
29
+ * is the Task 9.7 contract (the publish flow lands every case repo's development branch as `main`);
30
+ * a repo somehow missing it fails loudly here instead of landing on an arbitrary default branch.
31
+ */
32
+ export function gitCloneMainCommand(repoUrl, targetDir) {
33
+ return { command: "git", args: ["clone", "--branch", "main", repoUrl, targetDir] };
34
+ }
35
+ /** Fetch case → status gate → guard the target dir → direct clone of main → ownership check → orient. */
36
+ export async function runCheckout(options) {
37
+ const home = options.home ?? os.homedir();
38
+ const client = options.client ?? createFitoApiClient();
39
+ const exec = options.exec ?? (await import("../../shared/shell-exec/exec.js")).shellExec;
40
+ // Best-effort session (the open.ts enrollment pattern): a published checkout needs no login,
41
+ // but with one the backend serves the owner's own DRAFT (getCase's optional bearer, Task 9.7).
42
+ let accessToken;
43
+ try {
44
+ accessToken = (await resolveFitoSession(client, home)).tokens.accessToken;
45
+ }
46
+ catch {
47
+ accessToken = undefined;
48
+ }
49
+ const detail = await fetchDetail(client, options.caseId, accessToken);
50
+ gateStatus(detail, "checkout");
51
+ if (detail.gitPlatform !== "GITHUB") {
52
+ throw new Error(`case git platform ${detail.gitPlatform} is not supported — non-GitHub platforms are deferred to post-MVP`);
53
+ }
54
+ const repo = parseGithubHttpsUrl(detail.repositoryUrl);
55
+ if (repo === null) {
56
+ throw new Error(`the registered repository URL is not an https github.com URL: ${detail.repositoryUrl}`);
57
+ }
58
+ const targetDir = options.dir ? path.resolve(options.dir) : path.join(home, ".fito", "authoring", options.caseId);
59
+ if (existsSync(targetDir) && readdirSync(targetDir).length > 0) {
60
+ throw new Error(`A directory already exists and is not empty:\n ${targetDir}\n` +
61
+ `If it is your earlier authoring checkout, keep working there. Otherwise move or remove it,\n` +
62
+ `or pass --dir <path> to clone elsewhere — Fito will not overwrite it.`);
63
+ }
64
+ mkdirSync(path.dirname(targetDir), { recursive: true });
65
+ try {
66
+ await exec(gitCloneMainCommand(detail.repositoryUrl, targetDir), { cwd: path.dirname(targetDir) });
67
+ }
68
+ catch (error) {
69
+ const reason = error instanceof Error ? error.message : String(error);
70
+ // The one clone failure with a Fito-specific story (F15): a repo carrying only frozen refs.
71
+ if (/remote branch main not found/i.test(reason)) {
72
+ throw new Error(`The case repository has no \`main\` development branch:\n ${detail.repositoryUrl}\n` +
73
+ `Every editable case needs one — the Fito publish flow creates it, so this repo was likely\n` +
74
+ `published outside that flow (frozen version refs only). Push a \`main\` branch to the repo\n` +
75
+ `(e.g. from the \`${detail.versionRef}\` tip), then re-run.`);
76
+ }
77
+ throw error;
78
+ }
79
+ // Ownership is advisory (Task 9.7: warn, do not refuse): editing locally is always fine, and a
80
+ // non-owner push fails on its own later — this just says so before the author invests the work.
81
+ let ghLogin;
82
+ let ownershipWarning;
83
+ try {
84
+ const login = (await exec(ghCurrentLoginCommand(), { cwd: targetDir })).trim();
85
+ // An empty login is "unverifiable", not "a mismatch with nobody" — route it to the catch.
86
+ if (login.length === 0) {
87
+ throw new Error("gh returned an empty login");
88
+ }
89
+ ghLogin = login;
90
+ if (ghLogin.toLowerCase() !== repo.owner.toLowerCase()) {
91
+ // Informational, not an alarm (F10): the owner-string compare cannot see org write
92
+ // access, so an org member/admin publishing for their org is already covered.
93
+ ownershipWarning =
94
+ `Your gh account (\`${ghLogin}\`) is not \`${repo.owner}\`, which owns ${repo.owner}/${repo.repo}.\n` +
95
+ ` Editing locally is fine. Publishing needs write access to the case repo — an org\n` +
96
+ ` member or admin publishing for their org already has it; otherwise publish with\n` +
97
+ ` an account that does.`;
98
+ }
99
+ }
100
+ catch (error) {
101
+ const reason = error instanceof Error ? error.message : String(error);
102
+ ownershipWarning =
103
+ `Could not verify repo ownership (${reason.trimEnd()})\n` +
104
+ ` Continuing — the version-publish push will need a gh login with write access to ${repo.owner}/${repo.repo}.`;
105
+ }
106
+ // The .case/ summary is read from the tree just produced; a tree that doesn't read cleanly is a
107
+ // warning, not a failure — the checkout is on disk and the validator names what to fix.
108
+ let manifest;
109
+ let structuralWarning;
110
+ try {
111
+ const loaded = loadCaseDir(targetDir);
112
+ manifest = manifestSchema.parse(loaded.content.manifest);
113
+ }
114
+ catch (error) {
115
+ const reason = error instanceof Error ? error.message : String(error);
116
+ structuralWarning =
117
+ `The checked-out .case/ tree does not read cleanly (${reason.trimEnd()})\n` +
118
+ ` Run the validator before editing further: node validate.js ${targetDir}`;
119
+ }
120
+ return {
121
+ caseId: options.caseId,
122
+ title: detail.title,
123
+ version: detail.version,
124
+ versionRef: detail.versionRef,
125
+ changeDescription: detail.changeDescription,
126
+ repositoryUrl: detail.repositoryUrl,
127
+ workDir: targetDir,
128
+ branch: "main",
129
+ ...(ghLogin === undefined ? {} : { ghLogin }),
130
+ ...(ownershipWarning === undefined ? {} : { ownershipWarning }),
131
+ ...(structuralWarning === undefined ? {} : { structuralWarning }),
132
+ ...(manifest === undefined ? {} : { manifest }),
133
+ };
134
+ }
135
+ /** Fetch the detail, mapping API errors to author-facing messages (the case-detail.ts parity). */
136
+ async function fetchDetail(client, caseId, accessToken) {
137
+ try {
138
+ return await client.getCase(caseId, accessToken);
139
+ }
140
+ catch (error) {
141
+ if (error instanceof FitoApiError && error.status === 404) {
142
+ // An unauthenticated read cannot see anyone's draft — say so instead of a dead end.
143
+ const draftHint = accessToken === undefined
144
+ ? `\n(A draft case is visible only to its logged-in owner — if this is your draft, run /fito-login and re-run.)`
145
+ : "";
146
+ throw new Error(`No case found for id "${caseId}".${draftHint}`);
147
+ }
148
+ if (error instanceof FitoApiError) {
149
+ throw new Error(`Could not fetch case "${caseId}" (${error.status}): ${error.message}`);
150
+ }
151
+ throw error;
152
+ }
153
+ }
154
+ /** The orientation brief `main` prints and `/fito-case-edit` relays: the facts, then the ADR-009 update rules. */
155
+ export function renderOrientation(result) {
156
+ const manifestLine = result.manifest === undefined
157
+ ? []
158
+ : [
159
+ ` type: ${result.manifest.type} · ~${result.manifest.estimated_duration_minutes} min · ` +
160
+ `${result.manifest.language} · tags: ${result.manifest.tags.join(", ")}`,
161
+ ];
162
+ return [
163
+ `Case: ${result.title ?? "(untitled)"} (${result.caseId})`,
164
+ ...manifestLine,
165
+ ` currently published: ${result.version} (${result.versionRef})`,
166
+ result.changeDescription === null
167
+ ? ` last change: — (initial version — no change description yet)`
168
+ : ` last change: ${result.changeDescription}`,
169
+ ``,
170
+ `Update rules — the reference set is frozen:`,
171
+ ` - A correction that changes the knowledge references is a new case — design it with`,
172
+ ` /fito-case-design and deprecate this one.`,
173
+ ` - A same-reference perfection is a versioned publish: edit on main, re-validate, publish vX.Y.Z.`,
174
+ ` - Published refs (vX.Y.Z and case/solution-vX.Y.Z) are never rewritten.`,
175
+ ].join("\n");
176
+ }
177
+ const USAGE = "usage: node checkout.js <case-id> [--dir <target>]";
178
+ /** Parse the checkout CLI args (`argv` minus the node/script prefix): the case id plus an optional target dir. */
179
+ export function parseCheckoutArgs(args) {
180
+ const [caseId, ...rest] = args;
181
+ if (!caseId || caseId.startsWith("--")) {
182
+ throw new Error(USAGE);
183
+ }
184
+ if (rest.length === 0)
185
+ return { caseId, dir: undefined };
186
+ if (rest.length === 2 && rest[0] === "--dir" && !rest[1].startsWith("--")) {
187
+ return { caseId, dir: rest[1] };
188
+ }
189
+ throw new Error(USAGE);
190
+ }
191
+ async function main() {
192
+ let parsed;
193
+ try {
194
+ parsed = parseCheckoutArgs(process.argv.slice(2));
195
+ }
196
+ catch (error) {
197
+ // Usage errors exit 2, real failures 1 — the publish.ts CLI convention.
198
+ console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
199
+ process.exitCode = 2;
200
+ return;
201
+ }
202
+ const result = await runCheckout({ caseId: parsed.caseId, dir: parsed.dir });
203
+ console.log(`✓ Cloned ${result.repositoryUrl} (no fork — this is the case repo itself).`);
204
+ console.log(`✓ Authoring checkout at:\n ${result.workDir}\n on branch 'main' — the development branch, not the frozen ref.`);
205
+ console.log("");
206
+ console.log(renderOrientation(result));
207
+ if (result.ownershipWarning) {
208
+ console.error(`⚠ ${result.ownershipWarning}`);
209
+ }
210
+ if (result.structuralWarning) {
211
+ console.error(`⚠ ${result.structuralWarning}`);
212
+ }
213
+ }
214
+ /** Only auto-invoke the CLI when run directly (`node checkout.js …`), not when imported (e.g. by tests). */
215
+ const entry = process.argv[1];
216
+ const isMainModule = !!entry && path.resolve(entry) === fileURLToPath(import.meta.url);
217
+ if (isMainModule) {
218
+ main().catch((error) => {
219
+ console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
220
+ process.exitCode = 1;
221
+ });
222
+ }