Skip to content

Commit d0b362f

Browse files
steipetePeter Steinberger
andauthored
fix(commitments): make dismissal atomic and truthful (#117591)
* fix(commitments): report atomic dismissals truthfully * docs(commitments): explain dismissal JSON results --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent fedb61b commit d0b362f

5 files changed

Lines changed: 226 additions & 21 deletions

File tree

‎docs/cli/commitments.md‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,32 @@ and one row per commitment:
8686
JSON output includes the count, the active status and agent filters, the
8787
shared SQLite database path, and the full stored records.
8888

89+
### Dismissal output
90+
91+
`dismiss` changes only active `pending` or `snoozed` commitments. Missing,
92+
already dismissed, sent, and expired commitments remain unchanged. Duplicate
93+
IDs are ignored after their first occurrence, and results preserve request order.
94+
95+
When every requested commitment is dismissed, `--json` returns:
96+
97+
```json
98+
{ "dismissed": ["cm_abc123", "cm_def456"] }
99+
```
100+
101+
When a request includes stale or inactive IDs, the command reports both results
102+
and exits with status `1`:
103+
104+
```json
105+
{ "dismissed": ["cm_abc123"], "notDismissed": ["cm_missing", "cm_expired"] }
106+
```
107+
108+
If no requested commitment can be dismissed, the command still exits with status
109+
`1`:
110+
111+
```json
112+
{ "dismissed": [], "notDismissed": ["cm_missing"] }
113+
```
114+
89115
## Related
90116

91117
- [Inferred commitments](/concepts/commitments)

‎src/commands/commitments.test.ts‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,38 @@ describe("commitments command", () => {
7070
beforeEach(() => {
7171
vi.clearAllMocks();
7272
mocks.listCommitments.mockResolvedValue([commitment()]);
73+
mocks.markCommitmentsStatus.mockResolvedValue(["cm_escape"]);
74+
});
75+
76+
it("sanitizes invalid status values before rendering errors", async () => {
77+
const { runtime } = createRuntime();
78+
79+
await commitmentsListCommand(
80+
{ status: "bad\u001b]52;c;Zm9yZ2Vk\u0007\nforged: yes\u001b[31m" },
81+
runtime,
82+
);
83+
84+
expect(runtime.error).toHaveBeenCalledWith(
85+
"Unknown commitment status: bad\\nforged: yes. Use one of: pending, sent, dismissed, snoozed, expired.",
86+
);
87+
expect(runtime.exit).toHaveBeenCalledWith(1);
88+
expect(mocks.listCommitments).not.toHaveBeenCalled();
89+
});
90+
91+
it("sanitizes agent filters and database paths in human-readable output", async () => {
92+
const unsafeText = "\u001b]52;c;Zm9yZ2Vk\u0007\nforged: yes\u001b[31m";
93+
mocks.resolveCommitmentDatabasePath.mockReturnValueOnce(`/tmp/${unsafeText}.sqlite`);
94+
mocks.listCommitments.mockResolvedValueOnce([]);
95+
const { runtime, logs } = createRuntime();
96+
97+
await commitmentsListCommand({ agent: `main${unsafeText}` }, runtime);
98+
99+
expect(logs.map(stripAnsi)).toContain("Store: /tmp/\\nforged: yes.sqlite");
100+
expect(logs.map(stripAnsi)).toContain("Agent filter: main\\nforged: yes");
101+
for (const line of logs) {
102+
expect(line).not.toContain("\u0007");
103+
expect(line).not.toContain("\n");
104+
}
73105
});
74106

75107
it("sanitizes untrusted commitment fields in table output", async () => {
@@ -241,4 +273,80 @@ describe("commitments command", () => {
241273
nowMs: expect.any(Number),
242274
});
243275
});
276+
277+
it("reports only actually dismissed ids and explains skipped ids", async () => {
278+
mocks.markCommitmentsStatus.mockResolvedValueOnce(["cm_valid"]);
279+
const { runtime, logs } = createRuntime();
280+
281+
await commitmentsDismissCommand(
282+
{ ids: [" cm_valid ", "cm_missing", "cm_valid", "cm_terminal"] },
283+
runtime,
284+
);
285+
286+
expect(mocks.markCommitmentsStatus).toHaveBeenCalledWith({
287+
cfg: {},
288+
ids: ["cm_valid", "cm_missing", "cm_terminal"],
289+
status: "dismissed",
290+
nowMs: expect.any(Number),
291+
});
292+
expect(logs.map(stripAnsi)).toEqual(["Dismissed commitments: cm_valid"]);
293+
expect(runtime.error).toHaveBeenCalledWith(
294+
"Commitments not found or no longer active: cm_missing, cm_terminal. Run openclaw commitments --all to inspect current state.",
295+
);
296+
expect(runtime.exit).toHaveBeenCalledWith(1);
297+
});
298+
299+
it("rejects dismissals when no requested commitment is active", async () => {
300+
mocks.markCommitmentsStatus.mockResolvedValueOnce([]);
301+
const { runtime, logs } = createRuntime();
302+
303+
await commitmentsDismissCommand({ ids: ["cm_missing", "cm_terminal"] }, runtime);
304+
305+
expect(logs).toEqual([]);
306+
expect(runtime.error).toHaveBeenCalledWith(
307+
"Commitments not found or no longer active: cm_missing, cm_terminal. Run openclaw commitments --all to inspect current state.",
308+
);
309+
expect(runtime.exit).toHaveBeenCalledWith(1);
310+
});
311+
312+
it("keeps unsuccessful dismissals truthful and machine-readable", async () => {
313+
mocks.markCommitmentsStatus.mockResolvedValueOnce([]);
314+
const { runtime, logs, stdout } = createRuntime();
315+
316+
await commitmentsDismissCommand({ ids: ["cm_missing"], json: true }, runtime);
317+
318+
expect(logs).toEqual([]);
319+
expect(stdout).toEqual([
320+
JSON.stringify({ dismissed: [], notDismissed: ["cm_missing"] }, null, 2),
321+
]);
322+
expect(runtime.exit).toHaveBeenCalledWith(1);
323+
});
324+
325+
it("sanitizes dismissed ids in human output while preserving raw JSON", async () => {
326+
const unsafeId = "cm_\u001b]52;c;Zm9yZ2Vk\u0007\nforged: yes\u001b[31m";
327+
mocks.markCommitmentsStatus.mockResolvedValue([unsafeId]);
328+
const human = createRuntime();
329+
const json = createRuntime();
330+
331+
await commitmentsDismissCommand({ ids: [unsafeId] }, human.runtime);
332+
await commitmentsDismissCommand({ ids: [unsafeId], json: true }, json.runtime);
333+
334+
expect(human.logs.map(stripAnsi)).toEqual(["Dismissed commitments: cm_\\nforged: yes"]);
335+
expect(human.logs[0]).not.toContain("\u0007");
336+
expect(human.logs[0]).not.toContain("\n");
337+
expect(JSON.parse(json.stdout[0] ?? "{}")).toStrictEqual({ dismissed: [unsafeId] });
338+
});
339+
340+
it("sanitizes skipped dismiss ids in human-readable failure output", async () => {
341+
const unsafeId = "cm_\u001b]52;c;Zm9yZ2Vk\u0007\nforged: yes\u001b[31m";
342+
mocks.markCommitmentsStatus.mockResolvedValueOnce([]);
343+
const { runtime } = createRuntime();
344+
345+
await commitmentsDismissCommand({ ids: [unsafeId] }, runtime);
346+
347+
expect(runtime.error).toHaveBeenCalledWith(
348+
"Commitments not found or no longer active: cm_\\nforged: yes. Run openclaw commitments --all to inspect current state.",
349+
);
350+
expect(runtime.exit).toHaveBeenCalledWith(1);
351+
});
244352
});

‎src/commands/commitments.ts‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Implements commitment listing and dismissal commands for scheduled follow-up records.
22
import { timestampMsToIsoString } from "@openclaw/normalization-core/number-coercion";
33
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
4-
import { normalizeStringEntries } from "@openclaw/normalization-core/string-normalization";
4+
import { normalizeUniqueStringEntries } from "@openclaw/normalization-core/string-normalization";
55
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
66
import { sanitizeTerminalText } from "../../packages/terminal-core/src/safe-text.js";
77
import { isRich, theme } from "../../packages/terminal-core/src/theme.js";
@@ -41,7 +41,7 @@ function parseStatus(raw: string | undefined, runtime: RuntimeEnv): CommitmentSt
4141
return status as CommitmentStatus;
4242
}
4343
runtime.error(
44-
`Unknown commitment status: ${status}. Use one of: ${Array.from(STATUS_VALUES).join(", ")}.`,
44+
`Unknown commitment status: ${safe(status)}. Use one of: ${Array.from(STATUS_VALUES).join(", ")}.`,
4545
);
4646
runtime.exit(1);
4747
return undefined;
@@ -120,12 +120,12 @@ export async function commitmentsListCommand(
120120
}
121121

