From 62aaf5ef18b62109de20c56ce9a30266de43a0f5 Mon Sep 17 00:00:00 2001 From: FreshlyBrewedCode Date: Sun, 13 Sep 2026 10:03:09 +0000 Subject: [PATCH] feat(cli): close the command-surface gaps around maps, goals, and artifacts - `map archive` / `map unarchive`, with `map list --all`; a map-scoped command against an archived map names the archive and how to restore it instead of claiming the map does not exist. - `map create --allowed-step-types` and `map restrict` set or clear a map's allowed step types; `map show` reports the current value. - `context --map ` renders artifact (and step) scope without WAYFUL_MAP set. - `goal show` reports a goal's description, body, required output slots, and current attachments. - `artifact show` dereferences an attached markdown `file:` ref and prints its content, keeping opaque refs opaque and refusing unattached refs. Both filesystem and GitHub backends implement the new MapStore operations: filesystem stamps `archived_at` in `map.toml`; GitHub closes and reopens the map issue and carries the restriction in the issue body. --- packages/cli/src/backend/MapStore.ts | 27 ++ packages/cli/src/backend/backend.ts | 6 +- packages/cli/src/backend/filesystem/decode.ts | 4 + .../src/backend/filesystem/layer/ops/map.ts | 68 ++++- .../src/backend/github/github-backend.live.ts | 37 ++- .../cli/src/backend/github/goalStore.test.ts | 1 + packages/cli/src/backend/github/map.ts | 1 + .../cli/src/backend/github/mapStore.test.ts | 119 ++++++++- packages/cli/src/backend/github/mapStore.ts | 76 +++++- .../src/backend/github/readArtifact.test.ts | 1 + .../cli/src/backend/github/snapshot.test.ts | 1 + .../cli/src/backend/github/stepStore.test.ts | 1 + .../src/cli/commands/artifact-goal.test.ts | 33 ++- packages/cli/src/cli/commands/artifact.ts | 29 +- .../src/cli/commands/command-surface.test.ts | 248 ++++++++++++++++++ .../src/cli/commands/context-project.test.ts | 4 +- packages/cli/src/cli/commands/context.ts | 10 +- packages/cli/src/cli/commands/goal.ts | 55 +++- packages/cli/src/cli/commands/map.test.ts | 2 + packages/cli/src/cli/commands/map.ts | 154 ++++++++++- packages/cli/src/domain/model.ts | 7 + packages/cli/src/scope.ts | 25 +- packages/cli/src/server/server-github.test.ts | 4 + packages/cli/src/server/server.test.ts | 1 + packages/cli/test/support/domain-fixtures.ts | 1 + .../cli/test/support/map-store-contract.ts | 81 ++++++ 26 files changed, 932 insertions(+), 64 deletions(-) create mode 100644 packages/cli/src/cli/commands/command-surface.test.ts diff --git a/packages/cli/src/backend/MapStore.ts b/packages/cli/src/backend/MapStore.ts index c97e40f..bb531aa 100644 --- a/packages/cli/src/backend/MapStore.ts +++ b/packages/cli/src/backend/MapStore.ts @@ -36,8 +36,13 @@ export interface MapHandle { export class MapStore extends Context.Service< MapStore, { + /** + * Every map, in no particular order. Archived maps are omitted unless + * `includeArchived` is set, so the default listing is the live set. + */ readonly listMaps: ( project: ProjectHandle, + options?: { readonly includeArchived?: boolean }, ) => Effect.Effect, WayfulError>; readonly createMap: ( project: ProjectHandle, @@ -46,6 +51,8 @@ export class MapStore extends Context.Service< readonly start: string; readonly goal: string; readonly goalBody: string; + /** Narrows the map's allowed step types; absent permits every project type. */ + readonly allowedStepTypes?: readonly string[]; }, ) => Effect.Effect; readonly openMap: ( @@ -53,6 +60,26 @@ export class MapStore extends Context.Service< name: string, ) => Effect.Effect; + /** + * Archives a live map, hiding it from the default listing while keeping + * every step and goal intact. Fails if the map is absent or already + * archived. + */ + readonly archiveMap: (project: ProjectHandle, name: string) => Effect.Effect; + /** Restores an archived map with its steps and goals intact. Fails if it is not archived. */ + readonly unarchiveMap: ( + project: ProjectHandle, + name: string, + ) => Effect.Effect; + /** + * Sets or clears a map's allowed-step-types restriction. `undefined` + * clears it, permitting every project type; a list narrows it. + */ + readonly setAllowedStepTypes: ( + map: MapHandle, + allowed: readonly string[] | undefined, + ) => Effect.Effect; + readonly listSteps: (map: MapHandle) => Effect.Effect, WayfulError>; readonly createStep: ( map: MapHandle, diff --git a/packages/cli/src/backend/backend.ts b/packages/cli/src/backend/backend.ts index 38f3ca5..642a2bc 100644 --- a/packages/cli/src/backend/backend.ts +++ b/packages/cli/src/backend/backend.ts @@ -22,9 +22,13 @@ export const RoutedMapStore = Layer.effect( const storeFor = (backend: ProjectBackend) => (backend === "github" ? github : local); return MapStore.of({ - listMaps: (project) => storeFor(project.backend).listMaps(project), + listMaps: (project, options) => storeFor(project.backend).listMaps(project, options), createMap: (project, options) => storeFor(project.backend).createMap(project, options), openMap: (project, name) => storeFor(project.backend).openMap(project, name), + archiveMap: (project, name) => storeFor(project.backend).archiveMap(project, name), + unarchiveMap: (project, name) => storeFor(project.backend).unarchiveMap(project, name), + setAllowedStepTypes: (map, allowed) => + storeFor(map.project.backend).setAllowedStepTypes(map, allowed), listSteps: (map) => storeFor(map.project.backend).listSteps(map), createStep: (map, step) => storeFor(map.project.backend).createStep(map, step), saveStep: (map, step) => storeFor(map.project.backend).saveStep(map, step), diff --git a/packages/cli/src/backend/filesystem/decode.ts b/packages/cli/src/backend/filesystem/decode.ts index 70588c5..c084275 100644 --- a/packages/cli/src/backend/filesystem/decode.ts +++ b/packages/cli/src/backend/filesystem/decode.ts @@ -71,6 +71,7 @@ export function decodeMapMetadata(data: unknown, expectedName: string): MapMetad "start", "step_id_counter", "allowed_step_types", + "archived_at", "created_at", "updated_at", ]); @@ -93,11 +94,14 @@ export function decodeMapMetadata(data: unknown, expectedName: string): MapMetad } const createdAt = timestamp(record.created_at, "map created_at"); const updatedAt = timestamp(record.updated_at, "map updated_at"); + const archivedAt = + record.archived_at === undefined ? undefined : timestamp(record.archived_at, "map archived_at"); return { format_version: CURRENT_FORMAT_VERSION, name: expectedName, start: record.start as string, allowed_step_types: allowedStepTypes, + archived: archivedAt !== undefined, created_at: createdAt, updated_at: updatedAt, }; diff --git a/packages/cli/src/backend/filesystem/layer/ops/map.ts b/packages/cli/src/backend/filesystem/layer/ops/map.ts index de6e729..20d8197 100644 --- a/packages/cli/src/backend/filesystem/layer/ops/map.ts +++ b/packages/cli/src/backend/filesystem/layer/ops/map.ts @@ -37,8 +37,42 @@ export function makeMapOps(fs: FileSystem.FileSystem, path: Path.Path) { return { project, name, metadata }; }); + /** + * The raw `map.toml` document behind a map, so a rewrite preserves fields + * this layer does not model (`step_id_counter`). Decoding is left to the + * caller; this only guarantees the file exists and parses as a TOML table. + */ + const readMapDocument = ( + project: ProjectHandle, + name: string, + ): Effect.Effect< + { readonly file: string; readonly data: Record }, + WayfulError + > => + Effect.gen(function* () { + yield* liftSync(() => identifier(name, "map name")); + const file = mapFile(path, mapDir(path, project.root, name)); + const exists = yield* fs.exists(file).pipe(Effect.mapError(accessError)); + if (!exists) return yield* fail(`map '${name}' does not exist.`); + const text = yield* readTextFile(fs, file, `cannot read ${file}.`); + const data = yield* liftSync(() => parseToml(text, file)); + if (!data || typeof data !== "object" || Array.isArray(data)) + return yield* fail(`malformed map metadata in ${file}.`); + return { file, data: data as Record }; + }); + + /** Rewrites a map's metadata document, advancing `updated_at` from the injected clock. */ + const writeMapDocument = ( + file: string, + data: Record, + ): Effect.Effect => + Effect.gen(function* () { + const now = yield* nowISO; + yield* writeAtomic(fs, file, stringifyToml({ ...data, updated_at: now })); + }); + return { - listMaps: (project: ProjectHandle) => + listMaps: (project: ProjectHandle, options: { readonly includeArchived?: boolean } = {}) => Effect.gen(function* () { const dir = mapsDir(path, project.root); const exists = yield* fs.exists(dir).pipe(Effect.mapError(accessError)); @@ -58,8 +92,9 @@ export function makeMapOps(fs: FileSystem.FileSystem, path: Path.Path) { (name) => `${name}/map.toml`, (name) => openMapHandle(project, name), ); + const records = result.records.map((handle) => handle.metadata); return { - records: result.records.map((handle) => handle.metadata), + records: options.includeArchived ? records : records.filter((map) => !map.archived), errors: result.errors, }; }), @@ -71,11 +106,13 @@ export function makeMapOps(fs: FileSystem.FileSystem, path: Path.Path) { start, goal, goalBody, + allowedStepTypes, }: { readonly name: string; readonly start: string; readonly goal: string; readonly goalBody: string; + readonly allowedStepTypes?: readonly string[]; }, ) => Effect.gen(function* () { @@ -105,6 +142,7 @@ export function makeMapOps(fs: FileSystem.FileSystem, path: Path.Path) { name, start: trimmedStart, step_id_counter: 1, + ...(allowedStepTypes !== undefined ? { allowed_step_types: allowedStepTypes } : {}), created_at: now, updated_at: now, }), @@ -128,5 +166,31 @@ export function makeMapOps(fs: FileSystem.FileSystem, path: Path.Path) { }), openMap: (project: ProjectHandle, name: string) => openMapHandle(project, name), + + archiveMap: (project: ProjectHandle, name: string) => + Effect.gen(function* () { + const { file, data } = yield* readMapDocument(project, name); + if (data.archived_at !== undefined) + return yield* fail(`map '${name}' is already archived.`); + const now = yield* nowISO; + yield* writeMapDocument(file, { ...data, archived_at: now }); + }), + + unarchiveMap: (project: ProjectHandle, name: string) => + Effect.gen(function* () { + const { file, data } = yield* readMapDocument(project, name); + if (data.archived_at === undefined) return yield* fail(`map '${name}' is not archived.`); + const { archived_at: _archived, ...rest } = data; + yield* writeMapDocument(file, rest); + }), + + setAllowedStepTypes: (map: MapHandle, allowed: readonly string[] | undefined) => + Effect.gen(function* () { + const { file, data } = yield* readMapDocument(map.project, map.name); + const next = { ...data }; + if (allowed === undefined) delete next.allowed_step_types; + else next.allowed_step_types = allowed; + yield* writeMapDocument(file, next); + }), }; } diff --git a/packages/cli/src/backend/github/github-backend.live.ts b/packages/cli/src/backend/github/github-backend.live.ts index 9d7e487..c9dd733 100644 --- a/packages/cli/src/backend/github/github-backend.live.ts +++ b/packages/cli/src/backend/github/github-backend.live.ts @@ -4,13 +4,7 @@ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { - addSubIssue, - createIssue, - getIssue, - listSubIssues, - updateIssue, -} from "@backend/github/api"; +import { addSubIssue, createIssue, getIssue, listSubIssues } from "@backend/github/api"; import { SUB_ISSUE_CAP, subIssueCapError } from "@backend/github/subIssues"; import { MapStore } from "@backend/MapStore"; import { @@ -316,29 +310,32 @@ suite(`live GitHub backend suite against ${process.env[LIVE_REPO_ENV] ?? "a scra }), ); - // Archive and reopen. Closing the map issue is the archive: it disappears - // from `listMaps`/`openMap` but its sub-issues persist, so reopening - // restores the map intact. A fresh run gives fresh, unmemoized reads. + // Archive and reopen through the backend's own operations. Closing the map + // issue is the archive: it disappears from `listMaps` but its sub-issues + // persist, so reopening restores the map intact. A fresh run gives fresh, + // unmemoized reads. await runLive( Effect.gen(function* () { const store = yield* MapStore; - yield* updateIssue(target.ref, target.token, created.mapNumber, { - state: "closed", - state_reason: "completed", - }); + yield* store.archiveMap(target.project, mapName); yield* poll( `map '${mapName}' to be archived`, store.listMaps(target.project), (read) => !read.records.some((map) => map.name === mapName), ); - const absent = yield* Effect.flip(store.openMap(target.project, mapName)); - expect(absent.message).toContain("does not exist"); + const archived = yield* poll( + `map '${mapName}' to read back archived`, + store.openMap(target.project, mapName), + (map) => map.metadata.archived, + ); + expect(archived.metadata.archived).toBe(true); - yield* updateIssue(target.ref, target.token, created.mapNumber, { state: "open" }); const reopened = yield* poll( - `map '${mapName}' to reappear`, - store.openMap(target.project, mapName), - () => true, + `map '${mapName}' to be restored`, + store + .unarchiveMap(target.project, mapName) + .pipe(Effect.andThen(store.openMap(target.project, mapName))), + (map) => !map.metadata.archived, ); expect(reopened.number).toBe(created.mapNumber); yield* poll( diff --git a/packages/cli/src/backend/github/goalStore.test.ts b/packages/cli/src/backend/github/goalStore.test.ts index 95c0ca7..42e2e2a 100644 --- a/packages/cli/src/backend/github/goalStore.test.ts +++ b/packages/cli/src/backend/github/goalStore.test.ts @@ -24,6 +24,7 @@ function metadata(name: string): MapMetadata { name, start: "here", allowed_step_types: undefined, + archived: false, created_at: ISSUE_TIME, updated_at: ISSUE_TIME, }; diff --git a/packages/cli/src/backend/github/map.ts b/packages/cli/src/backend/github/map.ts index 098c300..b596fd0 100644 --- a/packages/cli/src/backend/github/map.ts +++ b/packages/cli/src/backend/github/map.ts @@ -38,6 +38,7 @@ export function decodeMapIssue(issue: GithubIssue): MapMetadata { name, start: nonEmpty(issue.title, "map start"), allowed_step_types: decodeAllowedStepTypes(data.allowed_step_types), + archived: issue.state === "closed", created_at: timestamp(issue.created_at, `map #${issue.number} created_at`), updated_at: timestamp(issue.updated_at, `map #${issue.number} updated_at`), }; diff --git a/packages/cli/src/backend/github/mapStore.test.ts b/packages/cli/src/backend/github/mapStore.test.ts index 02abd78..e6c1bb1 100644 --- a/packages/cli/src/backend/github/mapStore.test.ts +++ b/packages/cli/src/backend/github/mapStore.test.ts @@ -46,6 +46,7 @@ function metadata(name: string, start: string): MapMetadata { name, start, allowed_step_types: undefined, + archived: false, created_at: ISSUE_TIME, updated_at: ISSUE_TIME, }; @@ -266,7 +267,7 @@ describe("GithubMapStore: openMap", () => { expect(map.metadata).toEqual(metadata("beta", "second")); }); - test("reports a closed map as absent", async () => { + test("reports a genuinely missing map as absent", async () => { const error = await run( () => jsonResponse(200, []), Effect.gen(function* () { @@ -277,6 +278,18 @@ describe("GithubMapStore: openMap", () => { expect(error.message).toBe("map 'archived' does not exist."); }); + test("resolves a closed map as archived rather than absent", async () => { + const map = await run( + () => jsonResponse(200, [mapIssue(9, "alpha", { title: "here", state: "closed" })]), + Effect.gen(function* () { + const store = yield* MapStore; + return yield* store.openMap(project, "alpha"); + }), + ); + expect(map.metadata.archived).toBe(true); + expect(map.number).toBe(9); + }); + test("uses the enterprise host resolved from the remote", async () => { let seen = ""; await run( @@ -295,3 +308,107 @@ describe("GithubMapStore: openMap", () => { ); }); }); + +describe("GithubMapStore: archiving and restrictions", () => { + test("listMaps includeArchived returns closed map issues marked archived", async () => { + const result = await run( + () => jsonResponse(200, [mapIssue(9, "alpha", { title: "here", state: "closed" })]), + Effect.gen(function* () { + const store = yield* MapStore; + return yield* store.listMaps(project, { includeArchived: true }); + }), + ); + expect(result.records).toEqual([{ ...metadata("alpha", "here"), archived: true }]); + }); + + test("archiveMap closes the map issue as not_planned", async () => { + const patches: unknown[] = []; + await run( + (request) => { + if (request.method === "PATCH") { + patches.push(JSON.parse(bodyText(request))); + return jsonResponse(200, issueJson(9)); + } + return jsonResponse(200, [mapIssue(9, "alpha", { title: "here" })]); + }, + Effect.gen(function* () { + const store = yield* MapStore; + yield* store.archiveMap(project, "alpha"); + }), + ); + expect(patches).toEqual([{ state: "closed", state_reason: "not_planned" }]); + }); + + test("unarchiveMap reopens the map issue and refuses a live map", async () => { + const patches: unknown[] = []; + let state = "closed"; + const error = await run( + (request) => { + if (request.method === "PATCH") { + const patch = JSON.parse(bodyText(request)) as { state: "open" | "closed" }; + patches.push(patch); + state = patch.state; + return jsonResponse(200, issueJson(9, { state })); + } + return jsonResponse(200, [mapIssue(9, "alpha", { title: "here", state })]); + }, + Effect.gen(function* () { + const store = yield* MapStore; + yield* store.unarchiveMap(project, "alpha"); + return yield* Effect.flip(store.unarchiveMap(project, "alpha")); + }), + ); + expect(patches).toEqual([{ state: "open" }]); + expect(error.message).toContain("not archived"); + }); + + test("createMap records an allowed step types restriction in the issue body", async () => { + let created: HttpClientRequest.HttpClientRequest | undefined; + await run( + (request) => { + const pathname = new URL(request.url).pathname; + if (request.method === "GET") return jsonResponse(200, []); + if (pathname.endsWith("/sub_issues")) return jsonResponse(201, issueJson(13)); + const body = JSON.parse(bodyText(request)) as { labels: string[] }; + if (!body.labels.includes("wayful:map")) return jsonResponse(201, issueJson(13)); + created = request; + return jsonResponse(201, issueJson(12, { title: "here" })); + }, + Effect.gen(function* () { + const store = yield* MapStore; + yield* store.createMap(project, { + name: "redesign", + start: "here", + goal: "done", + goalBody: "", + allowedStepTypes: ["task"], + }); + }), + ); + const payload = JSON.parse(bodyText(created!)) as { body: string }; + expect(payload.body).toContain("allowed_step_types"); + expect(payload.body).toContain("task"); + }); + + test("setAllowedStepTypes patches the map body, and clearing removes the key", async () => { + const patches: string[] = []; + await run( + (request) => { + if (request.method === "PATCH") { + patches.push((JSON.parse(bodyText(request)) as { body: string }).body); + return jsonResponse(200, issueJson(9)); + } + return jsonResponse(200, [mapIssue(9, "alpha", { title: "here" })]); + }, + Effect.gen(function* () { + const store = yield* MapStore; + const map = yield* store.openMap(project, "alpha"); + yield* store.setAllowedStepTypes(map, ["task"]); + yield* store.setAllowedStepTypes(map, undefined); + }), + ); + expect(patches[0]).toContain("allowed_step_types"); + expect(patches[0]).toContain("task"); + expect(patches[1]).not.toContain("allowed_step_types"); + }); +}); diff --git a/packages/cli/src/backend/github/mapStore.ts b/packages/cli/src/backend/github/mapStore.ts index 7598619..7f72466 100644 --- a/packages/cli/src/backend/github/mapStore.ts +++ b/packages/cli/src/backend/github/mapStore.ts @@ -256,24 +256,24 @@ export const makeGithubMapStore = Effect.gen(function* () { ? fail(`map '${map.name}' is missing its github issue number.`) : Effect.succeed(map.number); - // Reads every open `wayful:map` issue once, decoding each into metadata and + // Reads every `wayful:map` issue once, decoding each into metadata and // keeping the issue number the decoder cannot carry (metadata is portable - // across backends; the number is not). - const readMaps = (project: ProjectHandle) => + // across backends; the number is not). Archived maps are closed issues: + // `includeArchived` widens the listing to every state, while the default + // `state=open` is the server-side half of hiding them. Callers that want the + // live set only (and trust the listing) can still filter on `archived`. + const readMaps = (project: ProjectHandle, options: { readonly includeArchived?: boolean } = {}) => withInfra( Effect.gen(function* () { const { ref, token } = yield* context(project); const issues = yield* listIssues(ref, token, { labels: [WAYFUL_MAP_LABEL], - state: "open", + state: options.includeArchived ? "all" : "open", }); const records: MapMetadata[] = []; const errors: DecodeError[] = []; const numbers = new Map(); for (const issue of issues) { - // `state=open` already excludes closed issues server-side; this is - // the belt to that braces, so a closed map is never returned. - if (issue.state !== "open") continue; const decoded = yield* Effect.result(liftSync(() => decodeMapIssue(issue))); if (Result.isFailure(decoded)) errors.push({ file: `#${issue.number}`, message: describeError(decoded.failure) }); @@ -286,10 +286,12 @@ export const makeGithubMapStore = Effect.gen(function* () { }), ); - const listMaps = (project: ProjectHandle) => - readMaps(project).pipe( + const listMaps = (project: ProjectHandle, options: { readonly includeArchived?: boolean } = {}) => + readMaps(project, options).pipe( Effect.map(({ records, errors }) => ({ - records: records.toSorted((a, b) => a.name.localeCompare(b.name)), + records: records + .filter((map) => options.includeArchived || !map.archived) + .toSorted((a, b) => a.name.localeCompare(b.name)), errors, })), ); @@ -301,11 +303,13 @@ export const makeGithubMapStore = Effect.gen(function* () { start, goal, goalBody, + allowedStepTypes, }: { readonly name: string; readonly start: string; readonly goal: string; readonly goalBody: string; + readonly allowedStepTypes?: readonly string[]; }, ) => withInfra( @@ -313,13 +317,13 @@ export const makeGithubMapStore = Effect.gen(function* () { yield* liftSync(() => identifier(name, "map name", true)); const trimmedStart = yield* liftSync(() => nonEmpty(start, "map start")); const trimmedGoal = yield* liftSync(() => nonEmpty(goal, "map goal")); - const { records } = yield* readMaps(project); + const { records } = yield* readMaps(project, { includeArchived: true }); if (records.some((map) => map.name === name)) return yield* fail(`map '${name}' already exists.`); const { ref, token } = yield* context(project); const map = yield* createIssue(ref, token, { title: trimmedStart, - body: encodeIssueBody("", mapIssueData(name)), + body: encodeIssueBody("", mapIssueData(name, allowedStepTypes)), labels: [WAYFUL_MAP_LABEL], }); // A map is born with one goal, itself a sub-issue, so the map is @@ -343,13 +347,56 @@ export const makeGithubMapStore = Effect.gen(function* () { withInfra( Effect.gen(function* () { yield* liftSync(() => identifier(name, "map name", true)); - const { records, numbers } = yield* readMaps(project); + const { records, numbers } = yield* readMaps(project, { includeArchived: true }); const metadata = records.find((candidate) => candidate.name === name); if (metadata === undefined) return yield* fail(`map '${name}' does not exist.`); return { project, name, metadata, number: numbers.get(name) }; }), ); + // Closing the map issue is the archive under GitHub: it carries the map's + // native state, so archiving hides it from the open-only listing while its + // step and goal sub-issues persist untouched and reopening restores it. + const archiveMap = (project: ProjectHandle, name: string) => + withInfra( + Effect.gen(function* () { + const map = yield* openMap(project, name); + if (map.metadata.archived) return yield* fail(`map '${name}' is already archived.`); + const { ref, token } = yield* context(project); + yield* updateIssue(ref, token, yield* mapNumber(map), { + state: "closed", + state_reason: "not_planned", + }); + yield* invalidateSnapshot(map); + }), + ); + + const unarchiveMap = (project: ProjectHandle, name: string) => + withInfra( + Effect.gen(function* () { + const map = yield* openMap(project, name); + if (!map.metadata.archived) return yield* fail(`map '${name}' is not archived.`); + const { ref, token } = yield* context(project); + yield* updateIssue(ref, token, yield* mapNumber(map), { state: "open" }); + yield* invalidateSnapshot(map); + }), + ); + + const setAllowedStepTypes = (map: MapHandle, allowed: readonly string[] | undefined) => + withInfra( + Effect.gen(function* () { + if (map.metadata.archived) + return yield* fail( + `map '${map.name}' is archived; run 'wayful map unarchive --map ${map.name}' to restore it.`, + ); + const { ref, token } = yield* context(map.project); + yield* updateIssue(ref, token, yield* mapNumber(map), { + body: encodeIssueBody("", mapIssueData(map.name, allowed)), + }); + yield* invalidateSnapshot(map); + }), + ); + const listSteps = (map: MapHandle): Effect.Effect, WayfulError> => withInfra( Effect.gen(function* () { @@ -634,6 +681,9 @@ export const makeGithubMapStore = Effect.gen(function* () { listMaps, createMap, openMap, + archiveMap, + unarchiveMap, + setAllowedStepTypes, listSteps, createStep, saveStep, diff --git a/packages/cli/src/backend/github/readArtifact.test.ts b/packages/cli/src/backend/github/readArtifact.test.ts index f675333..6a12613 100644 --- a/packages/cli/src/backend/github/readArtifact.test.ts +++ b/packages/cli/src/backend/github/readArtifact.test.ts @@ -25,6 +25,7 @@ const metadata: MapMetadata = { name: "plan", start: "here", allowed_step_types: undefined, + archived: false, created_at: ISSUE_TIME, updated_at: ISSUE_TIME, }; diff --git a/packages/cli/src/backend/github/snapshot.test.ts b/packages/cli/src/backend/github/snapshot.test.ts index e2f577f..c7f4757 100644 --- a/packages/cli/src/backend/github/snapshot.test.ts +++ b/packages/cli/src/backend/github/snapshot.test.ts @@ -28,6 +28,7 @@ const metadata: MapMetadata = { name: "plan", start: "here", allowed_step_types: undefined, + archived: false, created_at: ISSUE_TIME, updated_at: ISSUE_TIME, }; diff --git a/packages/cli/src/backend/github/stepStore.test.ts b/packages/cli/src/backend/github/stepStore.test.ts index fb62d7d..351a65d 100644 --- a/packages/cli/src/backend/github/stepStore.test.ts +++ b/packages/cli/src/backend/github/stepStore.test.ts @@ -24,6 +24,7 @@ function metadata(name: string): MapMetadata { name, start: "here", allowed_step_types: undefined, + archived: false, created_at: ISSUE_TIME, updated_at: ISSUE_TIME, }; diff --git a/packages/cli/src/cli/commands/artifact-goal.test.ts b/packages/cli/src/cli/commands/artifact-goal.test.ts index c064b54..c502a1d 100644 --- a/packages/cli/src/cli/commands/artifact-goal.test.ts +++ b/packages/cli/src/cli/commands/artifact-goal.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { readFile, rm, writeFile } from "node:fs/promises"; +import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { CURRENT_FORMAT_VERSION } from "@domain/model"; @@ -153,8 +153,10 @@ describe("artifacts, goals, and validation", () => { ); }); - test("artifact show prints an artifact's ref and kind, derived from its attachments", async () => { + test("artifact show prints an artifact's ref and kind plus the content behind a markdown file: ref", async () => { const project = await projectFixture(); + await mkdir(join(project, "docs"), { recursive: true }); + await writeFile(join(project, "docs", "brief.md"), "# Brief\n\nDetails.\n"); await writeStepFixture(project, { id: 1, name: "producer", @@ -169,6 +171,7 @@ describe("artifacts, goals, and validation", () => { const view = JSON.parse(result.stdout); expect(view.ref).toBe("file:docs/brief.md"); expect(view.kind).toBe("document"); + expect(view.content).toBe("# Brief\n\nDetails.\n"); const human = invoke( ["artifact", "show", "file:docs/brief.md", "--map", "plan"], @@ -176,12 +179,38 @@ describe("artifacts, goals, and validation", () => { ).stdout; expect(human).toContain("Ref: file:docs/brief.md"); expect(human).toContain("Kind: document"); + expect(human).toContain("Content:\n# Brief\n\nDetails."); expectCommandError( invoke(["artifact", "show", "file:does-not-exist", "--map", "plan"], project), ); }); + test("artifact show keeps an opaque ref opaque and refuses an unattached one", async () => { + const project = await projectFixture(); + await writeStepFixture(project, { + id: 1, + name: "producer", + outputs: [{ ref: "git:abc123", kind: "document" }], + }); + + const result = invoke(["artifact", "show", "git:abc123", "--map", "plan", "--json"], project); + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ ref: "git:abc123", kind: "document" }); + + const human = invoke(["artifact", "show", "git:abc123", "--map", "plan"], project).stdout; + expect(human).toContain("Ref: git:abc123"); + expect(human).toContain("only file: refs are dereferenced"); + + // A ref not attached anywhere on the map is refused, even though the file + // might exist: the readable set is closed. + await mkdir(join(project, "docs"), { recursive: true }); + await writeFile(join(project, "docs", "unattached.md"), "# Nope\n"); + expectCommandError( + invoke(["artifact", "show", "file:docs/unattached.md", "--map", "plan"], project), + ); + }); + test("artifact list prints every artifact on a map, uncapped, sorted by ref", async () => { const project = await projectFixture(); await writeStepFixture(project, { diff --git a/packages/cli/src/cli/commands/artifact.ts b/packages/cli/src/cli/commands/artifact.ts index e2a73a4..3d85cdf 100644 --- a/packages/cli/src/cli/commands/artifact.ts +++ b/packages/cli/src/cli/commands/artifact.ts @@ -1,8 +1,9 @@ import { Effect } from "effect"; import { Argument, Command } from "effect/unstable/cli"; +import { MapStore } from "@backend/MapStore"; import { liftSync } from "@backend/filesystem/documents"; -import { normalizeRef } from "@domain/artifact-ref"; +import { classifyRef, normalizeRef } from "@domain/artifact-ref"; import { buildSnapshot, fail, resolveMap, resolveProject } from "@/scope"; import { jsonFlag, mapFlag } from "@cli/flags"; import { handle, printOutput } from "@cli/render"; @@ -27,6 +28,7 @@ const artifactShowCommand = Command.make( Effect.gen(function* () { const parent = yield* artifactParent; const root = yield* wayfulRoot; + const mapStore = yield* MapStore; const project = yield* resolveProject(root.project); const map = yield* resolveMap(parent.map, project); const normalizedRef = yield* liftSync(() => normalizeRef(ref)); @@ -34,7 +36,30 @@ const artifactShowCommand = Command.make( if (errors.length) return yield* fail(errors[0]!.message); const target = snapshot.artifacts.find((a) => a.ref === normalizedRef); if (!target) return yield* fail(`artifact '${normalizedRef}' does not exist.`); - const human = [`Ref: ${target.ref}`, `Kind: ${target.kind}`].join("\n"); + // Only markdown file: refs resolve to bytes; every other scheme is + // opaque, so its ref and kind are the whole answer. A readable ref is + // dereferenced through the backend, which enforces the closed set. + if (classifyRef(normalizedRef).kind === "file") { + const content = yield* mapStore.readArtifact(map, normalizedRef); + const human = [ + `Ref: ${content.ref}`, + `Kind: ${target.kind}`, + "Content:", + content.content || "(empty)", + ...(content.truncated ? ["(truncated)"] : []), + ].join("\n"); + yield* printOutput( + json, + { ...target, content: content.content, truncated: content.truncated }, + human, + ); + return; + } + const human = [ + `Ref: ${target.ref}`, + `Kind: ${target.kind}`, + "Content: unavailable; only file: refs are dereferenced.", + ].join("\n"); yield* printOutput(json, target, human); }), ), diff --git a/packages/cli/src/cli/commands/command-surface.test.ts b/packages/cli/src/cli/commands/command-surface.test.ts new file mode 100644 index 0000000..313e085 --- /dev/null +++ b/packages/cli/src/cli/commands/command-surface.test.ts @@ -0,0 +1,248 @@ +import { describe, expect, test } from "bun:test"; +import { readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { CURRENT_FORMAT_VERSION } from "@domain/model"; +import { expectCommandError, makeCliHarness } from "@test/support/cli-harness"; + +const { invoke, projectFixture, writeGoal, writeStep, writeStepFixture } = makeCliHarness(); + +/** Adds a second project type, so an excluded type is a real choice rather than a missing one. */ +async function addType(project: string, name: string) { + await writeFile( + join(project, ".wayful", "types", `${name}.md`), + `---\nformat_version: ${CURRENT_FORMAT_VERSION}\nname: ${name}\ndescription: Another type\nrequired_inputs: []\nrequired_outputs: []\n---\n`, + ); +} + +describe("map archiving", () => { + test("archives, hides from the default listing, reports archived on map-scoped commands, and restores intact", async () => { + const project = await projectFixture(); + await writeStep(project, "work", 1); + await writeGoal(project, "ship", { description: "Ship it" }); + + expect(invoke(["map", "archive", "--map", "plan"], project).exitCode).toBe(0); + + expect(invoke(["map", "list"], project).stdout).not.toContain("plan"); + const all = invoke(["map", "list", "--all"], project); + expect(all.exitCode).toBe(0); + expect(all.stdout).toContain("plan (archived): here"); + const allJson = JSON.parse(invoke(["map", "list", "--all", "--json"], project).stdout); + expect(allJson[0].name).toBe("plan"); + expect(allJson[0].archived).toBe(true); + + // A map-scoped command names the archive and the way back, rather than + // claiming the map does not exist. + const scoped = invoke(["map", "show", "--map", "plan"], project); + expectCommandError(scoped); + expect(scoped.stderr).toContain("archived"); + expect(scoped.stderr).toContain("wayful map unarchive --map plan"); + expect(invoke(["step", "show", "1", "--map", "plan"], project).exitCode).toBe(2); + + // Archiving an already-archived map is refused. + expectCommandError(invoke(["map", "archive", "--map", "plan"], project)); + + expect(invoke(["map", "unarchive", "--map", "plan"], project).exitCode).toBe(0); + expect(invoke(["map", "list"], project).stdout).toContain("plan: here"); + expect(invoke(["step", "show", "1", "--map", "plan"], project).exitCode).toBe(0); + expect(invoke(["goal", "show", "--map", "plan", "--goal", "ship"], project).exitCode).toBe(0); + expectCommandError(invoke(["map", "unarchive", "--map", "plan"], project)); + + const mapFile = await readFile(join(project, ".wayful", "maps", "plan", "map.toml"), "utf8"); + expect(mapFile).not.toContain("archived_at"); + }); + + test("a missing map still reports that it does not exist", async () => { + const project = await projectFixture(); + const result = invoke(["map", "archive", "--map", "ghost"], project); + expectCommandError(result); + expect(result.stderr).toContain("does not exist"); + }); +}); + +describe("map type restrictions", () => { + test("map create accepts a restriction and step create refuses an excluded type", async () => { + const project = await projectFixture(); + await addType(project, "research"); + + expect( + invoke( + [ + "map", + "create", + "--map", + "focused", + "--start", + "here", + "--goal", + "done", + "--allowed-step-types", + "task", + ], + project, + ).exitCode, + ).toBe(0); + expect( + JSON.parse(invoke(["map", "show", "--map", "focused", "--json"], project).stdout) + .allowed_step_types, + ).toEqual(["task"]); + expect(invoke(["map", "show", "--map", "focused"], project).stdout).toContain( + "Allowed step types: task", + ); + + expect( + invoke( + ["step", "create", "work", "--map", "focused", "--type", "task", "--description", "Do it"], + project, + ).exitCode, + ).toBe(0); + const refused = invoke( + [ + "step", + "create", + "study", + "--map", + "focused", + "--type", + "research", + "--description", + "Read it", + ], + project, + ); + expectCommandError(refused); + expect(refused.stderr).toContain("not allowed"); + + expectCommandError( + invoke( + [ + "map", + "create", + "--map", + "bad", + "--start", + "here", + "--goal", + "done", + "--allowed-step-types", + "ghost", + ], + project, + ), + ); + }); + + test("restrict sets and clears the restriction on an existing map", async () => { + const project = await projectFixture(); + await addType(project, "research"); + + expect( + invoke(["map", "restrict", "--map", "plan", "--allowed-step-types", "task"], project) + .exitCode, + ).toBe(0); + expect( + JSON.parse(invoke(["map", "show", "--map", "plan", "--json"], project).stdout) + .allowed_step_types, + ).toEqual(["task"]); + expectCommandError( + invoke( + [ + "step", + "create", + "study", + "--map", + "plan", + "--type", + "research", + "--description", + "Read it", + ], + project, + ), + ); + + expect(invoke(["map", "restrict", "--map", "plan", "--clear"], project).exitCode).toBe(0); + expect( + JSON.parse(invoke(["map", "show", "--map", "plan", "--json"], project).stdout) + .allowed_step_types, + ).toBeUndefined(); + expect( + invoke( + [ + "step", + "create", + "study", + "--map", + "plan", + "--type", + "research", + "--description", + "Read it", + ], + project, + ).exitCode, + ).toBe(0); + + expectCommandError(invoke(["map", "restrict", "--map", "plan"], project)); + expectCommandError( + invoke( + ["map", "restrict", "--map", "plan", "--clear", "--allowed-step-types", "task"], + project, + ), + ); + expectCommandError( + invoke(["map", "restrict", "--map", "plan", "--allowed-step-types", "ghost"], project), + ); + }); +}); + +describe("context --map", () => { + test("renders artifact scope with no WAYFUL_MAP set", async () => { + const project = await projectFixture(); + await writeStepFixture(project, { + id: 1, + name: "producer", + outputs: [{ ref: "file:docs/doc.md", kind: "document" }], + }); + + const result = invoke(["context", "file:docs/doc.md", "--map", "plan", "--json"], project); + expect(result.exitCode).toBe(0); + const view = JSON.parse(result.stdout); + expect(view.scope).toBe("artifact"); + expect(view.map).toBe("plan"); + expect(view.ref).toBe("file:docs/doc.md"); + }); +}); + +describe("goal show", () => { + test("reports description, body, required outputs, and current attachments", async () => { + const project = await projectFixture(); + await writeGoal(project, "ship", { + description: "Ship it", + outputs: [ + { ref: "file:proof.md", slot: "evidence" }, + { ref: "git:notes", kind: "document" }, + ], + requiredOutputs: [{ name: "evidence", kind: "artifact" }], + }); + + const result = invoke(["goal", "show", "--map", "plan", "--goal", "ship", "--json"], project); + expect(result.exitCode).toBe(0); + const view = JSON.parse(result.stdout); + expect(view.name).toBe("ship"); + expect(view.description).toBe("Ship it"); + expect(view.required_outputs).toEqual([{ name: "evidence", kind: "artifact" }]); + expect(view.outputs).toEqual([ + { ref: "file:proof.md", slot: "evidence" }, + { ref: "git:notes", kind: "document" }, + ]); + + const human = invoke(["goal", "show", "--map", "plan", "--goal", "ship"], project).stdout; + expect(human).toContain("ship: Ship it"); + expect(human).toContain("Required outputs:\n- evidence (artifact)"); + expect(human).toContain("- evidence: file:proof.md"); + expect(human).toContain("- git:notes (document)"); + + expectCommandError(invoke(["goal", "show", "--map", "plan", "--goal", "missing"], project)); + }); +}); diff --git a/packages/cli/src/cli/commands/context-project.test.ts b/packages/cli/src/cli/commands/context-project.test.ts index d37ba09..5b779e3 100644 --- a/packages/cli/src/cli/commands/context-project.test.ts +++ b/packages/cli/src/cli/commands/context-project.test.ts @@ -41,11 +41,11 @@ describe("project scope", () => { expect(human).toContain("Maps:\n- none"); }); - test("context --help documents no --map flag and no --limit flag", async () => { + test("context --help documents --map, --since, and --json but no --limit flag", async () => { const project = await temporaryDirectory(); const result = invoke(["context", "--help"], project); expect(result.exitCode).toBe(0); - expect(result.stdout).not.toContain("--map "); + expect(result.stdout).toContain("--map "); expect(result.stdout).not.toContain("--limit"); expect(result.stdout).toContain("--since"); expect(result.stdout).toContain("--json"); diff --git a/packages/cli/src/cli/commands/context.ts b/packages/cli/src/cli/commands/context.ts index 0e0d9fc..a520ffa 100644 --- a/packages/cli/src/cli/commands/context.ts +++ b/packages/cli/src/cli/commands/context.ts @@ -17,7 +17,7 @@ import { normalizeRef, SCHEME } from "@domain/artifact-ref"; import type { DecodeError } from "@domain/model"; import { describeToken, parseReference, resolveToken } from "@domain/reference"; import { buildSnapshot, fail, resolveMap, resolveProject, resolveReferencedMap } from "@/scope"; -import { jsonFlag } from "@cli/flags"; +import { jsonFlag, mapFlag } from "@cli/flags"; import { handle, printOutput } from "@cli/render"; import { renderArtifactContext, @@ -52,8 +52,8 @@ const refArgument = Argument.string("ref").pipe( // sibling. const contextCommand = Command.make( "context", - { ref: refArgument, since: sinceFlag, json: jsonFlag }, - ({ ref, since, json }) => + { ref: refArgument, map: mapFlag, since: sinceFlag, json: jsonFlag }, + ({ ref, map: contextMap, since, json }) => handle( json, Effect.gen(function* () { @@ -112,7 +112,7 @@ const contextCommand = Command.make( // reference correctly is what's tested). if (SCHEME.test(ref.value)) { const normalizedRef = yield* liftSync(() => normalizeRef(ref.value)); - const map = yield* resolveMap(Option.none(), project); + const map = yield* resolveMap(contextMap, project); const { snapshot, errors } = yield* buildSnapshot(map); const target = snapshot.artifacts.find((a) => a.ref === normalizedRef); if (!target) return yield* fail(`artifact '${normalizedRef}' does not exist.`); @@ -155,7 +155,7 @@ const contextCommand = Command.make( } // reference.kind === "step" - const map = yield* resolveReferencedMap(reference.map, Option.none(), project); + const map = yield* resolveReferencedMap(reference.map, contextMap, project); const { snapshot, errors } = yield* buildSnapshot(map); const target = resolveToken(reference.token, snapshot.steps); if (!target) return yield* fail(`step '${describeToken(reference.token)}' does not exist.`); diff --git a/packages/cli/src/cli/commands/goal.ts b/packages/cli/src/cli/commands/goal.ts index 36f4e1d..aa03e62 100644 --- a/packages/cli/src/cli/commands/goal.ts +++ b/packages/cli/src/cli/commands/goal.ts @@ -5,7 +5,7 @@ import { MapStore } from "@backend/MapStore"; import { liftSync } from "@backend/filesystem/documents"; import { normalizeRef } from "@domain/artifact-ref"; import { WayfulError } from "@domain/errors"; -import { attachmentOK } from "@domain/graph"; +import { attachmentOK, normalizedAttachments } from "@domain/graph"; import { identifier, nonEmpty, slots } from "@domain/identifier"; import type { Slot } from "@domain/identifier"; import { CURRENT_FORMAT_VERSION, type Attachment } from "@domain/model"; @@ -37,6 +37,51 @@ const goalListCommand = Command.make("list", { json: jsonFlag }, ({ json }) => ), ).pipe(Command.withDescription("List goals")); +const goalShowCommand = Command.make( + "show", + { + goal: Flag.string("goal").pipe(Flag.withMetavar("NAME"), Flag.withDescription("Goal name")), + json: jsonFlag, + }, + ({ goal, json }) => + handle( + json, + Effect.gen(function* () { + const parent = yield* goalParent; + const mapStore = yield* MapStore; + const root = yield* wayfulRoot; + const project = yield* resolveProject(root.project); + const map = yield* resolveMap(parent.map, project); + const goals = yield* strict(yield* mapStore.listGoals(map)); + const resolvedGoalName = yield* liftSync(() => identifier(goal, "goal name")); + const target = goals.find((candidate) => candidate.name === resolvedGoalName); + if (!target) return yield* fail(`goal '${resolvedGoalName}' does not exist.`); + const requiredOutputs = target.required_outputs.length + ? target.required_outputs.map((slot) => `- ${slot.name} (${slot.kind})`) + : ["- none"]; + const attachments = normalizedAttachments(target.outputs); + const attachmentLines = attachments.length + ? attachments.map((attachment) => + attachment.slot !== undefined + ? `- ${attachment.slot}: ${attachment.ref}` + : `- ${attachment.ref} (${attachment.kind})`, + ) + : ["- none"]; + const human = [ + `${target.name}: ${target.description}`, + ...bodyLines(target.body), + "Required outputs:", + ...requiredOutputs, + "Attachments:", + ...attachmentLines, + ].join("\n"); + yield* printOutput(json, target, human); + }), + ), +).pipe( + Command.withDescription("Show a goal's description, body, required outputs, and attachments"), +); + function parseRequiredOutputs(json: string): readonly Slot[] { let parsed: unknown; try { @@ -191,5 +236,11 @@ const goalSatisfyCommand = Command.make( ).pipe(Command.withDescription("Satisfy a goal once its required output slots are filled")); export const goalCommand = goalParent.pipe( - Command.withSubcommands([goalListCommand, goalAddCommand, goalOutputCommand, goalSatisfyCommand]), + Command.withSubcommands([ + goalListCommand, + goalShowCommand, + goalAddCommand, + goalOutputCommand, + goalSatisfyCommand, + ]), ); diff --git a/packages/cli/src/cli/commands/map.test.ts b/packages/cli/src/cli/commands/map.test.ts index fdb6565..114e395 100644 --- a/packages/cli/src/cli/commands/map.test.ts +++ b/packages/cli/src/cli/commands/map.test.ts @@ -122,11 +122,13 @@ describe("maps, types, and readable rendering", () => { format_version: CURRENT_FORMAT_VERSION, name: "plan", start: "here", + archived: false, }, { format_version: CURRENT_FORMAT_VERSION, name: "release-plan", start: "now", + archived: false, }, ]); }); diff --git a/packages/cli/src/cli/commands/map.ts b/packages/cli/src/cli/commands/map.ts index d2b1450..e993b4e 100644 --- a/packages/cli/src/cli/commands/map.ts +++ b/packages/cli/src/cli/commands/map.ts @@ -1,13 +1,16 @@ -import { Console, Effect, Result, Schema } from "effect"; +import { Console, Effect, Option, Result, Schema } from "effect"; import { Command, Flag } from "effect/unstable/cli"; import { MapStore } from "@backend/MapStore"; -import { MapMetadataError } from "@domain/errors"; +import { ProjectStore, type ProjectHandle } from "@backend/ProjectStore"; +import { liftSync } from "@backend/filesystem/documents"; +import { MapMetadataError, WayfulError } from "@domain/errors"; import { deriveArtifacts, nextSteps } from "@domain/graph"; +import { identifier } from "@domain/identifier"; import type { DecodeError } from "@domain/model"; import { mapStatus } from "@domain/status"; import { validateMap } from "@domain/validate"; -import { buildSnapshot, resolveMap, resolveProject } from "@/scope"; +import { buildSnapshot, fail, resolveMap, resolveMapName, resolveProject, strict } from "@/scope"; import { jsonFlag, mapFlag } from "@cli/flags"; import { bodyLines, handle, printOutput } from "@cli/render"; import { wayfulRoot } from "@cli/root"; @@ -17,6 +20,37 @@ function errorLines(errors: readonly DecodeError[]): string[] { return errors.length ? ["Errors:", ...errors.map((e) => `- ${e.file}: ${e.message}`)] : []; } +/** Parses a comma-separated `--allowed-step-types` value into validated, unique type names. */ +function parseAllowedStepTypes(raw: string): Effect.Effect { + return liftSync(() => { + const parts = raw + .split(",") + .map((part) => part.trim()) + .filter((part) => part.length > 0); + if (parts.length === 0) + throw new WayfulError({ message: "--allowed-step-types must name at least one type." }); + const names = parts.map((part) => identifier(part, "allowed step type")); + if (new Set(names).size !== names.length) + throw new WayfulError({ message: "--allowed-step-types repeats a type." }); + return names; + }); +} + +/** Fails unless every name is one of the project's types, so a restriction can never name a phantom. */ +function requireKnownTypes( + project: ProjectHandle, + names: readonly string[], +): Effect.Effect { + return Effect.gen(function* () { + const projectStore = yield* ProjectStore; + const types = yield* strict(yield* projectStore.listTypes(project)); + const known = new Set(types.map((type) => type.name)); + for (const name of names) { + if (!known.has(name)) return yield* fail(`type '${name}' does not exist.`); + } + }); +} + const mapCreateCommand = Command.make( "create", { @@ -34,32 +68,128 @@ const mapCreateCommand = Command.make( Flag.withDescription("Optional initial goal Markdown body"), Flag.withDefault(""), ), + allowedStepTypes: Flag.string("allowed-step-types").pipe( + Flag.withMetavar("CSV"), + Flag.withDescription("Comma-separated step types this map permits (default: every type)"), + Flag.optional, + ), }, - ({ map, start, goal, goalBody }) => + ({ map, start, goal, goalBody, allowedStepTypes }) => handle( false, Effect.gen(function* () { const root = yield* wayfulRoot; const mapStore = yield* MapStore; const p = yield* resolveProject(root.project); - yield* mapStore.createMap(p, { name: map, start, goal, goalBody }); + let allowed: readonly string[] | undefined; + if (Option.isSome(allowedStepTypes)) { + allowed = yield* parseAllowedStepTypes(allowedStepTypes.value); + yield* requireKnownTypes(p, allowed); + } + yield* mapStore.createMap(p, { + name: map, + start, + goal, + goalBody, + ...(allowed !== undefined ? { allowedStepTypes: allowed } : {}), + }); yield* Console.log(`Created map '${map}'.`); }), ), ).pipe(Command.withDescription("Create a map")); -const mapListCommand = Command.make("list", { json: jsonFlag }, ({ json }) => +const mapListCommand = Command.make( + "list", + { + all: Flag.boolean("all").pipe( + Flag.withDescription("Include archived maps"), + Flag.withDefault(false), + ), + json: jsonFlag, + }, + ({ all, json }) => + handle( + json, + Effect.gen(function* () { + const root = yield* wayfulRoot; + const mapStore = yield* MapStore; + const p = yield* resolveProject(root.project); + const maps = (yield* mapStore.listMaps(p, { includeArchived: all })).records; + yield* printOutput( + json, + maps, + maps.map((m) => `${m.name}${m.archived ? " (archived)" : ""}: ${m.start}`).join("\n"), + ); + }), + ), +).pipe(Command.withDescription("List every map in the project")); + +const mapArchiveCommand = Command.make("archive", { map: mapFlag }, ({ map }) => handle( - json, + false, Effect.gen(function* () { const root = yield* wayfulRoot; const mapStore = yield* MapStore; const p = yield* resolveProject(root.project); - const maps = (yield* mapStore.listMaps(p)).records; - yield* printOutput(json, maps, maps.map((m) => `${m.name}: ${m.start}`).join("\n")); + const name = yield* resolveMapName(map); + yield* mapStore.archiveMap(p, name); + yield* Console.log(`Archived map '${name}'.`); }), ), -).pipe(Command.withDescription("List every map in the project")); +).pipe(Command.withDescription("Archive a map, keeping its steps and goals")); + +const mapUnarchiveCommand = Command.make("unarchive", { map: mapFlag }, ({ map }) => + handle( + false, + Effect.gen(function* () { + const root = yield* wayfulRoot; + const mapStore = yield* MapStore; + const p = yield* resolveProject(root.project); + const name = yield* resolveMapName(map); + yield* mapStore.unarchiveMap(p, name); + yield* Console.log(`Restored map '${name}'.`); + }), + ), +).pipe(Command.withDescription("Restore an archived map with its steps and goals")); + +const mapRestrictCommand = Command.make( + "restrict", + { + map: mapFlag, + allowedStepTypes: Flag.string("allowed-step-types").pipe( + Flag.withMetavar("CSV"), + Flag.withDescription("Comma-separated step types this map permits"), + Flag.optional, + ), + clear: Flag.boolean("clear").pipe( + Flag.withDescription("Remove the restriction, permitting every type"), + Flag.withDefault(false), + ), + }, + ({ map, allowedStepTypes, clear }) => + handle( + false, + Effect.gen(function* () { + const root = yield* wayfulRoot; + const mapStore = yield* MapStore; + const p = yield* resolveProject(root.project); + if (clear && Option.isSome(allowedStepTypes)) + return yield* fail("--clear and --allowed-step-types are mutually exclusive."); + if (!clear && Option.isNone(allowedStepTypes)) + return yield* fail("pass --allowed-step-types to restrict, or --clear to remove it."); + const target = yield* resolveMap(map, p); + if (clear) { + yield* mapStore.setAllowedStepTypes(target, undefined); + yield* Console.log(`Cleared the type restriction on map '${target.name}'.`); + } else { + const allowed = yield* parseAllowedStepTypes(Option.getOrThrow(allowedStepTypes)); + yield* requireKnownTypes(p, allowed); + yield* mapStore.setAllowedStepTypes(target, allowed); + yield* Console.log(`Restricted map '${target.name}' to types: ${allowed.join(", ")}.`); + } + }), + ), +).pipe(Command.withDescription("Set or clear a map's allowed step types")); const mapValidateCommand = Command.make( "validate", @@ -131,6 +261,7 @@ const mapShowCommand = Command.make("show", { map: mapFlag, json: jsonFlag }, ({ const human = [ `Map ${m.name}`, `Start: ${m.metadata.start}`, + `Allowed step types: ${m.metadata.allowed_step_types?.join(", ") ?? "(all)"}`, "Goals:", ...(goals.length ? goals.flatMap((g) => [`- ${g.name}: ${g.description}`, ...bodyLines(g.body, " ")]) @@ -210,6 +341,9 @@ export const mapCommand = Command.make("map").pipe( Command.withSubcommands([ mapCreateCommand, mapListCommand, + mapArchiveCommand, + mapUnarchiveCommand, + mapRestrictCommand, mapValidateCommand, mapShowCommand, mapNextCommand, diff --git a/packages/cli/src/domain/model.ts b/packages/cli/src/domain/model.ts index 76e2123..5a28228 100644 --- a/packages/cli/src/domain/model.ts +++ b/packages/cli/src/domain/model.ts @@ -21,6 +21,13 @@ export interface MapMetadata { readonly name: string; readonly start: string; readonly allowed_step_types?: readonly string[]; + /** + * Whether the map is archived. Derived per backend from the state that + * already expresses it — a `map.toml` `archived_at` stamp on the + * filesystem, the map issue's closed state under GitHub — never a second + * stored fact. + */ + readonly archived: boolean; readonly created_at: string; readonly updated_at: string; } diff --git a/packages/cli/src/scope.ts b/packages/cli/src/scope.ts index ed7db36..7f62081 100644 --- a/packages/cli/src/scope.ts +++ b/packages/cli/src/scope.ts @@ -41,6 +41,21 @@ export function resolveProject( }); } +/** + * Resolves the map name a command targets: explicit `--map`, then + * `WAYFUL_MAP`. A missing value is the shared context error. Kept separate + * from `resolveMap` because archive/unarchive must name an archived map that + * `resolveMap` deliberately refuses. + */ +export function resolveMapName(mapFlag: Option.Option): Effect.Effect { + return Effect.gen(function* () { + const name = Option.orElse(mapFlag, () => envOption("WAYFUL_MAP")); + if (Option.isNone(name)) + return yield* fail("map context is required; pass --map or set WAYFUL_MAP."); + return name.value; + }); +} + export function resolveMap( mapFlag: Option.Option, project: ProjectHandle, @@ -48,10 +63,12 @@ export function resolveMap( return Effect.gen(function* () { const mapStore = yield* MapStore; const projectStore = yield* ProjectStore; - const name = Option.orElse(mapFlag, () => envOption("WAYFUL_MAP")); - if (Option.isNone(name)) - return yield* fail("map context is required; pass --map or set WAYFUL_MAP."); - const map = yield* mapStore.openMap(project, name.value); + const name = yield* resolveMapName(mapFlag); + const map = yield* mapStore.openMap(project, name); + if (map.metadata.archived) + return yield* fail( + `map '${name}' is archived; run 'wayful map unarchive --map ${name}' to restore it.`, + ); if (map.metadata.allowed_step_types !== undefined) { const types = yield* projectStore.listTypes(project); const known = new Set(types.records.map((type) => type.name)); diff --git a/packages/cli/src/server/server-github.test.ts b/packages/cli/src/server/server-github.test.ts index cc81e5f..0c606a5 100644 --- a/packages/cli/src/server/server-github.test.ts +++ b/packages/cli/src/server/server-github.test.ts @@ -48,6 +48,7 @@ const metadata = { format_version: CURRENT_FORMAT_VERSION, name: "plan", start: "here", + archived: false, created_at: FIXTURE_TIME, updated_at: FIXTURE_TIME, }; @@ -80,6 +81,9 @@ function stubMapStore() { createMap: unused, openMap: (_project, name) => Effect.succeed({ project: _project, name, metadata } as MapHandle), + archiveMap: unused, + unarchiveMap: unused, + setAllowedStepTypes: unused, listSteps: unused, createStep: unused, saveStep: unused, diff --git a/packages/cli/src/server/server.test.ts b/packages/cli/src/server/server.test.ts index 2f3eac4..193b675 100644 --- a/packages/cli/src/server/server.test.ts +++ b/packages/cli/src/server/server.test.ts @@ -104,6 +104,7 @@ describe("the JSON API the UI requires", () => { format_version: CURRENT_FORMAT_VERSION, name: "plan", start: "here", + archived: false, created_at: FIXTURE_TIME, updated_at: FIXTURE_TIME, status: { diff --git a/packages/cli/test/support/domain-fixtures.ts b/packages/cli/test/support/domain-fixtures.ts index 93bdf83..2c52c09 100644 --- a/packages/cli/test/support/domain-fixtures.ts +++ b/packages/cli/test/support/domain-fixtures.ts @@ -69,6 +69,7 @@ export function map(overrides: Partial = {}): MapMetadata { format_version: CURRENT_FORMAT_VERSION, name: "plan", start: "here", + archived: false, created_at: T, updated_at: T, ...overrides, diff --git a/packages/cli/test/support/map-store-contract.ts b/packages/cli/test/support/map-store-contract.ts index bf4b9dd..5c9a5c5 100644 --- a/packages/cli/test/support/map-store-contract.ts +++ b/packages/cli/test/support/map-store-contract.ts @@ -78,6 +78,7 @@ export function describeMapStoreContract(name: string, mapStoreLayer: Layer.Laye name: "plan", start: "here", allowed_step_types: undefined, + archived: false, created_at: T0, updated_at: T0, }); @@ -136,6 +137,86 @@ export function describeMapStoreContract(name: string, mapStoreLayer: Layer.Laye expect(error).not.toBeInstanceOf(MapMetadataError); expect((error as WayfulError).message).toContain("does not exist"); }); + + test("createMap records an allowed step types restriction", async () => { + const project = await initializedProject(); + const map = await run( + Effect.gen(function* () { + const b = yield* backend(); + yield* b.createMap(project, { + name: "plan", + start: "here", + goal: "done", + goalBody: "", + allowedStepTypes: ["task"], + }); + return yield* b.openMap(project, "plan"); + }), + ); + expect(map.metadata.allowed_step_types).toEqual(["task"]); + }); + + test("setAllowedStepTypes sets and clears the restriction on an existing map", async () => { + const map = await initializedMap(); + const restricted = await run( + Effect.gen(function* () { + const b = yield* backend(); + yield* b.setAllowedStepTypes(map, ["task"]); + return (yield* b.openMap(map.project, "plan")).metadata.allowed_step_types; + }), + ); + expect(restricted).toEqual(["task"]); + const cleared = await run( + Effect.gen(function* () { + const b = yield* backend(); + yield* b.setAllowedStepTypes(map, undefined); + return (yield* b.openMap(map.project, "plan")).metadata.allowed_step_types; + }), + ); + expect(cleared).toBeUndefined(); + }); + + test("archiveMap hides a map from the default listing and unarchiveMap restores it with its steps", async () => { + const map = await initializedMap(); + const archived = await run( + Effect.gen(function* () { + const b = yield* backend(); + yield* b.createStep(map, newStep({ name: "work" })); + yield* b.archiveMap(map.project, "plan"); + const invalid = yield* Effect.flip(b.archiveMap(map.project, "plan")); + return { + live: (yield* b.listMaps(map.project)).records, + all: (yield* b.listMaps(map.project, { includeArchived: true })).records, + reopened: (yield* b.openMap(map.project, "plan")).metadata.archived, + steps: (yield* b.listSteps(yield* b.openMap(map.project, "plan"))).records.map( + (step) => step.name, + ), + reinvalid: invalid.message, + }; + }), + ); + expect(archived.live).toEqual([]); + expect(archived.all).toEqual([{ ...map.metadata, archived: true }]); + expect(archived.reopened).toBe(true); + expect(archived.steps).toEqual(["work"]); + expect(archived.reinvalid).toContain("already archived"); + + const restored = await run( + Effect.gen(function* () { + const b = yield* backend(); + yield* b.unarchiveMap(map.project, "plan"); + const invalid = yield* Effect.flip(b.unarchiveMap(map.project, "plan")); + return { + live: (yield* b.listMaps(map.project)).records.map((entry) => entry.name), + archived: (yield* b.openMap(map.project, "plan")).metadata.archived, + reinvalid: invalid.message, + }; + }), + ); + expect(restored.live).toEqual(["plan"]); + expect(restored.archived).toBe(false); + expect(restored.reinvalid).toContain("not archived"); + }); }); describe("steps", () => {