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

- `context task rollback` no longer gets stuck with an unfinished production stage: `context close` and the build accept the active rollback, and the rollback cleanup removes the stage. Previously close stopped with `production-not-complete` and the cleanup could not run.
- The rollback preview shows what happens to the current production stage (`production.effect`): `discard-whole-task` deletes the stage, its unfinished tasks and its working directory at cleanup; `keep` means only a page revision that interrupted production is rolled back, and production resumes unchanged. Previously abandoning such a revision also deleted production.
- While a rollback is active, the build no longer checks a partial-delivery selection that the rollback removed ("No reviewed articles can be delivered"); the rollback cleanup settles it.
- Rollback cleanup removes production before the rollback record, so a cleanup that fails can be retried.

## 0.7.98 - 2026-11-11

- 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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,11 @@ restoring an absent file. Include changed sources/configuration/processed scopes
when they belong to the rollback. Leave unrelated and pre-existing edits alone.
An empty list only discards unfinished work and must not be described as undoing
already delivered pages. The preview shows actual before/after contents and
draft loss. Once the user approves that exact scope, run the preview's apply
draft loss, including the open production stage: `production.effect` is
`discard-whole-task` (cleanup deletes the stage, its unfinished tasks and every
unsubmitted file in its working directory) or `keep` (only a page revision that
interrupted production is rolled back; production resumes unchanged). State this
to the user. Once the user approves that exact scope, run the preview's apply
command with its plan digest. Then follow the rollback Route through close,
build and cleanup. A failed build retries delivery, not the already-applied
reversions. Begin the independent task only after cleanup succeeds.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,11 @@ restoring an absent file. Include changed sources/configuration/processed scopes
when they belong to the rollback. Leave unrelated and pre-existing edits alone.
An empty list only discards unfinished work and must not be described as undoing
already delivered pages. The preview shows actual before/after contents and
draft loss. Once the user approves that exact scope, run the preview's apply
draft loss, including the open production stage: `production.effect` is
`discard-whole-task` (cleanup deletes the stage, its unfinished tasks and every
unsubmitted file in its working directory) or `keep` (only a page revision that
interrupted production is rolled back; production resumes unchanged). State this
to the user. Once the user approves that exact scope, run the preview's apply
command with its plan digest. Then follow the rollback Route through close,
build and cleanup. A failed build retries delivery, not the already-applied
reversions. Begin the independent task only after cleanup succeeds.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -708,3 +708,51 @@ test("the actual completion command accepts stage-relative file results and retu
expect(value.stage_state).toBe("ended");
expect(value).not.toHaveProperty("result_file");
}, 30_000);

