diff --git a/CHANGELOG.md b/CHANGELOG.md index 45a402df..0737357e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ All notable changes to Context are documented here. +## Unreleased + +- With `CONTEXT_LARK_IDENTITY=bot`, a document the bot cannot open (Lark code 3380004) is now read again as the user, as the bot mode intends; previously this real error did not trigger the fallback. +- A Lark capture records which identity read the document, why the bot could not read it, and access changes made during the capture in its capture report. `context status` keeps showing a fallback ("the bot could not read this document … it was read as the user", with the risk and what to do) after the capture finished; reports written before this version remain valid. +- An unchanged Lark revision is captured again in full when it is read by a different identity than before or when access changed during the capture, instead of reusing the earlier snapshot. +- When a document cannot be acquired, the warning keeps its next step and the Lark error (credentials hidden) instead of only the cause; a document the capturing identity cannot open (code 3380004) asks to have it shared instead of suggesting to sign in again. + ## 0.7.97 - 2026-11-10 - Production-stage article submissions report every citation problem of the article at once, one entry per fragment. A citation that repeats an earlier citation's lines keeps that evidence: it stays when the text is unchanged, follows the text when it moved to one unique place, and is reported with its state (changed, ambiguous or unreadable) and, when available, where the text now is; the current text at the old lines is never signed in its place. diff --git a/packages/context-cli/README.md b/packages/context-cli/README.md index 67121b4c..2fb280bc 100644 --- a/packages/context-cli/README.md +++ b/packages/context-cli/README.md @@ -320,7 +320,10 @@ MIT. mode, a credential/scope/access failure retries once as the current user; the rest of that capture keeps the fallback identity for pagination and resources. Network, rate-limit and parsing errors do not trigger a user authorization -attempt. This does not change source-read consent or the audience of published +attempt. The capture report records which identity read the document and why a +fallback happened; `context status` keeps warning about the fallback, because +content only that user can see is now in the snapshot and later bot captures may +not read it. This does not change source-read consent or the audience of published knowledge. Host-managed OAuth must use the host's authorization flow. ### Workspace updates diff --git a/packages/context-cli/README.zh-CN.md b/packages/context-cli/README.zh-CN.md index aba905c4..5ff51e18 100644 --- a/packages/context-cli/README.zh-CN.md +++ b/packages/context-cli/README.zh-CN.md @@ -71,6 +71,8 @@ Provider Skill 投影到 Claude、Codex 和 Cursor 的用户技能目录。 命令的 shell 都需传入该环境变量;仅在提示词中写配置并不会自动导出环境变量。 `bot` 模式先使用应用身份,遇到凭证、scope 或访问权限错误时回退当前用户一次, 本次采集后续分页、引用与资源下载沿用回退身份。网络、限流和解析错误不切换身份。 +采集报告记录读取身份与回退原因;`context status` 会持续提示该回退:仅该用户可见的内容 +已进入快照,之后用机器人采集可能读不到。 该配置不扩大来源授权或知识产物可见范围;托管运行时的用户授权遵循宿主流程。 ## 一个 Agent 入口如何驱动整套工作流 diff --git a/packages/context-cli/context-workflow/resources/manuals/guides/lark-resources.md b/packages/context-cli/context-workflow/resources/manuals/guides/lark-resources.md index 216fcf59..0cdfeeee 100644 --- a/packages/context-cli/context-workflow/resources/manuals/guides/lark-resources.md +++ b/packages/context-cli/context-workflow/resources/manuals/guides/lark-resources.md @@ -270,6 +270,8 @@ tokens in generated pages or claim that excluded images have been interpreted. The selected document identity remains fixed for resource reads. In Bot mode, only an authorization failure while reading the body can restart the article as the current user. Resource failures never trigger that identity fallback. +The capture report records the identity and the reason for a fallback, and +`context status` keeps showing it until the document is captured again. Images may use the official same-identity preview endpoint after download permission is denied. Previews are marked explicitly; unavailable resources retain references and diagnostics. Use available body evidence without inferring diff --git a/packages/context-cli/context-workflow/resources/procedures/document-capture.md b/packages/context-cli/context-workflow/resources/procedures/document-capture.md index 1670a766..1d12ac4e 100644 --- a/packages/context-cli/context-workflow/resources/procedures/document-capture.md +++ b/packages/context-cli/context-workflow/resources/procedures/document-capture.md @@ -72,7 +72,13 @@ The fallback restarts the entire body, including pagination; never combine body pages from different identities. Once the body is available, its identity is fixed for all media, synced references, Sheets, Base and whiteboard reads. Resource failures do not request user authorization or restart the article. -Network, rate-limit and format errors do not switch identity. +Network, rate-limit and format errors do not switch identity. When a capture +result or `context status` reports `lark.capture.identity-fallback`, tell the +user which documents were read as them, the risk (content only they can see is +now in the snapshot; later bot captures may not read it) and the remedy (ask the +document's owner to share it with the bot). When a capture is deferred +(`document.acquisition-unavailable`), relay the warning's `next` instead of +retrying on your own. An image download denied by permissions may use the official preview endpoint once with the same identity. A captured preview is explicitly marked as such. diff --git a/packages/context-cli/src/__tests__/documentLarkCaptureReportV062.test.ts b/packages/context-cli/src/__tests__/documentLarkCaptureReportV062.test.ts index f1276687..f63a7a2d 100644 --- a/packages/context-cli/src/__tests__/documentLarkCaptureReportV062.test.ts +++ b/packages/context-cli/src/__tests__/documentLarkCaptureReportV062.test.ts @@ -125,4 +125,22 @@ describe("0.6.2 compact Lark capture report", () => { })).toThrow(); }); + test("keeps the access record and still reads reports written before it existed", () => { + const base = { + schema_version: "context.lark-capture-report.v1", + fidelity: { status: "complete", evidence_status: "complete", + projection_status: "complete", discovered: {}, converted: {}, skipped: [], issues: [] }, + resource_materialization: { status: "complete", discovered: {}, materialized: {}, reference_only: {}, failed: {} }, + resources: [], + }; + expect(parseLarkCaptureReport(base).access).toBeUndefined(); + const access = { + identity: "user", fallback: { from: "bot", cause: "lark error 3380004" }, + events: [{ kind: "viewer-added", message: "app cli_x was added as a viewer", app_id: "cli_x", changed_access: true }], + }; + expect(parseLarkCaptureReport({ ...base, access }).access).toEqual(access as never); + expect(() => parseLarkCaptureReport({ ...base, access: { identity: "someone" } })).toThrow(/access.identity/u); + expect(() => parseLarkCaptureReport({ ...base, access: { identity: "user", events: [{ kind: "x" }] } })).toThrow(/access.events/u); + }); + }); diff --git a/packages/context-cli/src/__tests__/documentLarkIdentityV062.test.ts b/packages/context-cli/src/__tests__/documentLarkIdentityV062.test.ts index 5f5fcc53..d1b3078d 100644 --- a/packages/context-cli/src/__tests__/documentLarkIdentityV062.test.ts +++ b/packages/context-cli/src/__tests__/documentLarkIdentityV062.test.ts @@ -65,6 +65,9 @@ describe("Lark capture identity selection", () => { expect(result.accessIdentity).toBe("bot"); expect(result.identityFallback).toBe(true); + // A user → bot switch is not the bot → user fallback whose risk the report records. + expect(result.access.fallback).toBeUndefined(); + expect(result.access.identity).toBe("bot"); expect(result.markdown).toContain("Body"); expect(result.markdown).toContain("assets/materialized/image/"); expect(identities).toEqual([ diff --git a/packages/context-cli/src/__tests__/larkReadIdentity.test.ts b/packages/context-cli/src/__tests__/larkReadIdentity.test.ts index fbcffed9..4a67778f 100644 --- a/packages/context-cli/src/__tests__/larkReadIdentity.test.ts +++ b/packages/context-cli/src/__tests__/larkReadIdentity.test.ts @@ -46,6 +46,22 @@ describe("configured Lark read identity", () => { expect(session.usedFallback).toBe(true); }); + test("bot falls back when the Docs API denies the document (code 3380004)", async () => { + // Recorded from lark-cli 1.0.98: the envelope is printed on stderr with exit code 1. + const documentDenied = { exitCode: 1, stdout: "", stderr: JSON.stringify({ ok: false, identity: "bot", error: { + type: "api", subtype: "unknown", code: 3380004, + message: "No permission to operate on this document: the current user lacks view or edit access.", + } }) }; + const seen: string[] = []; + const session = createLarkReadSession(async args => { + seen.push(as(args)!); + return as(args) === "bot" ? documentDenied : success; + }, "bot"); + await session.readDocument(() => session.run(["docs", "+fetch", "--as", "bot"])); + expect(seen).toEqual(["bot", "user"]); + expect(session.usedFallback).toBe(true); + }); + test.each(["rate_limit", "network", "validation", "parse"])("does not switch on %s errors", async type => { const seen: string[] = []; const session = createLarkReadSession(async args => { @@ -135,6 +151,57 @@ describe("configured Lark read identity", () => { expect(result.identityFallback).toBe(true); }); + test("a real document denial falls back and records why in the capture report", async () => { + const documentDenied = { exitCode: 1, stdout: "", stderr: JSON.stringify({ ok: false, identity: "bot", error: { + type: "api", subtype: "unknown", code: 3380004, message: "No permission to operate on this document", + } }) }; + const runner: LarkRunner = async args => as(args) === "bot" ? documentDenied : { + ...success, stdout: JSON.stringify({ ok: true, identity: "user", data: { document: { content: "
Body
" } } }), + }; + const result = await fetchFeishuDocSnapshot({ url: "https://example.test/docx/shared", identity: "bot", docsApiVersion: "v2" }, runner); + expect(result.access).toMatchObject({ identity: "user", fallback: { from: "bot", cause: "lark error 3380004" } }); + const report = JSON.parse(Buffer.from(result.assets.find(asset => asset.path === "capture-report.json")!.bytes!).toString("utf8")); + expect(report.access).toEqual(result.access); + }); + + test("an unchanged revision read by a different identity re-reads resources instead of reusing the snapshot", async () => { + process.env.CONTEXT_LARK_IDENTITY = "user"; + const runner: LarkRunner = async args => ({ ...success, stdout: JSON.stringify({ ok: true, identity: as(args), + data: { document: { content: "Body
", revision_id: 7 } } }) }); + const same = await fetchFeishuDocSnapshot({ url: "https://example.test/docx/a", identity: "user", docsApiVersion: "v2", + unchangedRevisionId: "7", unchangedAccess: { identity: "user" } }, runner); + expect(same.unchanged).toBe(true); + const switched = await fetchFeishuDocSnapshot({ url: "https://example.test/docx/a", identity: "user", docsApiVersion: "v2", + unchangedRevisionId: "7", unchangedAccess: { identity: "bot" } }, runner); + expect(switched.unchanged).toBeUndefined(); + expect(switched.assets.some(asset => asset.path === "capture-report.json")).toBe(true); + const events = [{ kind: "viewer-added", message: "app cli_x was added as a viewer", changed_access: true }]; + const granted = await fetchFeishuDocSnapshot({ url: "https://example.test/docx/a", identity: "user", docsApiVersion: "v2", + unchangedRevisionId: "7", unchangedAccess: { identity: "user" }, accessEvents: events }, runner); + expect(granted.unchanged).toBeUndefined(); + expect(granted.access.events).toEqual(events); + }); + + test("a document that still falls back to the user reuses its user snapshot at the same revision", async () => { + process.env.CONTEXT_LARK_IDENTITY = "bot"; + const denied3380004 = { exitCode: 1, stdout: "", stderr: JSON.stringify({ ok: false, error: { type: "api", subtype: "unknown", code: 3380004 } }) }; + // Builds that try to add the bot as a viewer first see that attempt fail here. + const runner: LarkRunner = async args => as(args) === "bot" || args[0] === "drive" ? denied3380004 + : { ...success, stdout: JSON.stringify({ ok: true, identity: "user", data: { document: { content: "Body
", revision_id: 7 } } }) }; + const first = await fetchFeishuDocSnapshot({ url: "https://example.test/docx/a", docsApiVersion: "v2", unchangedRevisionId: "7" }, runner); + expect(first.unchanged).toBeUndefined(); + const again = await fetchFeishuDocSnapshot({ url: "https://example.test/docx/a", docsApiVersion: "v2", + unchangedRevisionId: "7", unchangedAccess: first.access }, runner); + expect(again.accessIdentity).toBe("user"); + expect(again.unchanged).toBe(true); + // A snapshot that was read as the user on purpose did not record this fallback yet. + const newFallback = await fetchFeishuDocSnapshot({ url: "https://example.test/docx/a", docsApiVersion: "v2", + unchangedRevisionId: "7", unchangedAccess: { identity: "user" } }, runner); + expect(newFallback.unchanged).toBeUndefined(); + expect(newFallback.access.fallback?.cause).toBe("lark error 3380004"); + }); + + test("the official capture phase honors the environment without an identity argument", async () => { process.env.CONTEXT_LARK_IDENTITY = "bot"; const root = makeLarkCaptureTmp(); @@ -157,6 +224,31 @@ describe("configured Lark read identity", () => { } }); + test("a capture that fell back to the user stays visible in a later status read", async () => { + process.env.CONTEXT_LARK_IDENTITY = "bot"; + const root = makeLarkCaptureTmp(); + try { + const cwd = await createLarkCaptureProject(root); + const output = JSON.parse(await runLarkCapturePhase({ cwd, phaseId: "capture:lark:handbook", format: "json", + larkRunner: async args => { + if (args.includes("--help")) return { ...success, stdout: "Flags:\n --doc-format string\n --api-version string\n" }; + if (as(args) === "bot") return { exitCode: 1, stdout: "", stderr: JSON.stringify({ ok: false, identity: "bot", + error: { type: "api", subtype: "unknown", code: 3380004, message: "No permission to operate on this document" } }) }; + return { ...success, stdout: JSON.stringify({ ok: true, identity: "user", data: { + document: { content: "Body
" } } }) }; + }, + })); + expect(output.result.access).toMatchObject({ identity: "user", fallback: { cause: "lark error 3380004" } }); + expect(output.result.diagnostics.join("\n")).toContain("lark.capture.identity-fallback"); + const { readSourceStatus } = await import("../project/statusReaders.js"); + const source = (await readSourceStatus(cwd)).documentSources.find(item => item.name === "handbook")!; + expect(source.snapshotReady).toBe(true); + expect(source.diagnostics.join("\n")).toContain("lark.capture.identity-fallback: the bot could not read this document (lark error 3380004)"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + test("returns user error if both identities fail", async () => { const seen: string[] = []; const runner: LarkRunner = async args => { diff --git a/packages/context-cli/src/__tests__/projectCaptureLarkV062.test.ts b/packages/context-cli/src/__tests__/projectCaptureLarkV062.test.ts index 744204dd..8af0ab95 100644 --- a/packages/context-cli/src/__tests__/projectCaptureLarkV062.test.ts +++ b/packages/context-cli/src/__tests__/projectCaptureLarkV062.test.ts @@ -361,6 +361,32 @@ describe("0.6.2 Lark capture phase", () => { } }); + test("capture:lark warning for a denied document keeps the Lark error and the owner-sharing step", async () => { + const root = makeTmp(); + try { + const projectRoot = await createLarkProject(root); + const runner: LarkRunner = async (args) => { + if (args.includes("--help")) { + return { stdout: "Flags:\n --api-version string\n --doc-format string\n", stderr: "", exitCode: 0 }; + } + // Recorded from lark-cli 1.0.98 for an identity that cannot view the document. + return { stdout: "", exitCode: 1, stderr: JSON.stringify({ ok: false, identity: "user", error: { + type: "api", subtype: "unknown", code: 3380004, + message: "No permission to operate on this document: the current user lacks view or edit access.", + } }) }; + }; + const result = JSON.parse(await runPhase({ + cwd: projectRoot, phaseId: "capture:lark:handbook", format: "json", larkRunner: runner, + })); + expect(result.result.warning).toMatchObject({ state: "deferred-no-evidence", cause: "external.authorization-required" }); + expect(result.result.warning.stderr).toContain("3380004"); + expect(result.result.warning.next).toContain("owner to share it"); + expect(result.result.warning.next).not.toContain("auth login"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + test("capture:lark classifies unavailable credential storage as a host execution requirement", async () => { const root = makeTmp(); try { diff --git a/packages/context-cli/src/lib/feishu.ts b/packages/context-cli/src/lib/feishu.ts index 256bc81e..e97590b1 100644 --- a/packages/context-cli/src/lib/feishu.ts +++ b/packages/context-cli/src/lib/feishu.ts @@ -15,7 +15,7 @@ import { type LarkResourceMaterializationPolicy, type LarkResourceMaterializationReport, } from "./larkResourceMaterialization.js"; -import { createLarkCaptureReport } from "./larkCaptureReport.js"; +import { createLarkCaptureReport, sameLarkAccess, type LarkAccessEvent, type LarkCaptureAccess } from "./larkCaptureReport.js"; import { larkMarkdownImageResources, replaceLarkMarkdownImages } from "./larkMarkdownImages.js"; import { createLarkReadSession, resolveLarkReadIdentity } from "./larkReadIdentity.js"; @@ -109,6 +109,10 @@ export interface PrefetchedLarkDocument { export interface FetchFeishuDocInput { /** A validated local snapshot may skip embedded downloads at this revision. */ unchangedRevisionId?: string; + /** Access recorded with that snapshot; different access facts this time are captured again. */ + unchangedAccess?: LarkCaptureAccess; + /** Collects access changes made during this read (e.g. a viewer added); recorded in the capture report. */ + accessEvents?: LarkAccessEvent[]; requireCompleteBody?: boolean; /** Explicit standalone reads can lock identity; existing capture defaults remain unchanged. */ allowIdentityFallback?: boolean; @@ -151,6 +155,7 @@ export interface FetchFeishuDocSnapshotResult { resourceMaterialization: LarkResourceMaterializationReport; accessIdentity: LarkAccessIdentity; identityFallback: boolean; + access: LarkCaptureAccess; } export const DEFAULT_RESOURCE_POLICY: LarkResourceMaterializationPolicy = { @@ -455,6 +460,7 @@ function captureReportAsset(input: { fidelity: LarkCaptureFidelityReport; resourceMaterialization: LarkResourceMaterializationReport; resources: readonly LarkExternalResource[]; + access: LarkCaptureAccess; }): FetchFeishuDocAsset { const report = createLarkCaptureReport(input); return { @@ -696,17 +702,28 @@ export async function fetchFeishuDocSnapshot( }, }); } + const identityFallback = identityFetch.fallback || session.usedFallback; + const access: LarkCaptureAccess = { + identity: accessIdentity, + // Only the bot → user direction is recorded; legacy `auto` falls back the other way (user → bot). + ...(session.usedFallback ? { fallback: { from: "bot" as const, cause: session.fallbackCause ?? "credential failure" } } : {}), + ...(input.accessEvents?.length ? { events: [...input.accessEvents] } : {}), + }; + // Changed access facts (identity, fallback, events) must be recorded, so they cannot reuse the earlier + // snapshot; repeating the same facts can. Snapshots from before access was recorded are reused unless + // this read had to fall back. + const sameAccess = !input.accessEvents?.some(event => event.changed_access) && (input.unchangedAccess === undefined + ? !identityFallback : sameLarkAccess(input.unchangedAccess, access)); // Do not download embedded resources for an unchanged, complete document or // for an incomplete body that capture cannot safely promote. - if ((revisionId !== undefined && revisionId === input.unchangedRevisionId && fidelity.evidence_status !== "error" && fidelity.projection_status !== "error") || + if ((sameAccess && revisionId !== undefined && revisionId === input.unchangedRevisionId && fidelity.evidence_status !== "error" && fidelity.projection_status !== "error") || (input.requireCompleteBody === true && (fidelity.evidence_status === "error" || fidelity.projection_status === "error"))) { return { markdown: body, ...(title === undefined ? {} : { title }), ...(revisionId === undefined ? {} : { revisionId }), - ...(revisionId === input.unchangedRevisionId && fidelity.evidence_status !== "error" && fidelity.projection_status !== "error" ? { unchanged: true } : {}), - assets, fidelity, resourceMaterialization, accessIdentity, - identityFallback: identityFetch.fallback || session.usedFallback, + ...(sameAccess && revisionId === input.unchangedRevisionId && fidelity.evidence_status !== "error" && fidelity.projection_status !== "error" ? { unchanged: true } : {}), + assets, fidelity, resourceMaterialization, accessIdentity, identityFallback, access, }; } const resources = [...new Map([...(projection?.resources ?? []), ...larkMarkdownImageResources(body)] @@ -754,6 +771,7 @@ export async function fetchFeishuDocSnapshot( fidelity, resourceMaterialization, resources, + access, })); // Prepend title as H1 if the readable projection doesn't already lead with one — @@ -768,7 +786,8 @@ export async function fetchFeishuDocSnapshot( fidelity, resourceMaterialization, accessIdentity, - identityFallback: identityFetch.fallback || session.usedFallback, + identityFallback, + access, }; } return { @@ -779,7 +798,8 @@ export async function fetchFeishuDocSnapshot( fidelity, resourceMaterialization, accessIdentity, - identityFallback: identityFetch.fallback || session.usedFallback, + identityFallback, + access, }; } diff --git a/packages/context-cli/src/lib/larkCaptureReport.ts b/packages/context-cli/src/lib/larkCaptureReport.ts index 918c91fb..45d3cd8c 100644 --- a/packages/context-cli/src/lib/larkCaptureReport.ts +++ b/packages/context-cli/src/lib/larkCaptureReport.ts @@ -15,11 +15,30 @@ export interface LarkCaptureReportResource extends DocumentResourceMaterializati attributes: Record