ace-wake 0.2.0 → 0.4.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c2dff41db21b22ff36dbe9d9dda962979e2598072dfba16a406b81cdb1fb0cbf
4
- data.tar.gz: f303030a7487b009196d4a4f1ffe92ea90f4872e66b20a9549871c968c85eaa9
3
+ metadata.gz: 90d56b134bd020956dbdf73c1b52f3a6988bd2bce06dbf1b0bf8a52c9d5b089c
4
+ data.tar.gz: 0a7357f6d16c6c05d19fb58c473225473dea6aeff312fb4d77f7a2a4b3fc73a6
5
5
  SHA512:
6
- metadata.gz: e3284df4db91ce0b48fa1714b00b818622d0df1c20ee7d5f4b7812683f545696bbeed3bb11089a066825726cd3d5a81d09836747c9ee276b503bae19028770e8
7
- data.tar.gz: 9496ea0bc29040ce63e62c2be847a782b4b7c0237efa5982a9793dcc9b81de2d5e591bb3b33cc4d9b8e862b7fda6f0477b16a691e67ba2e2e3c5e33d9f77e358
6
+ metadata.gz: 45d4bc561feefe1142559eb996b7c5338082eb52993cb180d4fab926003b1c73e8cce58f4d309732939d2e42186256c6c581f425e4f8cf185a8d56ed97bf8185
7
+ data.tar.gz: e3ee0958695b688f938bd3c8e778edb8fd11fc992b4bdb747483b2f6c7d70f053f1ed1f09eda8edb23dbd3e0ed1ee09c9195547529b290b0257388e5f78e8fbd
data/CHANGELOG.md CHANGED
@@ -7,6 +7,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.4.0] - 2026-11-12
11
+
12
+ ### Changed
13
+
14
+ - Initialize configured eyes and compose report processing with healthy observation and exact revision acknowledgements.
15
+ - Show the pending wake-budget resume deadline in eyes status.
16
+
17
+ ### Fixed
18
+
19
+ - Describe the eyes deadline timestamp as absolute epoch milliseconds in the agent tool schema, preventing durations from being mistaken for future deadlines.
20
+
21
+
22
+ ## [0.3.0] - 2026-11-10
23
+
24
+ ### Added
25
+
26
+ - Publish observation evidence for Linux and macOS. Pace observation budgets, defer notifications until idle, and deliver deadlines after an in-flight observation without stale duplicate wakes.
27
+
28
+ ### Fixed
29
+
30
+ - Explicit reconciliation retries an unconfirmed notification in the same session while keeping confirmed deliveries suppressed until acknowledgment.
31
+
10
32
  ## [0.2.0] - 2026-10-31
11
33
 
12
34
  ### Added
data/README.md CHANGED
@@ -26,6 +26,24 @@ lives at `handbook/extensions/ace-wake/` (single copy) and ships in the
26
26
  into each manifest-declared extension directory (`gemset.extensions`),
27
27
  reporting the loaded version and any restart need.
28
28
 
29
+ ## Standing observation
30
+
31
+ `/eyes` keeps observing source revisions while an agent is working. It does
32
+ not enqueue a follow-up during that turn: the agent can acknowledge a revision
33
+ it handles itself. Once the agent is idle and its other pending messages have
34
+ cleared, the next observation delivers any still-unhandled revisions. This can
35
+ delay notification by one observation interval, but avoids turns for changes
36
+ already handled during the active turn.
37
+
38
+ The effective observation interval is the larger of `intervalSeconds` and
39
+ `3600 / maxObservationsPerHour` seconds, rounded up to a whole timer interval.
40
+ Local deadlines are checked on timer ticks even when source reads are throttled.
41
+ Extra observations can consume the remaining hourly allowance; the timer stays
42
+ armed and observation resumes automatically in the next window, including
43
+ after restart. The hourly wake allowance limits delivery while observation
44
+ continues to coalesce pending revisions. Delivery resumes with the next
45
+ window. Provider quota and failure breakers still require explicit recovery.
46
+
29
47
  ## Mount-aware poll fallback
30
48
 
31
49
  `/lab/state/hitl-address/ace` (the HITL transport folder) is a FUSE/virtiofs
@@ -1,10 +1,40 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { execFile } from "node:child_process";
3
+ import { execFile, execFileSync } from "node:child_process";
4
4
  import { promisify } from "node:util";
5
5
  import { Eyes, EYES_ENTRY } from "./eyes.js";
6
6
 
7
7
  const execute = promisify(execFile);
