Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 4 additions & 1 deletion packages/context-cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions packages/context-cli/README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ Provider Skill 投影到 Claude、Codex 和 Cursor 的用户技能目录。
命令的 shell 都需传入该环境变量;仅在提示词中写配置并不会自动导出环境变量。
`bot` 模式先使用应用身份,遇到凭证、scope 或访问权限错误时回退当前用户一次,
本次采集后续分页、引用与资源下载沿用回退身份。网络、限流和解析错误不切换身份。
采集报告记录读取身份与回退原因;`context status` 会持续提示该回退:仅该用户可见的内容
已进入快照,之后用机器人采集可能读不到。
该配置不扩大来源授权或知识产物可见范围;托管运行时的用户授权遵循宿主流程。

## 一个 Agent 入口如何驱动整套工作流
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

});
Original file line number Diff line number Diff line change
Expand Up @@ -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([
Expand Down
92 changes: 92 additions & 0 deletions packages/context-cli/src/__tests__/larkReadIdentity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down Expand Up @@ -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: "<p>Body</p>" } } }),
};
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: "<p>Body</p>", 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: "<p>Body</p>", 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();
Expand All @@ -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: "<title>Handbook</title><p>Body</p>" } } }) };
},
}));
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 => {
Expand Down
26 changes: 26 additions & 0 deletions packages/context-cli/src/__tests__/projectCaptureLarkV062.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading
Loading