test("rolling back a partially delivered article discards the task without the stale delivery blocking build", async () => {
const { rollbackProjectTask, finishTaskRollback, readTaskRollback } = await import("../project/taskRollback.js");
const f = await fixture(true);
execFileSync("git", ["init", "--quiet"], { cwd: f.root });
const approveAll = async () => {
const candidates = await readCandidateRecords(f.root);
const ids = candidates.map(candidate => candidate.candidate_id).sort();
await applyReviewDecisions({ projectRoot: f.root, payload: { scope: { kind: "all", count: ids.length,
visible_candidate_ids: ids, ids_sha256: candidateIdsHash(ids), candidates_sha256: candidateSetHash(candidates) },
decisions: ids.map(candidate_id => ({ candidate_id, status: "approved" })) } });
};
// Round 1 delivers article A ("one"); task "two" stays unfinished.
await writeFile(join(f.directory, f.input.path), YAML.stringify({ ...f.manifest, tasks: [f.manifest.tasks[0]] }));
await completeProductionSubmission(f.input);
await requestProductionDelivery(f.root);
await approveAll();
await closeProjectWorkspace(f.root);
await cp(resolve(import.meta.dir, "../../../context/templates/package-templates/kb"), join(f.root, "src/package-templates/kb"), { recursive: true });
const entryPath = join(f.root, "src/index.ts");
await writeFile(entryPath, (await readFile(entryPath, "utf8")).replace("import { defineProject }", "import { defineProject, kbPackage }")
.replace("packages: []", 'packages: [kbPackage({ name: "rollback-kb", template: { path: "src/package-templates/kb", vars: {} } })]'));
await acceptStarterPackageTemplates({ projectRoot: f.root });
await buildFixturePackages(f.root);
// Round 2 selects new article B ("two") for delivery and approves it.
await writeFile(join(f.directory, f.input.path), YAML.stringify({ ...f.manifest, tasks: [f.manifest.tasks[1]] }));
await completeProductionSubmission(f.input);
await requestProductionDelivery(f.root);
expect((await readProductionStage(f.root))!.delivery).toContain("two");
// The reviewer's case: only B is selected for this delivery (A came from an earlier one).
await saveProductionStage(f.root, { ...(await readProductionStage(f.root))!, delivery: ["two"] });
await approveAll();
await closeProjectWorkspace(f.root);
// Rolling B back deletes it and discards the current task.
const bPath = "knowledge/architecture/two.md";
const b = await readFile(join(f.root, bPath), "utf8");
const value = { summary: "Remove article B and discard the current task.", discard_unfinished: true as const,
files: [{ path: bPath, base_digest: durableContentDigest(b), content: null }] };
const plan = await rollbackProjectTask({ projectRoot: f.root, value });
await rollbackProjectTask({ projectRoot: f.root, value, apply: true, plan_digest: plan.revision });
await closeProjectWorkspace(f.root);
await buildFixturePackages(f.root);
await finishTaskRollback(f.root);
expect(await readTaskRollback(f.root)).toBeUndefined();
expect(await readProductionStage(f.root)).toBeUndefined();
expect(await readFile(join(f.root, "knowledge/architecture/one.md"), "utf8")).toContain("Combined behavior.");
await expect(readFile(join(f.root, bPath), "utf8")).rejects.toThrow();
}, 120_000);
81 changes: 81 additions & 0 deletions packages/context-cli/src/__tests__/projectKnowledgeUpdate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,87 @@ test("explicit rollback restores selected delivered bytes, discards drafts and k
expect(await readKnowledgeUpdate(root)).toBeDefined();
}, 60_000);

