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,144 @@
1
+ import {
2
+ FitoApiError,
3
+ type ComponentType,
4
+ type FitoApiClient,
5
+ type KnowledgeSearchItem,
6
+ createFitoApiClient,
7
+ } from "../fito-api/client.ts";
8
+
9
+ /**
10
+ * One knowledge component as a listing entry: enough to recognise and choose it, not enough to
11
+ * work from. `versions` are the technology-version **slugs** it is bound to; `tl_dr` is its summary,
12
+ * truncated (see [TL_DR_BUDGET]) and marked when cut.
13
+ *
14
+ * **The shape was decided from measurement, not intuition** (79 live components across five
15
+ * technologies). A full component record is ~11.7 KB — 270 KB for one practice, ~700 KB for a
16
+ * practice-and-Javalin case — which would swamp the flow that reads this and defeat the purpose of
17
+ * listing at all. Projected, a record is ~385 B, so today's largest technology (34 components) costs
18
+ * ~13 KB. There is deliberately **no per-type rule and no byte budget**: both were designed and
19
+ * declined as speculative at this scale. Revisit at ~100 components (~38 KB); 300 would cost ~115 KB.
20
+ *
21
+ * The field keeps the key `tl_dr` rather than something like `tl_dr_truncated` so the reader
22
+ * connects it to the same key on the full record it will see from `fito_knowledge_fetch`; the
23
+ * ` [...]` marker carries the truncation at the point of reading instead.
24
+ */
25
+ export interface KnowledgeComponentSummary {
26
+ id: string;
27
+ type: ComponentType;
28
+ name: string;
29
+ versions: string[];
30
+ tl_dr: string;
31
+ }
32
+
33
+ /** Characters of `tl_dr` a listing entry may carry before it is cut. */
34
+ const TL_DR_BUDGET = 225;
35
+
36
+ /** Appended to a `tl_dr` that was cut — and to nothing else, so its presence is the record of it. */
37
+ const TRUNCATION_MARKER = " [...]";
38
+
39
+ /**
40
+ * A sentence-ending mark that really ends a sentence: followed by whitespace, or by nothing —
41
+ * carrying any closing quotes or brackets with it, since `…the summary." Next` ends its sentence at
42
+ * the quote and not at the period.
43
+ */
44
+ const SENTENCE_END = /[.!?]["')\]]*(?=\s|$)/g;
45
+
46
+ /**
47
+ * Cut `text` to [TL_DR_BUDGET] characters at the last sentence boundary that fits, appending
48
+ * [TRUNCATION_MARKER]. A value already inside the budget is returned untouched and **unmarked**.
49
+ *
50
+ * The lookahead runs over the whole value rather than the cut window, so a decimal point or an
51
+ * abbreviation sitting exactly at the boundary is not mistaken for a sentence end. When no sentence
52
+ * ends inside the budget the cut falls back to the last word boundary — the rule names sentences and
53
+ * says nothing about a value without them, and the alternative is cutting mid-word.
54
+ */
55
+ function truncateTlDr(text: string): string {
56
+ if (text.length <= TL_DR_BUDGET) return text;
57
+
58
+ let cut = 0;
59
+ for (const match of text.matchAll(SENTENCE_END)) {
60
+ const end = match.index + match[0].length;
61
+ if (end > TL_DR_BUDGET) break;
62
+ cut = end;
63
+ }
64
+ if (cut === 0) {
65
+ const lastSpace = text.lastIndexOf(" ", TL_DR_BUDGET);
66
+ cut = lastSpace > 0 ? lastSpace : TL_DR_BUDGET;
67
+ }
68
+ return `${text.slice(0, cut)}${TRUNCATION_MARKER}`;
69
+ }
70
+
71
+ /**
72
+ * The component's `tl_dr` section value, or `""` when it is absent or not a plain string. `tl_dr` is
73
+ * a REQUIRED TEXT field on all five registered templates, so neither case is a shape this models —
74
+ * they are data faults, and a listing that threw on one would take a whole technology down with it.
75
+ */
76
+ function tlDrOf(component: KnowledgeSearchItem): string {
77
+ const section = component.sections.find((candidate) => candidate.key === "tl_dr");
78
+ return typeof section?.value === "string" ? section.value : "";
79
+ }
80
+
81
+ /**
82
+ * List one technology's knowledge components as recognisable summaries — the `fito_knowledge_search`
83
+ * custom tool's core, and the read that lets `/fito-case-design` **select** components instead of
84
+ * guessing their ids and probing one at a time.
85
+ *
86
+ * **Both filters are the backend's, and this module states them rather than applies them** (Task
87
+ * 11.4a6-1b). `version` travels as `technologyVersion`, which `GET /knowledge` scopes server-side
88
+ * and before any limit: an unscoped Javalin listing returns every component including the one that
89
+ * applies only to an older line, and a case declaring `javalin@7` could then cite a component that
90
+ * is not live at 7 with nothing marking it. Matching is on the version **slug**, and a component
91
+ * bound to several lines is kept when **any** of them matches — the same rule this module used to
92
+ * apply itself. Nothing is re-filtered on the way back: a redundant second pass would hand the
93
+ * caller a correct-looking list produced by the wrong component and hide a backend regression.
94
+ *
95
+ * **`excludeSuperseded` is fixed at `true` here and is not offered to callers.** Every consumer is
96
+ * an identify or generate persona running on a deliberately cheap model tier, and citing components
97
+ * that a newer revision had already replaced is the defect this guard exists to close — so exposing
98
+ * the switch would hand the guard's off-switch to the caller it guards against. A superseded
99
+ * component is still reachable by id through `fito_knowledge_fetch`; it is only never *offered*.
100
+ *
101
+ * Throws a plain `Error` (clear message) on a backend failure — callers surface `error.message` (the
102
+ * tool wrapper lets it propagate so pi marks the call as an error). Unlike its point-read siblings
103
+ * there is no not-found case: an unknown technology is an empty list, because this is a search and
104
+ * not an existence check. `options.client` keeps the HTTP boundary injectable for tests; production
105
+ * calls create the shared client per invocation (reading `FITO_API_BASE_URL`) and send no
106
+ * credentials because the read is public.
107
+ */
108
+ export async function searchKnowledgeComponents(
109
+ technology: string,
110
+ options: {
111
+ version?: string;
112
+ type?: ComponentType;
113
+ q?: string;
114
+ client?: Pick<FitoApiClient, "searchKnowledgeComponents">;
115
+ } = {},
116
+ ): Promise<KnowledgeComponentSummary[]> {
117
+ const client = options.client ?? createFitoApiClient();
118
+ let components: KnowledgeSearchItem[];
119
+ try {
120
+ components = await client.searchKnowledgeComponents({
121
+ technology,
122
+ // Hardcoded, and deliberately not reachable from this function's own signature: the
123
+ // callers are cheap-tier personas, and a listing that offers a replaced component is
124
+ // what this whole task family exists to stop.
125
+ excludeSuperseded: true,
126
+ ...(options.version !== undefined && { technologyVersion: options.version }),
127
+ ...(options.type !== undefined && { type: options.type }),
128
+ ...(options.q !== undefined && { q: options.q }),
129
+ });
130
+ } catch (error) {
131
+ if (error instanceof FitoApiError) {
132
+ throw new Error(`Search failed (${error.status}): ${error.message}`);
133
+ }
134
+ throw error;
135
+ }
136
+
137
+ return components.map((component) => ({
138
+ id: component.id,
139
+ type: component.type,
140
+ name: component.name,
141
+ versions: component.technologyVersions.map((bound) => bound.slug),
142
+ tl_dr: truncateTlDr(tlDrOf(component)),
143
+ }));
144
+ }
@@ -0,0 +1,104 @@
1
+ import { z } from "zod";
2
+ import { componentTypeSchema, createFitoApiClient, } from "../fito-api/client.js";
3
+ import { fetchTechnology } from "./technology-fetch.js";
4
+ /**
5
+ * The knowledge push flow's payload→request mapping (PLAN Task 8.5): turn a generator agent's
6
+ * output payload (`{metadata, content}`, one JSON per component — the Task 8.1 contract) into the
7
+ * write API's create input, and resolve the registered template the write must name. Domain logic
8
+ * over the `fito-api` transport, per ADR-006 (`fito-api/` mirrors endpoints; interpreting payloads
9
+ * belongs here). The file I/O and the 409-resolution orchestration live in the
10
+ * `skills/fito-knowledge-push/` scripts that import this module.
11
+ */
12
+ /**
13
+ * One generator output payload. `metadata` carries the keys the write contract needs — `name`,
14
+ * `type` (already the wire token, e.g. `execution-fact`), `technology_slug`, and
15
+ * `technology_versions` (the slugs of the technology versions the component applies to, ≥1,
16
+ * ADR-011 / Task 9a.5b) — plus traceability extras (source ids, audience) that pass through
17
+ * unvalidated. `content` is the registered template's field map: markdown-fragment values, a
18
+ * string per TEXT field and a string array per LIST field. Field-schema conformance itself is the
19
+ * backend's check (422 with per-field violations); this schema only guards the transport shape.
20
+ */
21
+ export const generatorPayloadSchema = z.object({
22
+ metadata: z.looseObject({
23
+ name: z.string().min(1),
24
+ type: componentTypeSchema,
25
+ technology_slug: z.string().min(1),
26
+ technology_versions: z.array(z.string().min(1)).min(1),
27
+ }),
28
+ content: z
29
+ .record(z.string(), z.union([z.string(), z.array(z.string())]))
30
+ .refine((fields) => Object.keys(fields).length > 0, "content must have at least one field"),
31
+ });
32
+ /**
33
+ * Map a parsed generator payload onto the write API's create input. `version` is included only
34
+ * when the author supplied a label (the supersede resolution's bump); otherwise the backend
35
+ * defaults it to `1.0.0` — right for a first version, the plain-create case.
36
+ */
37
+ export function toCreateInput(payload, templateId, version) {
38
+ return {
39
+ technology: payload.metadata.technology_slug,
40
+ technologyVersions: payload.metadata.technology_versions,
41
+ templateId,
42
+ name: payload.metadata.name,
43
+ ...(version ? { version } : {}),
44
+ content: payload.content,
45
+ };
46
+ }
47
+ /**
48
+ * Resolve the registered template a knowledge write for `type` must name.
49
+ *
50
+ * A component type carries many templates along **two independent axes**: the `appliesToKind`
51
+ * variant written for a technology kind, and the version revisions of one lineage. Resolution keys
52
+ * on the variant **first** — preferring a row matching the technology's own `kind`, falling back to
53
+ * the shared `any` row — and only then applies the newest-version rule *within* the winning group.
54
+ * Keying on version alone would bind every push, tool and practice alike, to whichever variant
55
+ * sorted higher: it does not throw, it stores the wrong template provenance, and the read path then
56
+ * renders the component with another kind's section labels and order.
57
+ *
58
+ * The wanted variant is derived from the technology, never declared by the caller — `technologySlug`
59
+ * is the payload's own `metadata.technology_slug`, and there is no parameter in which to assert a
60
+ * different one. Versions are compared by their numeric dot-parts, not lexically: the backend's
61
+ * version-ascending order is a string sort, where "10.0.0" comes before "9.0.0".
62
+ *
63
+ * Throws a plain `Error` when the type has no registered template at all (the vocabulary seed has
64
+ * not run — backend `FITO_SEED_KNOWLEDGE`) and a distinct one when it has templates but none that
65
+ * apply to this technology's kind, which is a missing *variant*, not a missing seed. An unknown
66
+ * technology surfaces `fetchTechnology`'s message, before anything is written.
67
+ */
68
+ export async function resolveRegisteredTemplate(type, technologySlug, client = createFitoApiClient()) {
69
+ const [templates, technology] = await Promise.all([
70
+ client.getKnowledgeTemplates(type),
71
+ fetchTechnology(technologySlug, { client }),
72
+ ]);
73
+ if (templates.length === 0) {
74
+ throw new Error(`No registered template for component type "${type}" — the backend knowledge vocabulary seed (FITO_SEED_KNOWLEDGE) has not run.`);
75
+ }
76
+ // Variant first: an exact kind match wins outright, so a newer `any` row cannot displace the
77
+ // variant written for this kind.
78
+ const matching = templates.filter((candidate) => candidate.appliesToKind === technology.kind);
79
+ const applicable = matching.length > 0 ? matching : templates.filter((candidate) => candidate.appliesToKind === "any");
80
+ if (applicable.length === 0) {
81
+ throw new Error(`No registered "${type}" template applies to ${technology.kind} technologies — "${technologySlug}" is a ${technology.kind}, ` +
82
+ `and the registered templates apply to: ${[...new Set(templates.map((t) => t.appliesToKind))].sort().join(", ")}.`);
83
+ }
84
+ // Then lineage: the newest version among the equally-matching rows.
85
+ let newest = applicable[0];
86
+ for (const candidate of applicable) {
87
+ if (compareVersions(candidate.version, newest.version) > 0) {
88
+ newest = candidate;
89
+ }
90
+ }
91
+ return newest;
92
+ }
93
+ /** Compare two dot-separated version labels by numeric parts (missing parts count as 0). */
94
+ function compareVersions(a, b) {
95
+ const partsA = a.split(".");
96
+ const partsB = b.split(".");
97
+ for (let i = 0; i < Math.max(partsA.length, partsB.length); i += 1) {
98
+ const numA = Number(partsA[i] ?? 0);
99
+ const numB = Number(partsB[i] ?? 0);
100
+ if (numA !== numB)
101
+ return numA - numB;
102
+ }
103
+ return 0;
104
+ }
@@ -0,0 +1,129 @@
1
+ import { z } from "zod";
2
+
3
+ import {
4
+ componentTypeSchema,
5
+ createFitoApiClient,
6
+ type ComponentType,
7
+ type CreateKnowledgeComponentInput,
8
+ type FitoApiClient,
9
+ type KnowledgeTemplate,
10
+ } from "../fito-api/client.ts";
11
+ import { fetchTechnology } from "./technology-fetch.ts";
12
+
13
+ /**
14
+ * The knowledge push flow's payload→request mapping (PLAN Task 8.5): turn a generator agent's
15
+ * output payload (`{metadata, content}`, one JSON per component — the Task 8.1 contract) into the
16
+ * write API's create input, and resolve the registered template the write must name. Domain logic
17
+ * over the `fito-api` transport, per ADR-006 (`fito-api/` mirrors endpoints; interpreting payloads
18
+ * belongs here). The file I/O and the 409-resolution orchestration live in the
19
+ * `skills/fito-knowledge-push/` scripts that import this module.
20
+ */
21
+
22
+ /**
23
+ * One generator output payload. `metadata` carries the keys the write contract needs — `name`,
24
+ * `type` (already the wire token, e.g. `execution-fact`), `technology_slug`, and
25
+ * `technology_versions` (the slugs of the technology versions the component applies to, ≥1,
26
+ * ADR-011 / Task 9a.5b) — plus traceability extras (source ids, audience) that pass through
27
+ * unvalidated. `content` is the registered template's field map: markdown-fragment values, a
28
+ * string per TEXT field and a string array per LIST field. Field-schema conformance itself is the
29
+ * backend's check (422 with per-field violations); this schema only guards the transport shape.
30
+ */
31
+ export const generatorPayloadSchema = z.object({
32
+ metadata: z.looseObject({
33
+ name: z.string().min(1),
34
+ type: componentTypeSchema,
35
+ technology_slug: z.string().min(1),
36
+ technology_versions: z.array(z.string().min(1)).min(1),
37
+ }),
38
+ content: z
39
+ .record(z.string(), z.union([z.string(), z.array(z.string())]))
40
+ .refine((fields) => Object.keys(fields).length > 0, "content must have at least one field"),
41
+ });
42
+ export type GeneratorPayload = z.infer<typeof generatorPayloadSchema>;
43
+
44
+ /**
45
+ * Map a parsed generator payload onto the write API's create input. `version` is included only
46
+ * when the author supplied a label (the supersede resolution's bump); otherwise the backend
47
+ * defaults it to `1.0.0` — right for a first version, the plain-create case.
48
+ */
49
+ export function toCreateInput(
50
+ payload: GeneratorPayload,
51
+ templateId: string,
52
+ version?: string,
53
+ ): CreateKnowledgeComponentInput {
54
+ return {
55
+ technology: payload.metadata.technology_slug,
56
+ technologyVersions: payload.metadata.technology_versions,
57
+ templateId,
58
+ name: payload.metadata.name,
59
+ ...(version ? { version } : {}),
60
+ content: payload.content,
61
+ };
62
+ }
63
+
64
+ /**
65
+ * Resolve the registered template a knowledge write for `type` must name.
66
+ *
67
+ * A component type carries many templates along **two independent axes**: the `appliesToKind`
68
+ * variant written for a technology kind, and the version revisions of one lineage. Resolution keys
69
+ * on the variant **first** — preferring a row matching the technology's own `kind`, falling back to
70
+ * the shared `any` row — and only then applies the newest-version rule *within* the winning group.
71
+ * Keying on version alone would bind every push, tool and practice alike, to whichever variant
72
+ * sorted higher: it does not throw, it stores the wrong template provenance, and the read path then
73
+ * renders the component with another kind's section labels and order.
74
+ *
75
+ * The wanted variant is derived from the technology, never declared by the caller — `technologySlug`
76
+ * is the payload's own `metadata.technology_slug`, and there is no parameter in which to assert a
77
+ * different one. Versions are compared by their numeric dot-parts, not lexically: the backend's
78
+ * version-ascending order is a string sort, where "10.0.0" comes before "9.0.0".
79
+ *
80
+ * Throws a plain `Error` when the type has no registered template at all (the vocabulary seed has
81
+ * not run — backend `FITO_SEED_KNOWLEDGE`) and a distinct one when it has templates but none that
82
+ * apply to this technology's kind, which is a missing *variant*, not a missing seed. An unknown
83
+ * technology surfaces `fetchTechnology`'s message, before anything is written.
84
+ */
85
+ export async function resolveRegisteredTemplate(
86
+ type: ComponentType,
87
+ technologySlug: string,
88
+ client: Pick<FitoApiClient, "getKnowledgeTemplates" | "getTechnology"> = createFitoApiClient(),
89
+ ): Promise<KnowledgeTemplate> {
90
+ const [templates, technology] = await Promise.all([
91
+ client.getKnowledgeTemplates(type),
92
+ fetchTechnology(technologySlug, { client }),
93
+ ]);
94
+ if (templates.length === 0) {
95
+ throw new Error(
96
+ `No registered template for component type "${type}" — the backend knowledge vocabulary seed (FITO_SEED_KNOWLEDGE) has not run.`,
97
+ );
98
+ }
99
+ // Variant first: an exact kind match wins outright, so a newer `any` row cannot displace the
100
+ // variant written for this kind.
101
+ const matching = templates.filter((candidate) => candidate.appliesToKind === technology.kind);
102
+ const applicable = matching.length > 0 ? matching : templates.filter((candidate) => candidate.appliesToKind === "any");
103
+ if (applicable.length === 0) {
104
+ throw new Error(
105
+ `No registered "${type}" template applies to ${technology.kind} technologies — "${technologySlug}" is a ${technology.kind}, ` +
106
+ `and the registered templates apply to: ${[...new Set(templates.map((t) => t.appliesToKind))].sort().join(", ")}.`,
107
+ );
108
+ }
109
+ // Then lineage: the newest version among the equally-matching rows.
110
+ let newest = applicable[0];
111
+ for (const candidate of applicable) {
112
+ if (compareVersions(candidate.version, newest.version) > 0) {
113
+ newest = candidate;
114
+ }
115
+ }
116
+ return newest;
117
+ }
118
+
119
+ /** Compare two dot-separated version labels by numeric parts (missing parts count as 0). */
120
+ function compareVersions(a: string, b: string): number {
121
+ const partsA = a.split(".");
122
+ const partsB = b.split(".");
123
+ for (let i = 0; i < Math.max(partsA.length, partsB.length); i += 1) {
124
+ const numA = Number(partsA[i] ?? 0);
125
+ const numB = Number(partsB[i] ?? 0);
126
+ if (numA !== numB) return numA - numB;
127
+ }
128
+ return 0;
129
+ }
@@ -0,0 +1,24 @@
1
+ import { COMPONENT_TYPES } from "../fito-api/client.js";
2
+ /**
3
+ * Parse a canonical knowledge-component reference (`<type>:<value>`) into its parts. Throws a
4
+ * plain `Error` with a clear message on a malformed input, an unknown type prefix, or an empty
5
+ * value — surfaced before any backend request is made. The type is validated against the known
6
+ * set client-side so an obvious typo gets an immediate, listing error instead of a round-trip.
7
+ */
8
+ export function parseKnowledgeReference(input) {
9
+ const trimmed = input.trim();
10
+ const separator = trimmed.indexOf(":");
11
+ if (separator <= 0) {
12
+ throw new Error(`"${input}" is not a <type>:<value> knowledge component id (e.g. concept:git.bisect)`);
13
+ }
14
+ const typeSegment = trimmed.slice(0, separator);
15
+ const slug = trimmed.slice(separator + 1);
16
+ const type = COMPONENT_TYPES.find((t) => t === typeSegment);
17
+ if (!type) {
18
+ throw new Error(`unknown knowledge component type "${typeSegment}" (expected one of: ${COMPONENT_TYPES.join(", ")})`);
19
+ }
20
+ if (!slug) {
21
+ throw new Error(`knowledge component id "${input}" has an empty value`);
22
+ }
23
+ return { type, slug };
24
+ }
@@ -0,0 +1,43 @@
1
+ import { COMPONENT_TYPES, type ComponentType } from "../fito-api/client.ts";
2
+
3
+ /**
4
+ * Pure parsing helper for the knowledge-components subject: turns a knowledge-component id in
5
+ * canonical reference form (`<type>:<tech-slug>.<component-slug>`, e.g. `concept:git.bisect`)
6
+ * into the `(type, slug)` parts the backend read API takes. Pure (no pi imports, no I/O) so it
7
+ * is unit-testable without a runtime; `knowledge-fetch.ts` composes it with the HTTP call. The
8
+ * reference⇄(type, slug) split is domain logic, kept out of the thin `fito-api` transport client
9
+ * (ADR-006: `fito-api/` mirrors endpoints; knowledge-component logic lives in `shared/knowledge-components/`).
10
+ */
11
+
12
+ /** A knowledge reference resolved into the backend's `GET /knowledge/{type}/{slug}` parts. */
13
+ export interface ParsedKnowledgeReference {
14
+ type: ComponentType;
15
+ /** The `<tech-slug>.<component-slug>` value — the backend's `{slug}` path variable. */
16
+ slug: string;
17
+ }
18
+
19
+ /**
20
+ * Parse a canonical knowledge-component reference (`<type>:<value>`) into its parts. Throws a
21
+ * plain `Error` with a clear message on a malformed input, an unknown type prefix, or an empty
22
+ * value — surfaced before any backend request is made. The type is validated against the known
23
+ * set client-side so an obvious typo gets an immediate, listing error instead of a round-trip.
24
+ */
25
+ export function parseKnowledgeReference(input: string): ParsedKnowledgeReference {
26
+ const trimmed = input.trim();
27
+ const separator = trimmed.indexOf(":");
28
+ if (separator <= 0) {
29
+ throw new Error(`"${input}" is not a <type>:<value> knowledge component id (e.g. concept:git.bisect)`);
30
+ }
31
+ const typeSegment = trimmed.slice(0, separator);
32
+ const slug = trimmed.slice(separator + 1);
33
+ const type = COMPONENT_TYPES.find((t) => t === typeSegment);
34
+ if (!type) {
35
+ throw new Error(
36
+ `unknown knowledge component type "${typeSegment}" (expected one of: ${COMPONENT_TYPES.join(", ")})`,
37
+ );
38
+ }
39
+ if (!slug) {
40
+ throw new Error(`knowledge component id "${input}" has an empty value`);
41
+ }
42
+ return { type, slug };
43
+ }
@@ -0,0 +1,30 @@
1
+ import { FitoApiError, createFitoApiClient, } from "../fito-api/client.js";
2
+ /**
3
+ * Resolve one technology slug to its overview + per-major-line version descriptions (Task 9a.6a,
4
+ * ADR-011 §9). The single public HTTP read is the `fito_technology_fetch` custom tool's core:
5
+ * `/fito-case-design` and `fito-case-source-planner` read each `TechnologyVersion.description` as a
6
+ * soft, prose-only cross-check of the author's declared toolchain. It parallels
7
+ * `fetchKnowledgeComponent` — the tool's `execute()` stays a thin adapter, and the backend-error
8
+ * mapping (a domain-facing concern, ADR-003/006) lives here rather than in the extension.
9
+ *
10
+ * Throws a plain `Error` (clear message) on a 404 (no such technology) or any other backend
11
+ * failure — callers surface `error.message` (the tool wrapper lets it propagate so pi marks the
12
+ * call as an error). `options.client` keeps the HTTP boundary injectable for tests; production
13
+ * calls create the shared client per invocation (reading `FITO_API_BASE_URL`) and send no
14
+ * credentials because the read is public.
15
+ */
16
+ export async function fetchTechnology(slug, options = {}) {
17
+ const client = options.client ?? createFitoApiClient();
18
+ try {
19
+ return await client.getTechnology(slug);
20
+ }
21
+ catch (error) {
22
+ if (error instanceof FitoApiError && error.status === 404) {
23
+ throw new Error(`No technology found for "${slug}".`);
24
+ }
25
+ if (error instanceof FitoApiError) {
26
+ throw new Error(`Fetch failed (${error.status}): ${error.message}`);
27
+ }
28
+ throw error;
29
+ }
30
+ }
@@ -0,0 +1,38 @@
1
+ import {
2
+ FitoApiError,
3
+ type FitoApiClient,
4
+ type TechnologySummary,
5
+ createFitoApiClient,
6
+ } from "../fito-api/client.ts";
7
+
8
+ /**
9
+ * Resolve one technology slug to its overview + per-major-line version descriptions (Task 9a.6a,
10
+ * ADR-011 §9). The single public HTTP read is the `fito_technology_fetch` custom tool's core:
11
+ * `/fito-case-design` and `fito-case-source-planner` read each `TechnologyVersion.description` as a
12
+ * soft, prose-only cross-check of the author's declared toolchain. It parallels
13
+ * `fetchKnowledgeComponent` — the tool's `execute()` stays a thin adapter, and the backend-error
14
+ * mapping (a domain-facing concern, ADR-003/006) lives here rather than in the extension.
15
+ *
16
+ * Throws a plain `Error` (clear message) on a 404 (no such technology) or any other backend
17
+ * failure — callers surface `error.message` (the tool wrapper lets it propagate so pi marks the
18
+ * call as an error). `options.client` keeps the HTTP boundary injectable for tests; production
19
+ * calls create the shared client per invocation (reading `FITO_API_BASE_URL`) and send no
20
+ * credentials because the read is public.
21
+ */
22
+ export async function fetchTechnology(
23
+ slug: string,
24
+ options: { client?: Pick<FitoApiClient, "getTechnology"> } = {},
25
+ ): Promise<TechnologySummary> {
26
+ const client = options.client ?? createFitoApiClient();
27
+ try {
28
+ return await client.getTechnology(slug);
29
+ } catch (error) {
30
+ if (error instanceof FitoApiError && error.status === 404) {
31
+ throw new Error(`No technology found for "${slug}".`);
32
+ }
33
+ if (error instanceof FitoApiError) {
34
+ throw new Error(`Fetch failed (${error.status}): ${error.message}`);
35
+ }
36
+ throw error;
37
+ }
38
+ }
@@ -0,0 +1,22 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ const execFileAsync = promisify(execFile);
4
+ const MAX_BUFFER = 16 * 1024 * 1024;
5
+ export const shellExec = async (command, options) => {
6
+ try {
7
+ const { stdout } = await execFileAsync(command.command, command.args, {
8
+ cwd: options.cwd,
9
+ encoding: "utf8",
10
+ maxBuffer: MAX_BUFFER,
11
+ });
12
+ return String(stdout);
13
+ }
14
+ catch (error) {
15
+ const e = error;
16
+ if (e.code === "ENOENT") {
17
+ throw new Error(`${command.command} not found on PATH`);
18
+ }
19
+ const detail = e.stderr?.trim() || e.message || "unknown error";
20
+ throw new Error(`\`${command.command} ${command.args.join(" ")}\` failed: ${detail}`);
21
+ }
22
+ };
@@ -0,0 +1,46 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+
4
+ /**
5
+ * The real `git`/`gh` executor, shared by every skill that spawns discrete commands (promoted here
6
+ * at the third consumer per ADR-006: `fito-case-runner` Task 5.2, `fito-source-ingestion` Task 8.2,
7
+ * `fito-case-author` Task 9.3 — Task 9.7a): runs each `{command, args}` in `cwd` with no shell (so
8
+ * nothing is shell-interpolated), returns stdout, and rejects with an actionable error on a missing
9
+ * binary or a non-zero exit. Each skill's pure command builders + orchestration are unit-tested
10
+ * against a fake executor; this thin I/O glue is locked by `exec.test.ts` (real subprocesses, no
11
+ * `git`/`gh` needed) with the live `git`/`gh` proof staying in the end-to-end runs.
12
+ *
13
+ * `fito-evaluator/criterion-exec.ts` is deliberately **not** this module: rubric criteria are
14
+ * free-form `sh -c` commands under a timeout budget whose non-zero exits are returned as evidence,
15
+ * not thrown — a different contract, kept skill-local.
16
+ */
17
+
18
+ /** A command to spawn: the binary plus its discrete argv elements (no shell). */
19
+ export interface ShellCommand {
20
+ command: string;
21
+ args: string[];
22
+ }
23
+
24
+ /** Runs a {@link ShellCommand} in `cwd`, resolving with stdout; rejects on a non-zero exit. */
25
+ export type Executor = (command: ShellCommand, options: { cwd: string }) => Promise<string>;
26
+
27
+ const execFileAsync = promisify(execFile);
28
+ const MAX_BUFFER = 16 * 1024 * 1024;
29
+
30
+ export const shellExec: Executor = async (command: ShellCommand, options: { cwd: string }): Promise<string> => {
31
+ try {
32
+ const { stdout } = await execFileAsync(command.command, command.args, {
33
+ cwd: options.cwd,
34
+ encoding: "utf8",
35
+ maxBuffer: MAX_BUFFER,
36
+ });
37
+ return String(stdout);
38
+ } catch (error) {
39
+ const e = error as { code?: string; stderr?: string; message?: string };
40
+ if (e.code === "ENOENT") {
41
+ throw new Error(`${command.command} not found on PATH`);
42
+ }
43
+ const detail = e.stderr?.trim() || e.message || "unknown error";
44
+ throw new Error(`\`${command.command} ${command.args.join(" ")}\` failed: ${detail}`);
45
+ }
46
+ };
@@ -0,0 +1,68 @@
1
+ ---
2
+ name: fito-auth
3
+ description: >
4
+ Authenticate the Fito TUI against the backend and manage the local credential
5
+ store. Use when the learner wants to log in, log out, or refresh their Fito
6
+ session — the /fito-login, /fito-logout, and /fito-auth-refresh commands.
7
+ allowed-tools: bash
8
+ ---
9
+
10
+ # Fito Auth
11
+
12
+ Handles the browser-based login handoff and the `~/.fito/credentials` token store
13
+ (file mode `0600`, dir `0700`). Backend access goes through the `fito-api` client
14
+ (ADR-003); this skill never sees a password — the browser performs the login and
15
+ hands back only the token pair.
16
+
17
+ Run the commands from wherever you are — each one below names this
18
+ skill's directory itself.
19
+
20
+ ## Configuration
21
+
22
+ | Env var | Default | Purpose |
23
+ |---|---|---|
24
+ | `FITO_WEB_ORIGIN` | `http://localhost:5173` | Web origin hosting the login page |
25
+ | `FITO_API_BASE_URL` | `http://localhost:8080` | Backend origin (used by logout/refresh) |
26
+
27
+ ## Log in
28
+
29
+ ```bash
30
+ node <fito-auth skill dir>/login.js
31
+ ```
32
+
33
+ Starts a loopback server on an ephemeral port, opens the system browser to
34
+ `<FITO_WEB_ORIGIN>/auth/login?return_to=tui&port=<port>`, and waits for the
35
+ browser to POST the freshly minted token pair back. On success it writes
36
+ `~/.fito/credentials` and prints a confirmation. The learner can complete either
37
+ auth flow (email/password or "Continue with GitHub") in the browser.
38
+
39
+ ## Log out
40
+
41
+ ```bash
42
+ node <fito-auth skill dir>/logout.js
43
+ ```
44
+
45
+ Best-effort revokes the refresh token server-side, then deletes
46
+ `~/.fito/credentials`. Idempotent — succeeds even when not logged in.
47
+
48
+ ## Refresh
49
+
50
+ ```bash
51
+ node <fito-auth skill dir>/auth-refresh.js
52
+ ```
53
+
54
+ Exchanges the stored refresh token for a fresh token pair via `POST /auth/refresh`
55
+ and rewrites `~/.fito/credentials`. Fails if not logged in.
56
+
57
+ ## Files
58
+
59
+ | File | Role |
60
+ |---|---|
61
+ | `callback-server.ts` | Loopback receiver for the browser token handoff (CORS) |
62
+ | `browser.ts` | Per-platform system-browser launcher |
63
+ | `login.ts` / `logout.ts` / `auth-refresh.ts` | CLI entrypoints (above) |
64
+
65
+ The `~/.fito/credentials` store (read/write/delete, `0600`, Zod-validated) lives in the
66
+ shared [`fito-session`](../../shared/fito-session/credentials.ts) module, reused by `fito-case-runner`.
67
+
68
+ See [the fito-api client](../../shared/fito-api/README.md) for how backend calls are made.