122122
runtime.log(info(`Commitments: ${commitments.length}`));
123-
runtime.log(info(`Store: ${resolveCommitmentDatabasePath()}`));
123+
runtime.log(info(`Store: ${safe(resolveCommitmentDatabasePath())}`));
124124
if (status) {
125125
runtime.log(info(`Status filter: ${status}`));
126126
}
127127
if (opts.agent) {
128-
runtime.log(info(`Agent filter: ${opts.agent}`));
128+
runtime.log(info(`Agent filter: ${safe(opts.agent)}`));
129129
}
130130
if (commitments.length === 0) {
131131
runtime.log(
@@ -143,7 +143,7 @@ export async function commitmentsDismissCommand(
143143
opts: { ids: string[]; json?: boolean },
144144
runtime: RuntimeEnv,
145145
): Promise<void> {
146-
const ids = normalizeStringEntries(opts.ids);
146+
const ids = normalizeUniqueStringEntries(opts.ids);
147147
if (ids.length === 0) {
148148
runtime.error(
149149
`At least one commitment id is required. Run ${formatCliCommand("openclaw commitments list")} to choose one.`,
@@ -152,15 +152,31 @@ export async function commitmentsDismissCommand(
152152
return;
153153
}
154154
const cfg = getRuntimeConfig();
155-
await markCommitmentsStatus({
155+
const dismissed = await markCommitmentsStatus({
156156
cfg,
157157
ids,
158158
status: "dismissed",
159159
nowMs: Date.now(),
160160
});
161+
const dismissedIds = new Set(dismissed);
162+
const notDismissed = ids.filter((id) => !dismissedIds.has(id));
161163
if (opts.json) {
162-
writeRuntimeJson(runtime, { dismissed: ids });
164+
writeRuntimeJson(runtime, {
165+
dismissed,
166+
...(notDismissed.length > 0 ? { notDismissed } : {}),
167+
});
168+
if (notDismissed.length > 0) {
169+
runtime.exit(1);
170+
}
163171
return;
164172
}
165-
runtime.log(info(`Dismissed commitments: ${ids.join(", ")}`));
173+
if (dismissed.length > 0) {
174+
runtime.log(info(`Dismissed commitments: ${dismissed.map(safe).join(", ")}`));
175+
}
176+
if (notDismissed.length > 0) {
177+
runtime.error(
178+
`Commitments not found or no longer active: ${notDismissed.map(safe).join(", ")}. Run ${formatCliCommand("openclaw commitments --all")} to inspect current state.`,
179+
);
180+
runtime.exit(1);
181+
}
166182
}

‎src/commitments/store.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,51 @@ describe("commitment SQLite store", () => {
289289
expect(byId.cm_raceB?.status).toBe("dismissed");
290290
});
291291

292+
it("reports only active rows updated in first-seen requested order", async () => {
293+
await useTempStateDir();
294+
seedCommitmentsForTest([
295+
commitment({ id: "cm_first", dedupeKey: "first" }),
296+
commitment({ id: "cm_second", dedupeKey: "second", status: "snoozed" }),
297+
commitment({
298+
id: "cm_terminal",
299+
dedupeKey: "terminal",
300+
status: "dismissed",
301+
dismissedAtMs: nowMs - 60_000,
302+
}),
303+
]);
304+
305+
await expect(
306+
markCommitmentsStatus({
307+
ids: [" cm_second ", "cm_missing", "cm_first", "cm_second", "cm_terminal"],
308+
status: "dismissed",
309+
nowMs,
310+
}),
311+
).resolves.toStrictEqual(["cm_second", "cm_first"]);
312+
313+
const byId = Object.fromEntries(readCommitmentsForTest().map((record) => [record.id, record]));
314+
expect(byId.cm_first).toMatchObject({ status: "dismissed", dismissedAtMs: nowMs });
315+
expect(byId.cm_second).toMatchObject({ status: "dismissed", dismissedAtMs: nowMs });
316+
expect(byId.cm_terminal?.dismissedAtMs).toBe(nowMs - 60_000);
317+
});
318+
319+
it("returns an empty update list without opening SQLite for empty ids", async () => {
320+
await expect(
321+
markCommitmentsStatus({ ids: ["", " "], status: "dismissed", nowMs }),
322+
).resolves.toStrictEqual([]);
323+
});
324+
325+
it("lets only one competing status transition claim the same commitment", async () => {
326+
await useTempStateDir();
327+
seedCommitmentsForTest([commitment({ id: "cm_race_claim" })]);
328+
329+
await expect(
330+
Promise.all([
331+
markCommitmentsStatus({ ids: ["cm_race_claim"], status: "dismissed", nowMs }),
332+
markCommitmentsStatus({ ids: ["cm_race_claim"], status: "dismissed", nowMs }),
333+
]),
334+
).resolves.toStrictEqual([["cm_race_claim"], []]);
335+
});
336+
292337
it("increments concurrent attempt bumps without losing a write", async () => {
293338
await useTempStateDir();
294339
seedCommitmentsForTest([commitment({ id: "cm_race_attempts", attempts: 0 })]);

‎src/commitments/store.ts‎

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Persists commitment records in the canonical shared SQLite database.
22
import { randomBytes } from "node:crypto";
33
import type { DatabaseSync } from "node:sqlite";
4+
import { normalizeUniqueStringEntries } from "@openclaw/normalization-core/string-normalization";
45
import type { OpenClawConfig } from "../config/config.js";
56
import {
67
executeSqliteQuerySync,
@@ -404,23 +405,30 @@ export async function markCommitmentsStatus(params: {
404405
ids: string[];
405406
status: Extract<CommitmentStatus, "sent" | "dismissed" | "expired">;
406407
nowMs?: number;
407-
}): Promise<void> {
408-
const ids = [...new Set(params.ids.map((id) => id.trim()).filter(Boolean))];
408+
}): Promise<string[]> {
409+
const ids = normalizeUniqueStringEntries(params.ids);
409410
if (ids.length === 0) {
410-
return;
411+
return [];
411412
}
412413
const nowMs = params.nowMs ?? Date.now();
413-
runOpenClawStateWriteTransaction(({ db }) => {
414+
return runOpenClawStateWriteTransaction(({ db }) => {
414415
const commitmentsDb = getNodeSqliteKysely<CommitmentsDatabase>(db);
415-
const rows = executeSqliteQuerySync(
416-
db,
417-
commitmentsDb
418-
.selectFrom("commitments")
419-
.selectAll()
420-
.where("id", "in", ids)
421-
.where("status", "in", [...ACTIVE_STATUSES]),
422-
).rows;
423-
for (const row of rows) {
416+
const rowsById = new Map(
417+
executeSqliteQuerySync(
418+
db,
419+
commitmentsDb
420+
.selectFrom("commitments")
421+
.selectAll()
422+
.where("id", "in", ids)
423+
.where("status", "in", [...ACTIVE_STATUSES]),
424+
).rows.map((row) => [row.id, row]),
425+
);
426+
const updatedIds: string[] = [];
427+
for (const id of ids) {
428+
const row = rowsById.get(id);
429+
if (!row) {
430+
continue;
431+
}
424432
const record = commitmentRecordFromRow(row);
425433
updateCommitmentRow(db, {
426434
...record,
@@ -430,7 +438,9 @@ export async function markCommitmentsStatus(params: {
430438
...(params.status === "dismissed" ? { dismissedAtMs: nowMs } : {}),
431439
...(params.status === "expired" ? { expiredAtMs: nowMs } : {}),
432440
});
441+
updatedIds.push(record.id);
433442
}
443+
return updatedIds;
434444
});
435445
}
436446

0 commit comments

Comments
 (0)