test("explicit rollback with an unfinished production stage closes, builds and clears the unfinished stage", async () => {
const { rollbackProjectTask, finishTaskRollback, readTaskRollback } = await import("../project/taskRollback.js");
const { beginDocumentRevision } = await import("../project/documentRevision.js");
const { durableContentDigest } = await import("../project/durableSingleFileTransaction.js");
const { productionPlanningRequest } = await import("../project/productionPlanning.js");
const { prepareCurrentProductionStage } = await import("../project/productionStagePreparation.js");
const { readProductionStage } = await import("../project/productionStageStore.js");
const { resumeWorkspaceTask } = await import("../project/taskResumption.js");
const { createDocumentRevisionWorkspace } = await import("./projectDocumentRevisionV074.fixture.js");
const root = await initialRevisionKnowledge(roots);
const structure = YAML.parse(await readFile(join(root, "knowledge/structure.yaml"), "utf8"));
const path = structure.articles[0].path;
const original = await readFile(join(root, "knowledge", path), "utf8");
await beginDocumentRevision({ projectRoot: root, selector: path, instruction: "Clarify the overview." });
const revision = (await readApprovedRevision(root))!;
await complete(root, { stage: "approved-revision", markdown: revision.target.markdown.replace(/(\n# [^\n]+)/u, "$1 clarified") });
await approveCandidates(root, await readCandidateRecords(root));
await closeProjectWorkspace(root); await buildProjectPackages(root);
const changed = await readFile(join(root, "knowledge", path), "utf8");
await resumeWorkspaceTask(root);
await prepareCurrentProductionStage({ projectRoot: root, revision: (await productionPlanningRequest(root))!.revision });
expect(await readProductionStage(root)).toBeDefined();
const value = { summary: "Restore the overview and discard unfinished production stage.",
discard_unfinished: true as const, files: [{ path: `knowledge/${path}`, base_digest: durableContentDigest(changed), content: original }] };
const plan = await rollbackProjectTask({ projectRoot: root, value });
await rollbackProjectTask({ projectRoot: root, value, apply: true, plan_digest: plan.revision });
expect((await collectProjectStatus(root, { managed: true })).workflow.current?.reason_code).toBe("route.rollback.close-required");
await closeProjectWorkspace(root);
await buildProjectPackages(root);
expect((await collectProjectStatus(root, { managed: true })).workflow.current?.reason_code).toBe("route.rollback.cleanup-required");
await finishTaskRollback(root);
expect(await readTaskRollback(root)).toBeUndefined();
expect(await readProductionStage(root)).toBeUndefined();

const coldRoot = await createDocumentRevisionWorkspace();
roots.push(coldRoot);
await prepareCurrentProductionStage({ projectRoot: coldRoot, revision: (await productionPlanningRequest(coldRoot))!.revision });
expect(await readProductionStage(coldRoot)).toBeDefined();
const coldValue = { summary: "Discard unfinished cold-start production stage.", discard_unfinished: true as const, files: [] };
const coldPlan = await rollbackProjectTask({ projectRoot: coldRoot, value: coldValue });
// The preview discloses that the whole current task, its unfinished tasks and working files go.
const coldStage = (await readProductionStage(coldRoot))!;
expect(coldPlan.production).toMatchObject({ stage: coldStage.id, effect: "discard-whole-task",
deleted_working_directory: `.tmp/agent-work/production-stages/${coldStage.id}` });
expect(coldPlan.production!.unfinished_tasks).toBe(coldStage.tasks.filter(task => ["pending", "issued", "blocked"].includes(task.status)).length);
await rollbackProjectTask({ projectRoot: coldRoot, value: coldValue, apply: true, plan_digest: coldPlan.revision });
expect((await collectProjectStatus(coldRoot, { managed: true })).workflow.current?.reason_code).toBe("route.rollback.close-required");
await closeProjectWorkspace(coldRoot);
expect((await collectProjectStatus(coldRoot, { managed: true })).workflow.current?.reason_code).toBe("route.rollback.cleanup-required");
await finishTaskRollback(coldRoot);
expect(await readTaskRollback(coldRoot)).toBeUndefined();
expect(await readProductionStage(coldRoot)).toBeUndefined();
}, 60_000);

test("abandoning a page revision that interrupted production keeps production unchanged", async () => {
const { rollbackProjectTask, finishTaskRollback, readTaskRollback } = await import("../project/taskRollback.js");
const { beginDocumentRevision } = await import("../project/documentRevision.js");
const { productionPlanningRequest } = await import("../project/productionPlanning.js");
const { prepareCurrentProductionStage } = await import("../project/productionStagePreparation.js");
const { readProductionStage } = await import("../project/productionStageStore.js");
const { resumeWorkspaceTask } = await import("../project/taskResumption.js");
const root = await initialRevisionKnowledge(roots);
const structure = YAML.parse(await readFile(join(root, "knowledge/structure.yaml"), "utf8"));
const path = structure.articles[0].path;
await resumeWorkspaceTask(root);
await prepareCurrentProductionStage({ projectRoot: root, revision: (await productionPlanningRequest(root))!.revision });
const before = (await readProductionStage(root))!;
// A page revision interrupts production, then the user abandons it ("Abandon this update").
await beginDocumentRevision({ projectRoot: root, selector: path, instruction: "Clarify the overview." });
const value = { summary: "Abandon the overview revision.", discard_unfinished: true as const, files: [] };
const plan = await rollbackProjectTask({ projectRoot: root, value });
expect(plan.production).toMatchObject({ stage: before.id, effect: "keep" });
await rollbackProjectTask({ projectRoot: root, value, apply: true, plan_digest: plan.revision });
await closeProjectWorkspace(root);
await buildProjectPackages(root);
expect(await finishTaskRollback(root)).toMatchObject({ action: "finished", production: "resumed" });
expect(await readTaskRollback(root)).toBeUndefined();
expect(await readApprovedRevision(root)).toBeUndefined();
expect(await readProductionStage(root)).toEqual(before);
}, 60_000);

test.each(["architecture", "standards"])("explicit page move to %s preserves identity and updates incoming navigation through Review apply", async (collection) => {
const { beginDocumentRevision } = await import("../project/documentRevision.js");
const { access } = await import("node:fs/promises");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@ import { productionAgentDirectory } from "./productionSubmissionFiles.js";
import { assertProductionPlanRequirementsCurrent } from "./productionPlanning.js";
import { readMaintenance } from "./maintenanceStorage.js";
import { readApprovedRevision } from "./approvedRevision.js";
import { readTaskRollback } from "./taskRollback.js";

/** Review may reject prose, but rejection alone does not cancel a required
* article in the accepted plan. Keep the Author available for repair. */
export async function assertRequiredArticlesReviewed(root: string, candidates: readonly CandidateRecord[]): Promise<void> {
// Maintenance has its own revision/Review authority; it cannot settle the
// suspended production stage. Build completion keeps that stage intact.
if ((await readMaintenance(root)).active || await readApprovedRevision(root)) return;
// Maintenance, approved revisions and explicit task rollbacks have their own
// authority; they do not settle an unfinished production stage during close.
if ((await readMaintenance(root)).active || await readApprovedRevision(root) || await readTaskRollback(root)) return;
const rejected = candidates.filter(candidate => candidate.status === "rejected" && candidate.indexer_candidate);
const production = await readProductionStage(root);
if (production) {
Expand Down
8 changes: 5 additions & 3 deletions packages/context-cli/src/project/lifecycleCleanup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ const COMPLETED_RUNTIME_PATHS = [
INDEXER_RUNTIME_ROOT,
] as const;

export async function clearCompletedLifecycle(projectRoot: string): Promise<void> {
export async function clearCompletedLifecycle(projectRoot: string, options: { discardUnfinishedProduction?: boolean } = {}): Promise<void> {
const production = await readProductionStage(projectRoot);
if (production) {
if (production && !options.discardUnfinishedProduction) {
if (production.delivery) throw new TypeError("Partial delivery must retain the production stage and its unfinished tasks; finish the build or explicitly resume writing.");
// Review of an interrupting revision does not authorize deleting production.
// Enforce this at the deletion boundary, regardless of the caller's owner.
Expand Down Expand Up @@ -64,6 +64,8 @@ export async function clearCompletedLifecycle(projectRoot: string): Promise<void
await rm(join(compile, "current.json"), { force: true });
// Empty directory removal is cosmetic; no task state remains at this point.
await rm(indexer, { recursive: true, force: true });
await rm(join(projectRoot, APPROVED_REVISION_PATH), { force: true });
// Production goes before the revision/rollback pointer: if its cleanup fails,
// the remaining pointer keeps the task open and a retry finishes it.
if (production) await clearCompletedProduction(projectRoot, production);
await rm(join(projectRoot, APPROVED_REVISION_PATH), { force: true });
}
7 changes: 6 additions & 1 deletion packages/context-cli/src/project/packageBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,12 @@ export async function collectPackageFreshness(

export async function buildProjectPackages(projectRoot: string, options: { delivery?: boolean } = {}): Promise<ProjectBuildResult> {
return withProjectWriteLock(projectRoot, "build-packages", async () => {
const partial = options.delivery !== false && !!(await readProductionStage(projectRoot))?.delivery;
// A task rollback discards the current production stage with its delivery
// selection; the rollback finish settles it, so build neither checks nor
// finishes that stale selection.
const { readTaskRollback } = await import("./taskRollback.js");
const partial = options.delivery !== false && !!(await readProductionStage(projectRoot))?.delivery &&
!await readTaskRollback(projectRoot);
if (partial) await assertProductionDeliveryReady(projectRoot);
const result = await buildProjectPackagesInternal(projectRoot, options);
if (partial) await finishProductionDelivery(projectRoot);
Expand Down
Loading
Loading