fito-tui 0.7.0 → 0.8.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fito-tui",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Fito for pi: case-based practice for software engineers, in your terminal.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -16,12 +16,19 @@ Use the `fito-case-runner` skill (read its `SKILL.md`), then run:
16
16
  node "<fito-case-runner skill dir>/open.js" $1
17
17
  ```
18
18
 
19
- This forks the case repo to the learner's GitHub account, clones it into
20
- `~/.fito/cases/$1/`, checks out the published version, **structurally
21
- re-validates** the `.case/` checkout, and creates the working branch.
19
+ This checks the learner's Fito login, forks the case repo to the learner's
20
+ GitHub account, clones it into `~/.fito/cases/$1/`, checks out the published
21
+ version, **structurally re-validates** the `.case/` checkout, creates the
22
+ working branch, and records the enrollment with Fito.
22
23
 
23
24
  - Stream the output so the learner sees which GitHub account owns the fork (ask
24
25
  them to confirm it is their Fito-linked account) and the checkout path.
26
+ - If it refuses because the learner is **not logged in** to Fito, relay its
27
+ message and stop: they run `/fito-login`, then `/fito-case-open $1` again.
28
+ Nothing was forked or cloned.
29
+ - If it stops because Fito **could not record** the open, relay its message
30
+ verbatim and stop. The open removed its own folder, so the learner re-runs
31
+ `/fito-case-open $1` when Fito answers again.
25
32
  - If it prints a "case source malformed" report (structural errors and **no**
26
33
  branch created), **stop here — do not orient.** Show the errors and the report
27
34
  affordance; suggest re-running `/fito-case-open $1` later or reporting the case.
@@ -47,11 +47,17 @@ exist surfaces nowhere: step 3's search filters by version and returns an **empt
47
47
  reads exactly like a technology whose components have not been pushed yet, and sends the author to
48
48
  the knowledge pipeline over a typo.
49
49
 
50
- Every write here is authenticated. If a write reports no session, relay it: run `/fito-login`,
51
- then re-run this command.
50
+ Every write here needs a Fito login, so confirm it now, before any competence work starts:
51
+
52
+ ```bash
53
+ node "<fito-auth skill dir>/status.js"
54
+ ```
55
+
56
+ On a non-zero exit, relay its message and stop: the author runs `/fito-login`, then re-runs this
57
+ command.
52
58
 
53
59
  **Done when** the technology and the declared major line are both live, exactly as the author
54
- spelled them.
60
+ spelled them, and `status.js` confirmed the login.
55
61
 
56
62
  ## 2. Read what the technology already demands
57
63
 
@@ -42,11 +42,17 @@ Without `--technology`, or when its value carries no `@`, stop and ask:
42
42
  > for a practice with no release line). The slug and the major line are yours to declare — the
43
43
  > pipeline never infers them from the source."
44
44
 
45
- Both writes are authenticated. If a write later reports no session, relay it: run `/fito-login`,
46
- then re-run this command.
45
+ Both writes need a Fito login, so confirm it now, before any source is read:
46
+
47
+ ```bash
48
+ node "<fito-auth skill dir>/status.js"
49
+ ```
50
+
51
+ On a non-zero exit, relay its message and stop: the author runs `/fito-login`, then re-runs this
52
+ command.
47
53
 
48
54
  **Done when** the slug and the major-line version are both in hand, exactly as the author spelled
49
- them.
55
+ them, and `status.js` confirmed the login.
50
56
 
51
57
  ## 2. Ingest the grounding sources
52
58
 
@@ -34,6 +34,14 @@ Two prerequisites, both before anything is pushed: a **Fito login**
34
34
  bearer-authenticated) and an authenticated **`gh`** (`gh auth login` — the
35
35
  initial publish creates and pushes the repo under this local account; an
36
36
  update's push needs its credentials to hold write access to the case repo).
37
+ Confirm the Fito login now, before any drafting or commit:
38
+
39
+ ```bash
40
+ node "<fito-auth skill dir>/status.js"
41
+ ```
42
+
43
+ On a non-zero exit, relay its message and stop: the author runs `/fito-login`,
44
+ then re-runs this command.
37
45
 
38
46
  The directory must contain `.case/` — otherwise stop and point the author at
39
47
  `/fito-case-generate` (a new case) or `/fito-case-edit <case-id>` (an update
@@ -62,8 +70,9 @@ committed. If `git status` shows uncommitted changes, surface them and
62
70
  settle them with the author before going on — both scripts refuse a dirty
63
71
  tree, because what is validated must be exactly what is pushed.
64
72
 
65
- **Done when** both prerequisites hold, the route is known, and the tree is
66
- clean — or the route was `deprecated` and you relayed and stopped.
73
+ **Done when** both prerequisites hold (`status.js` confirmed the Fito login),
74
+ the route is known, and the tree is clean — or the route was `deprecated` and
75
+ you relayed and stopped.
67
76
 
68
77
  # The initial publish (route: initial)
69
78
 
@@ -171,7 +171,7 @@ directly without an HTTP-mock library.
171
171
  | `publishCase` | `POST /cases/{id}/publish` | Publish a registered draft (bearer, owner-only): S1 presentation + role-grouped references + optional quiz + structural attestation; the backend pings the repo and resolves every reference — each rejection is a 422 whose problem detail the flow relays verbatim. A `prerequisites` reference carries the author's optional **`description`** (Task 12a.3) alongside `componentId` + `bloomLevel` — it is persisted and rendered under the entry on the case cover, and was dropped on this wire before that task, which is why every stored row held `NULL`; `rubric.yaml` has no criterion-level description, so a rubric entry's is always absent |
172
172
  | `publishCaseVersion` | `POST /cases/{id}/versions` | Publish a correction/perfection **version** of a published case (bearer, owner-only; Task 9.4, ADR-009 — the Task 9.8 update flow): the publish payload plus `version`/`versionRef` (exactly `"v" + version`, strictly increasing) and the required `changeDescription`; the reference set is **frozen** across versions on `(componentId, bloomLevel, role)` — each rejection is a 422 relayed verbatim |
173
173
  | `getCaseLearningObjectives` / `getCasePrerequisites` / `getCaseRubric` | `GET /cases/{id}/{learning-objectives\|prerequisite-components\|rubric}` | The stored role-grouped references resolved to knowledge-component names (public reads, Task 3.3c) — the baseline the version-publish preflight compares the local `.case/` tree against (Task 9.8) |
174
- | `createCaseEnrollment` | `POST /cases/{id}/enrollments` | Record a learner's case open as an enrollment (bearer; body-less — the backend pins the case's **current** version; idempotent per `(learner, case, version)`, 201 fresh vs 200 existing; Task 9.5) — posted best-effort by the case-runner after a successful open |
174
+ | `createCaseEnrollment` | `POST /cases/{id}/enrollments` | Record a learner's case open as an enrollment (bearer; body-less — the backend pins the case's **current** version; idempotent per `(learner, case, version)`, 201 fresh vs 200 existing; Task 9.5) — posted by the case-runner after a successful open, which stops when the post fails (Task 17.25) |
175
175
  | `getCaseParticipation` | `GET /cases/{id}/enrollments/me` | Whether the authenticated learner participates in the case — an enrollment **or** a recorded submission exists (bearer, learner-scoped; never a 404 — an unknown case reads `participant: false`, the `submissions/me` existence-hiding precedent; Task 9.6) — gates the case-runner's open of a deprecated case |
176
176
  | `createSubmission` | `POST /submissions` | Record an opened PR as a submission (bearer; idempotent on the PR — the backend find-or-creates, returning 200 for an existing row vs 201 for a new one); carries the checkout's `versionRef`, pinning the exact case version the learner solved (Task 9.4) — an unregistered ref is a 422 |
177
177
  | `submitEvaluationResults` | `POST /submissions/{id}/results` | Record the reviewer's per-criterion scores for a submission (bearer); flips it to `EVALUATED` and records proficiency per knowledge component |
@@ -3,7 +3,8 @@ name: fito-auth
3
3
  description: >
4
4
  Authenticate the Fito TUI against the backend and manage the local credential
5
5
  store. Use when the learner wants to log in, log out, or refresh their Fito
6
- session — the /fito-login, /fito-logout, and /fito-auth-refresh commands.
6
+ session — the /fito-login, /fito-logout, and /fito-auth-refresh commands — or
7
+ when a command confirms the login before it writes to Fito.
7
8
  allowed-tools: bash
8
9
  ---
9
10
 
@@ -48,13 +49,24 @@ node "<fito-auth skill dir>/auth-refresh.js"
48
49
  Exchanges the stored refresh token for a fresh token pair via `POST /auth/refresh`
49
50
  and rewrites this Fito's credentials file. Fails if not logged in.
50
51
 
52
+ ## Check the login
53
+
54
+ ```bash
55
+ node "<fito-auth skill dir>/status.js"
56
+ ```
57
+
58
+ Confirms this Fito's login through `GET /me`, saving a refreshed token pair, and
59
+ prints `✓ Logged in to Fito at <url> as <username>.` Without a login it prints the
60
+ `/fito-login` guidance and exits non-zero. A command that writes to Fito runs it
61
+ first, so a logged-out author stops before any work.
62
+
51
63
  ## Files
52
64
 
53
65
  | File | Role |
54
66
  |---|---|
55
67
  | `callback-server.ts` | Loopback receiver for the browser token handoff (CORS) |
56
68
  | `browser.ts` | Per-platform system-browser launcher |
57
- | `login.ts` / `logout.ts` / `auth-refresh.ts` | CLI entrypoints (above) |
69
+ | `login.ts` / `logout.ts` / `auth-refresh.ts` / `status.ts` | CLI entrypoints (above) |
58
70
 
59
71
  The credentials store (read/write/delete, Zod-validated) lives in the
60
72
  shared [`fito-session`](../../shared/fito-session/credentials.ts) module, reused by `fito-case-runner`.
@@ -0,0 +1,33 @@
1
+ /**
2
+ * `node status.js` — confirms the Fito login before a command that writes to Fito does any work
3
+ * (Task 17.25). It resolves the session the way the write scripts do ([resolveFitoSession]: this
4
+ * Fito's `~/.fito/credentials-<host>`, `GET /me`, and a refresh on a 401 that it saves) and prints
5
+ * who is logged in, or exits 1 with the "not logged in" message. The write scripts keep their own
6
+ * check, because a session can end between the two.
7
+ *
8
+ * `runStatus` is the testable core (everything injectable); `main` is the thin CLI wrapper.
9
+ */
10
+ import * as os from "node:os";
11
+ import * as path from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+ import { createFitoApiClient } from "../../shared/fito-api/client.js";
14
+ import { resolveFitoSession } from "../../shared/fito-session/session.js";
15
+ import { fitoUrl } from "../../shared/fito-url/fito-url.js";
16
+ /** Resolve the session on the Fito at `url` and return the line that names who is logged in; throws without a login. */
17
+ export async function runStatus(options = {}) {
18
+ const url = options.url ?? fitoUrl();
19
+ const { user } = await resolveFitoSession(options.client ?? createFitoApiClient(), options.home ?? os.homedir(), url);
20
+ return `✓ Logged in to Fito at ${url} as ${user.username}.`;
21
+ }
22
+ async function main() {
23
+ console.log(await runStatus());
24
+ }
25
+ /** Only auto-invoke the CLI when run directly (`node status.js`), not when imported (e.g. by tests). */
26
+ const entry = process.argv[1];
27
+ const isMainModule = !!entry && path.resolve(entry) === fileURLToPath(import.meta.url);
28
+ if (isMainModule) {
29
+ main().catch((error) => {
30
+ console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
31
+ process.exitCode = 1;
32
+ });
33
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * `node status.js` — confirms the Fito login before a command that writes to Fito does any work
3
+ * (Task 17.25). It resolves the session the way the write scripts do ([resolveFitoSession]: this
4
+ * Fito's `~/.fito/credentials-<host>`, `GET /me`, and a refresh on a 401 that it saves) and prints
5
+ * who is logged in, or exits 1 with the "not logged in" message. The write scripts keep their own
6
+ * check, because a session can end between the two.
7
+ *
8
+ * `runStatus` is the testable core (everything injectable); `main` is the thin CLI wrapper.
9
+ */
10
+ import * as os from "node:os";
11
+ import * as path from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+
14
+ import { type FitoApiClient, createFitoApiClient } from "../../shared/fito-api/client.ts";
15
+ import { resolveFitoSession } from "../../shared/fito-session/session.ts";
16
+ import { fitoUrl } from "../../shared/fito-url/fito-url.ts";
17
+
18
+ export interface RunStatusOptions {
19
+ home?: string;
20
+ /** The Fito whose login is checked; defaults to the one `shared/fito-url/` gives. */
21
+ url?: string;
22
+ client?: Pick<FitoApiClient, "meWithRefresh">;
23
+ }
24
+
25
+ /** Resolve the session on the Fito at `url` and return the line that names who is logged in; throws without a login. */
26
+ export async function runStatus(options: RunStatusOptions = {}): Promise<string> {
27
+ const url = options.url ?? fitoUrl();
28
+ const { user } = await resolveFitoSession(
29
+ options.client ?? createFitoApiClient(),
30
+ options.home ?? os.homedir(),
31
+ url,
32
+ );
33
+ return `✓ Logged in to Fito at ${url} as ${user.username}.`;
34
+ }
35
+
36
+ async function main(): Promise<void> {
37
+ console.log(await runStatus());
38
+ }
39
+
40
+ /** Only auto-invoke the CLI when run directly (`node status.js`), not when imported (e.g. by tests). */
41
+ const entry = process.argv[1];
42
+ const isMainModule = !!entry && path.resolve(entry) === fileURLToPath(import.meta.url);
43
+ if (isMainModule) {
44
+ main().catch((error: unknown) => {
45
+ console.error(`✗ ${error instanceof Error ? error.message : String(error)}`);
46
+ process.exitCode = 1;
47
+ });
48
+ }
@@ -54,8 +54,8 @@ export async function runCheckout(options) {
54
54
  const home = options.home ?? os.homedir();
55
55
  const client = options.client ?? createFitoApiClient();
56
56
  const exec = options.exec ?? (await import("../../shared/shell-exec/exec.js")).shellExec;
57
- // Best-effort session (the open.ts enrollment pattern): a published checkout needs no login,
58
- // but with one the backend serves the owner's own DRAFT (getCase's optional bearer, Task 9.7).
57
+ // Best-effort session: a published checkout needs no login, but with one the backend serves the
58
+ // owner's own DRAFT (getCase's optional bearer, Task 9.7).
59
59
  let accessToken;
60
60
  try {
61
61
  accessToken = (await resolveFitoSession(client, home)).tokens.accessToken;
@@ -100,8 +100,8 @@ export async function runCheckout(options: RunCheckoutOptions): Promise<RunCheck
100
100
  const client = options.client ?? createFitoApiClient();
101
101
  const exec = options.exec ?? (await import("../../shared/shell-exec/exec.ts")).shellExec;
102
102
 
103
- // Best-effort session (the open.ts enrollment pattern): a published checkout needs no login,
104
- // but with one the backend serves the owner's own DRAFT (getCase's optional bearer, Task 9.7).
103
+ // Best-effort session: a published checkout needs no login, but with one the backend serves the
104
+ // owner's own DRAFT (getCase's optional bearer, Task 9.7).
105
105
  let accessToken: string | undefined;
106
106
  try {
107
107
  accessToken = (await resolveFitoSession(client, home)).tokens.accessToken;
@@ -221,7 +221,7 @@ export async function runPublishVersion(options) {
221
221
  * Never fatal. The version is already published and registered by the time this runs, so an
222
222
  * offline machine, a credential prompt or a slow remote must not turn a successful publish into a
223
223
  * failure the author would try to fix by re-running it — the failure becomes the warning the
224
- * caller prints, exactly as `runOpen` does with its enrollment record.
224
+ * caller prints.
225
225
  */
226
226
  async function refreshLocalRepoView(run) {
227
227
  try {
@@ -92,7 +92,7 @@ export interface RunPublishVersionResult {
92
92
  /**
93
93
  * Set when the best-effort post-publish refresh failed (Task 12a.8, F58) — the version itself is
94
94
  * published and registered; only the checkout's tracking refs are stale. The caller prints this
95
- * as a warning, never an error (the `runOpen`/`enrollmentWarning` precedent).
95
+ * as a warning, never an error.
96
96
  */
97
97
  refreshWarning?: string;
98
98
  }
@@ -339,7 +339,7 @@ export async function runPublishVersion(options: RunPublishVersionOptions): Prom
339
339
  * Never fatal. The version is already published and registered by the time this runs, so an
340
340
  * offline machine, a credential prompt or a slow remote must not turn a successful publish into a
341
341
  * failure the author would try to fix by re-running it — the failure becomes the warning the
342
- * caller prints, exactly as `runOpen` does with its enrollment record.
342
+ * caller prints.
343
343
  */
344
344
  async function refreshLocalRepoView(run: (command: ShellCommand) => Promise<string>): Promise<string | undefined> {
345
345
  try {
@@ -19,9 +19,9 @@ per-case checkout at `~/.fito/cases/<case-id>/`, so open and submit always agree
19
19
  Fito profile (see below). Both commands fail with an actionable message if `gh` is missing or
20
20
  unauthenticated.
21
21
  - **`git`** on `PATH`.
22
- - **Fito login (submit only)** — `/fito-login`. Submit records a server-side submission and resolves
23
- the learner's Fito-linked GitHub identity via `GET /me`; open needs no login (the case read is
24
- public — a logged-in open additionally records participation, see below).
22
+ - **Fito login** — `/fito-login`. Open records the learner's enrollment and submit records a
23
+ server-side submission, so both refuse to start without a login. Submit also resolves the
24
+ learner's Fito-linked GitHub identity via `GET /me`.
25
25
 
26
26
  ## Open a case
27
27
 
@@ -38,16 +38,18 @@ it to the learner's GitHub account, clones the fork into `~/.fito/cases/<case-id
38
38
  prints the structural errors + a report affordance, creates **no** branch, and exits non-zero — stop
