Merge pull request #75 from yunyingk/codex/sync-test-knowledge-documents
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled

Add full coverage knowledge document synchronization to sync-test
This commit is contained in:
yunyingk authored and GitHub committed 2026-09-11 12:21:29 +08:00
commit 39ca400322
8 files changed
+327 -31

No files matched your search

+12
View File
@@ -1369,6 +1369,18 @@
}
}
}
},
"delete": {
"tags": [
"Approval Knowledge"
],
"operationId": "deleteApprovalDocument",
"summary": "Delete approval knowledge document",
"responses": {
"200": {
"description": "Deleted document confirmation."
}
}
}
},
"/v1/approval/style-preferences": {
+7
View File
@@ -265,6 +265,13 @@ paths:
application/json:
schema:
$ref: ../components/schemas/index.yaml#/ApprovalDocument
delete:
tags: [Approval Knowledge]
operationId: deleteApprovalDocument
summary: Delete approval knowledge document
responses:
"200":
description: Deleted document confirmation.
/v1/approval/style-preferences:
get:
tags: [Approval Knowledge]
+122 -2
View File
@@ -256,6 +256,15 @@ describe("corps sync-test", () => {
expect(parsed.rulesPlan.targetExistingDraftRuleCount).toBe(1);
expect(parsed.rulesPlan.toDeleteCount).toBe(1);
expect(parsed.rulesPlan.toCreateCount).toBe(2);
expect(parsed.documentsPlan).toBeDefined();
expect(parsed.documentsPlan.sourceDocumentCount).toBe(2);
expect(parsed.documentsPlan.targetExistingDocumentCount).toBe(2);
expect(parsed.documentsPlan.toCreateCount).toBe(1);
expect(parsed.documentsPlan.toCreate[0].title).toBe("Doc Alpha");
expect(parsed.documentsPlan.toUpdateCount).toBe(1);
expect(parsed.documentsPlan.toUpdate[0].title).toBe("Doc Beta");
expect(parsed.documentsPlan.toDeleteCount).toBe(1);
expect(parsed.documentsPlan.toDelete[0].title).toBe("Doc Gamma Old");
expect(parsed.productionGuarantees.prodRulesStayDraft).toBe(true);
expect(parsed.productionGuarantees.prodVersionPublished).toBe(false);
@@ -304,6 +313,15 @@ describe("corps sync-test", () => {
expect(parsed.target.createdDraftRulesCount).toBe(2);
expect(parsed.target.publishedVersion.versionName).toBe("v1.5-staging");
expect(parsed.target.publishedVersion.versionNumber).toBe(3);
expect(parsed.documents).toBeDefined();
expect(parsed.documents.sourceCount).toBe(2);
expect(parsed.documents.targetExistingCount).toBe(2);
expect(parsed.documents.createdCount).toBe(1);
expect(parsed.documents.created[0].title).toBe("Doc Alpha");
expect(parsed.documents.updatedCount).toBe(1);
expect(parsed.documents.updated[0].title).toBe("Doc Beta");
expect(parsed.documents.deletedCount).toBe(1);
expect(parsed.documents.deleted[0].title).toBe("Doc Gamma Old");
expect(parsed.productionGuarantees.prodRulesStayDraft).toBe(true);
expect(parsed.productionGuarantees.prodVersionPublished).toBe(false);
@@ -319,6 +337,17 @@ describe("corps sync-test", () => {
expect(postPref).toBeDefined();
expect((postPref?.body as any).decisionPreferences?.explicitApprove).toBe("Prod approve note");
const deleteDoc = requests.find((r) => r.method === "DELETE" && r.path === "/api/v1/knowledge/articles/test-doc-old");
expect(deleteDoc).toBeDefined();
const patchDoc = requests.find((r) => r.method === "PATCH" && r.path === "/api/v1/knowledge/articles/test-doc-2");
expect(patchDoc).toBeDefined();
expect((patchDoc?.body as any).attributes?.content).toBe("Content Beta Updated");
const postDoc = requests.find((r) => r.method === "POST" && r.path === "/api/v1/knowledge/articles");
expect(postDoc).toBeDefined();
expect((postDoc?.body as any).title).toBe("Doc Alpha");
const deleteRule = requests.find((r) => r.method === "DELETE" && r.path === "/api/v1/rules/test-rule-old");
expect(deleteRule).toBeDefined();
@@ -335,7 +364,7 @@ describe("corps sync-test", () => {
expect(allPublishCalls.length).toBe(1);
});
test("sync-test formats semantic version name [Prod v22 · #1] and rules map inspects local snapshot", async () => {
test("sync-test formats semantic version name [Prod v22 · #1 -> Test v3] and rules map inspects local snapshot", async () => {
setupTestEnv();
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
@@ -353,7 +382,7 @@ describe("corps sync-test", () => {
expect(syncResult.isError).toBe(false);
const parsed = JSON.parse(syncResult.stdout);
expect(parsed.target.publishedVersion.versionName).toBe("Sync from Acme Production [Prod v22 · #1]");
expect(parsed.target.publishedVersion.versionName).toBe("Sync from Acme Production [Prod v22 · #1 -> Test v3]");
expect(parsed.versionMapping.sourceProdVersionNumber).toBe(22);
expect(parsed.ruleMapping).toHaveLength(2);
@@ -458,6 +487,97 @@ function mockSealSyncRequests(options: {
return jsonResponse({ data: { success: true } });
}
if (url.pathname === "/api/v1/knowledge/articles" && method === "GET") {
if (isProd) {
return jsonResponse({
data: {
articles: [
{
id: "prod-doc-1",
title: "Doc Alpha",
purpose: "Purpose Alpha",
content: "Content Alpha",
contentType: "policy",
status: "published",
enabled: true,
scenarios: ["audit"],
tags: []
},
{
id: "prod-doc-2",
title: "Doc Beta",
purpose: "Purpose Beta",
content: "Content Beta Updated",
contentType: "policy",
status: "published",
enabled: true,
scenarios: ["audit"],
tags: []
}
],
total: 2
}
});
} else {
return jsonResponse({
data: {
articles: [
{
id: "test-doc-2",
title: "Doc Beta",
purpose: "Purpose Beta",
content: "Content Beta Old",
contentType: "policy",
status: "published",
enabled: true,
scenarios: ["audit"],
tags: []
},
{
id: "test-doc-old",
title: "Doc Gamma Old",
purpose: "Redundant doc",
content: "To be deleted",
contentType: "policy",
status: "published",
enabled: true,
scenarios: ["audit"],
tags: []
}
],
total: 2
}
});
}
}
if (url.pathname.startsWith("/api/v1/knowledge/articles/") && method === "DELETE") {
options.onMutation?.("DELETE", url.pathname);
return jsonResponse({ data: { success: true } });
}
if (url.pathname.startsWith("/api/v1/knowledge/articles/") && method === "PATCH") {
const body = JSON.parse(rawBody || "{}");
options.onMutation?.("PATCH", url.pathname, body);
return jsonResponse({
data: {
id: url.pathname.split("/").pop(),
...body.attributes
}
});
}
if (url.pathname === "/api/v1/knowledge/articles" && method === "POST") {
const body = JSON.parse(rawBody || "{}");
options.onMutation?.("POST", url.pathname, body);
return jsonResponse({
data: {
id: `new-doc-${Date.now()}`,
...body
}
});
}
if (url.pathname === "/api/v1/rules" && method === "GET") {
if (isProd) {
return jsonResponse({
+146 -15
View File
@@ -283,22 +283,82 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
const prodClient = await createSealClient(prodCorp);
const testClient = await createSealClient(testCorp);
const prodPref = (await api.getApprovalStylePreferences(prodClient, prodCorp.seal.endpoints.approvalStylePreferences)) as any;
const testPref = (await api.getApprovalStylePreferences(testClient, testCorp.seal.endpoints.approvalStylePreferences)) as any;
const [
prodPref,
testPref,
prodRules,
testRules,
prodVersions,
testVersions,
prodDocsRes,
testDocsRes
] = await Promise.all([
api.getApprovalStylePreferences(prodClient, prodCorp.seal.endpoints.approvalStylePreferences).catch(() => ({} as any)),
api.getApprovalStylePreferences(testClient, testCorp.seal.endpoints.approvalStylePreferences).catch(() => ({} as any)),
api.listApprovalRules(prodClient),
api.listApprovalRules(testClient),
api.listApprovalRuleVersions(prodClient).catch(() => []),
api.listApprovalRuleVersions(testClient).catch(() => []),
api.listApprovalDocuments(prodClient, { limit: 100 }).catch(() => ({ articles: [] })),
api.listApprovalDocuments(testClient, { limit: 100 }).catch(() => ({ articles: [] }))
]);
const prodRules = await api.listApprovalRules(prodClient);
const testRules = await api.listApprovalRules(testClient);
const prodDocs = (prodDocsRes.articles || []).filter((d) => !d.isDeleted);
const testDocs = (testDocsRes.articles || []).filter((d) => !d.isDeleted);
const prodVersions = await api.listApprovalRuleVersions(prodClient).catch(() => []);
const testVersions = await api.listApprovalRuleVersions(testClient).catch(() => []);
const testDocsByTitle = new Map(testDocs.map((d) => [d.title.trim(), d]));
const docsToCreate = [];
const docsToUpdate = [];
const prodTitles = new Set(prodDocs.map((d) => d.title.trim()));
for (const prodDoc of prodDocs) {
const title = prodDoc.title.trim();
const existing = testDocsByTitle.get(title);
if (!existing) {
docsToCreate.push(prodDoc);
} else {
const contentChanged = existing.content !== prodDoc.content;
const purposeChanged = (existing.purpose ?? "") !== (prodDoc.purpose ?? "");
const enabledChanged = existing.enabled !== prodDoc.enabled;
const contentTypeChanged = existing.contentType !== prodDoc.contentType;
const statusChanged = (existing.status ?? "") !== (prodDoc.status ?? "");
const scenariosChanged = JSON.stringify([...(existing.scenarios ?? [])].sort()) !==
JSON.stringify([...(prodDoc.scenarios ?? [])].sort());
const tagsChanged = JSON.stringify([...(existing.tags ?? [])].sort()) !==
JSON.stringify([...(prodDoc.tags ?? [])].sort());
if (contentChanged || purposeChanged || enabledChanged || contentTypeChanged || statusChanged || scenariosChanged || tagsChanged) {
docsToUpdate.push({
testId: existing.id,
prodDoc,
reasons: [
...(contentChanged ? ["content"] : []),
...(purposeChanged ? ["purpose"] : []),
...(enabledChanged ? ["enabled"] : []),
...(contentTypeChanged ? ["contentType"] : []),
...(statusChanged ? ["status"] : []),
...(scenariosChanged ? ["scenarios"] : []),
...(tagsChanged ? ["tags"] : [])
]
});
}
}
}
const docsToDelete = testDocs.filter(
(td) => !prodTitles.has(td.title.trim())
);
const sortedProdVersions = [...prodVersions].sort((a, b) => b.versionNumber - a.versionNumber);
const latestProd = sortedProdVersions[0];
const prodVersionNumber = latestProd?.versionNumber;
const sortedTestVersions = [...testVersions].sort((a, b) => b.versionNumber - a.versionNumber);
const targetTestExpectedVersionNumber = (sortedTestVersions[0]?.versionNumber ?? 0) + 1;
const nextIteration = computeNextSyncIteration(prodCorp.name, prodVersionNumber, testVersions);
const customVersionName = stringOption(args.options["version-name"]) ?? stringOption(args.options.versionName);
const versionName = customVersionName ?? formatSyncVersionName(prodCorp.name, prodVersionNumber, nextIteration);
const versionName = customVersionName ?? formatSyncVersionName(prodCorp.name, prodVersionNumber, nextIteration, targetTestExpectedVersionNumber);
const updatedTestPref = {
...testPref,
@@ -324,7 +384,8 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
latestPublishedVersion: latestProd ? {
versionNumber: latestProd.versionNumber,
versionName: latestProd.versionName
} : null
} : null,
documentsCount: prodDocs.length
},
target: {
id: testCorp.id,
@@ -334,7 +395,7 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
versionMappingPlan: {
sourceProdVersionNumber: prodVersionNumber ?? null,
sourceProdVersionName: latestProd?.versionName ?? null,
targetTestExpectedVersionNumber: (testVersions[0]?.versionNumber ?? 0) + 1,
targetTestExpectedVersionNumber,
targetTestPublishVersionName: versionName,
iteration: nextIteration
},
@@ -363,6 +424,28 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
strictness: r.strictness
}))
},
documentsPlan: {
sourceDocumentCount: prodDocs.length,
targetExistingDocumentCount: testDocs.length,
toCreateCount: docsToCreate.length,
toCreate: docsToCreate.map((d) => ({
title: d.title,
purpose: d.purpose,
contentType: d.contentType,
scenarios: d.scenarios
})),
toUpdateCount: docsToUpdate.length,
toUpdate: docsToUpdate.map((d) => ({
targetDocumentId: d.testId,
title: d.prodDoc.title,
reasons: d.reasons
})),
toDeleteCount: docsToDelete.length,
toDelete: docsToDelete.map((d) => ({
targetDocumentId: d.id,
title: d.title
}))
},
publishingPlan: {
targetCorpId: testCorp.id,
publishVersionName: versionName,
@@ -379,7 +462,7 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
throw confirmationRequired(
`Refusing to overwrite test enterprise '${testCorp.name}' (${testCorp.id}) with preferences and ${prodRules.rules.length} draft rules from production enterprise '${prodCorp.name}' (${prodCorp.id}) without --yes. This will replace test draft rules and publish a new version on the test enterprise.`,
`Refusing to overwrite test enterprise '${testCorp.name}' (${testCorp.id}) with preferences, ${prodRules.rules.length} draft rules, and ${prodDocs.length} knowledge documents from production enterprise '${prodCorp.name}' (${prodCorp.id}) without --yes. This will replace test draft rules, synchronize knowledge documents, and publish a new version on the test enterprise.`,
`seal-use corps sync-test ${prodCorp.id} --yes`
);
}
@@ -387,12 +470,49 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
// 1. Update style & decision preferences in test enterprise
await api.updateApprovalStylePreferences(testClient, updatedTestPref, testCorp.seal.endpoints.approvalStylePreferences);
// 2. Clear old draft rules in test enterprise
// 2. Synchronize knowledge documents in test enterprise (full coverage, delete redundant test documents)
const deletedDocs: Array<{ id: string; title: string }> = [];
for (const doc of docsToDelete) {
await api.deleteApprovalDocument(testClient, doc.id);
deletedDocs.push({ id: doc.id, title: doc.title });
}
const updatedDocs: Array<{ id: string; title: string; reasons: string[] }> = [];
for (const item of docsToUpdate) {
await api.updateApprovalDocument(testClient, item.testId, {
title: item.prodDoc.title,
purpose: item.prodDoc.purpose,
content: item.prodDoc.content,
contentType: item.prodDoc.contentType,
status: item.prodDoc.status,
enabled: item.prodDoc.enabled,
scenarios: item.prodDoc.scenarios && item.prodDoc.scenarios.length > 0 ? item.prodDoc.scenarios : ["audit"],
tags: item.prodDoc.tags
});
updatedDocs.push({ id: item.testId, title: item.prodDoc.title, reasons: item.reasons });
}
const createdDocs: Array<{ id: string; title: string }> = [];
for (const doc of docsToCreate) {
const created = await api.createApprovalDocument(testClient, {
title: doc.title,
purpose: doc.purpose,
content: doc.content,
contentType: doc.contentType,
status: doc.status,
enabled: doc.enabled,
scenarios: doc.scenarios && doc.scenarios.length > 0 ? doc.scenarios : ["audit"],
tags: doc.tags
});
createdDocs.push({ id: created.id, title: created.title });
}
// 3. Clear old draft rules in test enterprise
for (const rule of testRules.rules) {
await api.deleteApprovalRule(testClient, rule.id);
}
// 3. Create new draft rules in test enterprise
// 4. Create new draft rules in test enterprise
const createdRules: any[] = [];
for (const rule of prodRules.rules) {
const created = await api.createApprovalRule(testClient, {
@@ -403,10 +523,10 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
createdRules.push(created);
}
// 4. Batch recode rules in test enterprise
// 5. Batch recode rules in test enterprise
await api.recodeApprovalRules(testClient).catch(() => undefined);
// 5. Publish new version in test enterprise
// 6. Publish new version in test enterprise
const published = await api.publishApprovalRuleVersion(testClient, versionName);
const publishedRules = published.version.rules ?? [];
@@ -465,7 +585,8 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
versionNumber: latestProd.versionNumber,
versionName: latestProd.versionName
} : null,
draftRulesCount: prodRules.rules.length
draftRulesCount: prodRules.rules.length,
documentsCount: prodDocs.length
},
target: {
id: testCorp.id,
@@ -480,6 +601,16 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
rulesCount: published.rulesCount
}
},
documents: {
sourceCount: prodDocs.length,
targetExistingCount: testDocs.length,
createdCount: createdDocs.length,
created: createdDocs,
updatedCount: updatedDocs.length,
updated: updatedDocs,
deletedCount: deletedDocs.length,
deleted: deletedDocs
},
versionMapping,
ruleMapping,
...(mappingSavedTo ? { mappingSavedTo } : {}),
+11 -1
View File
@@ -215,6 +215,7 @@ export async function createApprovalDocument(
content: string;
contentType?: string;
status?: string;
enabled?: boolean;
scenarios?: string[];
tags?: string[];
}
@@ -225,7 +226,8 @@ export async function createApprovalDocument(
...params,
contentType: params.contentType ?? "policy",
status: params.status ?? "published",
scenarios: params.scenarios ?? [],
enabled: params.enabled ?? true,
scenarios: params.scenarios && params.scenarios.length > 0 ? params.scenarios : ["audit"],
tags: params.tags ?? []
}
}),
@@ -259,6 +261,14 @@ export async function updateApprovalDocument(
);
}
export async function deleteApprovalDocument(
client: KyInstance,
documentId: string
): Promise<{ success: boolean; id: string }> {
await client.delete(`api/v1/knowledge/articles/${documentId}`);
return { success: true, id: documentId };
}
export async function getApprovalStylePreferences(
client: KyInstance,
endpoint = "api/v1/agent/ai-approval/config"
+12 -9
View File
@@ -148,36 +148,39 @@ describe("rule-mapping", () => {
])
).toBe(2);
// 3. Structured iterations exist for same prodVersion
// 3. Structured iterations exist for same prodVersion (including with target test version)
expect(
computeNextSyncIteration("Acme Corp", 22, [
{ versionName: "Sync from Acme Corp [Prod v22 · #1]" },
{ versionName: "Sync from Acme Corp [Prod v22 · #2]" }
{ versionName: "Sync from Acme Corp [Prod v22 · #1 -> Test v1]" },
{ versionName: "Sync from Acme Corp [Prod v22 · #2 -> Test v2]" }
])
).toBe(3);
// 4. Production version bumped to 23 -> resets to 1
expect(
computeNextSyncIteration("Acme Corp", 23, [
{ versionName: "Sync from Acme Corp [Prod v22 · #1]" },
{ versionName: "Sync from Acme Corp [Prod v22 · #2]" }
{ versionName: "Sync from Acme Corp [Prod v22 · #1 -> Test v1]" },
{ versionName: "Sync from Acme Corp [Prod v22 · #2 -> Test v2]" }
])
).toBe(1);
// 5. Production has no published version (draft only)
expect(
computeNextSyncIteration("Acme Corp", undefined, [
{ versionName: "Sync from Acme Corp [Prod draft · #1]" }
{ versionName: "Sync from Acme Corp [Prod draft · #1 -> Test v1]" }
])
).toBe(2);
});
test("formatSyncVersionName formats cleanly without redundant date", () => {
test("formatSyncVersionName formats cleanly with test version mapping", () => {
expect(formatSyncVersionName("Acme Corp", 22, 1, 3)).toBe(
"Sync from Acme Corp [Prod v22 · #1 -> Test v3]"
);
expect(formatSyncVersionName("Acme Corp", 22, 1)).toBe(
"Sync from Acme Corp [Prod v22 · #1]"
);
expect(formatSyncVersionName("Acme Corp", undefined, 1)).toBe(
"Sync from Acme Corp [Prod draft · #1]"
expect(formatSyncVersionName("Acme Corp", undefined, 1, 5)).toBe(
"Sync from Acme Corp [Prod draft · #1 -> Test v5]"
);
});
});
+6 -4
View File
@@ -108,8 +108,8 @@ export function computeNextSyncIteration(
): number {
let maxIteration = 0;
const prefixRegex = prodVersionNumber !== undefined
? new RegExp(`\\[Prod v${prodVersionNumber}\\s*·\\s*#(\\d+)\\]`)
: /\[Prod draft\s*·\s*#(\d+)\]/;
? new RegExp(`\\[Prod v${prodVersionNumber}\\s*·\\s*#(\\d+)(?:[^\\]]*)\\]`)
: /\[Prod draft\s*·\s*#(\d+)(?:[^\]]*)\]/;
for (const tv of testVersions) {
if (!tv.versionName) continue;
@@ -145,8 +145,10 @@ export function computeNextSyncIteration(
export function formatSyncVersionName(
prodCorpName: string,
prodVersionNumber: number | undefined,
iteration: number
iteration: number,
targetTestVersionNumber?: number
): string {
const prodLabel = prodVersionNumber !== undefined ? `Prod v${prodVersionNumber}` : "Prod draft";
return `Sync from ${prodCorpName} [${prodLabel} · #${iteration}]`;
const testLabel = targetTestVersionNumber !== undefined ? ` -> Test v${targetTestVersionNumber}` : "";
return `Sync from ${prodCorpName} [${prodLabel} · #${iteration}${testLabel}]`;
}
+11
View File
@@ -847,6 +847,7 @@ export const sealTools = [
content: z.string().describe("正文,通常为 Markdown"),
contentType: z.string().optional(),
status: z.string().optional(),
enabled: z.boolean().optional(),
scenarios: z.array(z.string()).optional(),
tags: z.array(z.string()).optional()
}),
@@ -858,6 +859,7 @@ export const sealTools = [
content: string;
contentType?: string;
status?: string;
enabled?: boolean;
scenarios?: string[];
tags?: string[];
}
@@ -895,6 +897,15 @@ export const sealTools = [
return api.updateApprovalDocument(client, documentId, rest);
}
},
{
name: "seal_approval_delete_document",
description: "删除 Seal 审批知识文档",
parameters: z.object({
documentId: z.string().describe("知识文档 ID")
}),
handler: (client: KyInstance, params: { documentId: string }) =>
api.deleteApprovalDocument(client, params.documentId)
},
{
name: "seal_approval_search",
description: "按关键词组检索 Seal 审批规则、审批文档和审批偏好配置,返回命中位置、字段、行号和前后三行上下文",