8
+ export const EYES_BINDING = "ace-wake-eyes-binding";
9
+
10
+ // Birth identity is immutable for this process. Probe once at session binding,
11
+ // never during observation polling. Darwin uses the same native libproc owner
12
+ // as the Ruby readiness reader; second-resolution ps timestamps are insufficient.
13
+ let ownIdentity;
14
+ export function eyesProcessIdentity() {
15
+ if (ownIdentity === undefined) ownIdentity = readEyesProcessIdentity();
16
+ return ownIdentity;
17
+ }
18
+
19
+ export function readEyesProcessIdentity({ platform = process.platform, pid = process.pid,
20
+ readFile = fs.readFileSync, run = execFileSync } = {}) {
21
+ try {
22
+ if (platform === "darwin") {
23
+ const birth = run("ruby", ["-r", "ace/runtime/molecules/process_identity", "-e",
24
+ "print Ace::Runtime::Molecules::ProcessIdentity.new.native_birth(Integer(ARGV.fetch(0)))", String(pid)],
25
+ { encoding: "utf8", timeout: 2000, killSignal: "SIGKILL", maxBuffer: 1024, stdio: ["ignore", "pipe", "pipe"] }).trim();
26
+ return /^darwin:[1-9][0-9]*:[0-9]{1,6}$/.test(birth) ? { pid, startedAt: birth } : null;
27
+ }
28
+ if (platform !== "linux") return null;
29
+ const stat = readFile(`/proc/${pid}/stat`, "utf8");
30
+ const end = stat.lastIndexOf(") ");
31
+ if (end < 0) return null;
32
+ const ticks = stat.slice(end + 2).trim().split(/\s+/)[19];
33
+ const boot = readFile("/proc/sys/kernel/random/boot_id", "utf8").trim();
34
+ if (!/^[1-9][0-9]*$/.test(ticks) || !/^[0-9a-f-]{36}$/.test(boot)) return null;
35
+ return { pid, startedAt: `linux:${boot}:${ticks}` };
36
+ } catch { return null; }
37
+ }
8
38
 
9
39
  /** Existing native sync owns canonical import; HITL owns event projection.
10
40
  * No Ruby parsing, private text, shell command strings or model work here. */
@@ -20,23 +50,38 @@ export async function observeHitl(cwd, config) {
20
50
  if (!Array.isArray(result.errors) || result.errors.length) throw new Error("Native synchronization incomplete");
21
51
  }
22
52
  const { stdout } = await execute("ace-overseer", ["observe", "--owner", config.recipient, "--scope", config.scope, "--limit", String(config.maxEvents)], options);
23
- return JSON.parse(stdout);
53
+ const result = JSON.parse(stdout);
54
+ if (!result?.sources || typeof result.sources !== "object" || Array.isArray(result.sources) ||
55
+ Object.keys(result.sources).length === 0) throw new Error("Observation source health is missing");
56
+ return result;
57
+ }
58
+
59
+ export async function processReports(cwd, config, signal) {
60
+ const { stdout } = await execute("ace-overseer", ["process-reports", "--json",
61
+ "--owner", config.recipient, "--scope", config.scope],
62
+ { cwd, signal, maxBuffer: 8 * 1024 * 1024, encoding: "utf8" });
63
+ const result = JSON.parse(stdout);
64
+ if (!Array.isArray(result?.outcomes) || result.dry_run !== false)
65
+ throw new Error("Invalid report-processing receipt");
66
+ return result;
24
67
  }
25
68
 
