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.
- package/README.md +88 -0
- package/agents/fito-case-source-planner.md +265 -0
- package/agents/fito-performance-reviewer.md +231 -0
- package/agents/fito-practice-concept-content-generator.md +318 -0
- package/agents/fito-practice-concept-identifier.md +482 -0
- package/agents/fito-practice-execution-fact-content-generator.md +299 -0
- package/agents/fito-practice-execution-fact-identifier.md +367 -0
- package/agents/fito-practice-usage-scenario-content-generator.md +331 -0
- package/agents/fito-practice-usage-scenario-identifier.md +397 -0
- package/agents/fito-subagent-selftest.md +27 -0
- package/agents/fito-technology-generator.md +207 -0
- package/agents/fito-tool-concept-content-generator.md +282 -0
- package/agents/fito-tool-concept-identifier.md +384 -0
- package/agents/fito-tool-execution-fact-content-generator.md +382 -0
- package/agents/fito-tool-execution-fact-identifier.md +360 -0
- package/agents/fito-tool-usage-scenario-content-generator.md +381 -0
- package/agents/fito-tool-usage-scenario-identifier.md +432 -0
- package/agents/fito-tutor.md +185 -0
- package/extensions/fito-delegate.js +539 -0
- package/extensions/fito-delegate.ts +691 -0
- package/extensions/fito-fetch-tools.js +380 -0
- package/extensions/fito-fetch-tools.ts +419 -0
- package/extensions/fito-startup.js +166 -0
- package/extensions/fito-startup.ts +188 -0
- package/package.json +56 -0
- package/prompts/fito-auth-refresh.md +15 -0
- package/prompts/fito-case-design.md +506 -0
- package/prompts/fito-case-edit.md +91 -0
- package/prompts/fito-case-generate.md +222 -0
- package/prompts/fito-case-open.md +124 -0
- package/prompts/fito-case-plan-source.md +114 -0
- package/prompts/fito-create-or-update-competence.md +261 -0
- package/prompts/fito-create-or-update-technology.md +199 -0
- package/prompts/fito-delete-competence.md +147 -0
- package/prompts/fito-evaluate.md +148 -0
- package/prompts/fito-fetch-urls-content.md +35 -0
- package/prompts/fito-generate-domain-concepts.md +85 -0
- package/prompts/fito-generate-execution-facts.md +85 -0
- package/prompts/fito-generate-usage-scenarios.md +85 -0
- package/prompts/fito-identify-domain-concepts.md +49 -0
- package/prompts/fito-identify-execution-facts.md +49 -0
- package/prompts/fito-identify-usage-scenarios.md +49 -0
- package/prompts/fito-login.md +21 -0
- package/prompts/fito-logout.md +14 -0
- package/prompts/fito-publish-case.md +266 -0
- package/prompts/fito-push-knowledge.md +84 -0
- package/prompts/fito-submit.md +208 -0
- package/prompts/fito-tutor.md +120 -0
- package/shared/case-briefing/briefing.js +221 -0
- package/shared/case-briefing/briefing.ts +261 -0
- package/shared/case-quiz/scoring.js +16 -0
- package/shared/case-quiz/scoring.ts +61 -0
- package/shared/case-validation/case-loader.js +88 -0
- package/shared/case-validation/case-loader.ts +106 -0
- package/shared/case-validation/case-schema.js +716 -0
- package/shared/case-validation/case-schema.ts +895 -0
- package/shared/competences/competence-list.js +29 -0
- package/shared/competences/competence-list.ts +32 -0
- package/shared/fito-api/README.md +192 -0
- package/shared/fito-api/client.js +731 -0
- package/shared/fito-api/client.ts +1426 -0
- package/shared/fito-session/credentials.js +79 -0
- package/shared/fito-session/credentials.ts +88 -0
- package/shared/fito-session/session.js +16 -0
- package/shared/fito-session/session.ts +35 -0
- package/shared/github-url/parse.js +26 -0
- package/shared/github-url/parse.ts +35 -0
- package/shared/knowledge-components/component-names.js +35 -0
- package/shared/knowledge-components/component-names.ts +39 -0
- package/shared/knowledge-components/knowledge-fetch.js +46 -0
- package/shared/knowledge-components/knowledge-fetch.ts +57 -0
- package/shared/knowledge-components/knowledge-search.js +101 -0
- package/shared/knowledge-components/knowledge-search.ts +144 -0
- package/shared/knowledge-components/push-payload.js +104 -0
- package/shared/knowledge-components/push-payload.ts +129 -0
- package/shared/knowledge-components/reference.js +24 -0
- package/shared/knowledge-components/reference.ts +43 -0
- package/shared/knowledge-components/technology-fetch.js +30 -0
- package/shared/knowledge-components/technology-fetch.ts +38 -0
- package/shared/shell-exec/exec.js +22 -0
- package/shared/shell-exec/exec.ts +46 -0
- package/skills/fito-auth/SKILL.md +68 -0
- package/skills/fito-auth/auth-refresh.js +23 -0
- package/skills/fito-auth/auth-refresh.ts +25 -0
- package/skills/fito-auth/browser.js +35 -0
- package/skills/fito-auth/browser.ts +57 -0
- package/skills/fito-auth/callback-server.js +152 -0
- package/skills/fito-auth/callback-server.ts +189 -0
- package/skills/fito-auth/login.js +37 -0
- package/skills/fito-auth/login.ts +42 -0
- package/skills/fito-auth/logout.js +24 -0
- package/skills/fito-auth/logout.ts +25 -0
- package/skills/fito-case-author/SKILL.md +179 -0
- package/skills/fito-case-author/checkout.js +222 -0
- package/skills/fito-case-author/checkout.ts +281 -0
- package/skills/fito-case-author/github-publish.js +218 -0
- package/skills/fito-case-author/github-publish.ts +251 -0
- package/skills/fito-case-author/publish-payload.js +108 -0
- package/skills/fito-case-author/publish-payload.ts +186 -0
- package/skills/fito-case-author/publish-state.js +72 -0
- package/skills/fito-case-author/publish-state.ts +87 -0
- package/skills/fito-case-author/publish-version.js +364 -0
- package/skills/fito-case-author/publish-version.ts +495 -0
- package/skills/fito-case-author/publish.js +284 -0
- package/skills/fito-case-author/publish.ts +394 -0
- package/skills/fito-case-author/semver.js +55 -0
- package/skills/fito-case-author/semver.ts +63 -0
- package/skills/fito-case-author/status-gate.js +34 -0
- package/skills/fito-case-author/status-gate.ts +54 -0
- package/skills/fito-case-author/validate.js +62 -0
- package/skills/fito-case-author/validate.ts +64 -0
- package/skills/fito-case-runner/SKILL.md +119 -0
- package/skills/fito-case-runner/case-component-names.js +45 -0
- package/skills/fito-case-runner/case-component-names.ts +65 -0
- package/skills/fito-case-runner/case-detail.js +20 -0
- package/skills/fito-case-runner/case-detail.ts +20 -0
- package/skills/fito-case-runner/github.js +234 -0
- package/skills/fito-case-runner/github.ts +287 -0
- package/skills/fito-case-runner/manifest.js +56 -0
- package/skills/fito-case-runner/manifest.ts +73 -0
- package/skills/fito-case-runner/open.js +175 -0
- package/skills/fito-case-runner/open.ts +241 -0
- package/skills/fito-case-runner/report.js +22 -0
- package/skills/fito-case-runner/report.ts +24 -0
- package/skills/fito-case-runner/runner.js +158 -0
- package/skills/fito-case-runner/runner.ts +304 -0
- package/skills/fito-case-runner/score-quiz-mc.js +85 -0
- package/skills/fito-case-runner/score-quiz-mc.ts +99 -0
- package/skills/fito-case-runner/submit-evaluation.js +73 -0
- package/skills/fito-case-runner/submit-evaluation.ts +98 -0
- package/skills/fito-case-runner/submit-quiz-result.js +75 -0
- package/skills/fito-case-runner/submit-quiz-result.ts +100 -0
- package/skills/fito-case-runner/submit.js +85 -0
- package/skills/fito-case-runner/submit.ts +111 -0
- package/skills/fito-case-runner/workdir.js +10 -0
- package/skills/fito-case-runner/workdir.ts +11 -0
- package/skills/fito-competence-write/SKILL.md +155 -0
- package/skills/fito-competence-write/create.js +64 -0
- package/skills/fito-competence-write/create.ts +80 -0
- package/skills/fito-competence-write/delete.js +136 -0
- package/skills/fito-competence-write/delete.ts +166 -0
- package/skills/fito-competence-write/display.js +20 -0
- package/skills/fito-competence-write/display.ts +21 -0
- package/skills/fito-competence-write/payload.js +96 -0
- package/skills/fito-competence-write/payload.ts +115 -0
- package/skills/fito-competence-write/update.js +155 -0
- package/skills/fito-competence-write/update.ts +206 -0
- package/skills/fito-evaluator/SKILL.md +73 -0
- package/skills/fito-evaluator/criterion-exec.js +64 -0
- package/skills/fito-evaluator/criterion-exec.ts +73 -0
- package/skills/fito-evaluator/evaluate-automated.js +57 -0
- package/skills/fito-evaluator/evaluate-automated.ts +84 -0
- package/skills/fito-evaluator/evaluate.js +28 -0
- package/skills/fito-evaluator/evaluate.ts +86 -0
- package/skills/fito-evaluator/report.js +112 -0
- package/skills/fito-evaluator/report.ts +128 -0
- package/skills/fito-evaluator/rubric.js +90 -0
- package/skills/fito-evaluator/rubric.ts +170 -0
- package/skills/fito-knowledge-push/SKILL.md +114 -0
- package/skills/fito-knowledge-push/push.js +282 -0
- package/skills/fito-knowledge-push/push.ts +360 -0
- package/skills/fito-source-ingestion/SKILL.md +77 -0
- package/skills/fito-source-ingestion/authoring-check.js +128 -0
- package/skills/fito-source-ingestion/authoring-check.ts +155 -0
- package/skills/fito-source-ingestion/bundle.js +198 -0
- package/skills/fito-source-ingestion/bundle.ts +246 -0
- package/skills/fito-technology-write/SKILL.md +108 -0
- package/skills/fito-technology-write/create.js +134 -0
- package/skills/fito-technology-write/create.ts +161 -0
- package/skills/fito-technology-write/payload.js +64 -0
- package/skills/fito-technology-write/payload.ts +70 -0
- package/skills/fito-technology-write/update.js +122 -0
- package/skills/fito-technology-write/update.ts +171 -0
- package/skills/fito-url-content-fetcher/SKILL.md +213 -0
- package/templates/concept-practice-content-template.md +281 -0
- package/templates/concept-tool-content-template.md +207 -0
- package/templates/execution-fact-practice-content-template.md +372 -0
- package/templates/execution-fact-tool-content-template.md +307 -0
- package/templates/usage-scenario-content-template.md +248 -0
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `node publish.js <case-dir> --repo <owner>/<name> --overview <file> [--case-id <uuid>]
|
|
3
|
+
* [--accept-gh-mismatch]` — the `fito-case-author` publish entrypoint (Task 9.3): take a finished
|
|
4
|
+
* case working directory and make it a published Fito case. Driven by the `/fito-publish-case`
|
|
5
|
+
* orchestrator; `runPublish` is the testable core (injectable executor + client), `main` the thin
|
|
6
|
+
* CLI wrapper.
|
|
7
|
+
*
|
|
8
|
+
* The sequence: structural validation (in-process, over the tree as it stands — the attestation the
|
|
9
|
+
* backend receives is by construction from the *last* run over the finished tree, never a saved
|
|
10
|
+
* file) → local guards (clean tree, solution branch) → gh login + Fito session → identity check →
|
|
11
|
+
* published-guard → reconcile the solution branch's `.case/` with the canonical branch's (Task
|
|
12
|
+
* 9a.7 parity) → create the GitHub repo if absent → push `main` + the frozen `vX.Y.Z` branch/tag
|
|
13
|
+
* + the `case/solution-vX.Y.Z` branch → `POST /cases` (draft) → `POST /cases/{id}/publish`.
|
|
14
|
+
*
|
|
15
|
+
* Failure leaves the local checkout intact for fix-and-retry: backend rejections surface their
|
|
16
|
+
* problem detail **verbatim**, the minted draft id is remembered in `~/.fito/publish-state.json`
|
|
17
|
+
* (registration is not idempotent), and a re-run never creates a duplicate GitHub repo (the
|
|
18
|
+
* `gh repo view` probe) nor a duplicate case (the published-guard).
|
|
19
|
+
*/
|
|
20
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
21
|
+
import * as os from "node:os";
|
|
22
|
+
import * as path from "node:path";
|
|
23
|
+
import { fileURLToPath } from "node:url";
|
|
24
|
+
import { loadCaseDir } from "../../shared/case-validation/case-loader.js";
|
|
25
|
+
import { validateCaseContent } from "../../shared/case-validation/case-schema.js";
|
|
26
|
+
import { DEFAULT_BASE_URL, FitoApiError, createFitoApiClient } from "../../shared/fito-api/client.js";
|
|
27
|
+
import { resolveFitoSession } from "../../shared/fito-session/session.js";
|
|
28
|
+
import { caseRepoHttpsUrl, ghAuthStatusCommand, ghCurrentLoginCommand, ghRepoCreateCommand, ghRepoViewCommand, gitCaseParityDiffCommand, gitCheckoutCommand, gitCommitCaseParityCommand, gitCurrentBranchCommand, gitListLocalBranchCommand, gitPushCaseRefsCommand, gitRestoreCaseDirCommand, gitStatusPorcelainCommand, parseRepoArg, withoutAuthoringHarnessPaths, } from "./github-publish.js";
|
|
29
|
+
import { buildCaseWritePayloads, readCasePublishFacts } from "./publish-payload.js";
|
|
30
|
+
import { clearPublishState, readPublishState, writePublishState } from "./publish-state.js";
|
|
31
|
+
/** A backend rejection of the register/publish call: the problem detail verbatim, plus the retry id. */
|
|
32
|
+
export class PublishRejectedError extends Error {
|
|
33
|
+
status;
|
|
34
|
+
/** The draft id to retry with — remembered in the publish state unless it was the author's own `--case-id`. */
|
|
35
|
+
caseId;
|
|
36
|
+
constructor(message, status, caseId) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.name = "PublishRejectedError";
|
|
39
|
+
this.status = status;
|
|
40
|
+
this.caseId = caseId;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** Publish a finished case working directory: validate → guard → push → register → publish. */
|
|
44
|
+
export async function runPublish(options) {
|
|
45
|
+
const caseDir = path.resolve(options.caseDir);
|
|
46
|
+
const home = options.home ?? os.homedir();
|
|
47
|
+
const env = options.env ?? process.env;
|
|
48
|
+
const apiBaseUrl = options.apiBaseUrl ?? DEFAULT_BASE_URL;
|
|
49
|
+
const client = options.client ?? createFitoApiClient({ baseUrl: apiBaseUrl });
|
|
50
|
+
const exec = options.exec ?? (await import("../../shared/shell-exec/exec.js")).shellExec;
|
|
51
|
+
const run = (command) => exec(command, { cwd: caseDir });
|
|
52
|
+
if (!existsSync(path.join(caseDir, ".case"))) {
|
|
53
|
+
throw new Error(`Not a case working directory (no .case/):\n ${caseDir}\nGenerate the case first: /fito-case-generate`);
|
|
54
|
+
}
|
|
55
|
+
const overview = readOverview(options.overviewFile);
|
|
56
|
+
// Fresh structural validation over the tree as it stands — the attestation forwarded to the
|
|
57
|
+
// backend is from THIS run (ADR-005: never a saved file).
|
|
58
|
+
const { content, attestation } = validateOrThrow(caseDir);
|
|
59
|
+
const facts = readCasePublishFacts(content);
|
|
60
|
+
// Local guards, before any network write.
|
|
61
|
+
await run(ghAuthStatusCommand());
|
|
62
|
+
// An untracked legacy `.pi-subagents/` run-store (F23 — where pi-subagents v0.35.1 wrote it),
|
|
63
|
+
// `output/` (the knowledge pipeline's stage workspace, F30) or `.pi/` (the pi project dir, F31) is
|
|
64
|
+
// filtered out — authoring-harness noise a designed workflow writes into the case dir, never a
|
|
65
|
+
// case artifact, never pushed; every other change still gates. The shipped 0.50.0 writes the
|
|
66
|
+
// run-store to `.pi/subagents` instead, which the `.pi/` member already covers, so the legacy
|
|
67
|
+
// entry stays for authors on an older copy — see `AUTHORING_HARNESS_PATHS`.
|
|
68
|
+
const dirty = withoutAuthoringHarnessPaths(await run(gitStatusPorcelainCommand()));
|
|
69
|
+
if (dirty.length > 0) {
|
|
70
|
+
throw new Error(`The working tree has uncommitted changes — commit (or stash) them first; what is validated must be exactly what is pushed:\n${dirty}`);
|
|
71
|
+
}
|
|
72
|
+
if ((await run(gitListLocalBranchCommand(facts.solutionBranch))).trim().length === 0) {
|
|
73
|
+
throw new Error(`The local solution branch \`${facts.solutionBranch}\` (named by .case/solution.yaml) does not exist.\n` +
|
|
74
|
+
"The publish pushes it as the case's exemplar. Build it per the source plan (/fito-case-plan-source, " +
|
|
75
|
+
"executed outside Fito), then re-run.");
|
|
76
|
+
}
|
|
77
|
+
const ghLogin = (await run(ghCurrentLoginCommand())).trim();
|
|
78
|
+
const session = await resolveFitoSession(client, home);
|
|
79
|
+
// Decision 4 (2026-07-08): a gh↔Fito identity mismatch warns and stops for the author's explicit
|
|
80
|
+
// confirmation — never refuses outright (publishing under an org is supported).
|
|
81
|
+
const linkedLogin = session.user.githubLogin ?? null;
|
|
82
|
+
const mismatched = linkedLogin === null || linkedLogin.toLowerCase() !== ghLogin.toLowerCase();
|
|
83
|
+
if (mismatched && !options.acceptGhMismatch) {
|
|
84
|
+
const linkedLabel = linkedLogin === null ? "no linked GitHub identity" : `linked GitHub identity \`${linkedLogin}\``;
|
|
85
|
+
throw new Error(`Your local gh account (\`${ghLogin}\`) is not your Fito account's ${linkedLabel}.\n` +
|
|
86
|
+
`The repo will be created and pushed under \`${ghLogin}\` (or the org you chose) — the Fito case ` +
|
|
87
|
+
"owner is your Fito login either way.\nIf that is intended, re-run with --accept-gh-mismatch.");
|
|
88
|
+
}
|
|
89
|
+
const repoArg = parseRepoArg(options.repo);
|
|
90
|
+
const owner = repoArg.owner ?? env.FITO_PUBLISH_GITHUB_OWNER ?? ghLogin;
|
|
91
|
+
const slug = `${owner}/${repoArg.name}`;
|
|
92
|
+
const repositoryUrl = caseRepoHttpsUrl(owner, repoArg.name);
|
|
93
|
+
// Build both payloads before any GitHub write, so a payload problem fails with nothing created.
|
|
94
|
+
const payloads = buildCaseWritePayloads({
|
|
95
|
+
content,
|
|
96
|
+
repositoryUrl,
|
|
97
|
+
descriptionOverview: overview,
|
|
98
|
+
attestation,
|
|
99
|
+
});
|
|
100
|
+
// Published-guard: an already-published case at this URL is an update, not an initial publish —
|
|
101
|
+
// that is the version-publish flow (publish-version.ts, Task 9.8). Also keeps the forced
|
|
102
|
+
// version-ref push (and a duplicate registration) away from published, immutable refs.
|
|
103
|
+
const publishedAtUrl = await client.listCases({ repositoryUrl });
|
|
104
|
+
if (publishedAtUrl.total >= 1) {
|
|
105
|
+
throw new Error(`${repositoryUrl} is already a published Fito case.\n` +
|
|
106
|
+
"Updating it is the version-publish flow: check it out with /fito-case-edit, then run\n" +
|
|
107
|
+
"/fito-publish-case from that authoring checkout — it routes to the update path automatically.");
|
|
108
|
+
}
|
|
109
|
+
// F9 parity: the solution branch's .case/ must equal the canonical branch's before both refs
|
|
110
|
+
// are pushed. Local mutation, so it runs after every guard and before any GitHub write.
|
|
111
|
+
const caseReconciled = await reconcileSolutionBranchCase(run, facts.solutionBranch);
|
|
112
|
+
// Create the repo only when absent — a fix-and-retry re-run must never create a duplicate.
|
|
113
|
+
let repoCreated = false;
|
|
114
|
+
try {
|
|
115
|
+
await run(ghRepoViewCommand(slug));
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
await run(ghRepoCreateCommand(slug, facts.title));
|
|
119
|
+
repoCreated = true;
|
|
120
|
+
}
|
|
121
|
+
await run(gitPushCaseRefsCommand(repositoryUrl, facts.versionRef, facts.solutionBranch));
|
|
122
|
+
// Register (or reuse the draft id): POST /cases is not idempotent, so the minted id is
|
|
123
|
+
// remembered in ~/.fito/publish-state.json until the publish succeeds.
|
|
124
|
+
const rememberedId = options.caseId ?? readPublishState(repositoryUrl, apiBaseUrl, home);
|
|
125
|
+
let caseId = rememberedId;
|
|
126
|
+
if (caseId === null || caseId === undefined) {
|
|
127
|
+
caseId = await register(client, session.tokens.accessToken, payloads.register, repositoryUrl, apiBaseUrl, home);
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
await publishOnce(client, session.tokens.accessToken, caseId, payloads.publish);
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
// A remembered id that 404s is stale state (a different/reset backend) — fall back to a fresh
|
|
134
|
+
// registration. An explicit --case-id is the author's claim: never silently replaced.
|
|
135
|
+
const staleRemembered = error instanceof PublishRejectedError && error.status === 404 && options.caseId === undefined && rememberedId !== null;
|
|
136
|
+
if (!staleRemembered)
|
|
137
|
+
throw error;
|
|
138
|
+
clearPublishState(repositoryUrl, home);
|
|
139
|
+
caseId = await register(client, session.tokens.accessToken, payloads.register, repositoryUrl, apiBaseUrl, home);
|
|
140
|
+
await publishOnce(client, session.tokens.accessToken, caseId, payloads.publish);
|
|
141
|
+
}
|
|
142
|
+
clearPublishState(repositoryUrl, home);
|
|
143
|
+
const webOrigin = env.FITO_WEB_ORIGIN ?? "http://localhost:5173";
|
|
144
|
+
return {
|
|
145
|
+
caseId,
|
|
146
|
+
status: "PUBLISHED",
|
|
147
|
+
repositoryUrl,
|
|
148
|
+
versionRef: facts.versionRef,
|
|
149
|
+
repoCreated,
|
|
150
|
+
caseReconciled,
|
|
151
|
+
ghLogin,
|
|
152
|
+
title: facts.title,
|
|
153
|
+
webUrl: `${webOrigin}/cases/${caseId}`,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Enforce the `.case/` parity invariant (Task 9a.7, F9): `.case/` describes the case, not the
|
|
158
|
+
* branch — but plan-source finalizes `artifacts.yaml` on the canonical branch after the solution
|
|
159
|
+
* branch was cut, so the two diverge. Before the push, treat the current branch's `.case/` as
|
|
160
|
+
* canonical and reconcile the solution branch to it: checkout → replace `.case/` wholesale
|
|
161
|
+
* (pathspec-limited; `src/` untouched) → commit → return. Idempotent — identical trees produce
|
|
162
|
+
* no commit. Runs behind the clean-tree guard, so the checkouts move between clean trees.
|
|
163
|
+
* Returns whether a reconcile commit was made.
|
|
164
|
+
*/
|
|
165
|
+
export async function reconcileSolutionBranchCase(run, solutionBranch) {
|
|
166
|
+
const divergent = (await run(gitCaseParityDiffCommand(solutionBranch))).trim().length > 0;
|
|
167
|
+
if (!divergent)
|
|
168
|
+
return false;
|
|
169
|
+
const currentBranch = (await run(gitCurrentBranchCommand())).trim();
|
|
170
|
+
// A detached HEAD has no branch name to restore from or return to — the return checkout would
|
|
171
|
+
// silently strand the flow on the solution branch (and push it as main).
|
|
172
|
+
if (currentBranch === "HEAD") {
|
|
173
|
+
throw new Error(`The solution branch's .case/ diverged from this checkout's, but HEAD is detached — ` +
|
|
174
|
+
"there is no branch to reconcile from.\nCheck out the branch that carries the canonical .case/ " +
|
|
175
|
+
"(the one this publish pushes as main), then re-run.");
|
|
176
|
+
}
|
|
177
|
+
await run(gitCheckoutCommand(solutionBranch));
|
|
178
|
+
await run(gitRestoreCaseDirCommand(currentBranch));
|
|
179
|
+
await run(gitCommitCaseParityCommand());
|
|
180
|
+
await run(gitCheckoutCommand(currentBranch));
|
|
181
|
+
return true;
|
|
182
|
+
}
|
|
183
|
+
/** Read the overview file, failing with the flow that produces it. */
|
|
184
|
+
function readOverview(file) {
|
|
185
|
+
try {
|
|
186
|
+
return readFileSync(file, "utf8");
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
throw new Error(`Cannot read the description-overview file:\n ${file}\n` +
|
|
190
|
+
"It is the case's storefront description — /fito-publish-case drafts it with you into .authoring/description-overview.md.");
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
/** Load + validate the `.case/` tree; on any structural error, throw them all, scoped per file. */
|
|
194
|
+
export function validateOrThrow(caseDir) {
|
|
195
|
+
const loaded = loadCaseDir(caseDir);
|
|
196
|
+
const result = validateCaseContent({ content: loaded.content, presentFiles: loaded.presentFiles });
|
|
197
|
+
const errors = [...loaded.parseErrors, ...(result.ok ? [] : result.errors)];
|
|
198
|
+
if (!result.ok || errors.length > 0) {
|
|
199
|
+
const lines = errors.map((e) => ` .case/${e.file}${e.path?.length ? ` (${e.path.join(".")})` : ""}: ${e.message}`);
|
|
200
|
+
throw new Error(`The .case/ tree fails structural validation — fix the named files and re-run:\n${lines.join("\n")}`);
|
|
201
|
+
}
|
|
202
|
+
return { content: loaded.content, attestation: result.attestation };
|
|
203
|
+
}
|
|
204
|
+
/** `POST /cases`, remembering the minted draft id for retries before returning it. */
|
|
205
|
+
async function register(client, accessToken, input, repositoryUrl, apiBaseUrl, home) {
|
|
206
|
+
const draft = await wrapRejection("", () => client.registerCase(accessToken, input));
|
|
207
|
+
writePublishState(repositoryUrl, { caseId: draft.id, apiBaseUrl }, home);
|
|
208
|
+
return draft.id;
|
|
209
|
+
}
|
|
210
|
+
/** `POST /cases/{id}/publish`, mapping a FitoApiError to a PublishRejectedError carrying the id. */
|
|
211
|
+
async function publishOnce(client, accessToken, caseId, input) {
|
|
212
|
+
await wrapRejection(caseId, () => client.publishCase(accessToken, caseId, input));
|
|
213
|
+
}
|
|
214
|
+
/** Run a backend write, rethrowing a FitoApiError as a PublishRejectedError (problem detail verbatim). */
|
|
215
|
+
async function wrapRejection(caseId, call) {
|
|
216
|
+
try {
|
|
217
|
+
return await call();
|
|
218
|
+
}
|
|
219
|
+
catch (error) {
|
|
220
|
+
if (error instanceof FitoApiError) {
|
|
221
|
+
throw new PublishRejectedError(error.message, error.status, caseId);
|
|
222
|
+
}
|
|
223
|
+
throw error;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
async function main() {
|
|
227
|
+
const args = process.argv.slice(2);
|
|
228
|
+
const positionals = [];
|
|
229
|
+
let repo;
|
|
230
|
+
let overviewFile;
|
|
231
|
+
let caseId;
|
|
232
|
+
let acceptGhMismatch = false;
|
|
233
|
+
for (let i = 0; i < args.length; i++) {
|
|
234
|
+
const arg = args[i];
|
|
235
|
+
if (arg === "--repo")
|
|
236
|
+
repo = args[++i];
|
|
237
|
+
else if (arg === "--overview")
|
|
238
|
+
overviewFile = args[++i];
|
|
239
|
+
else if (arg === "--case-id")
|
|
240
|
+
caseId = args[++i];
|
|
241
|
+
else if (arg === "--accept-gh-mismatch")
|
|
242
|
+
acceptGhMismatch = true;
|
|
243
|
+
else
|
|
244
|
+
positionals.push(arg);
|
|
245
|
+
}
|
|
246
|
+
const caseDir = positionals[0];
|
|
247
|
+
if (!caseDir || !repo || !overviewFile) {
|
|
248
|
+
console.error("Usage: node publish.js <case-dir> --repo <owner>/<name> --overview <file> [--case-id <uuid>] [--accept-gh-mismatch]");
|
|
249
|
+
process.exitCode = 2;
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
try {
|
|
253
|
+
const result = await runPublish({ caseDir, repo, overviewFile, caseId, acceptGhMismatch });
|
|
254
|
+
console.log(`✓ Repo ${result.repoCreated ? "created" : "reused"}: ${result.repositoryUrl} (gh: @${result.ghLogin})`);
|
|
255
|
+
if (result.caseReconciled) {
|
|
256
|
+
console.log("✓ Reconciled the solution branch's .case/ with main (it had diverged) before the push.");
|
|
257
|
+
}
|
|
258
|
+
console.log(`✓ Pushed main, ${result.versionRef} (branch + tag), and the solution branch.`);
|
|
259
|
+
console.log(`✓ Published "${result.title}" — backend case id: ${result.caseId} (${result.status}).`);
|
|
260
|
+
console.log(`✓ Listed at: ${result.webUrl}`);
|
|
261
|
+
}
|
|
262
|
+
catch (error) {
|
|
263
|
+
if (error instanceof PublishRejectedError) {
|
|
264
|
+
console.error(`✗ The backend rejected the publish (HTTP ${error.status}):\n ${error.message}`);
|
|
265
|
+
if (error.caseId) {
|
|
266
|
+
console.error(`\nThe draft (case id: ${error.caseId}) is registered and remembered — fix the cause locally, then re-run;\n` +
|
|
267
|
+
"the same draft is reused (or pass --case-id explicitly). The local checkout is untouched.");
|
|
268
|
+
}
|
|
269
|
+
process.exitCode = 1;
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
|
|
273
|
+
process.exitCode = 1;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
/** Only auto-invoke the CLI when run directly (`node publish.js …`), not when imported (e.g. by tests). */
|
|
277
|
+
const entry = process.argv[1];
|
|
278
|
+
const isMainModule = !!entry && path.resolve(entry) === fileURLToPath(import.meta.url);
|
|
279
|
+
if (isMainModule) {
|
|
280
|
+
main().catch((error) => {
|
|
281
|
+
console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
|
|
282
|
+
process.exitCode = 1;
|
|
283
|
+
});
|
|
284
|
+
}
|
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `node publish.js <case-dir> --repo <owner>/<name> --overview <file> [--case-id <uuid>]
|
|
3
|
+
* [--accept-gh-mismatch]` — the `fito-case-author` publish entrypoint (Task 9.3): take a finished
|
|
4
|
+
* case working directory and make it a published Fito case. Driven by the `/fito-publish-case`
|
|
5
|
+
* orchestrator; `runPublish` is the testable core (injectable executor + client), `main` the thin
|
|
6
|
+
* CLI wrapper.
|
|
7
|
+
*
|
|
8
|
+
* The sequence: structural validation (in-process, over the tree as it stands — the attestation the
|
|
9
|
+
* backend receives is by construction from the *last* run over the finished tree, never a saved
|
|
10
|
+
* file) → local guards (clean tree, solution branch) → gh login + Fito session → identity check →
|
|
11
|
+
* published-guard → reconcile the solution branch's `.case/` with the canonical branch's (Task
|
|
12
|
+
* 9a.7 parity) → create the GitHub repo if absent → push `main` + the frozen `vX.Y.Z` branch/tag
|
|
13
|
+
* + the `case/solution-vX.Y.Z` branch → `POST /cases` (draft) → `POST /cases/{id}/publish`.
|
|
14
|
+
*
|
|
15
|
+
* Failure leaves the local checkout intact for fix-and-retry: backend rejections surface their
|
|
16
|
+
* problem detail **verbatim**, the minted draft id is remembered in `~/.fito/publish-state.json`
|
|
17
|
+
* (registration is not idempotent), and a re-run never creates a duplicate GitHub repo (the
|
|
18
|
+
* `gh repo view` probe) nor a duplicate case (the published-guard).
|
|
19
|
+
*/
|
|
20
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
21
|
+
import * as os from "node:os";
|
|
22
|
+
import * as path from "node:path";
|
|
23
|
+
import { fileURLToPath } from "node:url";
|
|
24
|
+
|
|
25
|
+
import { loadCaseDir } from "../../shared/case-validation/case-loader.ts";
|
|
26
|
+
import { validateCaseContent } from "../../shared/case-validation/case-schema.ts";
|
|
27
|
+
import type { Attestation, CaseContent, ValidationError } from "../../shared/case-validation/case-schema.ts";
|
|
28
|
+
import { DEFAULT_BASE_URL, FitoApiError, createFitoApiClient } from "../../shared/fito-api/client.ts";
|
|
29
|
+
import type { FitoApiClient } from "../../shared/fito-api/client.ts";
|
|
30
|
+
import { resolveFitoSession } from "../../shared/fito-session/session.ts";
|
|
31
|
+
import type { Executor } from "../../shared/shell-exec/exec.ts";
|
|
32
|
+
import {
|
|
33
|
+
caseRepoHttpsUrl,
|
|
34
|
+
ghAuthStatusCommand,
|
|
35
|
+
ghCurrentLoginCommand,
|
|
36
|
+
ghRepoCreateCommand,
|
|
37
|
+
ghRepoViewCommand,
|
|
38
|
+
gitCaseParityDiffCommand,
|
|
39
|
+
gitCheckoutCommand,
|
|
40
|
+
gitCommitCaseParityCommand,
|
|
41
|
+
gitCurrentBranchCommand,
|
|
42
|
+
gitListLocalBranchCommand,
|
|
43
|
+
gitPushCaseRefsCommand,
|
|
44
|
+
gitRestoreCaseDirCommand,
|
|
45
|
+
gitStatusPorcelainCommand,
|
|
46
|
+
parseRepoArg,
|
|
47
|
+
withoutAuthoringHarnessPaths,
|
|
48
|
+
} from "./github-publish.ts";
|
|
49
|
+
import type { ShellCommand } from "./github-publish.ts";
|
|
50
|
+
import { buildCaseWritePayloads, readCasePublishFacts } from "./publish-payload.ts";
|
|
51
|
+
import { clearPublishState, readPublishState, writePublishState } from "./publish-state.ts";
|
|
52
|
+
|
|
53
|
+
/** Spawns one `{command, args}` in `cwd` and resolves its stdout (the shared `shell-exec` contract). */
|
|
54
|
+
export type { Executor };
|
|
55
|
+
|
|
56
|
+
/** The fito-api surface the publish flow needs. */
|
|
57
|
+
export type PublishClient = Pick<FitoApiClient, "meWithRefresh" | "listCases" | "registerCase" | "publishCase">;
|
|
58
|
+
|
|
59
|
+
export interface RunPublishOptions {
|
|
60
|
+
/** The case working directory (contains `.case/`). */
|
|
61
|
+
caseDir: string;
|
|
62
|
+
/** `--repo`: `<owner>/<name>`, or a bare `<name>` whose owner the default chain fills. */
|
|
63
|
+
repo: string;
|
|
64
|
+
/** `--overview`: the author-approved storefront markdown file (S1 `descriptionOverview`). */
|
|
65
|
+
overviewFile: string;
|
|
66
|
+
/** `--case-id`: an already-registered draft to publish (skips registration). */
|
|
67
|
+
caseId?: string;
|
|
68
|
+
/** `--accept-gh-mismatch`: the author confirmed publishing despite the gh↔Fito identity mismatch. */
|
|
69
|
+
acceptGhMismatch?: boolean;
|
|
70
|
+
home?: string;
|
|
71
|
+
/** The backend origin — must match the client's; also stamps the retry state. */
|
|
72
|
+
apiBaseUrl?: string;
|
|
73
|
+
/** Environment (FITO_PUBLISH_GITHUB_OWNER, FITO_WEB_ORIGIN); defaults to `process.env`. */
|
|
74
|
+
env?: Record<string, string | undefined>;
|
|
75
|
+
client?: PublishClient;
|
|
76
|
+
exec?: Executor;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface RunPublishResult {
|
|
80
|
+
caseId: string;
|
|
81
|
+
status: string;
|
|
82
|
+
repositoryUrl: string;
|
|
83
|
+
versionRef: string;
|
|
84
|
+
/** Whether this run created the GitHub repo (false: it already existed and was reused). */
|
|
85
|
+
repoCreated: boolean;
|
|
86
|
+
/** Whether the solution branch's `.case/` had diverged and was reconciled before the push (Task 9a.7). */
|
|
87
|
+
caseReconciled: boolean;
|
|
88
|
+
ghLogin: string;
|
|
89
|
+
title: string;
|
|
90
|
+
/** The case's web address (`FITO_WEB_ORIGIN`-based) — where it is now listed and openable. */
|
|
91
|
+
webUrl: string;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** A backend rejection of the register/publish call: the problem detail verbatim, plus the retry id. */
|
|
95
|
+
export class PublishRejectedError extends Error {
|
|
96
|
+
readonly status: number;
|
|
97
|
+
/** The draft id to retry with — remembered in the publish state unless it was the author's own `--case-id`. */
|
|
98
|
+
readonly caseId: string;
|
|
99
|
+
|
|
100
|
+
constructor(message: string, status: number, caseId: string) {
|
|
101
|
+
super(message);
|
|
102
|
+
this.name = "PublishRejectedError";
|
|
103
|
+
this.status = status;
|
|
104
|
+
this.caseId = caseId;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Publish a finished case working directory: validate → guard → push → register → publish. */
|
|
109
|
+
export async function runPublish(options: RunPublishOptions): Promise<RunPublishResult> {
|
|
110
|
+
const caseDir = path.resolve(options.caseDir);
|
|
111
|
+
const home = options.home ?? os.homedir();
|
|
112
|
+
const env = options.env ?? process.env;
|
|
113
|
+
const apiBaseUrl = options.apiBaseUrl ?? DEFAULT_BASE_URL;
|
|
114
|
+
const client = options.client ?? createFitoApiClient({ baseUrl: apiBaseUrl });
|
|
115
|
+
const exec = options.exec ?? (await import("../../shared/shell-exec/exec.ts")).shellExec;
|
|
116
|
+
const run = (command: ShellCommand): Promise<string> => exec(command, { cwd: caseDir });
|
|
117
|
+
|
|
118
|
+
if (!existsSync(path.join(caseDir, ".case"))) {
|
|
119
|
+
throw new Error(
|
|
120
|
+
`Not a case working directory (no .case/):\n ${caseDir}\nGenerate the case first: /fito-case-generate`,
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
const overview = readOverview(options.overviewFile);
|
|
124
|
+
|
|
125
|
+
// Fresh structural validation over the tree as it stands — the attestation forwarded to the
|
|
126
|
+
// backend is from THIS run (ADR-005: never a saved file).
|
|
127
|
+
const { content, attestation } = validateOrThrow(caseDir);
|
|
128
|
+
const facts = readCasePublishFacts(content);
|
|
129
|
+
|
|
130
|
+
// Local guards, before any network write.
|
|
131
|
+
await run(ghAuthStatusCommand());
|
|
132
|
+
// An untracked legacy `.pi-subagents/` run-store (F23 — where pi-subagents v0.35.1 wrote it),
|
|
133
|
+
// `output/` (the knowledge pipeline's stage workspace, F30) or `.pi/` (the pi project dir, F31) is
|
|
134
|
+
// filtered out — authoring-harness noise a designed workflow writes into the case dir, never a
|
|
135
|
+
// case artifact, never pushed; every other change still gates. The shipped 0.50.0 writes the
|
|
136
|
+
// run-store to `.pi/subagents` instead, which the `.pi/` member already covers, so the legacy
|
|
137
|
+
// entry stays for authors on an older copy — see `AUTHORING_HARNESS_PATHS`.
|
|
138
|
+
const dirty = withoutAuthoringHarnessPaths(await run(gitStatusPorcelainCommand()));
|
|
139
|
+
if (dirty.length > 0) {
|
|
140
|
+
throw new Error(
|
|
141
|
+
`The working tree has uncommitted changes — commit (or stash) them first; what is validated must be exactly what is pushed:\n${dirty}`,
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
if ((await run(gitListLocalBranchCommand(facts.solutionBranch))).trim().length === 0) {
|
|
145
|
+
throw new Error(
|
|
146
|
+
`The local solution branch \`${facts.solutionBranch}\` (named by .case/solution.yaml) does not exist.\n` +
|
|
147
|
+
"The publish pushes it as the case's exemplar. Build it per the source plan (/fito-case-plan-source, " +
|
|
148
|
+
"executed outside Fito), then re-run.",
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const ghLogin = (await run(ghCurrentLoginCommand())).trim();
|
|
153
|
+
const session = await resolveFitoSession(client, home);
|
|
154
|
+
|
|
155
|
+
// Decision 4 (2026-07-08): a gh↔Fito identity mismatch warns and stops for the author's explicit
|
|
156
|
+
// confirmation — never refuses outright (publishing under an org is supported).
|
|
157
|
+
const linkedLogin = session.user.githubLogin ?? null;
|
|
158
|
+
const mismatched = linkedLogin === null || linkedLogin.toLowerCase() !== ghLogin.toLowerCase();
|
|
159
|
+
if (mismatched && !options.acceptGhMismatch) {
|
|
160
|
+
const linkedLabel = linkedLogin === null ? "no linked GitHub identity" : `linked GitHub identity \`${linkedLogin}\``;
|
|
161
|
+
throw new Error(
|
|
162
|
+
`Your local gh account (\`${ghLogin}\`) is not your Fito account's ${linkedLabel}.\n` +
|
|
163
|
+
`The repo will be created and pushed under \`${ghLogin}\` (or the org you chose) — the Fito case ` +
|
|
164
|
+
"owner is your Fito login either way.\nIf that is intended, re-run with --accept-gh-mismatch.",
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const repoArg = parseRepoArg(options.repo);
|
|
169
|
+
const owner = repoArg.owner ?? env.FITO_PUBLISH_GITHUB_OWNER ?? ghLogin;
|
|
170
|
+
const slug = `${owner}/${repoArg.name}`;
|
|
171
|
+
const repositoryUrl = caseRepoHttpsUrl(owner, repoArg.name);
|
|
172
|
+
|
|
173
|
+
// Build both payloads before any GitHub write, so a payload problem fails with nothing created.
|
|
174
|
+
const payloads = buildCaseWritePayloads({
|
|
175
|
+
content,
|
|
176
|
+
repositoryUrl,
|
|
177
|
+
descriptionOverview: overview,
|
|
178
|
+
attestation,
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
// Published-guard: an already-published case at this URL is an update, not an initial publish —
|
|
182
|
+
// that is the version-publish flow (publish-version.ts, Task 9.8). Also keeps the forced
|
|
183
|
+
// version-ref push (and a duplicate registration) away from published, immutable refs.
|
|
184
|
+
const publishedAtUrl = await client.listCases({ repositoryUrl });
|
|
185
|
+
if (publishedAtUrl.total >= 1) {
|
|
186
|
+
throw new Error(
|
|
187
|
+
`${repositoryUrl} is already a published Fito case.\n` +
|
|
188
|
+
"Updating it is the version-publish flow: check it out with /fito-case-edit, then run\n" +
|
|
189
|
+
"/fito-publish-case from that authoring checkout — it routes to the update path automatically.",
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// F9 parity: the solution branch's .case/ must equal the canonical branch's before both refs
|
|
194
|
+
// are pushed. Local mutation, so it runs after every guard and before any GitHub write.
|
|
195
|
+
const caseReconciled = await reconcileSolutionBranchCase(run, facts.solutionBranch);
|
|
196
|
+
|
|
197
|
+
// Create the repo only when absent — a fix-and-retry re-run must never create a duplicate.
|
|
198
|
+
let repoCreated = false;
|
|
199
|
+
try {
|
|
200
|
+
await run(ghRepoViewCommand(slug));
|
|
201
|
+
} catch {
|
|
202
|
+
await run(ghRepoCreateCommand(slug, facts.title));
|
|
203
|
+
repoCreated = true;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
await run(gitPushCaseRefsCommand(repositoryUrl, facts.versionRef, facts.solutionBranch));
|
|
207
|
+
|
|
208
|
+
// Register (or reuse the draft id): POST /cases is not idempotent, so the minted id is
|
|
209
|
+
// remembered in ~/.fito/publish-state.json until the publish succeeds.
|
|
210
|
+
const rememberedId = options.caseId ?? readPublishState(repositoryUrl, apiBaseUrl, home);
|
|
211
|
+
let caseId = rememberedId;
|
|
212
|
+
if (caseId === null || caseId === undefined) {
|
|
213
|
+
caseId = await register(client, session.tokens.accessToken, payloads.register, repositoryUrl, apiBaseUrl, home);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
try {
|
|
217
|
+
await publishOnce(client, session.tokens.accessToken, caseId, payloads.publish);
|
|
218
|
+
} catch (error) {
|
|
219
|
+
// A remembered id that 404s is stale state (a different/reset backend) — fall back to a fresh
|
|
220
|
+
// registration. An explicit --case-id is the author's claim: never silently replaced.
|
|
221
|
+
const staleRemembered =
|
|
222
|
+
error instanceof PublishRejectedError && error.status === 404 && options.caseId === undefined && rememberedId !== null;
|
|
223
|
+
if (!staleRemembered) throw error;
|
|
224
|
+
clearPublishState(repositoryUrl, home);
|
|
225
|
+
caseId = await register(client, session.tokens.accessToken, payloads.register, repositoryUrl, apiBaseUrl, home);
|
|
226
|
+
await publishOnce(client, session.tokens.accessToken, caseId, payloads.publish);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
clearPublishState(repositoryUrl, home);
|
|
230
|
+
const webOrigin = env.FITO_WEB_ORIGIN ?? "http://localhost:5173";
|
|
231
|
+
return {
|
|
232
|
+
caseId,
|
|
233
|
+
status: "PUBLISHED",
|
|
234
|
+
repositoryUrl,
|
|
235
|
+
versionRef: facts.versionRef,
|
|
236
|
+
repoCreated,
|
|
237
|
+
caseReconciled,
|
|
238
|
+
ghLogin,
|
|
239
|
+
title: facts.title,
|
|
240
|
+
webUrl: `${webOrigin}/cases/${caseId}`,
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Enforce the `.case/` parity invariant (Task 9a.7, F9): `.case/` describes the case, not the
|
|
246
|
+
* branch — but plan-source finalizes `artifacts.yaml` on the canonical branch after the solution
|
|
247
|
+
* branch was cut, so the two diverge. Before the push, treat the current branch's `.case/` as
|
|
248
|
+
* canonical and reconcile the solution branch to it: checkout → replace `.case/` wholesale
|
|
249
|
+
* (pathspec-limited; `src/` untouched) → commit → return. Idempotent — identical trees produce
|
|
250
|
+
* no commit. Runs behind the clean-tree guard, so the checkouts move between clean trees.
|
|
251
|
+
* Returns whether a reconcile commit was made.
|
|
252
|
+
*/
|
|
253
|
+
export async function reconcileSolutionBranchCase(
|
|
254
|
+
run: (command: ShellCommand) => Promise<string>,
|
|
255
|
+
solutionBranch: string,
|
|
256
|
+
): Promise<boolean> {
|
|
257
|
+
const divergent = (await run(gitCaseParityDiffCommand(solutionBranch))).trim().length > 0;
|
|
258
|
+
if (!divergent) return false;
|
|
259
|
+
const currentBranch = (await run(gitCurrentBranchCommand())).trim();
|
|
260
|
+
// A detached HEAD has no branch name to restore from or return to — the return checkout would
|
|
261
|
+
// silently strand the flow on the solution branch (and push it as main).
|
|
262
|
+
if (currentBranch === "HEAD") {
|
|
263
|
+
throw new Error(
|
|
264
|
+
`The solution branch's .case/ diverged from this checkout's, but HEAD is detached — ` +
|
|
265
|
+
"there is no branch to reconcile from.\nCheck out the branch that carries the canonical .case/ " +
|
|
266
|
+
"(the one this publish pushes as main), then re-run.",
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
await run(gitCheckoutCommand(solutionBranch));
|
|
270
|
+
await run(gitRestoreCaseDirCommand(currentBranch));
|
|
271
|
+
await run(gitCommitCaseParityCommand());
|
|
272
|
+
await run(gitCheckoutCommand(currentBranch));
|
|
273
|
+
return true;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Read the overview file, failing with the flow that produces it. */
|
|
277
|
+
function readOverview(file: string): string {
|
|
278
|
+
try {
|
|
279
|
+
return readFileSync(file, "utf8");
|
|
280
|
+
} catch {
|
|
281
|
+
throw new Error(
|
|
282
|
+
`Cannot read the description-overview file:\n ${file}\n` +
|
|
283
|
+
"It is the case's storefront description — /fito-publish-case drafts it with you into .authoring/description-overview.md.",
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Load + validate the `.case/` tree; on any structural error, throw them all, scoped per file. */
|
|
289
|
+
export function validateOrThrow(caseDir: string): { content: CaseContent; attestation: Attestation } {
|
|
290
|
+
const loaded = loadCaseDir(caseDir);
|
|
291
|
+
const result = validateCaseContent({ content: loaded.content, presentFiles: loaded.presentFiles });
|
|
292
|
+
const errors: ValidationError[] = [...loaded.parseErrors, ...(result.ok ? [] : result.errors)];
|
|
293
|
+
if (!result.ok || errors.length > 0) {
|
|
294
|
+
const lines = errors.map((e) => ` .case/${e.file}${e.path?.length ? ` (${e.path.join(".")})` : ""}: ${e.message}`);
|
|
295
|
+
throw new Error(`The .case/ tree fails structural validation — fix the named files and re-run:\n${lines.join("\n")}`);
|
|
296
|
+
}
|
|
297
|
+
return { content: loaded.content, attestation: result.attestation };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** `POST /cases`, remembering the minted draft id for retries before returning it. */
|
|
301
|
+
async function register(
|
|
302
|
+
client: PublishClient,
|
|
303
|
+
accessToken: string,
|
|
304
|
+
input: Parameters<PublishClient["registerCase"]>[1],
|
|
305
|
+
repositoryUrl: string,
|
|
306
|
+
apiBaseUrl: string,
|
|
307
|
+
home: string,
|
|
308
|
+
): Promise<string> {
|
|
309
|
+
const draft = await wrapRejection("", () => client.registerCase(accessToken, input));
|
|
310
|
+
writePublishState(repositoryUrl, { caseId: draft.id, apiBaseUrl }, home);
|
|
311
|
+
return draft.id;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** `POST /cases/{id}/publish`, mapping a FitoApiError to a PublishRejectedError carrying the id. */
|
|
315
|
+
async function publishOnce(
|
|
316
|
+
client: PublishClient,
|
|
317
|
+
accessToken: string,
|
|
318
|
+
caseId: string,
|
|
319
|
+
input: Parameters<PublishClient["publishCase"]>[2],
|
|
320
|
+
): Promise<void> {
|
|
321
|
+
await wrapRejection(caseId, () => client.publishCase(accessToken, caseId, input));
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** Run a backend write, rethrowing a FitoApiError as a PublishRejectedError (problem detail verbatim). */
|
|
325
|
+
async function wrapRejection<T>(caseId: string, call: () => Promise<T>): Promise<T> {
|
|
326
|
+
try {
|
|
327
|
+
return await call();
|
|
328
|
+
} catch (error) {
|
|
329
|
+
if (error instanceof FitoApiError) {
|
|
330
|
+
throw new PublishRejectedError(error.message, error.status, caseId);
|
|
331
|
+
}
|
|
332
|
+
throw error;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
async function main(): Promise<void> {
|
|
337
|
+
const args = process.argv.slice(2);
|
|
338
|
+
const positionals: string[] = [];
|
|
339
|
+
let repo: string | undefined;
|
|
340
|
+
let overviewFile: string | undefined;
|
|
341
|
+
let caseId: string | undefined;
|
|
342
|
+
let acceptGhMismatch = false;
|
|
343
|
+
for (let i = 0; i < args.length; i++) {
|
|
344
|
+
const arg = args[i];
|
|
345
|
+
if (arg === "--repo") repo = args[++i];
|
|
346
|
+
else if (arg === "--overview") overviewFile = args[++i];
|
|
347
|
+
else if (arg === "--case-id") caseId = args[++i];
|
|
348
|
+
else if (arg === "--accept-gh-mismatch") acceptGhMismatch = true;
|
|
349
|
+
else positionals.push(arg);
|
|
350
|
+
}
|
|
351
|
+
const caseDir = positionals[0];
|
|
352
|
+
if (!caseDir || !repo || !overviewFile) {
|
|
353
|
+
console.error(
|
|
354
|
+
"Usage: node publish.js <case-dir> --repo <owner>/<name> --overview <file> [--case-id <uuid>] [--accept-gh-mismatch]",
|
|
355
|
+
);
|
|
356
|
+
process.exitCode = 2;
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
try {
|
|
361
|
+
const result = await runPublish({ caseDir, repo, overviewFile, caseId, acceptGhMismatch });
|
|
362
|
+
console.log(`✓ Repo ${result.repoCreated ? "created" : "reused"}: ${result.repositoryUrl} (gh: @${result.ghLogin})`);
|
|
363
|
+
if (result.caseReconciled) {
|
|
364
|
+
console.log("✓ Reconciled the solution branch's .case/ with main (it had diverged) before the push.");
|
|
365
|
+
}
|
|
366
|
+
console.log(`✓ Pushed main, ${result.versionRef} (branch + tag), and the solution branch.`);
|
|
367
|
+
console.log(`✓ Published "${result.title}" — backend case id: ${result.caseId} (${result.status}).`);
|
|
368
|
+
console.log(`✓ Listed at: ${result.webUrl}`);
|
|
369
|
+
} catch (error) {
|
|
370
|
+
if (error instanceof PublishRejectedError) {
|
|
371
|
+
console.error(`✗ The backend rejected the publish (HTTP ${error.status}):\n ${error.message}`);
|
|
372
|
+
if (error.caseId) {
|
|
373
|
+
console.error(
|
|
374
|
+
`\nThe draft (case id: ${error.caseId}) is registered and remembered — fix the cause locally, then re-run;\n` +
|
|
375
|
+
"the same draft is reused (or pass --case-id explicitly). The local checkout is untouched.",
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
process.exitCode = 1;
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
|
|
382
|
+
process.exitCode = 1;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** Only auto-invoke the CLI when run directly (`node publish.js …`), not when imported (e.g. by tests). */
|
|
387
|
+
const entry = process.argv[1];
|
|
388
|
+
const isMainModule = !!entry && path.resolve(entry) === fileURLToPath(import.meta.url);
|
|
389
|
+
if (isMainModule) {
|
|
390
|
+
main().catch((error: unknown) => {
|
|
391
|
+
console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
|
|
392
|
+
process.exitCode = 1;
|
|
393
|
+
});
|
|
394
|
+
}
|