39
39
  there; do not submit. (It refuses to overwrite a non-empty existing checkout.)
40
40
 
41
+ Without a Fito login, open prints `✗ Opening a case needs a Fito login…` and exits non-zero with
42
+ nothing forked or cloned — relay it: the learner runs `/fito-login`, then re-runs the open.
43
+
41
44
  After a successful open it records the learner's participation with the backend (`POST
42
- /cases/{id}/enrollments` — best-effort, Task 9.5). A `⚠ Fito couldn't record…` warning means only
43
- that this record failed (no login, backend unreachable): the checkout is fine — relay the warning
44
- and carry on; submitting records participation anyway. Never treat it as a failed open.
45
+ /cases/{id}/enrollments`, Task 9.5). The record is part of the open: when it fails, open removes its
46
+ own clone, prints `✗ Fito could not record…` with the reason, and exits non-zero — relay it and
47
+ stop; the learner re-runs the open when the backend answers.
45
48
 
46
49
  **Deprecated cases** (Task 9.6): a retired case takes no new learners. When the case is
47
50
  `DEPRECATED`, open verifies the learner's participation with the backend
48
51
  (`GET /cases/{id}/enrollments/me`) and **refuses** unless they already participate (an enrollment
49
- or submission on record) — verifying needs a Fito login, so a logged-out open of a deprecated case
50
- is refused with `/fito-login` guidance. A participant's open proceeds, printing a
52
+ or submission on record). A participant's open proceeds, printing a
51
53
  `⚠ This case has been deprecated…` warning — relay it and continue; finishing and submitting stay
52
54
  fully supported. An existing non-empty checkout is pointed at before the gate, so a mid-flight
53
55
  learner is never refused their own work.
@@ -1,8 +1,9 @@
1
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).
2
+ * `node open.js <case-id>` — the `fito-case-runner` open entrypoint (Task 5.2). Confirms the Fito
3
+ * login, fetches the case pointer, guards the per-case working dir, then runs the runner's fork →
4
+ * clone → upstream fetch → checkout → structural re-validation → student-branch flow into
5
+ * `~/.fito/cases/<case-id>/`, and records the enrollment. GitHub writes go through the
6
+ * locally-installed `gh` CLI (`gh auth login` prerequisite).
6
7
  *
7
8
  * `runOpen` is the testable core (everything injectable); `main` is the thin CLI wrapper (argv +
8
9
  * real deps + printing), invoked by the `/fito-case-open` orchestrator (Task 5.3).
@@ -19,22 +20,27 @@ import { fetchCaseDetail } from "./case-detail.js";
19
20
  import { readSubmissionBranches } from "./manifest.js";
20
21
  import { StudentBranchExistsError, openCase, } from "./runner.js";
21
22
  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
+ /** Confirm the login → fetch case → guard the per-case dir → gate a deprecated case → open (fork → clone → upstream fetch → checkout → validate → branch) → enroll. */
23
24
  export async function runOpen(options) {
24
25
  const home = options.home ?? os.homedir();
25
26
  const client = options.client ?? createFitoApiClient();
27
+ // First, so a logged-out run stops with nothing forked, cloned or created: every open records
28
+ // an enrollment (Task 17.25).
29
+ const accessToken = await requireSession(client, home);
26
30
  const detail = await fetchCaseDetail(client, options.caseId);
27
31
  const targetDir = caseWorkDir(options.caseId, home);
28
32
  // 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.
33
+ // by definition (until Task 17.25 an open without a login recorded no enrollment, so the backend
34
+ // may not know them) and must be pointed at their work — /fito-submit still accepts a deprecated
35
+ // case — never refused. This refusal records no enrollment: a record here would let any folder at
36
+ // this path enroll a learner in a deprecated case.
31
37
  if (existsSync(targetDir) && readdirSync(targetDir).length > 0) {
32
38
  throw new Error(`A working directory already exists and is not empty:\n ${targetDir}\n` +
33
39
  `Move or remove it first — Fito will not overwrite your work.`);
34
40
  }
35
41
  let deprecationWarning;
36
42
  if (detail.status === "DEPRECATED") {
37
- deprecationWarning = await guardDeprecatedCase(client, options.caseId, home);
43
+ deprecationWarning = await guardDeprecatedCase(client, accessToken, options.caseId);
38
44
  }
39
45
  mkdirSync(path.dirname(targetDir), { recursive: true });
40
46
  let result;
@@ -67,31 +73,36 @@ export async function runOpen(options) {
67
73
  }
68
74
  throw error;
69
75
  }
70
- const enrollmentWarning = await recordEnrollment(client, options.caseId, home);
76
+ await recordEnrollment(client, options.caseId, targetDir, home);
71
77
  return {
72
78
  ...result,
73
79
  ...(deprecationWarning === undefined ? {} : { deprecationWarning }),
74
- ...(enrollmentWarning === undefined ? {} : { enrollmentWarning }),
75
80
  };
76
81
  }
77
82
  /**
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.
83
+ * The login check every open makes first (Task 17.25): resolve the learner's session and return its
84
+ * access token, or stop the open before it does anything. The message carries the session's own
85
+ * reason, which names `/fito-login` when no login is stored.
84
86
  */
85
- async function guardDeprecatedCase(client, caseId, home) {
86
- let accessToken;
87
+ async function requireSession(client, home) {
87
88
  try {
88
- accessToken = (await resolveFitoSession(client, home)).tokens.accessToken;
89
+ return (await resolveFitoSession(client, home)).tokens.accessToken;
89
90
  }
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}`);
91
+ catch (error) {
92
+ const reason = error instanceof Error ? error.message : String(error);
93
+ throw new Error(`Opening a case needs a Fito login, because Fito records that you opened it. Nothing was opened.\n` +
94
+ ` ${reason.trimEnd()}`);
94
95
  }
