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,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `node open.js <case-id>` — the `fito-case-runner` open entrypoint (Task 5.2). Fetches the case
|
|
3
|
+
* pointer, guards the per-case working dir, then runs the runner's fork → clone → upstream fetch →
|
|
4
|
+
* checkout → structural re-validation → student-branch flow into `~/.fito/cases/<case-id>/`. GitHub writes go
|
|
5
|
+
* through the locally-installed `gh` CLI (`gh auth login` prerequisite).
|
|
6
|
+
*
|
|
7
|
+
* `runOpen` is the testable core (everything injectable); `main` is the thin CLI wrapper (argv +
|
|
8
|
+
* real deps + printing), invoked by the `/fito-case-open` orchestrator (Task 5.3).
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync, mkdirSync, readdirSync, rmSync } from "node:fs";
|
|
11
|
+
import * as os from "node:os";
|
|
12
|
+
import * as path from "node:path";
|
|
13
|
+
import { fileURLToPath } from "node:url";
|
|
14
|
+
import { validateCaseDir } from "../../shared/case-validation/case-loader.js";
|
|
15
|
+
import { createFitoApiClient } from "../../shared/fito-api/client.js";
|
|
16
|
+
import { resolveFitoSession } from "../../shared/fito-session/session.js";
|
|
17
|
+
import { shellExec } from "../../shared/shell-exec/exec.js";
|
|
18
|
+
import { fetchCaseDetail } from "./case-detail.js";
|
|
19
|
+
import { readSubmissionBranches } from "./manifest.js";
|
|
20
|
+
import { StudentBranchExistsError, openCase, } from "./runner.js";
|
|
21
|
+
import { caseWorkDir } from "./workdir.js";
|
|
22
|
+
/** Fetch case → guard the per-case dir → gate a deprecated case → open (fork → clone → upstream fetch → checkout → validate → branch) → enroll. */
|
|
23
|
+
export async function runOpen(options) {
|
|
24
|
+
const home = options.home ?? os.homedir();
|
|
25
|
+
const client = options.client ?? createFitoApiClient();
|
|
26
|
+
const detail = await fetchCaseDetail(client, options.caseId);
|
|
27
|
+
const targetDir = caseWorkDir(options.caseId, home);
|
|
28
|
+
// Deliberately ahead of the deprecation gate: a learner with a non-empty checkout is mid-flight
|
|
29
|
+
// by definition (enrollment is best-effort, so the backend may not know them) and must be pointed
|
|
30
|
+
// at their work — /fito-submit still accepts a deprecated case — never refused.
|
|
31
|
+
if (existsSync(targetDir) && readdirSync(targetDir).length > 0) {
|
|
32
|
+
throw new Error(`A working directory already exists and is not empty:\n ${targetDir}\n` +
|
|
33
|
+
`Move or remove it first — Fito will not overwrite your work.`);
|
|
34
|
+
}
|
|
35
|
+
let deprecationWarning;
|
|
36
|
+
if (detail.status === "DEPRECATED") {
|
|
37
|
+
deprecationWarning = await guardDeprecatedCase(client, options.caseId, home);
|
|
38
|
+
}
|
|
39
|
+
mkdirSync(path.dirname(targetDir), { recursive: true });
|
|
40
|
+
let result;
|
|
41
|
+
try {
|
|
42
|
+
result = await openCase({
|
|
43
|
+
pointer: {
|
|
44
|
+
repositoryUrl: detail.repositoryUrl,
|
|
45
|
+
versionRef: detail.versionRef,
|
|
46
|
+
gitPlatform: detail.gitPlatform,
|
|
47
|
+
},
|
|
48
|
+
targetDir,
|
|
49
|
+
exec: options.exec ?? shellExec,
|
|
50
|
+
validate: options.validate ?? validateCaseDir,
|
|
51
|
+
readBranches: options.readBranches ?? readSubmissionBranches,
|
|
52
|
+
mode: options.mode,
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
if (error instanceof StudentBranchExistsError) {
|
|
57
|
+
// Remove the clone this run just made (it holds nothing of the learner's) so the flagged
|
|
58
|
+
// re-run isn't blocked by the will-not-overwrite guard — each invocation stays stateless.
|
|
59
|
+
rmSync(targetDir, { recursive: true, force: true });
|
|
60
|
+
throw new Error(`Your fork already has a '${error.branch}' branch from a previous attempt on this case.\n` +
|
|
61
|
+
`Choose how to continue, then re-run with that choice:\n` +
|
|
62
|
+
` resume the previous attempt — keeps its commits and its open pull request:\n` +
|
|
63
|
+
` node open.js ${options.caseId} --resume\n` +
|
|
64
|
+
` start over from the published case — deletes '${error.branch}' on your fork, ` +
|
|
65
|
+
`closing its pull request; that attempt's unmerged work is lost:\n` +
|
|
66
|
+
` node open.js ${options.caseId} --start-over`);
|
|
67
|
+
}
|
|
68
|
+
throw error;
|
|
69
|
+
}
|
|
70
|
+
const enrollmentWarning = await recordEnrollment(client, options.caseId, home);
|
|
71
|
+
return {
|
|
72
|
+
...result,
|
|
73
|
+
...(deprecationWarning === undefined ? {} : { deprecationWarning }),
|
|
74
|
+
...(enrollmentWarning === undefined ? {} : { enrollmentWarning }),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The deprecated-case gate (Task 9.6, ADR-009 §5): a retired case takes no new learners, so the
|
|
79
|
+
* open proceeds only for a prior participant — the backend knows one by their enrollment or
|
|
80
|
+
* submission (`GET /cases/{id}/enrollments/me`). Participation is learner-scoped, so verifying it
|
|
81
|
+
* needs a logged-in session; no session, an unverifiable check, or a non-participant all refuse the
|
|
82
|
+
* open (fail-safe — the gate never guesses). A participant's open returns the warning the caller
|
|
83
|
+
* prints: the case is retired, but finishing it — including submit — keeps working.
|
|
84
|
+
*/
|
|
85
|
+
async function guardDeprecatedCase(client, caseId, home) {
|
|
86
|
+
let accessToken;
|
|
87
|
+
try {
|
|
88
|
+
accessToken = (await resolveFitoSession(client, home)).tokens.accessToken;
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
throw new Error(`This case has been deprecated — it is retired and no longer takes new learners.\n` +
|
|
92
|
+
`If you were already working on it, log in so Fito can confirm your participation:\n` +
|
|
93
|
+
` run /fito-login, then re-run /fito-case-open ${caseId}`);
|
|
94
|
+
}
|
|
95
|
+
let participant;
|
|
96
|
+
try {
|
|
97
|
+
participant = (await client.getCaseParticipation(accessToken, caseId)).participant;
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
101
|
+
throw new Error(`This case has been deprecated, and Fito could not confirm your participation ` +
|
|
102
|
+
`(${reason.trimEnd()})\n` +
|
|
103
|
+
` A deprecated case opens only for learners already working on it — try again shortly.`);
|
|
104
|
+
}
|
|
105
|
+
if (!participant) {
|
|
106
|
+
throw new Error(`This case has been deprecated — it is retired and no longer takes new learners.\n` +
|
|
107
|
+
`It may have been superseded; browse the case catalog for a current alternative.\n` +
|
|
108
|
+
`(Already working on it? Participation is per-account — log in with the Fito account ` +
|
|
109
|
+
`you opened or submitted it with.)`);
|
|
110
|
+
}
|
|
111
|
+
return (`This case has been deprecated — it is hidden from the catalog and may have been superseded.\n` +
|
|
112
|
+
` Your prior participation lets you finish it: your checkout, submissions, and assessments all keep working.`);
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Best-effort participation record (Task 9.5): after a successful open, tell the backend this
|
|
116
|
+
* learner opened this case (`POST /cases/{id}/enrollments` — idempotent per version, so re-opens
|
|
117
|
+
* are safe). The open must never break on it: any failure — no Fito login (open needs none), a
|
|
118
|
+
* backend hiccup — comes back as a warning string for the caller to print, never a thrown error.
|
|
119
|
+
* A missed enrollment is recovered later anyway: submitting also marks participation.
|
|
120
|
+
*/
|
|
121
|
+
async function recordEnrollment(client, caseId, home) {
|
|
122
|
+
try {
|
|
123
|
+
const session = await resolveFitoSession(client, home);
|
|
124
|
+
await client.createCaseEnrollment(session.tokens.accessToken, caseId);
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
129
|
+
return (`Fito couldn't record that you opened this case (${reason.trimEnd()})\n` +
|
|
130
|
+
` Your checkout is unaffected — carry on; submitting will record your participation anyway.`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
const USAGE = "usage: node open.js <case-id> [--resume | --start-over]";
|
|
134
|
+
/** Parse the open CLI args (`argv` minus the node/script prefix): the case id plus an optional reconciliation flag. */
|
|
135
|
+
export function parseOpenArgs(args) {
|
|
136
|
+
const [caseId, flag, ...rest] = args;
|
|
137
|
+
if (!caseId || caseId.startsWith("--") || rest.length > 0) {
|
|
138
|
+
throw new Error(USAGE);
|
|
139
|
+
}
|
|
140
|
+
if (flag === undefined)
|
|
141
|
+
return { caseId, mode: undefined };
|
|
142
|
+
if (flag === "--resume")
|
|
143
|
+
return { caseId, mode: "resume" };
|
|
144
|
+
if (flag === "--start-over")
|
|
145
|
+
return { caseId, mode: "start-over" };
|
|
146
|
+
throw new Error(`unknown flag '${flag}'\n${USAGE}`);
|
|
147
|
+
}
|
|
148
|
+
async function main() {
|
|
149
|
+
const { caseId, mode } = parseOpenArgs(process.argv.slice(2));
|
|
150
|
+
const result = await runOpen({ caseId, mode });
|
|
151
|
+
console.log(`✓ Forked as GitHub @${result.login} — confirm this is your Fito-linked account.`);
|
|
152
|
+
if (result.opened === "resumed") {
|
|
153
|
+
console.log(`✓ Resumed your previous attempt — '${result.branch}' tracks your fork's branch (its PR carries on).`);
|
|
154
|
+
}
|
|
155
|
+
else if (result.opened === "reset") {
|
|
156
|
+
console.log(`✓ Started over — your fork's previous '${result.branch}' was deleted (its PR closed).`);
|
|
157
|
+
}
|
|
158
|
+
console.log(`✓ Case opened at:\n ${result.workDir}\n on branch '${result.branch}'.`);
|
|
159
|
+
console.log(` Make your changes there, then submit: node submit.js ${caseId}`);
|
|
160
|
+
if (result.deprecationWarning) {
|
|
161
|
+
console.error(`⚠ ${result.deprecationWarning}`);
|
|
162
|
+
}
|
|
163
|
+
if (result.enrollmentWarning) {
|
|
164
|
+
console.error(`⚠ ${result.enrollmentWarning}`);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/** Only auto-invoke the CLI when run directly (`node open.js …`), not when imported (e.g. by tests). */
|
|
168
|
+
const entry = process.argv[1];
|
|
169
|
+
const isMainModule = !!entry && path.resolve(entry) === fileURLToPath(import.meta.url);
|
|
170
|
+
if (isMainModule) {
|
|
171
|
+
main().catch((error) => {
|
|
172
|
+
console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
|
|
173
|
+
process.exitCode = 1;
|
|
174
|
+
});
|
|
175
|
+
}
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `node open.js <case-id>` — the `fito-case-runner` open entrypoint (Task 5.2). Fetches the case
|
|
3
|
+
* pointer, guards the per-case working dir, then runs the runner's fork → clone → upstream fetch →
|
|
4
|
+
* checkout → structural re-validation → student-branch flow into `~/.fito/cases/<case-id>/`. GitHub writes go
|
|
5
|
+
* through the locally-installed `gh` CLI (`gh auth login` prerequisite).
|
|
6
|
+
*
|
|
7
|
+
* `runOpen` is the testable core (everything injectable); `main` is the thin CLI wrapper (argv +
|
|
8
|
+
* real deps + printing), invoked by the `/fito-case-open` orchestrator (Task 5.3).
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync, mkdirSync, readdirSync, rmSync } from "node:fs";
|
|
11
|
+
import * as os from "node:os";
|
|
12
|
+
import * as path from "node:path";
|
|
13
|
+
import { fileURLToPath } from "node:url";
|
|
14
|
+
|
|
15
|
+
import { validateCaseDir } from "../../shared/case-validation/case-loader.ts";
|
|
16
|
+
import { type FitoApiClient, createFitoApiClient } from "../../shared/fito-api/client.ts";
|
|
17
|
+
import { resolveFitoSession } from "../../shared/fito-session/session.ts";
|
|
18
|
+
import { shellExec } from "../../shared/shell-exec/exec.ts";
|
|
19
|
+
import { fetchCaseDetail } from "./case-detail.ts";
|
|
20
|
+
import { readSubmissionBranches } from "./manifest.ts";
|
|
21
|
+
import {
|
|
22
|
+
type BranchReader,
|
|
23
|
+
type CaseValidator,
|
|
24
|
+
type Executor,
|
|
25
|
+
type OpenCaseResult,
|
|
26
|
+
type OpenMode,
|
|
27
|
+
StudentBranchExistsError,
|
|
28
|
+
openCase,
|
|
29
|
+
} from "./runner.ts";
|
|
30
|
+
import { caseWorkDir } from "./workdir.ts";
|
|
31
|
+
|
|
32
|
+
export interface RunOpenOptions {
|
|
33
|
+
caseId: string;
|
|
34
|
+
home?: string;
|
|
35
|
+
/**
|
|
36
|
+
* Backend client (case fetch, the deprecated-case participant gate — Task 9.6, and the
|
|
37
|
+
* best-effort enrollment record — Task 9.5); defaults to the real one (reads `FITO_API_BASE_URL`).
|
|
38
|
+
*/
|
|
39
|
+
client?: Pick<FitoApiClient, "getCase" | "meWithRefresh" | "createCaseEnrollment" | "getCaseParticipation">;
|
|
40
|
+
exec?: Executor;
|
|
41
|
+
validate?: CaseValidator;
|
|
42
|
+
readBranches?: BranchReader;
|
|
43
|
+
/** Fork reconciliation choice (Task 7.6) — set only from the learner's explicit `--resume`/`--start-over`. */
|
|
44
|
+
mode?: OpenMode;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** An [OpenCaseResult] plus the open flow's own outcome fields. */
|
|
48
|
+
export interface RunOpenResult extends OpenCaseResult {
|
|
49
|
+
/**
|
|
50
|
+
* Set when the best-effort enrollment record failed (Task 9.5) — the open itself succeeded and
|
|
51
|
+
* the checkout is fully usable; the caller prints this as a warning, never an error.
|
|
52
|
+
*/
|
|
53
|
+
enrollmentWarning?: string;
|
|
54
|
+
/**
|
|
55
|
+
* Set when the case is deprecated and this learner's prior participation let the open proceed
|
|
56
|
+
* (Task 9.6) — the caller prints it as a warning so the learner knows the case is retired.
|
|
57
|
+
*/
|
|
58
|
+
deprecationWarning?: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Fetch case → guard the per-case dir → gate a deprecated case → open (fork → clone → upstream fetch → checkout → validate → branch) → enroll. */
|
|
62
|
+
export async function runOpen(options: RunOpenOptions): Promise<RunOpenResult> {
|
|
63
|
+
const home = options.home ?? os.homedir();
|
|
64
|
+
const client = options.client ?? createFitoApiClient();
|
|
65
|
+
|
|
66
|
+
const detail = await fetchCaseDetail(client, options.caseId);
|
|
67
|
+
const targetDir = caseWorkDir(options.caseId, home);
|
|
68
|
+
|
|
69
|
+
// Deliberately ahead of the deprecation gate: a learner with a non-empty checkout is mid-flight
|
|
70
|
+
// by definition (enrollment is best-effort, so the backend may not know them) and must be pointed
|
|
71
|
+
// at their work — /fito-submit still accepts a deprecated case — never refused.
|
|
72
|
+
if (existsSync(targetDir) && readdirSync(targetDir).length > 0) {
|
|
73
|
+
throw new Error(
|
|
74
|
+
`A working directory already exists and is not empty:\n ${targetDir}\n` +
|
|
75
|
+
`Move or remove it first — Fito will not overwrite your work.`,
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
let deprecationWarning: string | undefined;
|
|
80
|
+
if (detail.status === "DEPRECATED") {
|
|
81
|
+
deprecationWarning = await guardDeprecatedCase(client, options.caseId, home);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
mkdirSync(path.dirname(targetDir), { recursive: true });
|
|
85
|
+
|
|
86
|
+
let result: OpenCaseResult;
|
|
87
|
+
try {
|
|
88
|
+
result = await openCase({
|
|
89
|
+
pointer: {
|
|
90
|
+
repositoryUrl: detail.repositoryUrl,
|
|
91
|
+
versionRef: detail.versionRef,
|
|
92
|
+
gitPlatform: detail.gitPlatform,
|
|
93
|
+
},
|
|
94
|
+
targetDir,
|
|
95
|
+
exec: options.exec ?? shellExec,
|
|
96
|
+
validate: options.validate ?? validateCaseDir,
|
|
97
|
+
readBranches: options.readBranches ?? readSubmissionBranches,
|
|
98
|
+
mode: options.mode,
|
|
99
|
+
});
|
|
100
|
+
} catch (error) {
|
|
101
|
+
if (error instanceof StudentBranchExistsError) {
|
|
102
|
+
// Remove the clone this run just made (it holds nothing of the learner's) so the flagged
|
|
103
|
+
// re-run isn't blocked by the will-not-overwrite guard — each invocation stays stateless.
|
|
104
|
+
rmSync(targetDir, { recursive: true, force: true });
|
|
105
|
+
throw new Error(
|
|
106
|
+
`Your fork already has a '${error.branch}' branch from a previous attempt on this case.\n` +
|
|
107
|
+
`Choose how to continue, then re-run with that choice:\n` +
|
|
108
|
+
` resume the previous attempt — keeps its commits and its open pull request:\n` +
|
|
109
|
+
` node open.js ${options.caseId} --resume\n` +
|
|
110
|
+
` start over from the published case — deletes '${error.branch}' on your fork, ` +
|
|
111
|
+
`closing its pull request; that attempt's unmerged work is lost:\n` +
|
|
112
|
+
` node open.js ${options.caseId} --start-over`,
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
throw error;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const enrollmentWarning = await recordEnrollment(client, options.caseId, home);
|
|
119
|
+
return {
|
|
120
|
+
...result,
|
|
121
|
+
...(deprecationWarning === undefined ? {} : { deprecationWarning }),
|
|
122
|
+
...(enrollmentWarning === undefined ? {} : { enrollmentWarning }),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The deprecated-case gate (Task 9.6, ADR-009 §5): a retired case takes no new learners, so the
|
|
128
|
+
* open proceeds only for a prior participant — the backend knows one by their enrollment or
|
|
129
|
+
* submission (`GET /cases/{id}/enrollments/me`). Participation is learner-scoped, so verifying it
|
|
130
|
+
* needs a logged-in session; no session, an unverifiable check, or a non-participant all refuse the
|
|
131
|
+
* open (fail-safe — the gate never guesses). A participant's open returns the warning the caller
|
|
132
|
+
* prints: the case is retired, but finishing it — including submit — keeps working.
|
|
133
|
+
*/
|
|
134
|
+
async function guardDeprecatedCase(
|
|
135
|
+
client: Pick<FitoApiClient, "meWithRefresh" | "getCaseParticipation">,
|
|
136
|
+
caseId: string,
|
|
137
|
+
home: string,
|
|
138
|
+
): Promise<string> {
|
|
139
|
+
let accessToken: string;
|
|
140
|
+
try {
|
|
141
|
+
accessToken = (await resolveFitoSession(client, home)).tokens.accessToken;
|
|
142
|
+
} catch {
|
|
143
|
+
throw new Error(
|
|
144
|
+
`This case has been deprecated — it is retired and no longer takes new learners.\n` +
|
|
145
|
+
`If you were already working on it, log in so Fito can confirm your participation:\n` +
|
|
146
|
+
` run /fito-login, then re-run /fito-case-open ${caseId}`,
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
let participant: boolean;
|
|
151
|
+
try {
|
|
152
|
+
participant = (await client.getCaseParticipation(accessToken, caseId)).participant;
|
|
153
|
+
} catch (error) {
|
|
154
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
155
|
+
throw new Error(
|
|
156
|
+
`This case has been deprecated, and Fito could not confirm your participation ` +
|
|
157
|
+
`(${reason.trimEnd()})\n` +
|
|
158
|
+
` A deprecated case opens only for learners already working on it — try again shortly.`,
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
if (!participant) {
|
|
162
|
+
throw new Error(
|
|
163
|
+
`This case has been deprecated — it is retired and no longer takes new learners.\n` +
|
|
164
|
+
`It may have been superseded; browse the case catalog for a current alternative.\n` +
|
|
165
|
+
`(Already working on it? Participation is per-account — log in with the Fito account ` +
|
|
166
|
+
`you opened or submitted it with.)`,
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
return (
|
|
170
|
+
`This case has been deprecated — it is hidden from the catalog and may have been superseded.\n` +
|
|
171
|
+
` Your prior participation lets you finish it: your checkout, submissions, and assessments all keep working.`
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Best-effort participation record (Task 9.5): after a successful open, tell the backend this
|
|
177
|
+
* learner opened this case (`POST /cases/{id}/enrollments` — idempotent per version, so re-opens
|
|
178
|
+
* are safe). The open must never break on it: any failure — no Fito login (open needs none), a
|
|
179
|
+
* backend hiccup — comes back as a warning string for the caller to print, never a thrown error.
|
|
180
|
+
* A missed enrollment is recovered later anyway: submitting also marks participation.
|
|
181
|
+
*/
|
|
182
|
+
async function recordEnrollment(
|
|
183
|
+
client: Pick<FitoApiClient, "meWithRefresh" | "createCaseEnrollment">,
|
|
184
|
+
caseId: string,
|
|
185
|
+
home: string,
|
|
186
|
+
): Promise<string | undefined> {
|
|
187
|
+
try {
|
|
188
|
+
const session = await resolveFitoSession(client, home);
|
|
189
|
+
await client.createCaseEnrollment(session.tokens.accessToken, caseId);
|
|
190
|
+
return undefined;
|
|
191
|
+
} catch (error) {
|
|
192
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
193
|
+
return (
|
|
194
|
+
`Fito couldn't record that you opened this case (${reason.trimEnd()})\n` +
|
|
195
|
+
` Your checkout is unaffected — carry on; submitting will record your participation anyway.`
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const USAGE = "usage: node open.js <case-id> [--resume | --start-over]";
|
|
201
|
+
|
|
202
|
+
/** Parse the open CLI args (`argv` minus the node/script prefix): the case id plus an optional reconciliation flag. */
|
|
203
|
+
export function parseOpenArgs(args: string[]): { caseId: string; mode: OpenMode | undefined } {
|
|
204
|
+
const [caseId, flag, ...rest] = args;
|
|
205
|
+
if (!caseId || caseId.startsWith("--") || rest.length > 0) {
|
|
206
|
+
throw new Error(USAGE);
|
|
207
|
+
}
|
|
208
|
+
if (flag === undefined) return { caseId, mode: undefined };
|
|
209
|
+
if (flag === "--resume") return { caseId, mode: "resume" };
|
|
210
|
+
if (flag === "--start-over") return { caseId, mode: "start-over" };
|
|
211
|
+
throw new Error(`unknown flag '${flag}'\n${USAGE}`);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async function main(): Promise<void> {
|
|
215
|
+
const { caseId, mode } = parseOpenArgs(process.argv.slice(2));
|
|
216
|
+
const result = await runOpen({ caseId, mode });
|
|
217
|
+
console.log(`✓ Forked as GitHub @${result.login} — confirm this is your Fito-linked account.`);
|
|
218
|
+
if (result.opened === "resumed") {
|
|
219
|
+
console.log(`✓ Resumed your previous attempt — '${result.branch}' tracks your fork's branch (its PR carries on).`);
|
|
220
|
+
} else if (result.opened === "reset") {
|
|
221
|
+
console.log(`✓ Started over — your fork's previous '${result.branch}' was deleted (its PR closed).`);
|
|
222
|
+
}
|
|
223
|
+
console.log(`✓ Case opened at:\n ${result.workDir}\n on branch '${result.branch}'.`);
|
|
224
|
+
console.log(` Make your changes there, then submit: node submit.js ${caseId}`);
|
|
225
|
+
if (result.deprecationWarning) {
|
|
226
|
+
console.error(`⚠ ${result.deprecationWarning}`);
|
|
227
|
+
}
|
|
228
|
+
if (result.enrollmentWarning) {
|
|
229
|
+
console.error(`⚠ ${result.enrollmentWarning}`);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Only auto-invoke the CLI when run directly (`node open.js …`), not when imported (e.g. by tests). */
|
|
234
|
+
const entry = process.argv[1];
|
|
235
|
+
const isMainModule = !!entry && path.resolve(entry) === fileURLToPath(import.meta.url);
|
|
236
|
+
if (isMainModule) {
|
|
237
|
+
main().catch((error: unknown) => {
|
|
238
|
+
console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
|
|
239
|
+
process.exitCode = 1;
|
|
240
|
+
});
|
|
241
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Render the consumption-time backstop failure message (ADR-005 §6). When the structural
|
|
3
|
+
* re-validation of a freshly checked-out `.case/` fails, the skill must surface a clear "case source
|
|
4
|
+
* malformed" report — listing every structural error — and a **flag affordance** instead of dropping
|
|
5
|
+
* the learner into a broken case. Pure (returns the text); `run.ts` prints it and aborts before the
|
|
6
|
+
* student branch is created.
|
|
7
|
+
*
|
|
8
|
+
* The interactive flag flow (Curation Service) arrives in Phase 10; until then the affordance is an
|
|
9
|
+
* actionable instruction the learner can act on now (report the case id to the author / Fito team).
|
|
10
|
+
*/
|
|
11
|
+
export function formatValidationFailure(caseLabel, errors) {
|
|
12
|
+
const lines = [
|
|
13
|
+
`✗ Case source is malformed — ${caseLabel}`,
|
|
14
|
+
"",
|
|
15
|
+
"The case checkout failed structural re-validation, so it was not opened:",
|
|
16
|
+
...errors.map((e) => ` • ${e.file}: ${e.message}`),
|
|
17
|
+
"",
|
|
18
|
+
"You can flag this case as malformed so a maintainer can review it.",
|
|
19
|
+
"(Flagging from the TUI ships with the Curation features; for now, report the case id above to the case author or the Fito team.)",
|
|
20
|
+
];
|
|
21
|
+
return lines.join("\n");
|
|
22
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { ValidationError } from "../../shared/case-validation/case-schema.ts";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Render the consumption-time backstop failure message (ADR-005 §6). When the structural
|
|
5
|
+
* re-validation of a freshly checked-out `.case/` fails, the skill must surface a clear "case source
|
|
6
|
+
* malformed" report — listing every structural error — and a **flag affordance** instead of dropping
|
|
7
|
+
* the learner into a broken case. Pure (returns the text); `run.ts` prints it and aborts before the
|
|
8
|
+
* student branch is created.
|
|
9
|
+
*
|
|
10
|
+
* The interactive flag flow (Curation Service) arrives in Phase 10; until then the affordance is an
|
|
11
|
+
* actionable instruction the learner can act on now (report the case id to the author / Fito team).
|
|
12
|
+
*/
|
|
13
|
+
export function formatValidationFailure(caseLabel: string, errors: ValidationError[]): string {
|
|
14
|
+
const lines = [
|
|
15
|
+
`✗ Case source is malformed — ${caseLabel}`,
|
|
16
|
+
"",
|
|
17
|
+
"The case checkout failed structural re-validation, so it was not opened:",
|
|
18
|
+
...errors.map((e) => ` • ${e.file}: ${e.message}`),
|
|
19
|
+
"",
|
|
20
|
+
"You can flag this case as malformed so a maintainer can review it.",
|
|
21
|
+
"(Flagging from the TUI ships with the Curation features; for now, report the case id above to the case author or the Fito team.)",
|
|
22
|
+
];
|
|
23
|
+
return lines.join("\n");
|
|
24
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { dirname } from "node:path";
|
|
2
|
+
import { assertGithubPlatform, forkCloneUrl, ghAuthStatusCommand, ghCurrentLoginCommand, ghForkCommand, ghPrCreateCommand, ghPrListCommand, gitAddUpstreamRemoteCommand, gitCheckoutRefCommand, gitCheckoutTrackCommand, gitCloneCommand, gitCreateBranchCommand, gitDeleteRemoteBranchCommand, gitFetchUpstreamRefCommand, gitListRemoteBranchCommand, gitPushCommand, isDivergedPush, parseExistingPrUrl, parseGithubRepo, repoSlug, } from "./github.js";
|
|
3
|
+
import { formatValidationFailure } from "./report.js";
|
|
4
|
+
/** Upfront readiness: fail fast with an actionable message when `gh` is missing or unauthenticated. */
|
|
5
|
+
export async function ensureGhReady(exec, cwd) {
|
|
6
|
+
try {
|
|
7
|
+
await exec(ghAuthStatusCommand(), { cwd });
|
|
8
|
+
}
|
|
9
|
+
catch (error) {
|
|
10
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
11
|
+
throw new Error(`GitHub CLI is not ready — install gh and run 'gh auth login'.\n (${detail})`);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The fork already has the student branch from a previous attempt and no {@link OpenMode} was
|
|
16
|
+
* given. The resume-vs-start-over call is the learner's, never the agent's — the caller relays
|
|
17
|
+
* the choice and re-runs with the chosen mode.
|
|
18
|
+
*/
|
|
19
|
+
export class StudentBranchExistsError extends Error {
|
|
20
|
+
branch;
|
|
21
|
+
constructor(branch) {
|
|
22
|
+
super(`your fork already has a '${branch}' branch from a previous attempt`);
|
|
23
|
+
this.name = "StudentBranchExistsError";
|
|
24
|
+
this.branch = branch;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Open a case for work: fork it on GitHub, clone the fork into `targetDir`, fetch the immutable
|
|
29
|
+
* `versionRef` from the upstream case repo and check it out (the fork is never synced, so version
|
|
30
|
+
* reads must come from upstream's frozen refs — Task 9a.2), structurally re-validate the checkout's
|
|
31
|
+
* `.case/` (the Hybrid-H0 consumption backstop, ADR-005), then create the case's declared student
|
|
32
|
+
* branch and hand control back. On a malformed `.case/`, stops *before* branching and throws a
|
|
33
|
+
* clear "case source malformed" report.
|
|
34
|
+
*
|
|
35
|
+
* When the fork already carries the student branch from a previous attempt (Task 7.6), the branch
|
|
36
|
+
* step is the learner's call: with no `mode` it throws {@link StudentBranchExistsError} (the caller
|
|
37
|
+
* relays the choice), `resume` checks the fork branch out tracking it, and `start-over` deletes the
|
|
38
|
+
* fork branch (closing its PR) before branching fresh. A mode with no fork branch to act on is a
|
|
39
|
+
* stale choice and fails rather than silently falling back.
|
|
40
|
+
*/
|
|
41
|
+
export async function openCase(options) {
|
|
42
|
+
const { pointer, targetDir, exec, validate, readBranches, mode } = options;
|
|
43
|
+
assertGithubPlatform(pointer.gitPlatform);
|
|
44
|
+
const repo = parseGithubRepo(pointer.repositoryUrl);
|
|
45
|
+
const parentDir = dirname(targetDir);
|
|
46
|
+
await ensureGhReady(exec, parentDir);
|
|
47
|
+
// 1. Fork on GitHub (gh waits for the fork to be ready), then clone the fork into the case dir.
|
|
48
|
+
await exec(ghForkCommand(repoSlug(repo)), { cwd: parentDir });
|
|
49
|
+
const login = (await exec(ghCurrentLoginCommand(), { cwd: parentDir })).trim();
|
|
50
|
+
await exec(gitCloneCommand(forkCloneUrl(login, repo.repo), targetDir), { cwd: parentDir });
|
|
51
|
+
// 2. Check out the immutable version ref, read from the UPSTREAM case repo — never the fork
|
|
52
|
+
// (Task 9a.2): the fork is created once and never synced, so a version published after it is
|
|
53
|
+
// absent from origin (upstream/<ref> also dodges the tag/branch ambiguity, lesson 46).
|
|
54
|
+
await exec(gitAddUpstreamRemoteCommand(repo), { cwd: targetDir });
|
|
55
|
+
await exec(gitFetchUpstreamRefCommand(pointer.versionRef), { cwd: targetDir });
|
|
56
|
+
await exec(gitCheckoutRefCommand(pointer.versionRef), { cwd: targetDir });
|
|
57
|
+
// 3. Consumption-time structural backstop (ADR-005 §6): independently re-check the actual bytes.
|
|
58
|
+
const validation = validate(targetDir);
|
|
59
|
+
if (!validation.ok) {
|
|
60
|
+
throw new Error(formatValidationFailure(`${pointer.repositoryUrl} (${pointer.versionRef})`, validation.errors));
|
|
61
|
+
}
|
|
62
|
+
// 4. Reconcile with the fork: does it already carry the student branch the case DECLARES (from
|
|
63
|
+
// the manifest — not a hardcoded name) from a previous attempt? The probe reads the clone's
|
|
64
|
+
// remote-tracking refs, current as of the clone moments ago.
|
|
65
|
+
const { studentBranch } = readBranches(targetDir);
|
|
66
|
+
const forkHasBranch = (await exec(gitListRemoteBranchCommand(studentBranch), { cwd: targetDir })).trim().length > 0;
|
|
67
|
+
if (forkHasBranch && mode === undefined) {
|
|
68
|
+
throw new StudentBranchExistsError(studentBranch);
|
|
69
|
+
}
|
|
70
|
+
if (!forkHasBranch && mode !== undefined) {
|
|
71
|
+
throw new Error(`nothing to ${mode === "resume" ? "resume" : "start over"}: your fork has no '${studentBranch}' branch.\n` +
|
|
72
|
+
`Re-run the open without the flag for a fresh start.`);
|
|
73
|
+
}
|
|
74
|
+
// 5. Land on the student branch per the learner's (implicit or explicit) choice.
|
|
75
|
+
if (forkHasBranch && mode === "resume") {
|
|
76
|
+
await exec(gitCheckoutTrackCommand(studentBranch), { cwd: targetDir });
|
|
77
|
+
return { workDir: targetDir, branch: studentBranch, login, opened: "resumed" };
|
|
78
|
+
}
|
|
79
|
+
if (forkHasBranch && mode === "start-over") {
|
|
80
|
+
await exec(gitDeleteRemoteBranchCommand(studentBranch), { cwd: targetDir });
|
|
81
|
+
await exec(gitCreateBranchCommand(studentBranch), { cwd: targetDir });
|
|
82
|
+
return { workDir: targetDir, branch: studentBranch, login, opened: "reset" };
|
|
83
|
+
}
|
|
84
|
+
await exec(gitCreateBranchCommand(studentBranch), { cwd: targetDir });
|
|
85
|
+
return { workDir: targetDir, branch: studentBranch, login, opened: "fresh" };
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Submit the worked solution: push the case's declared student branch to the fork, open (or reuse) a
|
|
89
|
+
* PR against the case's declared target branch, then record the submission with the backend. Returns
|
|
90
|
+
* the PR URL.
|
|
91
|
+
*/
|
|
92
|
+
export async function submitSolution(options) {
|
|
93
|
+
const { pointer, targetDir, exec, readBranches, resolveLinkedGithubLogin, recordSubmission } = options;
|
|
94
|
+
assertGithubPlatform(pointer.gitPlatform);
|
|
95
|
+
const repo = parseGithubRepo(pointer.repositoryUrl);
|
|
96
|
+
await ensureGhReady(exec, targetDir);
|
|
97
|
+
// The local gh account that will own the fork branch + the PR.
|
|
98
|
+
const login = (await exec(ghCurrentLoginCommand(), { cwd: targetDir })).trim();
|
|
99
|
+
// Authoritative "Fito-linked ↔ gh-authenticated" match (Task 5.4): the backend associates a
|
|
100
|
+
// submission by the learner's Fito-linked GitHub identity, so require a link and confirm the local
|
|
101
|
+
// gh account matches it BEFORE pushing anything (SPEC §327 / Decision #8). Refuse, don't silently
|
|
102
|
+
// open a PR that would be recorded under a different account than the one that authored it.
|
|
103
|
+
const linkedLogin = await resolveLinkedGithubLogin();
|
|
104
|
+
if (linkedLogin === null) {
|
|
105
|
+
throw new Error("Your Fito account has no linked GitHub identity, which is required to submit.\n" +
|
|
106
|
+
"Link your GitHub account to Fito, then submit again.");
|
|
107
|
+
}
|
|
108
|
+
if (linkedLogin.toLowerCase() !== login.toLowerCase()) {
|
|
109
|
+
throw new Error(`GitHub account mismatch: your Fito-linked account is @${linkedLogin}, but gh is authenticated as @${login}.\n` +
|
|
110
|
+
`Run 'gh auth login' as @${linkedLogin}, or link @${login} to your Fito account, then submit again.`);
|
|
111
|
+
}
|
|
112
|
+
const { targetBranch, studentBranch } = readBranches(targetDir);
|
|
113
|
+
// Publish the working branch (a no-op if already pushed; updates the PR if there are new commits).
|
|
114
|
+
// A non-fast-forward rejection means the fork's branch diverged (a previous attempt — Task 7.6);
|
|
115
|
+
// the fix is the learner's resume/start-over choice at re-open, never a force-push here.
|
|
116
|
+
try {
|
|
117
|
+
await exec(gitPushCommand(studentBranch), { cwd: targetDir });
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
121
|
+
if (isDivergedPush(detail)) {
|
|
122
|
+
throw new Error(`The push was rejected: your fork's '${studentBranch}' branch has diverged from this checkout ` +
|
|
123
|
+
`(it carries a previous attempt).\n` +
|
|
124
|
+
`Do not force-push. Re-open the case with /fito-case-open and choose to resume the previous ` +
|
|
125
|
+
`attempt or start over, then submit again.\n (${detail})`);
|
|
126
|
+
}
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
// Record-aware retry: reuse an already-open PR rather than letting `gh pr create` fail on a
|
|
130
|
+
// duplicate (a prior submit may have opened the PR but failed to record it; or the learner
|
|
131
|
+
// re-submits).
|
|
132
|
+
const existingPr = parseExistingPrUrl(await exec(ghPrListCommand({ repoSlug: repoSlug(repo), base: targetBranch, headBranch: studentBranch }), {
|
|
133
|
+
cwd: targetDir,
|
|
134
|
+
}), login, studentBranch);
|
|
135
|
+
const prUrl = existingPr ??
|
|
136
|
+
(await exec(ghPrCreateCommand({
|
|
137
|
+
repoSlug: repoSlug(repo),
|
|
138
|
+
base: targetBranch,
|
|
139
|
+
headOwner: login,
|
|
140
|
+
headBranch: studentBranch,
|
|
141
|
+
title: options.title ?? "Fito case submission",
|
|
142
|
+
body: options.body ?? "Submitted via the Fito TUI.",
|
|
143
|
+
}), { cwd: targetDir })).trim();
|
|
144
|
+
// Record the submission with Fito (idempotent on the PR — the backend find-or-creates). The PR is
|
|
145
|
+
// the artifact of record (SPEC §Performance Reviewer), so on a record failure surface the PR URL:
|
|
146
|
+
// re-running /fito-submit reuses this PR and retries the record.
|
|
147
|
+
let submissionId;
|
|
148
|
+
try {
|
|
149
|
+
submissionId = await recordSubmission(prUrl);
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
153
|
+
throw new Error(`Your pull request is open:\n ${prUrl}\n` +
|
|
154
|
+
`…but recording the submission with Fito failed: ${detail}\n` +
|
|
155
|
+
`Re-run /fito-submit to retry — it reuses this PR.`);
|
|
156
|
+
}
|
|
157
|
+
return { prUrl, login, submissionId };
|
|
158
|
+
}
|