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,79 @@
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
+ * Persistent store for the TUI's backend credentials at `~/.fito/credentials`
7
+ * (file mode `0600`, dir `0700`). Only token material and metadata are stored —
8
+ * never a plaintext password (SPEC §841 / PLAN Task 1.5). Pure Node module (no pi
9
+ * imports) so it is unit-testable without a pi runtime; `home` is injectable so
10
+ * tests can point at a temp directory.
11
+ */
12
+ /** The token pair + metadata persisted to disk. Mirrors the backend token response. */
13
+ export const credentialsSchema = z.object({
14
+ accessToken: z.string().min(1),
15
+ refreshToken: z.string().min(1),
16
+ expiresIn: z.number(),
17
+ tokenType: z.string().min(1),
18
+ /** ISO-8601 timestamp of when these tokens were written. */
19
+ savedAt: z.string().min(1),
20
+ });
21
+ /** The `~/.fito` directory that holds the credentials file. */
22
+ export function credentialsDir(home = os.homedir()) {
23
+ return path.join(home, ".fito");
24
+ }
25
+ /** The `~/.fito/credentials` file path. */
26
+ export function credentialsPath(home = os.homedir()) {
27
+ return path.join(credentialsDir(home), "credentials");
28
+ }
29
+ /**
30
+ * Write the credentials as JSON, enforcing dir `0700` and file `0600`. The mode
31
+ * is re-applied with `chmod` after the write so an existing, loosely-permissioned
32
+ * file is tightened (the `mode` option on `writeFileSync` is ignored when the file
33
+ * already exists).
34
+ */
35
+ export function writeCredentials(credentials, home = os.homedir()) {
36
+ const dir = credentialsDir(home);
37
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
38
+ fs.chmodSync(dir, 0o700);
39
+ const file = credentialsPath(home);
40
+ fs.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 0o600 });
41
+ fs.chmodSync(file, 0o600);
42
+ }
43
+ /**
44
+ * Read and validate the stored credentials. Returns `null` when the file is
45
+ * absent or its contents do not match {@link credentialsSchema} (malformed or a
46
+ * stale shape), so callers treat a corrupt store as "logged out" rather than
47
+ * crashing.
48
+ */
49
+ export function readCredentials(home = os.homedir()) {
50
+ const file = credentialsPath(home);
51
+ let raw;
52
+ try {
53
+ raw = fs.readFileSync(file, "utf8");
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ const parsed = credentialsSchema.safeParse(safeJsonParse(raw));
59
+ return parsed.success ? parsed.data : null;
60
+ }
61
+ /** Delete the credentials file. Returns `true` if a file was removed, `false` if absent. */
62
+ export function deleteCredentials(home = os.homedir()) {
63
+ const file = credentialsPath(home);
64
+ try {
65
+ fs.rmSync(file);
66
+ return true;
67
+ }
68
+ catch {
69
+ return false;
70
+ }
71
+ }
72
+ function safeJsonParse(raw) {
73
+ try {
74
+ return JSON.parse(raw);
75
+ }
76
+ catch {
77
+ return null;
78
+ }
79
+ }
@@ -0,0 +1,88 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+
5
+ import { z } from "zod";
6
+
7
+ /**
8
+ * Persistent store for the TUI's backend credentials at `~/.fito/credentials`
9
+ * (file mode `0600`, dir `0700`). Only token material and metadata are stored —
10
+ * never a plaintext password (SPEC §841 / PLAN Task 1.5). Pure Node module (no pi
11
+ * imports) so it is unit-testable without a pi runtime; `home` is injectable so
12
+ * tests can point at a temp directory.
13
+ */
14
+
15
+ /** The token pair + metadata persisted to disk. Mirrors the backend token response. */
16
+ export const credentialsSchema = z.object({
17
+ accessToken: z.string().min(1),
18
+ refreshToken: z.string().min(1),
19
+ expiresIn: z.number(),
20
+ tokenType: z.string().min(1),
21
+ /** ISO-8601 timestamp of when these tokens were written. */
22
+ savedAt: z.string().min(1),
23
+ });
24
+
25
+ export type Credentials = z.infer<typeof credentialsSchema>;
26
+
27
+ /** The `~/.fito` directory that holds the credentials file. */
28
+ export function credentialsDir(home: string = os.homedir()): string {
29
+ return path.join(home, ".fito");
30
+ }
31
+
32
+ /** The `~/.fito/credentials` file path. */
33
+ export function credentialsPath(home: string = os.homedir()): string {
34
+ return path.join(credentialsDir(home), "credentials");
35
+ }
36
+
37
+ /**
38
+ * Write the credentials as JSON, enforcing dir `0700` and file `0600`. The mode
39
+ * is re-applied with `chmod` after the write so an existing, loosely-permissioned
40
+ * file is tightened (the `mode` option on `writeFileSync` is ignored when the file
41
+ * already exists).
42
+ */
43
+ export function writeCredentials(credentials: Credentials, home: string = os.homedir()): void {
44
+ const dir = credentialsDir(home);
45
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
46
+ fs.chmodSync(dir, 0o700);
47
+
48
+ const file = credentialsPath(home);
49
+ fs.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 0o600 });
50
+ fs.chmodSync(file, 0o600);
51
+ }
52
+
53
+ /**
54
+ * Read and validate the stored credentials. Returns `null` when the file is
55
+ * absent or its contents do not match {@link credentialsSchema} (malformed or a
56
+ * stale shape), so callers treat a corrupt store as "logged out" rather than
57
+ * crashing.
58
+ */
59
+ export function readCredentials(home: string = os.homedir()): Credentials | null {
60
+ const file = credentialsPath(home);
61
+ let raw: string;
62
+ try {
63
+ raw = fs.readFileSync(file, "utf8");
64
+ } catch {
65
+ return null;
66
+ }
67
+ const parsed = credentialsSchema.safeParse(safeJsonParse(raw));
68
+ return parsed.success ? parsed.data : null;
69
+ }
70
+
71
+ /** Delete the credentials file. Returns `true` if a file was removed, `false` if absent. */
72
+ export function deleteCredentials(home: string = os.homedir()): boolean {
73
+ const file = credentialsPath(home);
74
+ try {
75
+ fs.rmSync(file);
76
+ return true;
77
+ } catch {
78
+ return false;
79
+ }
80
+ }
81
+
82
+ function safeJsonParse(raw: string): unknown {
83
+ try {
84
+ return JSON.parse(raw);
85
+ } catch {
86
+ return null;
87
+ }
88
+ }
@@ -0,0 +1,16 @@
1
+ import { readCredentials, writeCredentials } from "./credentials.js";
2
+ /**
3
+ * Resolve the learner's Fito session. Throws when no credentials are stored — a backend-writing flow
4
+ * needs a logged-in session. Persists rotated tokens so the next call reuses them.
5
+ */
6
+ export async function resolveFitoSession(client, home) {
7
+ const credentials = readCredentials(home);
8
+ if (!credentials) {
9
+ throw new Error("You are not logged in to Fito. Run /fito-login first, then re-run this flow.");
10
+ }
11
+ const { user, tokens } = await client.meWithRefresh(credentials);
12
+ if (tokens.accessToken !== credentials.accessToken || tokens.refreshToken !== credentials.refreshToken) {
13
+ writeCredentials({ ...tokens, savedAt: new Date().toISOString() }, home);
14
+ }
15
+ return { user, tokens };
16
+ }
@@ -0,0 +1,35 @@
1
+ import { readCredentials, writeCredentials } from "./credentials.ts";
2
+ import type { FitoApiClient, SessionUser, TokenResponse } from "../fito-api/client.ts";
3
+
4
+ /**
5
+ * Resolving the learner's authenticated Fito session for a backend-writing TUI flow (submit, record
6
+ * evaluation): read `~/.fito/credentials`, verify it via `GET /me` (refreshing the access token on a
7
+ * 401 and persisting any rotated pair), and hand back the user plus the live tokens. The single place
8
+ * both `fito-case-runner/submit.ts` and `submit-evaluation.ts` get a session, so the
9
+ * credentials→/me→persist sequence lives once.
10
+ */
11
+
12
+ /** The resolved session: the authenticated user and the live (possibly refreshed) token pair. */
13
+ export interface FitoSession {
14
+ user: SessionUser;
15
+ tokens: TokenResponse;
16
+ }
17
+
18
+ /**
19
+ * Resolve the learner's Fito session. Throws when no credentials are stored — a backend-writing flow
20
+ * needs a logged-in session. Persists rotated tokens so the next call reuses them.
21
+ */
22
+ export async function resolveFitoSession(
23
+ client: Pick<FitoApiClient, "meWithRefresh">,
24
+ home: string,
25
+ ): Promise<FitoSession> {
26
+ const credentials = readCredentials(home);
27
+ if (!credentials) {
28
+ throw new Error("You are not logged in to Fito. Run /fito-login first, then re-run this flow.");
29
+ }
30
+ const { user, tokens } = await client.meWithRefresh(credentials);
31
+ if (tokens.accessToken !== credentials.accessToken || tokens.refreshToken !== credentials.refreshToken) {
32
+ writeCredentials({ ...tokens, savedAt: new Date().toISOString() }, home);
33
+ }
34
+ return { user, tokens };
35
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The GitHub repository-URL **grammar**, shared by every skill that names a repo from a URL
3
+ * (promoted here at the third consumer per ADR-006: `fito-case-runner`, `fito-source-ingestion`,
4
+ * `fito-case-author` — Task 9.7). Pure parsing only: both functions return `null` on a non-match,
5
+ * and each call site keeps its own policy (throw, warn, or treat as a verdict) and its own error
6
+ * voice.
7
+ *
8
+ * The https form mirrors the backend's `GITHUB_URL` reachability grammar (lesson 46): case
9
+ * `repositoryUrl`s are always `https://github.com/{owner}/{repo}`, optionally `.git`-suffixed or
10
+ * slash-terminated — never ssh. The lenient form adds the ssh spellings for classifying arbitrary
11
+ * local `origin` remotes, where ssh is legitimate because the URL only *names* the repo.
12
+ */
13
+ /** Matches `https://github.com/{owner}/{repo}` (optional `.git` / trailing slash). */
14
+ const GITHUB_HTTPS_URL = /^https:\/\/github\.com\/([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/;
15
+ /** Matches scp-like `git@github.com:{owner}/{repo}` and `ssh://git@github.com/{owner}/{repo}`. */
16
+ const GITHUB_SSH_URL = /^(?:ssh:\/\/)?git@github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/;
17
+ /** Parse the strict https form (the case-`repositoryUrl` grammar), or null when it doesn't match. */
18
+ export function parseGithubHttpsUrl(url) {
19
+ const match = GITHUB_HTTPS_URL.exec(url.trim());
20
+ return match ? { owner: match[1], repo: match[2] } : null;
21
+ }
22
+ /** Parse the lenient https-or-ssh form (arbitrary git origins), or null when the host isn't GitHub. */
23
+ export function parseGithubUrl(url) {
24
+ const match = GITHUB_HTTPS_URL.exec(url.trim()) ?? GITHUB_SSH_URL.exec(url.trim());
25
+ return match ? { owner: match[1], repo: match[2] } : null;
26
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The GitHub repository-URL **grammar**, shared by every skill that names a repo from a URL
3
+ * (promoted here at the third consumer per ADR-006: `fito-case-runner`, `fito-source-ingestion`,
4
+ * `fito-case-author` — Task 9.7). Pure parsing only: both functions return `null` on a non-match,
5
+ * and each call site keeps its own policy (throw, warn, or treat as a verdict) and its own error
6
+ * voice.
7
+ *
8
+ * The https form mirrors the backend's `GITHUB_URL` reachability grammar (lesson 46): case
9
+ * `repositoryUrl`s are always `https://github.com/{owner}/{repo}`, optionally `.git`-suffixed or
10
+ * slash-terminated — never ssh. The lenient form adds the ssh spellings for classifying arbitrary
11
+ * local `origin` remotes, where ssh is legitimate because the URL only *names* the repo.
12
+ */
13
+
14
+ /** An `owner`/`repo` pair parsed from a GitHub repository URL. */
15
+ export interface GithubOwnerRepo {
16
+ owner: string;
17
+ repo: string;
18
+ }
19
+
20
+ /** Matches `https://github.com/{owner}/{repo}` (optional `.git` / trailing slash). */
21
+ const GITHUB_HTTPS_URL = /^https:\/\/github\.com\/([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/;
22
+ /** Matches scp-like `git@github.com:{owner}/{repo}` and `ssh://git@github.com/{owner}/{repo}`. */
23
+ const GITHUB_SSH_URL = /^(?:ssh:\/\/)?git@github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/;
24
+
25
+ /** Parse the strict https form (the case-`repositoryUrl` grammar), or null when it doesn't match. */
26
+ export function parseGithubHttpsUrl(url: string): GithubOwnerRepo | null {
27
+ const match = GITHUB_HTTPS_URL.exec(url.trim());
28
+ return match ? { owner: match[1], repo: match[2] } : null;
29
+ }
30
+
31
+ /** Parse the lenient https-or-ssh form (arbitrary git origins), or null when the host isn't GitHub. */
32
+ export function parseGithubUrl(url: string): GithubOwnerRepo | null {
33
+ const match = GITHUB_HTTPS_URL.exec(url.trim()) ?? GITHUB_SSH_URL.exec(url.trim());
34
+ return match ? { owner: match[1], repo: match[2] } : null;
35
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Pure composition for the knowledge-components subject: turn a case's resolved references into the
3
+ * `id → name` view the `/fito-submit` and `/fito-evaluate` feedback uses to label rubric components
4
+ * by their canonical, backend-owned **name** (Task 6.5). The reviewer subagent has no backend reach,
5
+ * so it cites components by **id** only; the orchestrating prompts resolve names live from
6
+ * `GET /cases/{id}` (whose `learningObjectives` + `prerequisites` are already resolved, carrying `name`
7
+ * keyed by `componentId`) and relabel. Pure (no pi imports, no I/O) so it is unit-testable without a
8
+ * runtime; the `fito-case-runner` `case-component-names.ts` CLI composes it with the HTTP fetch.
9
+ *
10
+ * The reference⇄name view is domain logic, kept out of the thin `fito-api` transport client
11
+ * (ADR-006: `fito-api/` mirrors endpoints; knowledge-component logic lives here).
12
+ */
13
+ /**
14
+ * Build the `componentId → name` map from a case's resolved learning-objective and prerequisite
15
+ * references. A case detail carries these two reference kinds only (not its rubric), so a component
16
+ * that is *only* in the rubric is absent here — see [labelComponent]'s fallback. An id that is both a
17
+ * learning objective and a prerequisite carries the same name (it is one component), so a duplicate
18
+ * key is harmless.
19
+ */
20
+ export function buildComponentNameMap(detail) {
21
+ const names = new Map();
22
+ for (const ref of [...detail.learningObjectives, ...detail.prerequisites]) {
23
+ names.set(ref.componentId, ref.name);
24
+ }
25
+ return names;
26
+ }
27
+ /**
28
+ * Label a knowledge-component id for the learner-facing feedback: `name (id)` when the id resolves to
29
+ * a name (it is a declared learning objective/prerequisite), otherwise the bare `id`. The id fallback is the
30
+ * accepted known gap (Task 6.5): a rubric-only component has no resolved name in the case detail.
31
+ */
32
+ export function labelComponent(id, names) {
33
+ const name = names.get(id);
34
+ return name ? `${name} (${id})` : id;
35
+ }
@@ -0,0 +1,39 @@
1
+ import type { CaseDetail } from "../fito-api/client.ts";
2
+
3
+ /**
4
+ * Pure composition for the knowledge-components subject: turn a case's resolved references into the
5
+ * `id → name` view the `/fito-submit` and `/fito-evaluate` feedback uses to label rubric components
6
+ * by their canonical, backend-owned **name** (Task 6.5). The reviewer subagent has no backend reach,
7
+ * so it cites components by **id** only; the orchestrating prompts resolve names live from
8
+ * `GET /cases/{id}` (whose `learningObjectives` + `prerequisites` are already resolved, carrying `name`
9
+ * keyed by `componentId`) and relabel. Pure (no pi imports, no I/O) so it is unit-testable without a
10
+ * runtime; the `fito-case-runner` `case-component-names.ts` CLI composes it with the HTTP fetch.
11
+ *
12
+ * The reference⇄name view is domain logic, kept out of the thin `fito-api` transport client
13
+ * (ADR-006: `fito-api/` mirrors endpoints; knowledge-component logic lives here).
14
+ */
15
+
16
+ /**
17
+ * Build the `componentId → name` map from a case's resolved learning-objective and prerequisite
18
+ * references. A case detail carries these two reference kinds only (not its rubric), so a component
19
+ * that is *only* in the rubric is absent here — see [labelComponent]'s fallback. An id that is both a
20
+ * learning objective and a prerequisite carries the same name (it is one component), so a duplicate
21
+ * key is harmless.
22
+ */
23
+ export function buildComponentNameMap(detail: CaseDetail): Map<string, string> {
24
+ const names = new Map<string, string>();
25
+ for (const ref of [...detail.learningObjectives, ...detail.prerequisites]) {
26
+ names.set(ref.componentId, ref.name);
27
+ }
28
+ return names;
29
+ }
30
+
31
+ /**
32
+ * Label a knowledge-component id for the learner-facing feedback: `name (id)` when the id resolves to
33
+ * a name (it is a declared learning objective/prerequisite), otherwise the bare `id`. The id fallback is the
34
+ * accepted known gap (Task 6.5): a rubric-only component has no resolved name in the case detail.
35
+ */
36
+ export function labelComponent(id: string, names: Map<string, string>): string {
37
+ const name = names.get(id);
38
+ return name ? `${name} (${id})` : id;
39
+ }
@@ -0,0 +1,46 @@
1
+ import { FitoApiError, createFitoApiClient, } from "../fito-api/client.js";
2
+ import { parseKnowledgeReference } from "./reference.js";
3
+ /**
4
+ * Resolve one canonical knowledge-component reference (`<type>:<tech-slug>.<component-slug>`,
5
+ * e.g. `concept:git.bisect`) to its content. Parses the id (client-side type check, no
6
+ * round-trip on an obvious typo), fetches via the shared `fito-api` transport client, and maps
7
+ * backend failures to clear, single-line messages — the same contract the former
8
+ * `fito-knowledge-fetcher` skill's `fetch.ts` surfaced, now reusable as the `fito_knowledge_fetch`
9
+ * custom tool's core (ADR-006: `fito-api/` is the thin transport boundary; this knowledge-component
10
+ * composition is domain logic and lives in `shared/knowledge-components/`).
11
+ *
12
+ * Throws a plain `Error` (clear message) on a malformed id / unknown type (before any request),
13
+ * a 404 (no such component), or any other backend failure — callers surface `error.message`
14
+ * (the tool wrapper lets it propagate so pi marks the call as an error).
15
+ *
16
+ * `options.technologyVersion`, when present, scopes the read to one technology-version slug (9a.5d):
17
+ * a component live only for another major line then surfaces as the same not-found `Error`, so a
18
+ * version-aware caller never treats it as live. `options.client` keeps the HTTP boundary injectable
19
+ * for tests; production calls create the shared client per invocation (reading `FITO_API_BASE_URL`)
20
+ * and send no credentials because the read is public.
21
+ *
22
+ * It is named for the axis it filters, matching the wire and the transport client since Task
23
+ * 11.4a6-4: a component's technology version is the major line it applies to, while its `version` is
24
+ * its own revision, and the fetched component carries both. The `fito_knowledge_fetch` tool still
25
+ * exposes `version` to agents — renaming *that* would reach the seven identify/design artifacts — so
26
+ * the two vocabularies meet in the tool adapter (`extensions/fito-fetch-tools.ts`), which is the
27
+ * seam between them, rather than here in domain logic.
28
+ */
29
+ export async function fetchKnowledgeComponent(id, options = {}) {
30
+ const client = options.client ?? createFitoApiClient();
31
+ const { type, slug } = parseKnowledgeReference(id);
32
+ try {
33
+ return await client.getKnowledgeComponent(type, slug, {
34
+ technologyVersion: options.technologyVersion,
35
+ });
36
+ }
37
+ catch (error) {
38
+ if (error instanceof FitoApiError && error.status === 404) {
39
+ throw new Error(`No knowledge component found for "${id}".`);
40
+ }
41
+ if (error instanceof FitoApiError) {
42
+ throw new Error(`Fetch failed (${error.status}): ${error.message}`);
43
+ }
44
+ throw error;
45
+ }
46
+ }
@@ -0,0 +1,57 @@
1
+ import {
2
+ FitoApiError,
3
+ type FitoApiClient,
4
+ type KnowledgeComponent,
5
+ createFitoApiClient,
6
+ } from "../fito-api/client.ts";
7
+ import { parseKnowledgeReference } from "./reference.ts";
8
+
9
+ /**
10
+ * Resolve one canonical knowledge-component reference (`<type>:<tech-slug>.<component-slug>`,
11
+ * e.g. `concept:git.bisect`) to its content. Parses the id (client-side type check, no
12
+ * round-trip on an obvious typo), fetches via the shared `fito-api` transport client, and maps
13
+ * backend failures to clear, single-line messages — the same contract the former
14
+ * `fito-knowledge-fetcher` skill's `fetch.ts` surfaced, now reusable as the `fito_knowledge_fetch`
15
+ * custom tool's core (ADR-006: `fito-api/` is the thin transport boundary; this knowledge-component
16
+ * composition is domain logic and lives in `shared/knowledge-components/`).
17
+ *
18
+ * Throws a plain `Error` (clear message) on a malformed id / unknown type (before any request),
19
+ * a 404 (no such component), or any other backend failure — callers surface `error.message`
20
+ * (the tool wrapper lets it propagate so pi marks the call as an error).
21
+ *
22
+ * `options.technologyVersion`, when present, scopes the read to one technology-version slug (9a.5d):
23
+ * a component live only for another major line then surfaces as the same not-found `Error`, so a
24
+ * version-aware caller never treats it as live. `options.client` keeps the HTTP boundary injectable
25
+ * for tests; production calls create the shared client per invocation (reading `FITO_API_BASE_URL`)
26
+ * and send no credentials because the read is public.
27
+ *
28
+ * It is named for the axis it filters, matching the wire and the transport client since Task
29
+ * 11.4a6-4: a component's technology version is the major line it applies to, while its `version` is
30
+ * its own revision, and the fetched component carries both. The `fito_knowledge_fetch` tool still
31
+ * exposes `version` to agents — renaming *that* would reach the seven identify/design artifacts — so
32
+ * the two vocabularies meet in the tool adapter (`extensions/fito-fetch-tools.ts`), which is the
33
+ * seam between them, rather than here in domain logic.
34
+ */
35
+ export async function fetchKnowledgeComponent(
36
+ id: string,
37
+ options: {
38
+ technologyVersion?: string;
39
+ client?: Pick<FitoApiClient, "getKnowledgeComponent">;
40
+ } = {},
41
+ ): Promise<KnowledgeComponent> {
42
+ const client = options.client ?? createFitoApiClient();
43
+ const { type, slug } = parseKnowledgeReference(id);
44
+ try {
45
+ return await client.getKnowledgeComponent(type, slug, {
46
+ technologyVersion: options.technologyVersion,
47
+ });
48
+ } catch (error) {
49
+ if (error instanceof FitoApiError && error.status === 404) {
50
+ throw new Error(`No knowledge component found for "${id}".`);
51
+ }
52
+ if (error instanceof FitoApiError) {
53
+ throw new Error(`Fetch failed (${error.status}): ${error.message}`);
54
+ }
55
+ throw error;
56
+ }
57
+ }
@@ -0,0 +1,101 @@
1
+ import { FitoApiError, createFitoApiClient, } from "../fito-api/client.js";
2
+ /** Characters of `tl_dr` a listing entry may carry before it is cut. */
3
+ const TL_DR_BUDGET = 225;
4
+ /** Appended to a `tl_dr` that was cut — and to nothing else, so its presence is the record of it. */
5
+ const TRUNCATION_MARKER = " [...]";
6
+ /**
7
+ * A sentence-ending mark that really ends a sentence: followed by whitespace, or by nothing —
8
+ * carrying any closing quotes or brackets with it, since `…the summary." Next` ends its sentence at
9
+ * the quote and not at the period.
10
+ */
11
+ const SENTENCE_END = /[.!?]["')\]]*(?=\s|$)/g;
12
+ /**
13
+ * Cut `text` to [TL_DR_BUDGET] characters at the last sentence boundary that fits, appending
14
+ * [TRUNCATION_MARKER]. A value already inside the budget is returned untouched and **unmarked**.
15
+ *
16
+ * The lookahead runs over the whole value rather than the cut window, so a decimal point or an
17
+ * abbreviation sitting exactly at the boundary is not mistaken for a sentence end. When no sentence
18
+ * ends inside the budget the cut falls back to the last word boundary — the rule names sentences and
19
+ * says nothing about a value without them, and the alternative is cutting mid-word.
20
+ */
21
+ function truncateTlDr(text) {
22
+ if (text.length <= TL_DR_BUDGET)
23
+ return text;
24
+ let cut = 0;
25
+ for (const match of text.matchAll(SENTENCE_END)) {
26
+ const end = match.index + match[0].length;
27
+ if (end > TL_DR_BUDGET)
28
+ break;
29
+ cut = end;
30
+ }
31
+ if (cut === 0) {
32
+ const lastSpace = text.lastIndexOf(" ", TL_DR_BUDGET);
33
+ cut = lastSpace > 0 ? lastSpace : TL_DR_BUDGET;
34
+ }
35
+ return `${text.slice(0, cut)}${TRUNCATION_MARKER}`;
36
+ }
37
+ /**
38
+ * The component's `tl_dr` section value, or `""` when it is absent or not a plain string. `tl_dr` is
39
+ * a REQUIRED TEXT field on all five registered templates, so neither case is a shape this models —
40
+ * they are data faults, and a listing that threw on one would take a whole technology down with it.
41
+ */
42
+ function tlDrOf(component) {
43
+ const section = component.sections.find((candidate) => candidate.key === "tl_dr");
44
+ return typeof section?.value === "string" ? section.value : "";
45
+ }
46
+ /**
47
+ * List one technology's knowledge components as recognisable summaries — the `fito_knowledge_search`
48
+ * custom tool's core, and the read that lets `/fito-case-design` **select** components instead of
49
+ * guessing their ids and probing one at a time.
50
+ *
51
+ * **Both filters are the backend's, and this module states them rather than applies them** (Task
52
+ * 11.4a6-1b). `version` travels as `technologyVersion`, which `GET /knowledge` scopes server-side
53
+ * and before any limit: an unscoped Javalin listing returns every component including the one that
54
+ * applies only to an older line, and a case declaring `javalin@7` could then cite a component that
55
+ * is not live at 7 with nothing marking it. Matching is on the version **slug**, and a component
56
+ * bound to several lines is kept when **any** of them matches — the same rule this module used to
57
+ * apply itself. Nothing is re-filtered on the way back: a redundant second pass would hand the
58
+ * caller a correct-looking list produced by the wrong component and hide a backend regression.
59
+ *
60
+ * **`excludeSuperseded` is fixed at `true` here and is not offered to callers.** Every consumer is
61
+ * an identify or generate persona running on a deliberately cheap model tier, and citing components
62
+ * that a newer revision had already replaced is the defect this guard exists to close — so exposing
63
+ * the switch would hand the guard's off-switch to the caller it guards against. A superseded
64
+ * component is still reachable by id through `fito_knowledge_fetch`; it is only never *offered*.
65
+ *
66
+ * Throws a plain `Error` (clear message) on a backend failure — callers surface `error.message` (the
67
+ * tool wrapper lets it propagate so pi marks the call as an error). Unlike its point-read siblings
68
+ * there is no not-found case: an unknown technology is an empty list, because this is a search and
69
+ * not an existence check. `options.client` keeps the HTTP boundary injectable for tests; production
70
+ * calls create the shared client per invocation (reading `FITO_API_BASE_URL`) and send no
71
+ * credentials because the read is public.
72
+ */
73
+ export async function searchKnowledgeComponents(technology, options = {}) {
74
+ const client = options.client ?? createFitoApiClient();
75
+ let components;
76
+ try {
77
+ components = await client.searchKnowledgeComponents({
78
+ technology,
79
+ // Hardcoded, and deliberately not reachable from this function's own signature: the
80
+ // callers are cheap-tier personas, and a listing that offers a replaced component is
81
+ // what this whole task family exists to stop.
82
+ excludeSuperseded: true,
83
+ ...(options.version !== undefined && { technologyVersion: options.version }),
84
+ ...(options.type !== undefined && { type: options.type }),
85
+ ...(options.q !== undefined && { q: options.q }),
86
+ });
87
+ }
88
+ catch (error) {
89
+ if (error instanceof FitoApiError) {
90
+ throw new Error(`Search failed (${error.status}): ${error.message}`);
91
+ }
92
+ throw error;
93
+ }
94
+ return components.map((component) => ({
95
+ id: component.id,
96
+ type: component.type,
97
+ name: component.name,
98
+ versions: component.technologyVersions.map((bound) => bound.slug),
99
+ tl_dr: truncateTlDr(tlDrOf(component)),
100
+ }));
101
+ }