96
+ }
97
+ /**
98
+ * The deprecated-case gate (Task 9.6, ADR-009 §5): a retired case takes no new learners, so the
99
+ * open proceeds only for a prior participant — the backend knows one by their enrollment or
100
+ * submission (`GET /cases/{id}/enrollments/me`), read with the session the login check resolved. An
101
+ * unverifiable check or a non-participant refuses the open (fail-safe — the gate never guesses). A
102
+ * participant's open returns the warning the caller prints: the case is retired, but finishing it —
103
+ * including submit — keeps working.
104
+ */
105
+ async function guardDeprecatedCase(client, accessToken, caseId) {
95
106
  let participant;
96
107
  try {
97
108
  participant = (await client.getCaseParticipation(accessToken, caseId)).participant;
@@ -112,22 +123,25 @@ async function guardDeprecatedCase(client, caseId, home) {
112
123
  ` Your prior participation lets you finish it: your checkout, submissions, and assessments all keep working.`);
113
124
  }
114
125
  /**
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.
126
+ * The participation record (Task 9.5): after a successful open, tell the backend this learner opened
127
+ * this case (`POST /cases/{id}/enrollments` — idempotent per version, so re-opens are safe). It is
128
+ * part of the open (Task 17.25): when it fails, the open removes the clone it made and stops, so the
129
+ * re-run finds no folder in its way. The fork stays on GitHub, and the re-run uses it again.
130
+ *
131
+ * The session is resolved again rather than reused from the login check: the access token can
132
+ * expire while the fork and the clone run.
120
133
  */
121
- async function recordEnrollment(client, caseId, home) {
134
+ async function recordEnrollment(client, caseId, targetDir, home) {
122
135
  try {
123
136
  const session = await resolveFitoSession(client, home);
124
137
  await client.createCaseEnrollment(session.tokens.accessToken, caseId);
125
- return undefined;
126
138
  }
127
139
  catch (error) {
140
+ rmSync(targetDir, { recursive: true, force: true });
128
141
  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.`);
142
+ throw new Error(`Fito could not record that you opened this case (${reason.trimEnd()})\n` +
143
+ ` Opening a case needs that record, so the open stopped and removed its folder.\n` +
144
+ ` Your fork on GitHub stays. Re-run /fito-case-open ${caseId} when Fito answers again.`);
131
145
  }
132
146
  }
133
147
  const USAGE = "usage: node open.js <case-id> [--resume | --start-over]";
@@ -160,9 +174,6 @@ async function main() {
160
174
  if (result.deprecationWarning) {
161
175
  console.error(`⚠ ${result.deprecationWarning}`);
162
176
  }
163
- if (result.enrollmentWarning) {
164
- console.error(`⚠ ${result.enrollmentWarning}`);
165
- }
166
177
  }
167
178
  /** Only auto-invoke the CLI when run directly (`node open.js …`), not when imported (e.g. by tests). */
168
179
  const entry = process.argv[1];
@@ -1,8 +1,9 @@
1
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).
2
+ * `node open.js <case-id>` — the `fito-case-runner` open entrypoint (Task 5.2). Confirms the Fito
3
+ * login, fetches the case pointer, guards the per-case working dir, then runs the runner's fork →
4
+ * clone → upstream fetch → checkout → structural re-validation → student-branch flow into
5
+ * `~/.fito/cases/<case-id>/`, and records the enrollment. GitHub writes go through the
6
+ * locally-installed `gh` CLI (`gh auth login` prerequisite).
6
7
  *
7
8
  * `runOpen` is the testable core (everything injectable); `main` is the thin CLI wrapper (argv +
8
9
  * real deps + printing), invoked by the `/fito-case-open` orchestrator (Task 5.3).
@@ -33,8 +34,8 @@ export interface RunOpenOptions {
33
34
  caseId: string;
34
35
  home?: string;
35
36
  /**
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_URL`).
37
+ * Backend client (the login check, case fetch, the deprecated-case participant gate — Task 9.6,
38
+ * and the enrollment record — Task 9.5); defaults to the real one (reads `FITO_URL`).
38
39
  */
39
40
  client?: Pick<FitoApiClient, "getCase" | "meWithRefresh" | "createCaseEnrollment" | "getCaseParticipation">;
40
41
  exec?: Executor;
@@ -46,11 +47,6 @@ export interface RunOpenOptions {
46
47
 
47
48
  /** An [OpenCaseResult] plus the open flow's own outcome fields. */
48
49
  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
50
  /**
55
51
  * Set when the case is deprecated and this learner's prior participation let the open proceed
56
52
  * (Task 9.6) — the caller prints it as a warning so the learner knows the case is retired.
@@ -58,17 +54,23 @@ export interface RunOpenResult extends OpenCaseResult {
58
54
  deprecationWarning?: string;
59
55
  }
60
56
 
61
- /** Fetch case → guard the per-case dir → gate a deprecated case → open (fork → clone → upstream fetch → checkout → validate → branch) → enroll. */
57
+ /** Confirm the login → fetch case → guard the per-case dir → gate a deprecated case → open (fork → clone → upstream fetch → checkout → validate → branch) → enroll. */
62
58
  export async function runOpen(options: RunOpenOptions): Promise<RunOpenResult> {
63
59
  const home = options.home ?? os.homedir();
64
60
  const client = options.client ?? createFitoApiClient();
65
61
 
62
+ // First, so a logged-out run stops with nothing forked, cloned or created: every open records
63
+ // an enrollment (Task 17.25).
64
+ const accessToken = await requireSession(client, home);
65
+
66
66
  const detail = await fetchCaseDetail(client, options.caseId);
67
67
  const targetDir = caseWorkDir(options.caseId, home);
68
68
 
69
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.
70
+ // by definition (until Task 17.25 an open without a login recorded no enrollment, so the backend
71
+ // may not know them) and must be pointed at their work — /fito-submit still accepts a deprecated
72
+ // case — never refused. This refusal records no enrollment: a record here would let any folder at
73
+ // this path enroll a learner in a deprecated case.
72
74
  if (existsSync(targetDir) && readdirSync(targetDir).length > 0) {
73
75
  throw new Error(
74
76
  `A working directory already exists and is not empty:\n ${targetDir}\n` +
@@ -78,7 +80,7 @@ export async function runOpen(options: RunOpenOptions): Promise<RunOpenResult> {
78
80
 
79
81
  let deprecationWarning: string | undefined;
80
82
  if (detail.status === "DEPRECATED") {
81
- deprecationWarning = await guardDeprecatedCase(client, options.caseId, home);
83
+ deprecationWarning = await guardDeprecatedCase(client, accessToken, options.caseId);
82
84
  }
83
85
 
84
86
  mkdirSync(path.dirname(targetDir), { recursive: true });
@@ -115,38 +117,43 @@ export async function runOpen(options: RunOpenOptions): Promise<RunOpenResult> {
115
117
  throw error;
116
118
  }
117
119
 
118
- const enrollmentWarning = await recordEnrollment(client, options.caseId, home);
120
+ await recordEnrollment(client, options.caseId, targetDir, home);
119
121
  return {
120
122
  ...result,
121
123
  ...(deprecationWarning === undefined ? {} : { deprecationWarning }),
122
- ...(enrollmentWarning === undefined ? {} : { enrollmentWarning }),
123
124
  };
124
125
  }
125
126
 
126
127
  /**
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.
128
+ * The login check every open makes first (Task 17.25): resolve the learner's session and return its
129
+ * access token, or stop the open before it does anything. The message carries the session's own
130
+ * reason, which names `/fito-login` when no login is stored.
133
131
  */
134
- async function guardDeprecatedCase(
135
- client: Pick<FitoApiClient, "meWithRefresh" | "getCaseParticipation">,
136
- caseId: string,
137
- home: string,
138
- ): Promise<string> {
139
- let accessToken: string;
132
+ async function requireSession(client: Pick<FitoApiClient, "meWithRefresh">, home: string): Promise<string> {
140
133
  try {
141
- accessToken = (await resolveFitoSession(client, home)).tokens.accessToken;
142
- } catch {
134
+ return (await resolveFitoSession(client, home)).tokens.accessToken;
135
+ } catch (error) {
136
+ const reason = error instanceof Error ? error.message : String(error);
143
137
  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}`,
138
+ `Opening a case needs a Fito login, because Fito records that you opened it. Nothing was opened.\n` +
139
+ ` ${reason.trimEnd()}`,
147
140
  );
148
141
  }
142
+ }
149
143
 
144
+ /**
145
+ * The deprecated-case gate (Task 9.6, ADR-009 §5): a retired case takes no new learners, so the
146
+ * open proceeds only for a prior participant — the backend knows one by their enrollment or
147
+ * submission (`GET /cases/{id}/enrollments/me`), read with the session the login check resolved. An
148
+ * unverifiable check or a non-participant refuses the open (fail-safe — the gate never guesses). A
149
+ * participant's open returns the warning the caller prints: the case is retired, but finishing it —
150
+ * including submit — keeps working.
151
+ */
152
+ async function guardDeprecatedCase(
153
+ client: Pick<FitoApiClient, "getCaseParticipation">,
154
+ accessToken: string,
155
+ caseId: string,
156
+ ): Promise<string> {
150
157
  let participant: boolean;
151
158
  try {
152
159
  participant = (await client.getCaseParticipation(accessToken, caseId)).participant;
@@ -173,26 +180,30 @@ async function guardDeprecatedCase(
173
180
  }
174
181
 
175
182
  /**
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.
183
+ * The participation record (Task 9.5): after a successful open, tell the backend this learner opened
184
+ * this case (`POST /cases/{id}/enrollments` — idempotent per version, so re-opens are safe). It is
185
+ * part of the open (Task 17.25): when it fails, the open removes the clone it made and stops, so the
186
+ * re-run finds no folder in its way. The fork stays on GitHub, and the re-run uses it again.
187
+ *
188
+ * The session is resolved again rather than reused from the login check: the access token can
189
+ * expire while the fork and the clone run.
181
190
  */
182
191
  async function recordEnrollment(
183
192
  client: Pick<FitoApiClient, "meWithRefresh" | "createCaseEnrollment">,
184
193
  caseId: string,
194
+ targetDir: string,
185
195
  home: string,
186
- ): Promise<string | undefined> {
196
+ ): Promise<void> {
187
197
  try {
188
198
  const session = await resolveFitoSession(client, home);
189
199
  await client.createCaseEnrollment(session.tokens.accessToken, caseId);
190
- return undefined;
191
200
  } catch (error) {
201
+ rmSync(targetDir, { recursive: true, force: true });
192
202
  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.`
203
+ throw new Error(
204
+ `Fito could not record that you opened this case (${reason.trimEnd()})\n` +
205
+ ` Opening a case needs that record, so the open stopped and removed its folder.\n` +
206
+ ` Your fork on GitHub stays. Re-run /fito-case-open ${caseId} when Fito answers again.`,
196
207
  );
197
208
  }
198
209
  }
@@ -225,9 +236,6 @@ async function main(): Promise<void> {
225
236
  if (result.deprecationWarning) {
226
237
  console.error(`⚠ ${result.deprecationWarning}`);
227
238
  }
228
- if (result.enrollmentWarning) {
229
- console.error(`⚠ ${result.enrollmentWarning}`);
230
- }
231
239
  }
232
240
 
233
241
  /** Only auto-invoke the CLI when run directly (`node open.js …`), not when imported (e.g. by tests). */