diff --git a/README.md b/README.md index 0f98fbc..dfb33ca 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,11 @@ linear work search "release checklist" # by words, and by meaning linear work changes --since 7d # documents the syncs added, changed or removed ``` +A document you move to Linear's trash leaves the copy on the next `sync`, read from the workspace's audit log. A key +without audit-log access gets the warning `source.deletions-unchecked` on each sync, and trashed documents then leave +only with `sync --rescan`. A document you restore from the trash comes back only with `sync --rescan`, because Linear +does not mark a restore as a change. + ### Any Linear API operation ```sh diff --git a/changes/feat-documents-deletions.md b/changes/feat-documents-deletions.md new file mode 100644 index 0000000..fd1bd10 --- /dev/null +++ b/changes/feat-documents-deletions.md @@ -0,0 +1,7 @@ +### Fixed + +- **A document moved to Linear's trash leaves the local copy on the next sync.** Trashing a document does not change + its edit time, so a plain `sync` used to miss it until `sync --rescan`. The sync now also reads the workspace's audit + log of deleted documents. If Linear refuses the audit log to your key (it needs audit-log access), the sync still + succeeds and warns `source.deletions-unchecked`; `sync --rescan` then finds the trashed documents. A document you + restore from the trash comes back only with `sync --rescan`. diff --git a/package.json b/package.json index b478a54..fabdb2d 100644 --- a/package.json +++ b/package.json @@ -63,7 +63,7 @@ }, "dependencies": { "@wirecat/cli-base": "0.132.0", - "@wirecat/cli-core": "0.736.0", + "@wirecat/cli-core": "0.744.0", "commander": "15.0.0", "valibot": "1.5.0" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 077437f..067b4bf 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -16,8 +16,8 @@ importers: specifier: 0.132.0 version: 0.132.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5) '@wirecat/cli-core': - specifier: 0.736.0 - version: 0.736.0(@wirecat/cli-base@0.132.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7) + specifier: 0.744.0 + version: 0.744.0(@wirecat/cli-base@0.132.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7) commander: specifier: 15.0.0 version: 15.0.0 @@ -1213,8 +1213,8 @@ packages: '@wirecat/cli-core-sqlite@1.1.0': resolution: {integrity: sha512-GpGlh/dAIX/nblBYCdT6DfWSLFxav9mxxeELQAfEuw+QZdT9unKxbi5xa02s/s4JS1P7n0PQx2sCABj4FlMRNw==} - '@wirecat/cli-core@0.736.0': - resolution: {integrity: sha512-L9eIF503xg42gu9PQgESa43ZaQgBk452oY3H+QRaFrd/ysLXECWauJXQqJ9aiyn3Pdytzab2PDgluezApzbQyA==} + '@wirecat/cli-core@0.744.0': + resolution: {integrity: sha512-KqP/T5z5TLah1bqO4yBO5WdSKy/E6oqd9Id531i6LH/P68s3rC5M/PgBGwrm+x5FLEfIhYp91FlH1p9eHEx+5g==} engines: {node: ^22.16.0 || >=24} hasBin: true peerDependencies: @@ -3364,7 +3364,7 @@ snapshots: '@wirecat/cli-core-sqlite@1.1.0': {} - '@wirecat/cli-core@0.736.0(@wirecat/cli-base@0.132.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7)': + '@wirecat/cli-core@0.744.0(@wirecat/cli-base@0.132.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7)': dependencies: '@anthropic-ai/sdk': 1.3.0(zod@4.6.7) '@bomb.sh/tab': 0.0.22(commander@15.0.0) diff --git a/scripts/live.sh b/scripts/live.sh index d98fa53..85ed352 100755 --- a/scripts/live.sh +++ b/scripts/live.sh @@ -5,6 +5,7 @@ # scripts/live.sh < token-file # Needs: a Linear personal API key the owner chose for this check (keyring service linear), read access is enough # Needs: a workspace with at least one team and one issue the key can read +# Needs: write access and the workspace's audit log (an admin's key): the check makes a project with one document, trashes the document and the project set -euo pipefail root=$(cd -- "$(dirname -- "$0")/.." && pwd) work=$(mktemp -d) @@ -27,8 +28,31 @@ mkdir -p "$HOME" const answer = JSON.parse(require("fs").readFileSync(0, "utf8")) if (answer.wcat_describe !== 2 || !/^[0-9a-f]{64}$/.test(answer.manifest_sha256)) throw new Error("not format 2")' +# The check's own profile allows the raw writes and the delete key, so the trash steps run without a question; the file +# is in $work. +mkdir -p "$WCLINEAR_CONFIG_DIR" +printf '%s\n' '{"profiles":{"live":{"permissions":{"api":"allow","linear.delete":"allow"}}}}' >"$WCLINEAR_CONFIG_DIR/config.json" + "${cli[@]}" live session start --credential-storage file --json >/dev/null -trap '"${cli[@]}" live session end --json >/dev/null 2>&1 || true; rm -rf "$work"' EXIT +started=$(date -u +%Y-%m-%dT%H:%M:%SZ) +name="WireCat live check $(date -u +%Y%m%dT%H%M%SZ)" +project="" +# A check that fails half way still leaves its project in the trash, never in the workspace: found by its name when +# the create's answer gave no id. +cleanup() { + if [ -z "$project" ]; then + "${cli[@]}" live api projects --filter "{\"name\":{\"eq\":\"$name\"}}" --json >"$work/leftover.json" 2>/dev/null || true + project=$(node -e ' + try { + const answer = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")) + process.stdout.write(String((answer.items ?? answer.item?.nodes ?? [])[0]?.id ?? "")) + } catch {}' "$work/leftover.json") + fi + [ -z "$project" ] || "${cli[@]}" live api project-delete --id "$project" --yes --json >/dev/null 2>&1 || true + "${cli[@]}" live session end --json >/dev/null 2>&1 || true + rm -rf "$work" +} +trap cleanup EXIT "${cli[@]}" live sync --max-pages 40 --json >"$work/sync.json" # The second run sends what changed since the first: the changes calls with their updatedAt filter. @@ -56,5 +80,48 @@ node -e ' ' "$work" "${cli[@]}" live doctor --json >/dev/null +# A document trashed in Linear keeps its updatedAt, so only the audit log names it to the next sync. +field() { node -e ' + const answer = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")) + const value = process.argv[2].split(".").reduce((one, key) => one?.[key], answer) + // Names only, never values: the record is public. + const shape = (one) => (one && typeof one === "object" ? Object.keys(one).join(",") : typeof one) + if (value === undefined) + throw new Error(`${process.argv[1]} has no ${process.argv[2]}: keys ${shape(answer)}; item ${shape(answer.item ?? answer.items?.[0])}`) + process.stdout.write(String(value))' "$work/$1.json" "$2"; } +team=$(field teams items.0.external_id) +"${cli[@]}" live api project-create --input "{\"name\":\"$name\",\"teamIds\":[\"$team\"]}" \ + --json >"$work/project.json" +project=$(field project item.result.project.id) +"${cli[@]}" live api document-create --input "{\"title\":\"Live check\",\"content\":\"trashed by the live check\",\"projectId\":\"$project\"}" \ + --json >"$work/document.json" +document=$(field document item.result.document.id) +"${cli[@]}" live folders add "$project" --json >/dev/null +"${cli[@]}" live sync --max-pages 40 --json >"$work/saved.json" +"${cli[@]}" live api document-delete --id "$document" --yes --json >/dev/null +"${cli[@]}" live sync --max-pages 40 --json >"$work/trashed.json" +"${cli[@]}" live documents list --json >"$work/left.json" +# The document is new, so the documents listing names it too: the audit log is read on its own to show the sync's +# feed would find it after the listing's window has passed. +"${cli[@]}" live api audit-entries --filter "{\"type\":{\"eq\":\"documentDeleted\"},\"createdAt\":{\"gte\":\"$started\"}}" \ + --first 50 --json >"$work/audit.json" +node -e ' + const read = (name) => JSON.parse(require("fs").readFileSync(`${process.argv[1]}/${name}.json`, "utf8")) + const saved = read("saved").item?.documents ?? {} + if (!(saved.saved >= 1)) throw new Error(`the document was not saved: ${JSON.stringify(saved).slice(0, 300)}`) + const trashed = read("trashed").item?.documents ?? {} + if ((trashed.warnings ?? []).length) throw new Error(`the sync warned: ${JSON.stringify(trashed.warnings)}`) + if (trashed.removed !== 1) throw new Error(`the trashed document was not removed: ${JSON.stringify(trashed).slice(0, 300)}`) + if ((read("left").items ?? []).some((one) => one.id === process.argv[2])) throw new Error("documents list still shows it") + const audit = read("audit") + const entries = audit.items ?? audit.item?.nodes ?? [] + if (!entries.some((one) => one.metadata?.entityId === process.argv[2])) + throw new Error("the audit log has no documentDeleted entry with the document at metadata.entityId") + process.stdout.write("trashed document left the copy on a plain sync\n") +' "$work" "$document" +"${cli[@]}" live api project-delete --id "$project" --yes --json >/dev/null +project="" + "${cli[@]}" live session end --json >/dev/null -echo "live check passed: describe format 2, sign-in, full and changes sync, teams and issues from the copy, doctor, sign-out" +echo "live check passed: describe format 2, sign-in, full and changes sync, teams and issues from the copy, doctor," \ + "a trashed document removed by a plain sync, sign-out" diff --git a/src/commands/documents.ts b/src/commands/documents.ts index c4756ab..4951e37 100644 --- a/src/commands/documents.ts +++ b/src/commands/documents.ts @@ -45,7 +45,7 @@ export const linearDocuments = () => provider: PROVIDER, words: WORDS, service: SERVICE, - source: (command) => + source: (command, _events, { warn }) => linearDocumentSource( serviceApiCall({ manifest: API.manifest, @@ -53,6 +53,7 @@ export const linearDocuments = () => fetch: API_OPTIONS.fetch(command), token: () => tokenOf(command), }), + { warn }, ), ingestion: (store) => documentIngestion(store, { diff --git a/src/documents.test.ts b/src/documents.test.ts index b4f6d48..a078b95 100644 --- a/src/documents.test.ts +++ b/src/documents.test.ts @@ -1,4 +1,6 @@ -import { rmSync } from "node:fs" +import { mkdtempSync, rmSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" import { memoryKeyring } from "@wirecat/cli-base" import { documentCommandsContract } from "@wirecat/cli-core/documents/testing" import { pacePathFor } from "@wirecat/cli-core/sends" @@ -38,7 +40,7 @@ const issues = ({ selection }: { selection?: unknown }) => { } /** A workspace with a project document, a document on an issue, and one issue; profile personal signed in. */ -const signedIn = async () => { +const signedIn = async (own: NodeJS.ProcessEnv = {}) => { const linear = fakeLinearDocuments({ answers: { issues } }) fakes.push(linear) linear.addProject("p-1", "Roadmap") @@ -52,16 +54,17 @@ const signedIn = async () => { // A sync of issues and documents sends more than the pace's burst, and the rest would wait 1.5 s each for real. const service = { fetch: (input: string | URL | Request, init?: RequestInit) => { - rmSync(pacePathFor(IDENTITY, "personal", process.env), { force: true }) + rmSync(pacePathFor(IDENTITY, "personal", { ...process.env, ...own }), { force: true }) return linear.fetch(input, init) }, } - const run = (argv: string[], env?: NodeJS.ProcessEnv) => - runCli(["personal", ...argv, "--json"], { keyring, service, ...(env ? { env } : {}) }) + const run = (argv: string[], env: NodeJS.ProcessEnv = {}) => + runCli(["personal", ...argv, "--json"], { keyring, service, env: { ...own, ...env } }) const started = await runCli(["personal", "session", "start", "--json"], { keyring, service, stdin: FAKE_API_TOKEN, + env: own, }) expect(started.code, started.err).toBe(0) return { linear, run } @@ -105,6 +108,42 @@ describe("one linear sync copies issues and the documents of the chosen projects }) }) +describe("a document trashed in Linear", () => { + // A removal stays in the store and the profile's state: each test here keeps its own. + const syncedOnce = async () => { + const dir = mkdtempSync(join(tmpdir(), "trashed-")) + const signed = await signedIn({ WCLINEAR_STATE_DIR: join(dir, "state"), MESSAGING_STORE: join(dir, "wirecat.db") }) + await signed.run(["folders", "add", "linear:all"]) + expect((await signed.run(["sync"])).code).toBe(0) + // The CLI's change token is the real clock's: the trash must come after it. + signed.linear.advance(Date.now() - signed.linear.now() + 60_000) + signed.linear.trash("d-1") + return signed + } + + it("leaves the copy on the next plain sync", async () => { + const { run } = await syncedOnce() + const synced = await run(["sync"]) + expect(synced.code, synced.err).toBe(0) + expect(synced.json()).toMatchObject({ item: { documents: { complete: true, removed: 1 } } }) + expect(JSON.stringify((await run(["documents", "list"])).json())).not.toContain("Zeppelin plan") + }) + + it("stays while the audit log is refused, and the sync says why and succeeds", async () => { + const { run, linear } = await syncedOnce() + linear.refuseAudit() + const synced = await run(["sync"]) + expect(synced.code, synced.err).toBe(0) + expect(synced.json()).toMatchObject({ + item: { + documents: { complete: true, warnings: [{ code: "permission_error", reason: "source.deletions-unchecked" }] }, + }, + meta: { issues: expect.arrayContaining([expect.objectContaining({ reason: "source.deletions-unchecked" })]) }, + }) + expect(JSON.stringify((await run(["documents", "list"])).json())).toContain("Zeppelin plan") + }) +}) + it("chooses, lists and drops folders, pages the copy, and refuses --limit on the one sync", async () => { const { run } = await signedIn() expect((await run(["folders", "add", "p-1"])).code).toBe(0) diff --git a/src/documents/manifest.ts b/src/documents/manifest.ts index 333cb98..13e768d 100644 --- a/src/documents/manifest.ts +++ b/src/documents/manifest.ts @@ -28,6 +28,14 @@ export const DOCUMENT_MANIFEST = { }, children: { operation: "documents", body: { ...all, filter: { project: { id: { eq: "{id}" } } } } }, changes: { operation: "documents", body: { ...all, ...changed }, since: "iso", time: "updatedAt" }, + // Trashing keeps a document's updatedAt, so the changes listing misses it; only the audit log names it. + deletions: { + operation: "auditEntries", + body: { ...page, filter: { type: { eq: "documentDeleted" }, createdAt: { gte: "{since}" } } }, + since: "iso", + time: "createdAt", + id: "metadata.entityId", + }, content: { operation: "document", body: { id: "{id}" }, markdown: "content" }, reads: { project: { operation: "project", body: { id: "{id}" } }, diff --git a/src/documents/source.test.ts b/src/documents/source.test.ts index b6f8cae..898d202 100644 --- a/src/documents/source.test.ts +++ b/src/documents/source.test.ts @@ -4,7 +4,7 @@ import { join } from "node:path" import { CliError, isCliError } from "@wirecat/cli-base" import { serviceApiCall } from "@wirecat/cli-core/cli" import { syncDocuments } from "@wirecat/cli-core/documents" -import { documentProfile, parseDocumentManifest } from "@wirecat/cli-core/documents/cli" +import { type DocumentWarning, documentProfile, parseDocumentManifest } from "@wirecat/cli-core/documents/cli" import { type DocumentFaultRun, documentSourceContract } from "@wirecat/cli-core/documents/testing" import { afterEach, describe, expect, it } from "vitest" import { API } from "../config.js" @@ -34,10 +34,10 @@ const workspace = () => { return linear } -const sourceOver = (linear: FakeLinearDocuments) => +const sourceOver = (linear: FakeLinearDocuments, warnings: DocumentWarning[] = []) => linearDocumentSource( serviceApiCall({ manifest: API.manifest, service: "Linear", fetch: linear.fetch, token: () => FAKE_API_TOKEN }), - { now: linear.now }, + { now: linear.now, warn: (one) => warnings.push(one) }, ) /** The sync cli-core runs, over the profile's state files in a folder of its own and an index in memory. */ @@ -124,6 +124,9 @@ describe("the sync tells a deletion in Linear from a document it no longer sees" const linear = workspace() const run = syncer(linear) expect((await run.sync()).result).toMatchObject({ complete: true, saved: 4 }) + // A second round moves the token past the documents' updatedAt, so a trash reaches a round only by the audit log. + linear.advance(HOUR) + expect((await run.sync()).result).toMatchObject({ complete: true }) linear.advance(HOUR) return { linear, ...run } } @@ -137,9 +140,9 @@ describe("the sync tells a deletion in Linear from a document it no longer sees" expect((await source.children("p-1")).map((one) => one.parents)).toEqual([["p-1"], ["p-1"]]) }) - it("removes a document Linear trashed, as deleted", async () => { + it("removes a document Linear trashed, as deleted, though trashing left its updatedAt", async () => { const { linear, sync, held, removals } = await synced() - linear.edit("d-1", { trashed: true, archivedAt: new Date(linear.now()).toISOString() }) + linear.trash("d-1") expect((await sync()).result).toMatchObject({ removed: 1 }) expect(Object.fromEntries(removals)).toEqual({ "d-1": "deleted" }) expect(held.has("d-1")).toBe(false) @@ -171,7 +174,7 @@ describe("the sync tells a deletion in Linear from a document it no longer sees" it("marks nothing when a listing fails, and the next sync goes on", async () => { const { linear, sync, held } = await synced() - linear.edit("d-1", { trashed: true, archivedAt: new Date(linear.now()).toISOString() }) + linear.trash("d-1") linear.fail("documents") await expect(sync()).rejects.toThrow() expect(held.size).toBe(4) diff --git a/src/documents/source.ts b/src/documents/source.ts index 55f2f19..6a9a3e2 100644 --- a/src/documents/source.ts +++ b/src/documents/source.ts @@ -3,6 +3,7 @@ import type { ServiceApiCall } from "@wirecat/cli-core/cli" import type { SourceChange, SourceContent, SourceFile } from "@wirecat/cli-core/documents" import { type DocumentSlots, + type DocumentWarning, documentSourceFromManifest, type ManifestDocumentSource, } from "@wirecat/cli-core/documents/cli" @@ -97,12 +98,13 @@ const listingOf = (answer: unknown, name: string) => { */ export const linearDocumentSource = ( call: ServiceApiCall, - { now = Date.now }: { now?: () => number } = {}, + { now = Date.now, warn }: { now?: () => number; warn: (warning: DocumentWarning) => void }, ): LinearDocumentSource => documentSourceFromManifest(DOCUMENT_MANIFEST, { api: API.manifest, call, now, + warn, hooks: ({ read, file }) => { // A listing answers each document's text; the sync reads it right after, so the read is saved. const listed = new Map() diff --git a/src/testing/fake-documents.ts b/src/testing/fake-documents.ts index c10d550..fabfe55 100644 --- a/src/testing/fake-documents.ts +++ b/src/testing/fake-documents.ts @@ -28,6 +28,14 @@ export interface FakeProject { archivedAt?: string } +interface FakeAuditEntry { + id: string + type: "documentDeleted" + createdAt: string + updatedAt: string + metadata: { id: string; entityId: string; entityType: "document"; projectId: string | null } +} + type Variables = Readonly> type Selected = GraphqlFakeCall["selection"] @@ -59,6 +67,8 @@ export const fakeLinearDocuments = ({ let signedIn = viewer const documents = new Map() const projects = new Map() + const audit: FakeAuditEntry[] = [] + let auditRefusal: string | undefined const failing = new Set() const unmodelled: string[] = [] const stamp = () => new Date(now).toISOString() @@ -73,8 +83,8 @@ export const fakeLinearDocuments = ({ rows: T[], variables: Variables, selected: (row: T) => Record, + allowed = new Set(["first", "after", "includeArchived", "orderBy", "filter"]), ) => { - const allowed = new Set(["first", "after", "includeArchived", "orderBy", "filter"]) const extra = Object.keys(variables).filter((key) => !allowed.has(key)) if (extra.length) return refused(`${name}: the fake does not model ${extra.join(", ")}`) const first = (variables.first as number | undefined) ?? 50 @@ -116,6 +126,18 @@ export const fakeLinearDocuments = ({ ) } + // Only the source's own filter: deletions of documents since a time. + const auditFilter = (filter: unknown) => { + const { type, createdAt, ...rest } = (filter ?? {}) as { type?: { eq?: unknown }; createdAt?: { gte?: unknown } } + if (Object.keys(rest).length) return `auditEntries: the fake does not model filter ${Object.keys(rest).join(", ")}` + if (Object.keys(type ?? {}).join() !== "eq" || type?.eq !== "documentDeleted") + return "auditEntries: the fake models type only as { eq: documentDeleted }" + if (Object.keys(createdAt ?? {}).join() !== "gte" || typeof createdAt?.gte !== "string") + return "auditEntries: the fake models createdAt only as { gte }" + const since = Date.parse(createdAt.gte) + return audit.filter((entry) => Date.parse(entry.createdAt) >= since) + } + const documentRow = (one: FakeDocument) => ({ id: one.id, title: one.title, @@ -171,6 +193,20 @@ export const fakeLinearDocuments = ({ ? refused(rows) : page("projects", rows, variables, (one) => within(projectRow(one), asked)) }, + auditEntries: ({ variables, selection }: GraphqlFakeCall) => { + if (auditRefusal) return { errors: [{ message: "Forbidden", extensions: { code: auditRefusal } }] } + const rows = auditFilter(variables.filter) + const asked = nodesOf(selection) + return typeof rows === "string" + ? refused(rows) + : page( + "auditEntries", + rows, + variables, + (one) => within({ ...one }, asked), + new Set(["first", "after", "filter"]), + ) + }, project: ({ variables, selection }: GraphqlFakeCall) => { const one = projects.get(String(variables.id)) return one ? { data: within(projectRow(one), selection) } : missing("Project") @@ -202,6 +238,26 @@ export const fakeLinearDocuments = ({ if (!one) throw new Error(`no fake document ${id}`) documents.set(id, { ...one, ...fields, updatedAt: stamp() }) }, + /** + * Moves a document to the trash as Linear does: its listings show it trashed, its updatedAt stays, so only the + * audit log's documentDeleted entry names it to a round of changes. + */ + trash: (id: string) => { + const one = documents.get(id) + if (!one) throw new Error(`no fake document ${id}`) + documents.set(id, { ...one, trashed: true, archivedAt: stamp() }) + audit.push({ + id: `audit-${audit.length + 1}`, + type: "documentDeleted", + createdAt: stamp(), + updatedAt: stamp(), + metadata: { id, entityId: id, entityType: "document", projectId: one.project ?? null }, + }) + }, + /** The audit log answers this GraphQL code from now on, as Linear does for a sign-in without audit-log access. */ + refuseAudit: (code = "FORBIDDEN") => { + auditRefusal = code + }, /** The token now names another member, as a token replaced in the keyring would. */ signInAs: (id: string) => { signedIn = id