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,155 @@
1
+ /**
2
+ * `node authoring-check.js [path]` — the fito-source-ingestion **authoring-context check**
3
+ * (Task 8.2), gating the identify prompts' `--source .` offer on a case checkout.
4
+ *
5
+ * Verdict rule (parent-matches-the-registry): **not authoring** ⇔ the checkout's `origin` is a
6
+ * GitHub fork whose parent URL is a **published case registered in the backend** — learner clones
7
+ * are such forks by construction (`/fito-case-open`). Everything determinate else — no origin,
8
+ * a non-GitHub origin, a non-fork, or a fork of an unregistered repo — is **authoring**. When the
9
+ * check cannot decide (git/gh missing, gh unauthenticated, backend unreachable) it exits non-zero
10
+ * instead of guessing; the prompts treat that as "make no offer" (fail-safe).
11
+ *
12
+ * `checkAuthoringContext` is the testable core (executor + client injectable); `main` is the thin
13
+ * CLI wrapper — the `fito-case-runner` open.ts pattern.
14
+ */
15
+ import * as path from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+
18
+ import { type FitoApiClient, createFitoApiClient } from "../../shared/fito-api/client.ts";
19
+ import { parseGithubUrl } from "../../shared/github-url/parse.ts";
20
+ import { type Executor, type ShellCommand, shellExec } from "../../shared/shell-exec/exec.ts";
21
+
22
+ /** A command to spawn: the binary plus its discrete argv elements (the shared `shell-exec` contract). */
23
+ export type { Executor, ShellCommand };
24
+
25
+ export interface AuthoringVerdict {
26
+ verdict: "authoring" | "not-authoring";
27
+ reason: string;
28
+ /** The fork parent's canonical https URL — set once the check reaches the fork-parent step. */
29
+ parentUrl?: string;
30
+ }
31
+
32
+ /** `git remote get-url origin` — the checkout's origin URL (run in the checked dir). */
33
+ export function gitOriginUrlCommand(): ShellCommand {
34
+ return { command: "git", args: ["remote", "get-url", "origin"] };
35
+ }
36
+
37
+ /** `gh repo view <slug> --json isFork,parent` — is the origin repo a fork, and of what parent? */
38
+ export function ghRepoViewCommand(slug: string): ShellCommand {
39
+ return { command: "gh", args: ["repo", "view", slug, "--json", "isFork,parent"] };
40
+ }
41
+
42
+ /**
43
+ * Parse a git origin URL into its GitHub `{ owner, repo }`, or null when the origin is not a
44
+ * GitHub repository (the shared `github-url` grammar's lenient form). Unlike the case-runner's
45
+ * parser this accepts ssh forms too: the URL only names the repo for `gh repo view`, it is never
46
+ * handed to the backend reachability ping.
47
+ */
48
+ export function parseGithubOwnerRepo(url: string): { owner: string; repo: string } | null {
49
+ return parseGithubUrl(url);
50
+ }
51
+
52
+ /**
53
+ * Parse `gh repo view --json isFork,parent` stdout. For a fork, composes the parent's canonical
54
+ * https URL (`https://github.com/<owner-login>/<name>`) — already in the normalized form the
55
+ * backend's repositoryUrl filter matches. Malformed JSON, or a fork whose parent is missing,
56
+ * throws (the check cannot decide, so it must not guess).
57
+ */
58
+ export function parseRepoView(stdout: string): { isFork: boolean; parentUrl: string | null } {
59
+ let parsed: unknown;
60
+ try {
61
+ parsed = JSON.parse(stdout);
62
+ } catch (error) {
63
+ const detail = error instanceof Error ? error.message : String(error);
64
+ throw new Error(`gh repo view returned malformed JSON: ${detail}`);
65
+ }
66
+ const record = parsed as { isFork?: unknown; parent?: { name?: unknown; owner?: { login?: unknown } } | null };
67
+ if (record.isFork !== true) return { isFork: false, parentUrl: null };
68
+ const login = record.parent?.owner?.login;
69
+ const name = record.parent?.name;
70
+ if (typeof login !== "string" || login.length === 0 || typeof name !== "string" || name.length === 0) {
71
+ throw new Error("gh repo view reported a fork without a resolvable parent");
72
+ }
73
+ return { isFork: true, parentUrl: `https://github.com/${login}/${name}` };
74
+ }
75
+
76
+ export interface CheckOptions {
77
+ /** The checkout to classify; defaults to the current directory. */
78
+ dir?: string;
79
+ exec?: Executor;
80
+ /** Backend client (registry lookup); defaults to the real one (reads `FITO_API_BASE_URL`). */
81
+ client?: Pick<FitoApiClient, "listCases">;
82
+ }
83
+
84
+ /** Origin → `gh` fork/parent → registry match → verdict. */
85
+ export async function checkAuthoringContext(options: CheckOptions = {}): Promise<AuthoringVerdict> {
86
+ const dir = options.dir ?? ".";
87
+ const exec = options.exec ?? shellExec;
88
+ const client = options.client ?? createFitoApiClient();
89
+
90
+ let originUrl: string;
91
+ try {
92
+ originUrl = (await exec(gitOriginUrlCommand(), { cwd: dir })).trim();
93
+ } catch (error) {
94
+ // A missing git binary means the check cannot decide — propagate. A failing
95
+ // `remote get-url` (no origin remote, or not a git repo) is a determinate
96
+ // authoring signal: learner clones always have their fork as origin.
97
+ if (error instanceof Error && /not found on PATH/.test(error.message)) throw error;
98
+ return { verdict: "authoring", reason: "the checkout has no git origin remote" };
99
+ }
100
+
101
+ const repo = parseGithubOwnerRepo(originUrl);
102
+ if (repo === null) {
103
+ return { verdict: "authoring", reason: `origin ${originUrl} is not a GitHub repository` };
104
+ }
105
+
106
+ const slug = `${repo.owner}/${repo.repo}`;
107
+ const view = parseRepoView(await exec(ghRepoViewCommand(slug), { cwd: dir }));
108
+ if (!view.isFork) {
109
+ return { verdict: "authoring", reason: `origin ${slug} is not a fork` };
110
+ }
111
+
112
+ const parentUrl = view.parentUrl as string;
113
+ const page = await client.listCases({ repositoryUrl: parentUrl });
114
+ if (page.total >= 1) {
115
+ return {
116
+ verdict: "not-authoring",
117
+ reason: `origin ${slug} is a fork of ${parentUrl}, a registered case — this is a learner clone`,
118
+ parentUrl,
119
+ };
120
+ }
121
+ return {
122
+ verdict: "authoring",
123
+ reason: `origin ${slug} is a fork, but ${parentUrl} is not a registered case`,
124
+ parentUrl,
125
+ };
126
+ }
127
+
128
+ const USAGE = "usage: node authoring-check.js [path]";
129
+
130
+ /** Parse the check CLI args (`argv` minus the node/script prefix): one optional path. */
131
+ export function parseCheckArgs(args: string[]): { dir: string } {
132
+ const [dir, ...rest] = args;
133
+ if (rest.length > 0 || (dir !== undefined && dir.startsWith("--"))) {
134
+ throw new Error(USAGE);
135
+ }
136
+ return { dir: dir ?? "." };
137
+ }
138
+
139
+ async function main(): Promise<void> {
140
+ const { dir } = parseCheckArgs(process.argv.slice(2));
141
+ const result = await checkAuthoringContext({ dir });
142
+ console.log(`verdict: ${result.verdict}`);
143
+ console.log(`reason: ${result.reason}`);
144
+ if (result.parentUrl) console.log(`parent: ${result.parentUrl}`);
145
+ }
146
+
147
+ /** Only auto-invoke the CLI when run directly (`node authoring-check.js …`), not when imported. */
148
+ const entry = process.argv[1];
149
+ const isMainModule = !!entry && path.resolve(entry) === fileURLToPath(import.meta.url);
150
+ if (isMainModule) {
151
+ main().catch((error: unknown) => {
152
+ console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
153
+ process.exitCode = 1;
154
+ });
155
+ }
@@ -0,0 +1,198 @@
1
+ /**
2
+ * `node bundle.js <source-path> [--output <dir>]` — the fito-source-ingestion **source bundle**
3
+ * builder (Task 8.2, the INGEST step for the preferred source): walks a case's local checkout and
4
+ * materializes the ingestible subset for the identifier agents — a filtered mirror of the tree
5
+ * under `files/` (relative paths preserved, so `read`/`grep`/`find` behave like the real tree)
6
+ * plus a `bundle.json` manifest (per-file path + size, and every skipped file with its reason).
7
+ *
8
+ * What is *not* bundled: VCS/dependency/build directories and lockfiles (excluded by name — the
9
+ * pipeline's own `output/` workspace and the `.case/`/`.authoring/` authoring artifacts among
10
+ * them), binary files (NUL-byte sniff), files over the size cap, and symlinks (never followed).
11
+ * The walk collects first and materializes after, so a failed run leaves no partial bundle.
12
+ *
13
+ * `buildSourceBundle` is the testable core; `main` is the thin CLI wrapper — the
14
+ * `fito-case-runner` open.ts pattern.
15
+ */
16
+ import * as fs from "node:fs";
17
+ import * as path from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+ /** Where the bundle lands by default — beside the URL-fetcher's `extracted_links_content/`. */
20
+ export const DEFAULT_OUTPUT_DIR = path.join("output", "1-ingest", "source_bundle");
21
+ /** This file is `<root>/skills/fito-source-ingestion/bundle.ts`, wherever the package is installed. */
22
+ const TUI_PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
23
+ /** Skip files larger than this — big blobs (fixtures, minified assets) drown the identifiers. */
24
+ export const DEFAULT_MAX_FILE_BYTES = 256 * 1024;
25
+ /**
26
+ * Directory names that are never case source: VCS internals, dependency and build trees, IDE
27
+ * metadata, `output` (the knowledge pipeline's own per-stage workspace convention) — and the
28
+ * authoring artifacts `.case`/`.authoring`: a bundled `.case/` snapshot fed a stale
29
+ * `known_state.branch` value into a later generate run (F14, Task 9a.8).
30
+ */
31
+ const EXCLUDED_DIR_NAMES = new Set([
32
+ ".authoring",
33
+ ".case",
34
+ ".git",
35
+ ".hg",
36
+ ".svn",
37
+ ".gradle",
38
+ ".idea",
39
+ ".next",
40
+ ".svelte-kit",
41
+ ".venv",
42
+ ".vscode",
43
+ "__pycache__",
44
+ "build",
45
+ "coverage",
46
+ "dist",
47
+ "node_modules",
48
+ "output",
49
+ "target",
50
+ "venv",
51
+ ]);
52
+ /** Generated files with no instructional signal. */
53
+ const EXCLUDED_FILE_NAMES = new Set([".DS_Store", "bun.lockb", "package-lock.json", "pnpm-lock.yaml", "yarn.lock"]);
54
+ /** How many leading bytes to sniff for a NUL when classifying a file as binary. */
55
+ const SNIFF_BYTES = 8192;
56
+ /**
57
+ * Convert a platform-relative path to forward-slash form so `bundle.json` is portable across
58
+ * platforms (a Windows-built bundle stays readable everywhere). The separator is a parameter
59
+ * only so the conversion is testable from a single platform.
60
+ */
61
+ export function toPosixPath(relativePath, separator = path.sep) {
62
+ return separator === "/" ? relativePath : relativePath.split(separator).join("/");
63
+ }
64
+ /** Whether the file's leading bytes contain a NUL — the classic text-vs-binary sniff. */
65
+ function isBinary(file) {
66
+ const buffer = Buffer.alloc(SNIFF_BYTES);
67
+ const fd = fs.openSync(file, "r");
68
+ try {
69
+ const read = fs.readSync(fd, buffer, 0, SNIFF_BYTES, 0);
70
+ return buffer.subarray(0, read).includes(0);
71
+ }
72
+ finally {
73
+ fs.closeSync(fd);
74
+ }
75
+ }
76
+ /** Walk the source tree and produce the filtered mirror + `bundle.json` at `outputDir`. */
77
+ export async function buildSourceBundle(options) {
78
+ const sourceRoot = path.resolve(options.sourceDir);
79
+ const outputRoot = path.resolve(options.outputDir);
80
+ const maxFileBytes = options.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
81
+ if (!fs.existsSync(sourceRoot) || !fs.statSync(sourceRoot).isDirectory()) {
82
+ throw new Error(`source path is not a directory: ${sourceRoot}`);
83
+ }
84
+ // Materializing wipes the output dir, so it must never sit above (or be) the tree it reads from.
85
+ if (sourceRoot === outputRoot || sourceRoot.startsWith(outputRoot + path.sep)) {
86
+ throw new Error(`the output directory must not equal or contain the source tree:\n` +
87
+ ` source: ${sourceRoot}\n output: ${outputRoot}`);
88
+ }
89
+ // A bundle is a third-party source mirror; Fito's own tree is never its destination. Reaching
90
+ // here means the CWD was wrong — the house convention of driving a skill from its own directory
91
+ // does not apply to this script — and unnoticed it leaves megabytes of untracked source in the
92
+ // product repo for a later `git add -A` to commit (F26).
93
+ if (outputRoot === TUI_PACKAGE_ROOT || outputRoot.startsWith(TUI_PACKAGE_ROOT + path.sep)) {
94
+ throw new Error(`the output directory is inside the Fito TUI package and will not be written:\n` +
95
+ ` output: ${outputRoot}\n` +
96
+ ` tui package: ${TUI_PACKAGE_ROOT}\n` +
97
+ `--output resolves against the current working directory, so this is usually a run from ` +
98
+ `the skill's directory instead of your own. Run it from your working directory and the ` +
99
+ `default ./output/1-ingest/source_bundle/ lands beside it.`);
100
+ }
101
+ // Only a directory holding nothing but a bundle's own entries may be wiped and rebuilt —
102
+ // a stray bundle.json beside other content must not turn it into a wipe target.
103
+ if (fs.existsSync(outputRoot)) {
104
+ const foreign = fs.readdirSync(outputRoot).filter((name) => name !== "bundle.json" && name !== "files");
105
+ if (foreign.length > 0) {
106
+ throw new Error(`The output directory exists and holds content that is not a previous bundle:\n ${outputRoot}\n` +
107
+ `Move or remove it first — Fito will not overwrite it.`);
108
+ }
109
+ }
110
+ const files = [];
111
+ const skipped = [];
112
+ const walk = (dir) => {
113
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
114
+ const absolute = path.join(dir, entry.name);
115
+ const relative = toPosixPath(path.relative(sourceRoot, absolute));
116
+ if (entry.isSymbolicLink()) {
117
+ skipped.push({ path: relative, reason: "symlink (not followed)" });
118
+ continue;
119
+ }
120
+ if (entry.isDirectory()) {
121
+ // Never descend into the bundle target itself, wherever --output pointed it.
122
+ if (EXCLUDED_DIR_NAMES.has(entry.name) || absolute === outputRoot)
123
+ continue;
124
+ walk(absolute);
125
+ continue;
126
+ }
127
+ if (!entry.isFile() || EXCLUDED_FILE_NAMES.has(entry.name))
128
+ continue;
129
+ const bytes = fs.statSync(absolute).size;
130
+ if (bytes > maxFileBytes) {
131
+ skipped.push({ path: relative, reason: `too large (${bytes} bytes > ${maxFileBytes} cap)` });
132
+ continue;
133
+ }
134
+ if (isBinary(absolute)) {
135
+ skipped.push({ path: relative, reason: "binary" });
136
+ continue;
137
+ }
138
+ files.push({ absolute, relative, bytes });
139
+ }
140
+ };
141
+ walk(sourceRoot);
142
+ if (files.length === 0) {
143
+ throw new Error(`no ingestible files found under ${sourceRoot}`);
144
+ }
145
+ files.sort((a, b) => a.relative.localeCompare(b.relative));
146
+ skipped.sort((a, b) => a.path.localeCompare(b.path));
147
+ // Collect-then-materialize: only now touch the output (rebuilding drops a previous bundle whole).
148
+ fs.rmSync(outputRoot, { recursive: true, force: true });
149
+ for (const file of files) {
150
+ const target = path.join(outputRoot, "files", file.relative);
151
+ fs.mkdirSync(path.dirname(target), { recursive: true });
152
+ fs.copyFileSync(file.absolute, target);
153
+ }
154
+ const totalBytes = files.reduce((sum, file) => sum + file.bytes, 0);
155
+ const manifest = {
156
+ source_root: sourceRoot,
157
+ generated_at: new Date().toISOString(),
158
+ file_count: files.length,
159
+ total_bytes: totalBytes,
160
+ files: files.map((file) => ({ path: file.relative, bytes: file.bytes })),
161
+ skipped,
162
+ };
163
+ fs.writeFileSync(path.join(outputRoot, "bundle.json"), `${JSON.stringify(manifest, null, "\t")}\n`);
164
+ return { outputDir: outputRoot, fileCount: files.length, totalBytes, skipped };
165
+ }
166
+ const USAGE = "usage: node bundle.js <source-path> [--output <dir>]";
167
+ /** Parse the bundle CLI args (`argv` minus the node/script prefix): the source path + optional `--output`. */
168
+ export function parseBundleArgs(args) {
169
+ const [sourceDir, ...rest] = args;
170
+ if (!sourceDir || sourceDir.startsWith("--")) {
171
+ throw new Error(USAGE);
172
+ }
173
+ if (rest.length === 0) {
174
+ return { sourceDir, outputDir: DEFAULT_OUTPUT_DIR };
175
+ }
176
+ if (rest.length === 2 && rest[0] === "--output" && rest[1] && !rest[1].startsWith("--")) {
177
+ return { sourceDir, outputDir: rest[1] };
178
+ }
179
+ throw new Error(USAGE);
180
+ }
181
+ async function main() {
182
+ const { sourceDir, outputDir } = parseBundleArgs(process.argv.slice(2));
183
+ const result = await buildSourceBundle({ sourceDir, outputDir });
184
+ console.log(`✓ Bundled ${result.fileCount} files (${result.totalBytes} bytes) from ${path.resolve(sourceDir)}`);
185
+ console.log(` into ${result.outputDir}`);
186
+ if (result.skipped.length > 0) {
187
+ console.log(` ${result.skipped.length} skipped (binary / oversized / symlink) — see bundle.json`);
188
+ }
189
+ }
190
+ /** Only auto-invoke the CLI when run directly (`node bundle.js …`), not when imported (e.g. by tests). */
191
+ const entry = process.argv[1];
192
+ const isMainModule = !!entry && path.resolve(entry) === fileURLToPath(import.meta.url);
193
+ if (isMainModule) {
194
+ main().catch((error) => {
195
+ console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
196
+ process.exitCode = 1;
197
+ });
198
+ }
@@ -0,0 +1,246 @@
1
+ /**
2
+ * `node bundle.js <source-path> [--output <dir>]` — the fito-source-ingestion **source bundle**
3
+ * builder (Task 8.2, the INGEST step for the preferred source): walks a case's local checkout and
4
+ * materializes the ingestible subset for the identifier agents — a filtered mirror of the tree
5
+ * under `files/` (relative paths preserved, so `read`/`grep`/`find` behave like the real tree)
6
+ * plus a `bundle.json` manifest (per-file path + size, and every skipped file with its reason).
7
+ *
8
+ * What is *not* bundled: VCS/dependency/build directories and lockfiles (excluded by name — the
9
+ * pipeline's own `output/` workspace and the `.case/`/`.authoring/` authoring artifacts among
10
+ * them), binary files (NUL-byte sniff), files over the size cap, and symlinks (never followed).
11
+ * The walk collects first and materializes after, so a failed run leaves no partial bundle.
12
+ *
13
+ * `buildSourceBundle` is the testable core; `main` is the thin CLI wrapper — the
14
+ * `fito-case-runner` open.ts pattern.
15
+ */
16
+ import * as fs from "node:fs";
17
+ import * as path from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+
20
+ /** Where the bundle lands by default — beside the URL-fetcher's `extracted_links_content/`. */
21
+ export const DEFAULT_OUTPUT_DIR = path.join("output", "1-ingest", "source_bundle");
22
+
23
+ /** This file is `<root>/skills/fito-source-ingestion/bundle.ts`, wherever the package is installed. */
24
+ const TUI_PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
25
+
26
+ /** Skip files larger than this — big blobs (fixtures, minified assets) drown the identifiers. */
27
+ export const DEFAULT_MAX_FILE_BYTES = 256 * 1024;
28
+
29
+ /**
30
+ * Directory names that are never case source: VCS internals, dependency and build trees, IDE
31
+ * metadata, `output` (the knowledge pipeline's own per-stage workspace convention) — and the
32
+ * authoring artifacts `.case`/`.authoring`: a bundled `.case/` snapshot fed a stale
33
+ * `known_state.branch` value into a later generate run (F14, Task 9a.8).
34
+ */
35
+ const EXCLUDED_DIR_NAMES = new Set([
36
+ ".authoring",
37
+ ".case",
38
+ ".git",
39
+ ".hg",
40
+ ".svn",
41
+ ".gradle",
42
+ ".idea",
43
+ ".next",
44
+ ".svelte-kit",
45
+ ".venv",
46
+ ".vscode",
47
+ "__pycache__",
48
+ "build",
49
+ "coverage",
50
+ "dist",
51
+ "node_modules",
52
+ "output",
53
+ "target",
54
+ "venv",
55
+ ]);
56
+
57
+ /** Generated files with no instructional signal. */
58
+ const EXCLUDED_FILE_NAMES = new Set([".DS_Store", "bun.lockb", "package-lock.json", "pnpm-lock.yaml", "yarn.lock"]);
59
+
60
+ /** How many leading bytes to sniff for a NUL when classifying a file as binary. */
61
+ const SNIFF_BYTES = 8192;
62
+
63
+ /**
64
+ * Convert a platform-relative path to forward-slash form so `bundle.json` is portable across
65
+ * platforms (a Windows-built bundle stays readable everywhere). The separator is a parameter
66
+ * only so the conversion is testable from a single platform.
67
+ */
68
+ export function toPosixPath(relativePath: string, separator: string = path.sep): string {
69
+ return separator === "/" ? relativePath : relativePath.split(separator).join("/");
70
+ }
71
+
72
+ export interface BundleOptions {
73
+ sourceDir: string;
74
+ outputDir: string;
75
+ /** Per-file size cap in bytes; defaults to {@link DEFAULT_MAX_FILE_BYTES}. */
76
+ maxFileBytes?: number;
77
+ }
78
+
79
+ export interface SkippedFile {
80
+ /** Path relative to the source root. */
81
+ path: string;
82
+ reason: string;
83
+ }
84
+
85
+ export interface BundleResult {
86
+ outputDir: string;
87
+ fileCount: number;
88
+ totalBytes: number;
89
+ skipped: SkippedFile[];
90
+ }
91
+
92
+ interface CollectedFile {
93
+ absolute: string;
94
+ relative: string;
95
+ bytes: number;
96
+ }
97
+
98
+ /** Whether the file's leading bytes contain a NUL — the classic text-vs-binary sniff. */
99
+ function isBinary(file: string): boolean {
100
+ const buffer = Buffer.alloc(SNIFF_BYTES);
101
+ const fd = fs.openSync(file, "r");
102
+ try {
103
+ const read = fs.readSync(fd, buffer, 0, SNIFF_BYTES, 0);
104
+ return buffer.subarray(0, read).includes(0);
105
+ } finally {
106
+ fs.closeSync(fd);
107
+ }
108
+ }
109
+
110
+ /** Walk the source tree and produce the filtered mirror + `bundle.json` at `outputDir`. */
111
+ export async function buildSourceBundle(options: BundleOptions): Promise<BundleResult> {
112
+ const sourceRoot = path.resolve(options.sourceDir);
113
+ const outputRoot = path.resolve(options.outputDir);
114
+ const maxFileBytes = options.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
115
+
116
+ if (!fs.existsSync(sourceRoot) || !fs.statSync(sourceRoot).isDirectory()) {
117
+ throw new Error(`source path is not a directory: ${sourceRoot}`);
118
+ }
119
+ // Materializing wipes the output dir, so it must never sit above (or be) the tree it reads from.
120
+ if (sourceRoot === outputRoot || sourceRoot.startsWith(outputRoot + path.sep)) {
121
+ throw new Error(
122
+ `the output directory must not equal or contain the source tree:\n` +
123
+ ` source: ${sourceRoot}\n output: ${outputRoot}`,
124
+ );
125
+ }
126
+ // A bundle is a third-party source mirror; Fito's own tree is never its destination. Reaching
127
+ // here means the CWD was wrong — the house convention of driving a skill from its own directory
128
+ // does not apply to this script — and unnoticed it leaves megabytes of untracked source in the
129
+ // product repo for a later `git add -A` to commit (F26).
130
+ if (outputRoot === TUI_PACKAGE_ROOT || outputRoot.startsWith(TUI_PACKAGE_ROOT + path.sep)) {
131
+ throw new Error(
132
+ `the output directory is inside the Fito TUI package and will not be written:\n` +
133
+ ` output: ${outputRoot}\n` +
134
+ ` tui package: ${TUI_PACKAGE_ROOT}\n` +
135
+ `--output resolves against the current working directory, so this is usually a run from ` +
136
+ `the skill's directory instead of your own. Run it from your working directory and the ` +
137
+ `default ./output/1-ingest/source_bundle/ lands beside it.`,
138
+ );
139
+ }
140
+ // Only a directory holding nothing but a bundle's own entries may be wiped and rebuilt —
141
+ // a stray bundle.json beside other content must not turn it into a wipe target.
142
+ if (fs.existsSync(outputRoot)) {
143
+ const foreign = fs.readdirSync(outputRoot).filter((name) => name !== "bundle.json" && name !== "files");
144
+ if (foreign.length > 0) {
145
+ throw new Error(
146
+ `The output directory exists and holds content that is not a previous bundle:\n ${outputRoot}\n` +
147
+ `Move or remove it first — Fito will not overwrite it.`,
148
+ );
149
+ }
150
+ }
151
+
152
+ const files: CollectedFile[] = [];
153
+ const skipped: SkippedFile[] = [];
154
+
155
+ const walk = (dir: string): void => {
156
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
157
+ const absolute = path.join(dir, entry.name);
158
+ const relative = toPosixPath(path.relative(sourceRoot, absolute));
159
+ if (entry.isSymbolicLink()) {
160
+ skipped.push({ path: relative, reason: "symlink (not followed)" });
161
+ continue;
162
+ }
163
+ if (entry.isDirectory()) {
164
+ // Never descend into the bundle target itself, wherever --output pointed it.
165
+ if (EXCLUDED_DIR_NAMES.has(entry.name) || absolute === outputRoot) continue;
166
+ walk(absolute);
167
+ continue;
168
+ }
169
+ if (!entry.isFile() || EXCLUDED_FILE_NAMES.has(entry.name)) continue;
170
+ const bytes = fs.statSync(absolute).size;
171
+ if (bytes > maxFileBytes) {
172
+ skipped.push({ path: relative, reason: `too large (${bytes} bytes > ${maxFileBytes} cap)` });
173
+ continue;
174
+ }
175
+ if (isBinary(absolute)) {
176
+ skipped.push({ path: relative, reason: "binary" });
177
+ continue;
178
+ }
179
+ files.push({ absolute, relative, bytes });
180
+ }
181
+ };
182
+ walk(sourceRoot);
183
+
184
+ if (files.length === 0) {
185
+ throw new Error(`no ingestible files found under ${sourceRoot}`);
186
+ }
187
+ files.sort((a, b) => a.relative.localeCompare(b.relative));
188
+ skipped.sort((a, b) => a.path.localeCompare(b.path));
189
+
190
+ // Collect-then-materialize: only now touch the output (rebuilding drops a previous bundle whole).
191
+ fs.rmSync(outputRoot, { recursive: true, force: true });
192
+ for (const file of files) {
193
+ const target = path.join(outputRoot, "files", file.relative);
194
+ fs.mkdirSync(path.dirname(target), { recursive: true });
195
+ fs.copyFileSync(file.absolute, target);
196
+ }
197
+ const totalBytes = files.reduce((sum, file) => sum + file.bytes, 0);
198
+ const manifest = {
199
+ source_root: sourceRoot,
200
+ generated_at: new Date().toISOString(),
201
+ file_count: files.length,
202
+ total_bytes: totalBytes,
203
+ files: files.map((file) => ({ path: file.relative, bytes: file.bytes })),
204
+ skipped,
205
+ };
206
+ fs.writeFileSync(path.join(outputRoot, "bundle.json"), `${JSON.stringify(manifest, null, "\t")}\n`);
207
+
208
+ return { outputDir: outputRoot, fileCount: files.length, totalBytes, skipped };
209
+ }
210
+
211
+ const USAGE = "usage: node bundle.js <source-path> [--output <dir>]";
212
+
213
+ /** Parse the bundle CLI args (`argv` minus the node/script prefix): the source path + optional `--output`. */
214
+ export function parseBundleArgs(args: string[]): { sourceDir: string; outputDir: string } {
215
+ const [sourceDir, ...rest] = args;
216
+ if (!sourceDir || sourceDir.startsWith("--")) {
217
+ throw new Error(USAGE);
218
+ }
219
+ if (rest.length === 0) {
220
+ return { sourceDir, outputDir: DEFAULT_OUTPUT_DIR };
221
+ }
222
+ if (rest.length === 2 && rest[0] === "--output" && rest[1] && !rest[1].startsWith("--")) {
223
+ return { sourceDir, outputDir: rest[1] };
224
+ }
225
+ throw new Error(USAGE);
226
+ }
227
+
228
+ async function main(): Promise<void> {
229
+ const { sourceDir, outputDir } = parseBundleArgs(process.argv.slice(2));
230
+ const result = await buildSourceBundle({ sourceDir, outputDir });
231
+ console.log(`✓ Bundled ${result.fileCount} files (${result.totalBytes} bytes) from ${path.resolve(sourceDir)}`);
232
+ console.log(` into ${result.outputDir}`);
233
+ if (result.skipped.length > 0) {
234
+ console.log(` ${result.skipped.length} skipped (binary / oversized / symlink) — see bundle.json`);
235
+ }
236
+ }
237
+
238
+ /** Only auto-invoke the CLI when run directly (`node bundle.js …`), not when imported (e.g. by tests). */
239
+ const entry = process.argv[1];
240
+ const isMainModule = !!entry && path.resolve(entry) === fileURLToPath(import.meta.url);
241
+ if (isMainModule) {
242
+ main().catch((error: unknown) => {
243
+ console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
244
+ process.exitCode = 1;
245
+ });
246
+ }