@verax-ai/body 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/halt.js CHANGED
@@ -1,10 +1,35 @@
1
1
  import { createHash } from "node:crypto";
2
- import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
3
3
  import { userInfo } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { canonical } from "@cedulon/core";
6
+ import { clearProcessHalted, isProcessHalted, markProcessHalted, persistHaltedSwitch, } from "@verax-ai/proxy";
7
+ import { closeIncidentsOnResume } from "./incidents.js";
8
+ import { markHistoryUnavailable } from "./memory-store.js";
6
9
  const SWITCH = "halted";
7
10
  const HISTORY = "halt-history.jsonl";
11
+ function oneLine(err) {
12
+ const text = err instanceof Error ? err.message : String(err);
13
+ return text.replace(/[\r\n]+/g, " ").slice(0, 300);
14
+ }
15
+ /** The switch is an empty file. A folder at the path is a blocked write, not a halt. */
16
+ export function isHaltSwitchFile(stateDir) {
17
+ try {
18
+ return statSync(join(stateDir, SWITCH)).isFile();
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ }
24
+ /** Something occupies the switch path that is not the halt file (a folder, etc.). */
25
+ function isSwitchPathBlocked(stateDir) {
26
+ try {
27
+ return !statSync(join(stateDir, SWITCH)).isFile();
28
+ }
29
+ catch {
30
+ return false;
31
+ }
32
+ }
8
33
  function cliUser() {
9
34
  try {
10
35
  return userInfo().username || "unknown";
@@ -14,7 +39,15 @@ function cliUser() {
14
39
  }
15
40
  }
16
41
  function appendHistory(stateDir, event) {
17
- appendFileSync(join(stateDir, HISTORY), `${JSON.stringify(event)}\n`, { encoding: "utf8", mode: 0o600 });
42
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
43
+ const fd = openSync(join(stateDir, HISTORY), "a", 0o600);
44
+ try {
45
+ writeSync(fd, `${JSON.stringify(event)}\n`, null, "utf8");
46
+ fsyncSync(fd);
47
+ }
48
+ finally {
49
+ closeSync(fd);
50
+ }
18
51
  }
19
52
  /**
20
53
  * SHA-256 of the newest history line, as the control record names that line
@@ -40,6 +73,11 @@ export function historyTail(stateDir) {
40
73
  return null;
41
74
  return createHash("sha256").update(canonical(last), "utf8").digest("hex");
42
75
  }
76
+ function haltVia(raw) {
77
+ if (raw === "http" || raw === "integrity")
78
+ return raw;
79
+ return "cli";
80
+ }
43
81
  function lastHalt(stateDir) {
44
82
  let raw;
45
83
  try {
@@ -53,7 +91,16 @@ function lastHalt(stateDir) {
53
91
  try {
54
92
  const row = JSON.parse(lines[i] ?? "");
55
93
  if (row.action === "halt" && typeof row.atMs === "number" && typeof row.by === "string") {
56
- return { action: "halt", atMs: row.atMs, by: row.by, via: row.via === "http" ? "http" : "cli" };
94
+ const event = { action: "halt", atMs: row.atMs, by: row.by, via: haltVia(row.via) };
95
+ if (typeof row.eventId === "string" && row.eventId !== "")
96
+ event.eventId = row.eventId;
97
+ if (typeof row.triggerCode === "string" && row.triggerCode !== "")
98
+ event.triggerCode = row.triggerCode;
99
+ const head = row.memoryHead;
100
+ if (head && typeof head === "object" && typeof head.seq === "number" && typeof head.lastHash === "string") {
101
+ event.memoryHead = { seq: head.seq, lastHash: head.lastHash };
102
+ }
103
+ return event;
57
104
  }
58
105
  if (row.action === "resume")
59
106
  return undefined;
@@ -65,30 +112,71 @@ function lastHalt(stateDir) {
65
112
  return undefined;
66
113
  }
67
114
  export function readHalt(stateDir) {
68
- if (!existsSync(join(stateDir, SWITCH)))
115
+ if (!isHaltSwitchFile(stateDir))
69
116
  return { halted: false };
70
117
  const since = lastHalt(stateDir);
71
118
  return since ? { halted: true, since } : { halted: true };
72
119
  }
73
120
  /** Halting twice is one halt: the first line keeps saying who stopped it. */
74
- export function haltBody(stateDir, by, via, now = Date.now(), signature) {
75
- mkdirSync(stateDir, { recursive: true, mode: 0o700 });
76
- if (!existsSync(join(stateDir, SWITCH))) {
77
- writeFileSync(join(stateDir, SWITCH), "", { encoding: "utf8", mode: 0o600 });
78
- appendHistory(stateDir, { action: "halt", atMs: now, by, via, ...(signature ? { signature } : {}) });
121
+ export function haltBody(stateDir, by, via, now = Date.now(), signature, incident) {
122
+ try {
123
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
124
+ const hadSwitch = isHaltSwitchFile(stateDir);
125
+ if (!hadSwitch) {
126
+ writeFileSync(join(stateDir, SWITCH), "", { encoding: "utf8", mode: 0o600 });
127
+ }
128
+ // The file is the single source of truth once it exists. History is a
129
+ // separate write: an older flag-only halt must not survive a later
130
+ // successful switch, even if the history line cannot be appended.
131
+ if (isHaltSwitchFile(stateDir))
132
+ clearProcessHalted(stateDir);
133
+ if (!hadSwitch && isHaltSwitchFile(stateDir)) {
134
+ appendHistory(stateDir, {
135
+ action: "halt",
136
+ atMs: now,
137
+ by,
138
+ via,
139
+ ...(signature ? { signature } : {}),
140
+ ...(incident?.eventId ? { eventId: incident.eventId } : {}),
141
+ ...(incident?.triggerCode ? { triggerCode: incident.triggerCode } : {}),
142
+ ...(incident?.memoryHead ? { memoryHead: incident.memoryHead } : {}),
143
+ });
144
+ }
145
+ }
146
+ catch (err) {
147
+ process.stderr.write(`verax: halt: ${oneLine(err)}\n`);
148
+ if (isHaltSwitchFile(stateDir)) {
149
+ clearProcessHalted(stateDir);
150
+ throw err;
151
+ }
152
+ markProcessHalted(stateDir);
153
+ persistHaltedSwitch(stateDir);
154
+ if (!isHaltSwitchFile(stateDir)) {
155
+ markHistoryUnavailable(stateDir);
156
+ }
157
+ else {
158
+ clearProcessHalted(stateDir);
159
+ throw err;
160
+ }
79
161
  }
80
162
  return readHalt(stateDir);
81
163
  }
82
164
  /**
83
165
  * Resuming a body that is not halted changes nothing and writes nothing.
84
- * The line goes to the history before the switch is removed: if it cannot be
85
- * written, the append throws and the body stays halted, rather than running
86
- * again with no record of who let it.
166
+ * Undelivered incidents are verified/re-signed and written to the outbox, or
167
+ * marked closed-pending-delivery with an atomic write. If that mark cannot be
168
+ * written, this throws and the body stays halted. The history line is
169
+ * appended after the mark: if the append throws, the body stays halted
170
+ * rather than running again with no record of who let it. Then the switch
171
+ * is removed. A later integrity halt is a new event. Pending outbox files stay.
87
172
  */
88
- export function resumeBody(stateDir, by, via, now = Date.now(), signature) {
89
- if (existsSync(join(stateDir, SWITCH))) {
173
+ export function resumeBody(stateDir, by, via, now = Date.now(), signature, keysDir) {
174
+ if (isHaltSwitchFile(stateDir) || isProcessHalted(stateDir)) {
175
+ closeIncidentsOnResume(stateDir, keysDir);
90
176
  appendHistory(stateDir, { action: "resume", atMs: now, by, via, ...(signature ? { signature } : {}) });
91
- rmSync(join(stateDir, SWITCH), { force: true });
177
+ if (isHaltSwitchFile(stateDir))
178
+ rmSync(join(stateDir, SWITCH), { force: true });
179
+ clearProcessHalted(stateDir);
92
180
  }
93
181
  return readHalt(stateDir);
94
182
  }
@@ -97,7 +185,17 @@ export function runHalt(stateDir, writeErr = (s) => process.stderr.write(s)) {
97
185
  writeErr("verax halt <stateDir>\n");
98
186
  return 78;
99
187
  }
100
- haltBody(stateDir, cliUser(), "cli");
188
+ try {
189
+ haltBody(stateDir, cliUser(), "cli");
190
+ }
191
+ catch (err) {
192
+ writeErr(`halt-failed: ${oneLine(err)}\n`);
193
+ return 1;
194
+ }
195
+ if (!readHalt(stateDir).halted) {
196
+ writeErr("halt-failed: switch-unwritable\n");
197
+ return 1;
198
+ }
101
199
  writeErr("halted\n");
102
200
  return 0;
103
201
  }
@@ -106,11 +204,21 @@ export function runResume(stateDir, writeErr = (s) => process.stderr.write(s)) {
106
204
  writeErr("verax resume <stateDir>\n");
107
205
  return 78;
108
206
  }
109
- if (!existsSync(join(stateDir, SWITCH))) {
207
+ if (isSwitchPathBlocked(stateDir)) {
208
+ writeErr("resume-failed: switch-path-blocked; a running body may hold the halt in memory; clear the path and use POST /api/resume\n");
209
+ return 1;
210
+ }
211
+ if (!isHaltSwitchFile(stateDir) && !isProcessHalted(stateDir)) {
110
212
  writeErr("not halted\n");
111
213
  return 0;
112
214
  }
113
- resumeBody(stateDir, cliUser(), "cli");
215
+ try {
216
+ resumeBody(stateDir, cliUser(), "cli", Date.now(), undefined, process.env.VERAX_KEYS_DIR);
217
+ }
218
+ catch (err) {
219
+ writeErr(`resume-failed: ${oneLine(err)}\n`);
220
+ return 1;
221
+ }
114
222
  writeErr("resumed\n");
115
223
  return 0;
116
224
  }
@@ -0,0 +1,67 @@
1
+ import { type AlarmEnvelope } from "./alarm-outbox.ts";
2
+ import { type IntegrityReason } from "./memory-store.ts";
3
+ export declare const INCIDENT_BY = "verax:memory-integrity";
4
+ export declare const INCIDENT_RECORD = "incident.json";
5
+ export declare const INCIDENTS_DIR = "incidents";
6
+ export type IncidentPayload = {
7
+ v: 1;
8
+ purpose: "verax.incident.v1";
9
+ eventId: string;
10
+ observedAt: number;
11
+ triggerCode: string;
12
+ scopeKind: "global";
13
+ enforcementState: "halted";
14
+ keyId: string;
15
+ memoryHead?: {
16
+ seq: number;
17
+ lastHash: string;
18
+ };
19
+ };
20
+ export declare function recordKeyId(publicKeyPem: string): string;
21
+ export type IncidentEventIdGenerators = {
22
+ randomUUID: () => string;
23
+ randomBytes: (size: number) => Buffer;
24
+ };
25
+ /**
26
+ * randomUUID, then randomBytes, then a SHA-256 UUID of observedAt+trigger+record key.
27
+ * Generators are a parameter so a failing producer can be injected; that is
28
+ * dependency injection, not a product-code test hook. The last resort is
29
+ * stable for the same inputs (a retry of one incident stays one id).
30
+ */
31
+ export declare function incidentEventIdFrom(opts: {
32
+ observedAt: number;
33
+ triggerCode: string;
34
+ publicKeyPem: string;
35
+ }, generators: IncidentEventIdGenerators): string;
36
+ /** Production path: the same cascade; last resort mixes pid, a counter, and extra bytes. */
37
+ export declare function allocateIncidentEventId(opts: {
38
+ observedAt: number;
39
+ triggerCode: string;
40
+ publicKeyPem: string;
41
+ }): string;
42
+ export declare function signIncident(payload: IncidentPayload, privateKeyPem: string): AlarmEnvelope;
43
+ /** Resume: same verify/re-sign path; pending marker is atomic or resume does not finish. */
44
+ export declare function closeIncidentsOnResume(stateDir: string, keysDir?: string | null): void;
45
+ export declare function raiseMemoryIntegrityIncident(opts: {
46
+ stateDir: string;
47
+ reason: IntegrityReason;
48
+ publicKeyPem: string;
49
+ privateKeyPem: string;
50
+ memoryHead?: {
51
+ seq: number;
52
+ lastHash: string;
53
+ };
54
+ alarmWebhookUrl?: string;
55
+ now?: number;
56
+ }): AlarmEnvelope | null;
57
+ /** On open: finish a missing halt, a missing outbox, or a resume-pending delivery. Same eventId. */
58
+ export declare function completeMemoryIntegrityIncident(opts: {
59
+ stateDir: string;
60
+ publicKeyPem: string;
61
+ privateKeyPem: string;
62
+ memoryHead?: {
63
+ seq: number;
64
+ lastHash: string;
65
+ };
66
+ alarmWebhookUrl?: string;
67
+ }): AlarmEnvelope | null;