26
- export function registerEyes(pi, { observe = observeHitl, now = Date.now,
27
- schedule = (fn, ms) => setInterval(fn, ms), cancel = clearInterval } = {}) {
28
- let eyes, timer, attempt, observedSources, bindingGeneration = 0, compacting = false, running = false, arming = false;
69
+ export function registerEyes(pi, { observe = observeHitl, processReports: processReportOwner = processReports, env = process.env, now = Date.now,
70
+ schedule = (fn, ms) => setInterval(fn, ms), cancel = clearInterval, processIdentity = eyesProcessIdentity } = {}) {
71
+ let eyes, timer, attempt, observedSources, observedAt, bindingGeneration = 0, compacting = false, running = false, arming = false;
72
+ const clearEvidence = () => { observedSources = undefined; observedAt = undefined; };
29
73
  const stopTimer = () => { if (timer !== undefined) cancel(timer); timer = undefined; };
30
74
  function arm() {
31
75
  stopTimer();
32
76
  if (eyes?.s.enabled && !eyes.s.retired && !eyes.s.breaker) {
33
- timer = schedule(() => { void eyes.tick(); }, eyes.s.config.intervalSeconds * 1000);
77
+ timer = schedule(() => { void eyes.tick({ scheduled: true }); },
78
+ eyes.s.config.intervalSeconds * 1000);
34
79
  timer?.unref?.();
35
80
  }
36
81
  }
37
- const bind = (ctx) => {
82
+ const bind = async (ctx) => {
38
83
  const generation = ++bindingGeneration;
39
- stopTimer(); eyes?.dispose(); attempt = undefined; observedSources = undefined; compacting = false; running = false;
84
+ stopTimer(); eyes?.dispose(); attempt = undefined; clearEvidence(); compacting = false; running = false;
40
85
  const entries = ctx.sessionManager.getBranch();
41
86
  const snapshot = [...entries].reverse().find((e) => e.type === "custom" && e.customType === EYES_ENTRY)?.data;
42
87
  const ownerCwd = path.resolve(ctx.cwd);
@@ -45,20 +90,36 @@ export function registerEyes(pi, { observe = observeHitl, now = Date.now,
45
90
  ctx.ui?.setStatus?.("ace-eyes", "eyes blocked: session belongs to another project cwd");
46
91
  throw new Error("Eyes project owner mismatch; preserve this actor and use its original project session");
47
92
  }
93
+ const identity = processIdentity();
94
+ pi.appendEntry(EYES_BINDING, { ownerCwd, process: identity });
48
95
  eyes = new Eyes({ snapshot, now,
49
- save: (data) => pi.appendEntry(EYES_ENTRY, { ...data, ownerCwd }),
96
+ save: (data) => {
97
+ const entries = observedSources && typeof observedSources === "object" && !Array.isArray(observedSources) ? Object.entries(observedSources) : [];
98
+ const valid = entries.length > 0 && entries.length <= 64 && entries.every(([name, source]) =>
99
+ /^[a-zA-Z0-9_.:-]{1,128}$/.test(name) && source && ["ok", "degraded"].includes(source.status));
100
+ const sources = valid ? Object.fromEntries(entries.map(([name, source]) => [name, source.status]).sort()) : {};
101
+ pi.appendEntry(EYES_ENTRY, { ...data, ownerCwd, observerEvidence: {
102
+ process: identity, observedAt: observedAt ?? null, sources
103
+ } });
104
+ },
50
105
  status: (state) => {
51
- ctx.ui?.setStatus?.("ace-eyes", `eyes ${state.retired ? "retired" : state.breaker?.reason || (state.enabled ? "observing" : "off")} pending:${state.pending}`);
106
+ ctx.ui?.setStatus?.("ace-eyes", `eyes ${state.retired ? "retired" : state.breaker?.reason || (state.observationUnavailable ? "observation-unavailable" : state.wakeLimitedUntil && state.pending ? `wake-limited until ${new Date(state.wakeLimitedUntil).toISOString()}` : state.enabled ? "observing" : "off")} pending:${state.pending}`);
52
107
  if (state.breaker || state.retired) stopTimer();
53
108
  },
54
- observe: async (config) => {
55
- const result = await observe(ctx.cwd, config);
56
- // A disposed binding can still finish its asynchronous owner read.
57
- // Its source health is never evidence for the current session binding.
58
- if (generation === bindingGeneration) observedSources = result.sources;
59
- return result;
109
+ observe: (config) => observe(ctx.cwd, config),
110
+ // A result is evidence only after Eyes validated it and confirmed that
111
+ // the observer generation is still current.
112
+ onObserved: (result) => {
113
+ if (generation === bindingGeneration) { observedSources = result.sources; observedAt = now(); }
114
+ },
115
+ onObservationUnavailable: () => {
116
+ if (generation === bindingGeneration) clearEvidence();
60
117
  },
61
- canDeliver: () => !arming && !compacting && (ctx.isIdle() || running),
118
+ // Do not queue a follow-up while the current turn can still handle and
119
+ // acknowledge the same revision. Polling retains it until the agent is
120
+ // idle; already handled changes then require no extra model turn. Unlike
121
+ // eyes revisions, loop/watch messages cannot be acknowledged this way.
122
+ canDeliver: () => !arming && !compacting && !running && ctx.isIdle() && !ctx.hasPendingMessages(),
62
123
  deliveryStatus: () => {
63
124
  if (attempt?.accepted) return "accepted";
64
125
  // sendUserMessage is a void wrapper. Busy/queued is uncertain, not
@@ -69,23 +130,34 @@ export function registerEyes(pi, { observe = observeHitl, now = Date.now,
69
130
  deliver: async (batch) => {
70
131
  if (!ctx.model) return false;
71
132
  const text = `[ace-eyes] Pending task/assignment/HITL/deadline revisions: ${JSON.stringify(batch)}. ` +
72
- "Read ace-overseer observe and the original state owners; adopt reports through ace-overseer process-reports and existing task/assignment gates. " +
73
- "Reconcile uncertain effects; never repeat external actions on wake alone. After handling each exact revision, " +
133
+ "Read the original state owners. For reports use ace_eyes action process-reports; it accepts, continues and acknowledges exact completed revisions. " +
134
+ "Reconcile uncertain effects; never repeat external actions on wake alone. For other event types, after handling each exact revision, " +
74
135
  "acknowledge with the ace_eyes tool (action ack, key, revision). Settlement alone is not acknowledgement.";
136
+ const previous = attempt;
75
137
  attempt = { text, accepted: false };
76
138
  const result = pi.sendUserMessage(text, { deliverAs: "followUp" });
77
139
  // Some hosts expose a promise, the standard ExtensionAPI exposes void.
78
140
  // Neither completion nor void is proof of message consumption.
79
- if (result?.then) await result;
80
- return result !== false;
141
+ const submitted = await result;
142
+ if (submitted === false) attempt = previous;
143
+ return submitted !== false;
81
144
  } });
145
+ const configPath = env.ACE_OVERSEER_EYES_CONFIG;
146
+ if (configPath) {
147
+ const expected = path.join(ownerCwd, ".ace-local/overseer/eyes.json");
148
+ if (path.resolve(configPath) !== expected) throw new Error("Eyes config does not belong to this coordinator root");
149
+ eyes.start(JSON.parse(fs.readFileSync(configPath, "utf8")));
150
+ }
82
151
  arm();
83
- if (eyes.s.enabled) void eyes.tick();
152
+ if (eyes.s.enabled && configPath) {
153
+ arming = true;
154
+ try { await eyes.tick(); } finally { arming = false; }
155
+ } else if (eyes.s.enabled) void eyes.tick();
84
156
  };
85
157
  pi.on("session_start", async (_event, ctx) => bind(ctx));
86
158
  pi.on("session_tree", async (_event, ctx) => bind(ctx));
87
159
  pi.on("agent_start", async () => { running = true; });
88
- pi.on("agent_settled", async () => { running = false; });
160
+ pi.on("agent_settled", async () => { running = false; eyes?.persist(); });
89
161
  pi.on("message_start", async (event) => {
90
162
  if (event.message?.role !== "user" || !attempt) return;
91
163
  const text = typeof event.message.content === "string" ? event.message.content :
@@ -95,33 +167,62 @@ export function registerEyes(pi, { observe = observeHitl, now = Date.now,
95
167
  pi.on("session_before_compact", async (event) => { if (event.reason === "manual") compacting = true; });
96
168
  pi.on("session_compact", async () => { compacting = false; eyes?.persist(); });
97
169
  pi.on("session_compact_failed", async () => { compacting = false; });
98
- pi.on("session_shutdown", async () => { stopTimer(); eyes?.dispose(); });
170
+ pi.on("session_shutdown", async () => {
171
+ bindingGeneration++; stopTimer(); clearEvidence();
172
+ eyes?.persist(); eyes?.dispose(); eyes = undefined;
173
+ });
99
174
  pi.on("message_end", async (event) => {
100
175
  const message = event.message;
101
176
  if (message?.role === "assistant" && message.stopReason === "error") eyes?.quota(message.errorMessage);
102
177
  });
103
178
  pi.registerTool?.({
104
- name: "ace_eyes", label: "Eyes observation", description: "Start standing observation with an existing config file, read pending semantic events or acknowledge an exact handled revision. Does not accept reports, authorize effects, start actors or reset quota. Use existing report/assignment owners first. Deadlines require an operation identity and revision; cancel when no longer active.",
179
+ name: "ace_eyes", label: "Eyes observation", description: "Start standing observation with an existing config file, read pending semantic events or acknowledge an exact handled revision. Action process-reports invokes the existing report owner and acknowledges only its completed exact revisions. Other events require explicit ack. Does not reset quota. Deadlines require an operation identity and revision; cancel when no longer active.",
105
180
  parameters: { type: "object", properties: {
106
- action: { type: "string", enum: ["start", "status", "ack", "deadline", "cancel"] },
181
+ action: { type: "string", enum: ["start", "status", "process-reports", "ack", "deadline", "cancel"] },
107
182
  configPath: { type: "string" },
108
- key: { type: "string" }, revision: { type: "string" }, at: { type: "integer" }
183
+ key: { type: "string" }, revision: { type: "string" },
184
+ at: { type: "integer", description: "Absolute Unix epoch timestamp in milliseconds, NOT a duration. For five minutes from now use the current epoch milliseconds plus 300000; a past timestamp is immediately due." }
109
185
  }, required: ["action"], additionalProperties: false },
110
186
  execute: async (_id, args, _signal, _onUpdate, ctx) => {
111
187
  if (!eyes) {
112
188
  if (!ctx) throw new Error("Eyes session not initialized");
113
- bind(ctx);
189
+ await bind(ctx);
114
190
  }
191
+ let processing;
115
192
  if (args.action === "start") {
116
193
  if (!ctx || typeof args.configPath !== "string" || !args.configPath.trim()) {
117
194
  throw new Error("Eyes start requires configPath and the current session context");
118
195
  }
119
196
  const config = JSON.parse(fs.readFileSync(path.resolve(ctx.cwd, args.configPath), "utf8"));
120
- eyes.start(config); arm();
197
+ const current = eyes, generation = bindingGeneration;
198
+ clearEvidence(); current.start(config); arm();
121
199
  // Observe now, but do not enqueue a redundant model turn inside the
122
200
  // caller's turn. Pending revisions are returned to the caller below.
123
201
  arming = true;
124
- try { await eyes.tick(); } finally { arming = false; }
202
+ try { await current.tick(); } finally { if (current === eyes && generation === bindingGeneration) arming = false; }
203
+ if (current !== eyes || generation !== bindingGeneration) throw new Error("Eyes session changed during start");
204
+ }
205
+ else if (args.action === "process-reports") {
206
+ if (!ctx || !eyes.s.enabled) throw new Error("Report processing requires active eyes in this session");
207
+ const sources = observedSources && Object.values(observedSources);
208
+ const config = eyes.s.config;
209
+ const interval = config.intervalSeconds * 1000;
210
+ const cadence = Math.ceil(3600000 / (config.maxObservationsPerHour * interval)) * interval;
211
+ if (eyes.s.breaker || eyes.s.observationUnavailable || !sources?.length ||
212
+ sources.some(source => source.status !== "ok") || observedAt === undefined ||
213
+ now() - observedAt > cadence + config.timeoutMs)
214
+ throw new Error("Report processing blocked: required observation is unavailable, degraded or stale");
215
+ const current = eyes, generation = bindingGeneration;
216
+ processing = await processReportOwner(ctx.cwd, current.s.config, _signal);
217
+ if (current !== eyes || generation !== bindingGeneration)
218
+ throw new Error("Eyes session changed during report processing; retained receipts require reconciliation");
219
+ if (!Array.isArray(processing?.outcomes) || processing.dry_run !== false)
220
+ throw new Error("Invalid report-processing receipt");
221
+ for (const receipt of processing.outcomes) {
222
+ if (receipt.acknowledge !== true || receipt.accepted !== true || receipt.cleanup !== "complete") continue;
223
+ if (current.s.pending[receipt.key]?.revision === receipt.revision || current.sent.get(receipt.key) === receipt.revision)
224
+ current.ack(receipt.key, receipt.revision);
225
+ }
125
226
  }
126
227
  else if (args.action === "ack") eyes.ack(args.key, args.revision);
127
228
  else if (args.action === "deadline") eyes.deadline(args.key, args.at, args.revision);
@@ -129,21 +230,24 @@ export function registerEyes(pi, { observe = observeHitl, now = Date.now,
129
230
  else if (args.action !== "status") throw new Error("Unknown eyes action");
130
231
  // Do not send a second wake from inside the running model turn. The next
131
232
  // observation delivers remaining coalesced revisions through the same owner.
132
- const details = { ...eyes.summary(), sources: observedSources, pending: eyes.s.pending, deadlines: eyes.s.deadlines };
233
+ const details = { ...eyes.summary(), ...(processing ? { processing } : {}), sources: observedSources, pending: eyes.s.pending, deadlines: eyes.s.deadlines };
133
234
  return { content: [{ type: "text", text: JSON.stringify(details) }], details };
134
235
  }
135
236
  });
136
237
  pi.registerCommand("eyes", { description: "Event-driven HITL observation: start CONFIG | status | ack KEY REV | deadline NAME REVISION EPOCH_MS | cancel NAME | resume quota-verified | retire",
137
238
  handler: async (args, ctx) => {
138
239
  try {
139
- if (!eyes) bind(ctx);
240
+ if (!eyes) await bind(ctx);
140
241
  const [command, a, b, ...rest] = args.trim().split(/\s+/);
141
242
  if (rest.length && command !== "deadline") throw new Error("Too many arguments");
142
243
  switch (command) {
143
244
  case "start": {
144
245
  if (!a || b) throw new Error("Use eyes start CONFIG_JSON");
145
246
  const config = JSON.parse(fs.readFileSync(path.resolve(ctx.cwd, a), "utf8"));
146
- eyes.start(config); arm(); await eyes.tick(); break;
247
+ const current = eyes, generation = bindingGeneration;
248
+ clearEvidence(); current.start(config); arm(); await current.tick();
249
+ if (current !== eyes || generation !== bindingGeneration) throw new Error("Eyes session changed during start");
250
+ break;
147
251
  }
148
252
  case "status": ctx.ui?.notify?.(JSON.stringify({ ...eyes.summary(), pending: eyes.s.pending, deadlines: eyes.s.deadlines }), "info"); break;
149
253
  case "ack": eyes.ack(a, b); await eyes.tick(); break;
@@ -153,7 +257,13 @@ export function registerEyes(pi, { observe = observeHitl, now = Date.now,
153
257
  case "cancel": eyes.cancelDeadline(a); break;
154
258
  case "resume":
155
259
  if (a !== "quota-verified" || b) throw new Error("Explicit owner verification required: eyes resume quota-verified");
156
- await eyes.resume(); arm(); break;
260
+ {
261
+ const current = eyes, generation = bindingGeneration;
262
+ clearEvidence(); await current.resume();
263
+ if (current !== eyes || generation !== bindingGeneration) throw new Error("Eyes session changed during resume");
264
+ arm();
265
+ }
266
+ break;
157
267
  case "retire": eyes.retire(); stopTimer(); break;
158
268
  default: throw new Error("Unknown eyes command; use start, status, ack, deadline, cancel, resume or retire");
159
269
  }
@@ -3,14 +3,14 @@ import { createHash } from "node:crypto";
3
3
  const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
4
4
  export const EYES_ENTRY = "ace-wake-eyes";
5
5
  export const defaults = { intervalSeconds: 30, maxEvents: 500, maxObservationsPerHour: 120, maxWakesPerHour: 20,
6
- timeoutMs: 10000, maxErrors: 3, maxPending: 2000, scope: "current", recipient: "self", syncRoutes: [] };
6
+ timeoutMs: 60000, maxErrors: 3, maxPending: 2000, scope: "current", recipient: "self", syncRoutes: [] };
7
7
 
8
8
  export function validateConfig(input) {
9
9
  if (!input || typeof input !== "object" || Array.isArray(input) ||
10
10
  Object.keys(input).some(key => !(key in defaults))) throw new Error("Invalid eyes configuration");
11
11
  const config = { ...defaults, ...input };
12
12
  for (const [key, min, max] of [["intervalSeconds", 1, 3600], ["maxEvents", 1, 2000],
13
- ["maxObservationsPerHour", 1, 3600], ["maxWakesPerHour", 1, 1000], ["timeoutMs", 100, 30000], ["maxErrors", 1, 10], ["maxPending", 1, 10000]]) {
13
+ ["maxObservationsPerHour", 1, 3600], ["maxWakesPerHour", 1, 1000], ["timeoutMs", 100, 120000], ["maxErrors", 1, 10], ["maxPending", 1, 10000]]) {
14
14
  if (!Number.isInteger(config[key]) || config[key] < min || config[key] > max) throw new Error(`Invalid ${key}`);
15
15
  }
16
16
  if (typeof config.recipient !== "string" || !/^[a-zA-Z0-9_-]{1,64}$/.test(config.recipient)) throw new Error("Invalid observer recipient");
@@ -24,7 +24,7 @@ export function validateConfig(input) {
24
24
  /** Observation/delivery bookkeeping in the existing Pi session, not a work
25
25
  * queue. It never starts tasks or accepts reports on behalf of their owner. */
26
26
  export class Eyes {
27
- constructor({ snapshot, save, observe, deliver, now = Date.now, status = () => {}, deliveryStatus = () => "accepted", canDeliver = () => true }) {
27
+ constructor({ snapshot, save, observe, deliver, now = Date.now, status = () => {}, deliveryStatus = () => "accepted", canDeliver = () => true, onObserved = () => {}, onObservationUnavailable = () => {} }) {
28
28
  this.s = structuredClone(snapshot || { enabled: false, retired: false, config: defaults,
29
29
  pending: {}, acknowledged: {}, deadlines: {}, breaker: null, errors: 0, window: null });
30
30
  this.s.config = validateConfig(this.s.config);
@@ -33,31 +33,60 @@ export class Eyes {
33
33
  if (typeof this.s.enabled !== "boolean" || typeof this.s.retired !== "boolean" ||
34
34
  !Number.isInteger(this.s.errors) || this.s.errors < 0) throw new Error("Invalid persisted eyes state");
35
35
  this.save = save; this.observe = observe; this.deliver = deliver; this.now = now; this.status = status;
36
- this.deliveryStatus = deliveryStatus; this.canDeliver = canDeliver;
37
- this.busy = false; this.disposed = false;
36
+ this.deliveryStatus = deliveryStatus; this.canDeliver = canDeliver; this.onObserved = onObserved;
37
+ this.onObservationUnavailable = onObservationUnavailable;
38
+ this.busy = null; this.delivering = false; this.disposed = false;
38
39
  // A process restart does not imply receipt acknowledgement. Reconcile the
39
40
  // same pending revisions; business-effect idempotence remains with .5.4.
40
41
  this.inflight = false;
41
42
  this.sent = new Map();
43
+ this.lastDelivery = new Map();
42
44
  this.generation = 0;
43
45
  }
44
46
  persist() { this.save(structuredClone(this.s)); this.status(this.summary()); }
45
47
  summary() { return { enabled: this.s.enabled, retired: this.s.retired, pending: Object.keys(this.s.pending).length,
46
- breaker: this.s.breaker, errors: this.s.errors, observations: this.s.window?.count || 0, wakes: this.s.window?.wakes || 0 }; }
48
+ breaker: this.s.breaker, errors: this.s.errors + Number(this.s.observationUnavailable === true),
49
+ observationUnavailable: this.s.observationUnavailable === true,
50
+ observations: this.s.window?.count || 0, wakes: this.s.window?.wakes || 0,
51
+ wakeLimitedUntil: this.wakeLimitedUntil() }; }
52
+ wakeLimitedUntil() {
53
+ const window = this.s.window;
54
+ if (!window || (window.wakes || 0) < this.s.config.maxWakesPerHour) return null;
55
+
56
+ const until = window.start + 3600000;
57
+ return this.now() < until ? until : null;
58
+ }
47
59
  start(config) {
60
+ if (this.disposed) throw new Error("Disposed observer cannot start");
61
+ if (this.delivering) throw new Error("Observer cannot reconfigure during delivery");
48
62
  if (this.s.retired) throw new Error("Retired actor cannot restart its eyes; hand off pending to its owner");
49
63
  if (this.s.breaker) throw new Error("Resolve breaker with explicit resume first");
50
- this.s.config = validateConfig(config); this.s.enabled = true; this.persist();
64
+ const next = validateConfig(config);
65
+ this.generation++; this.s.config = next; this.s.enabled = true; this.persist();
51
66
  }
52
67
  block(reason) {
53
68
  if (!this.s.breaker) { this.s.breaker = { reason, at: this.now() }; this.persist(); }
54
69
  }
55
70
  async resume() {
71
+ if (this.disposed) throw new Error("Disposed observer cannot resume");
72
+ if (this.delivering) throw new Error("Observer cannot resume during delivery");
56
73
  if (this.s.retired) throw new Error("Retired actor cannot resume");
57
74
  // Explicit operator action; check source/transport readiness without a model
58
75
  // request. Quota availability must have been verified by the owner.
76
+ const generation = ++this.generation;
59
77
  const result = await this.observe(this.s.config);
78
+ if (this.disposed || generation !== this.generation) throw new Error("Observer changed during resume");
60
79
  this.validate(result);
80
+ this.onObserved(result);
81
+ this.s.observationUnavailable = false;
82
+ // Explicit reconciliation permits retrying an unconfirmed notification.
83
+ // Keep confirmed deliveries suppressed until their exact revision is acked.
84
+ if (this.s.breaker?.reason === "notification-unconfirmed") {
85
+ for (const [key, revision] of this.lastDelivery) {
86
+ if (this.sent.get(key) === revision) this.sent.delete(key);
87
+ }
88
+ this.lastDelivery.clear();
89
+ }
61
90
  this.s.breaker = null; this.s.errors = 0; this.s.window = null; this.inflight = false;
62
91
  this.s.enabled = true; this.persist();
63
92
  await this.tick();
@@ -99,54 +128,101 @@ export class Eyes {
99
128
  keys.add(event.key);
100
129
  }
101
130
  }
102
- async tick() {
103
- if (this.busy || this.disposed || !this.s.enabled || this.s.retired || this.s.breaker) return;
131
+ async tick({ scheduled = false } = {}) {
132
+ if (this.busy === this.generation || this.disposed || !this.s.enabled || this.s.retired || this.s.breaker) return;
104
133
  const now = this.now();
105
134
  if (!this.s.window || now - this.s.window.start >= 3600000) this.s.window = { start: now, count: 0, wakes: 0 };
106
- if (this.s.window.count >= this.s.config.maxObservationsPerHour) { this.block("observation-budget"); return; }
107
- this.s.window.count++; this.persist(); // Budget survives restart too.
108
- this.busy = true;
135
+ const timerInterval = this.s.config.intervalSeconds * 1000;
136
+ const cadence = Math.ceil(3600000 / (this.s.config.maxObservationsPerHour * timerInterval)) * timerInterval;
137
+ const due = !scheduled || this.s.window.lastAttemptAt === undefined ||
138
+ now - this.s.window.lastAttemptAt >= cadence;
139
+ const acquire = due && this.s.window.count < this.s.config.maxObservationsPerHour;
109
140
  const generation = this.generation;
141
+ this.busy = generation;
142
+ let observed = false;
110
143
  try {
111
- const result = await this.observe(this.s.config);
112
- if (generation !== this.generation || this.disposed) return;
113
- this.validate(result);
114
- for (const e of result.settled || []) {
115
- this.s.acknowledged[e.key] = e.revision;
116
- if (this.s.pending[e.key]?.revision === e.revision) delete this.s.pending[e.key];
117
- this.sent.delete(e.key);
118
- }
119
- if (this.inflight && this.sent.size === 0) this.inflight = false;
120
- for (const e of result.events) {
121
- if (this.s.acknowledged[e.key] !== e.revision) this.s.pending[e.key] = { id: e.id, revision: e.revision };
144
+ if (acquire) {
145
+ this.s.window.count++;
146
+ this.s.window.lastAttemptAt = now;
147
+ this.persist(); // Attempts and allowance survive restart.
148
+ let result;
149
+ try {
150
+ result = await this.observe(this.s.config);
151
+ } catch {
152
+ if (generation === this.generation && !this.disposed) {
153
+ // Reading again is safe. Retain pending work, but do not deliver
154
+ // it against stale evidence. The next scheduled acquisition uses
155
+ // the same cadence and hourly allowance.
156
+ this.s.observationUnavailable = true;
157
+ this.onObservationUnavailable();
158
+ this.persist();
159
+ }
160
+ return;
161
+ }
162
+ if (generation !== this.generation || this.disposed) return;
163
+ try {
164
+ this.validate(result);
165
+ } catch (error) {
166
+ this.s.observationUnavailable = true;
167
+ this.onObservationUnavailable();
168
+ throw error;
169
+ }
170
+ this.s.observationUnavailable = false;
171
+ this.onObserved(result);
172
+ for (const e of result.settled || []) {
173
+ this.s.acknowledged[e.key] = e.revision;
174
+ if (this.s.pending[e.key]?.revision === e.revision) delete this.s.pending[e.key];
175
+ this.sent.delete(e.key);
176
+ }
177
+ if (this.inflight && this.sent.size === 0) this.inflight = false;
178
+ for (const e of result.events) {
179
+ if (this.s.acknowledged[e.key] !== e.revision) this.s.pending[e.key] = { id: e.id, revision: e.revision };
180
+ }
181
+ observed = true;
122
182
  }
183
+ if (this.s.observationUnavailable) return;
123
184
  for (const [name, deadline] of Object.entries(this.s.deadlines)) {
124
185
  const { at, operationRevision } = deadline;
125
186
  const key = `deadline:${name}`, revision = hash([name, at, operationRevision]);
126
- if (now >= at && this.s.acknowledged[key] !== revision) this.s.pending[key] = { id: name, revision };
187
+ if (this.now() >= at && this.s.acknowledged[key] !== revision) this.s.pending[key] = { id: name, revision };
127
188
  }
128
189
  if (Object.keys(this.s.pending).length + Object.keys(this.s.acknowledged).length > this.s.config.maxPending) {
129
190
  this.block("retention-budget"); return;
130
191
  }
131
192
  this.persist();
132
- if (this.inflight && this.deliveryStatus() === "uncertain") {
193
+ const delivery = this.inflight ? this.deliveryStatus() : "accepted";
194
+ if (delivery === "uncertain") {
133
195
  this.block("notification-unconfirmed"); return;
134
196
  }
135
- if (!this.inflight && !this.s.breaker && Object.keys(this.s.pending).length && this.canDeliver()) {
197
+ // An accepted turn may deliberately leave work unacknowledged while a
198
+ // source is degraded. A fresh revision must still reach the idle owner.
199
+ const batch = Object.entries(this.s.pending)
200
+ .filter(([key, value]) => this.sent.get(key) !== value.revision).slice(0, 20);
201
+ if (delivery === "accepted" && !this.s.breaker && batch.length && this.canDeliver() &&
202
+ this.wakeLimitedUntil() === null) {
136
203
  // Retain identities before attempting delivery. A rejected send leaves
137
204
  // pending intact; acceptance by Pi is not application acknowledgement.
138
- if ((this.s.window.wakes || 0) >= this.s.config.maxWakesPerHour) { this.block("wake-budget"); return; }
139
205
  this.s.window.wakes = (this.s.window.wakes || 0) + 1;
140
206
  this.persist(); // Includes uncertain notification attempts, never token billing.
141
- const batch = Object.entries(this.s.pending).slice(0, 20);
142
- this.inflight = Boolean(await this.deliver(batch));
143
- if (this.inflight) this.sent = new Map(batch.map(([key, value]) => [key, value.revision]));
144
- if (!this.inflight) throw new Error("wake delivery refused");
207
+ this.delivering = true;
208
+ let delivered;
209
+ try { delivered = await this.deliver(batch); } finally { this.delivering = false; }
210
+ if (generation !== this.generation || this.disposed) return;
211
+ if (!delivered) throw new Error("wake delivery refused");
212
+ this.lastDelivery = new Map();
213
+ for (const [key, value] of batch) {
214
+ if (this.s.pending[key]?.revision === value.revision) {
215
+ this.sent.set(key, value.revision);
216
+ this.lastDelivery.set(key, value.revision);
217
+ }
218
+ }
219
+ this.inflight = this.sent.size > 0;
145
220
  }
146
- if (this.s.errors && (!this.inflight || this.deliveryStatus() === "accepted")) { this.s.errors = 0; this.persist(); }
221
+ if (observed && this.s.errors && (!this.inflight || this.deliveryStatus() === "accepted")) { this.s.errors = 0; this.persist(); }
147
222
  } catch {
223
+ if (generation !== this.generation || this.disposed) return;
148
224
  this.s.errors++; this.persist();
149
225
  if (this.s.errors >= this.s.config.maxErrors) this.block("observation-or-delivery-failure");
150
- } finally { this.busy = false; }
226
+ } finally { if (this.busy === generation) this.busy = null; }
151
227
  }
152
228
  }
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Ace
4
4
  module Wake
5
- VERSION = "0.2.0"
5
+ VERSION = "0.4.0"
6
6
  end
7
7
  end
metadata CHANGED
@@ -1,14 +1,34 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ace-wake
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.0
4
+ version: 0.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Michal Czyz
8
8
  bindir: exe
9
9
  cert_chain: []
10
- date: 2026-10-31 00:00:00.000000000 Z
11
- dependencies: []
10
+ date: 2026-11-12 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: ace-runtime
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '0.4'
19
+ - - ">="
20
+ - !ruby/object:Gem::Version
21
+ version: 0.4.2
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - "~>"
27
+ - !ruby/object:Gem::Version
28
+ version: '0.4'
29
+ - - ">="
30
+ - !ruby/object:Gem::Version
31
+ version: 0.4.2
12
32
  description: 'Publishable asset package for the ace-wake Pi harness extension: /loop
13
33
  timers and /watch file subscriptions that wake idle agents. Ships the extension
14
34
  through the standard handbook projection (ace-handbook sync --provider pi) and the