ace-wake 0.2.0 → 0.3.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: a679048243d6647fbd557f720145e244bd42198dfbbe3e6f290a7ac96e9cf2a6
4
+ data.tar.gz: 20ee3a591b2f8324fefe4927b3c5b3f820799d8769f2df6d357bc65f4c9dac76
5
5
  SHA512:
6
- metadata.gz: e3284df4db91ce0b48fa1714b00b818622d0df1c20ee7d5f4b7812683f545696bbeed3bb11089a066825726cd3d5a81d09836747c9ee276b503bae19028770e8
7
- data.tar.gz: 9496ea0bc29040ce63e62c2be847a782b4b7c0237efa5982a9793dcc9b81de2d5e591bb3b33cc4d9b8e862b7fda6f0477b16a691e67ba2e2e3c5e33d9f77e358
6
+ metadata.gz: 3988a72f9d1a5b4c6a687e265615e3036edfa08da782cdab5b5f3b20c84326751ffa18746d07def2fc90a90a86fe68d5cc31831df2442285f4e0e8849e440dc8
7
+ data.tar.gz: bba20957de9af875a32835e5ca1c500e924a0178282b19a6778e5af03f1789aa9863ceb3a542784a40bdeb7b90bb83a298b52fcd794c5a57b64a4a927927f15a
data/CHANGELOG.md CHANGED
@@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.3.0] - 2026-11-10
11
+
12
+ ### Added
13
+
14
+ - 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.
15
+
16
+ ### Fixed
17
+
18
+ - Explicit reconciliation retries an unconfirmed notification in the same session while keeping confirmed deliveries suppressed until acknowledgment.
19
+
10
20
  ## [0.2.0] - 2026-10-31
11
21
 
12
22
  ### 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,28 @@ 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;
24
57
  }
25
58
 
26
59
  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;
60
+ schedule = (fn, ms) => setInterval(fn, ms), cancel = clearInterval, processIdentity = eyesProcessIdentity } = {}) {
61
+ let eyes, timer, attempt, observedSources, observedAt, bindingGeneration = 0, compacting = false, running = false, arming = false;
62
+ const clearEvidence = () => { observedSources = undefined; observedAt = undefined; };
29
63
  const stopTimer = () => { if (timer !== undefined) cancel(timer); timer = undefined; };
30
64
  function arm() {
31
65
  stopTimer();
32
66
  if (eyes?.s.enabled && !eyes.s.retired && !eyes.s.breaker) {
33
- timer = schedule(() => { void eyes.tick(); }, eyes.s.config.intervalSeconds * 1000);
67
+ timer = schedule(() => { void eyes.tick({ scheduled: true }); },
68
+ eyes.s.config.intervalSeconds * 1000);
34
69
  timer?.unref?.();
35
70
  }
36
71
  }
37
72
  const bind = (ctx) => {
38
73
  const generation = ++bindingGeneration;
39
- stopTimer(); eyes?.dispose(); attempt = undefined; observedSources = undefined; compacting = false; running = false;
74
+ stopTimer(); eyes?.dispose(); attempt = undefined; clearEvidence(); compacting = false; running = false;
40
75
  const entries = ctx.sessionManager.getBranch();
41
76
  const snapshot = [...entries].reverse().find((e) => e.type === "custom" && e.customType === EYES_ENTRY)?.data;
42
77
  const ownerCwd = path.resolve(ctx.cwd);
@@ -45,20 +80,36 @@ export function registerEyes(pi, { observe = observeHitl, now = Date.now,
45
80
  ctx.ui?.setStatus?.("ace-eyes", "eyes blocked: session belongs to another project cwd");
46
81
  throw new Error("Eyes project owner mismatch; preserve this actor and use its original project session");
47
82
  }
83
+ const identity = processIdentity();
84
+ pi.appendEntry(EYES_BINDING, { ownerCwd, process: identity });
48
85
  eyes = new Eyes({ snapshot, now,
49
- save: (data) => pi.appendEntry(EYES_ENTRY, { ...data, ownerCwd }),
86
+ save: (data) => {
87
+ const entries = observedSources && typeof observedSources === "object" && !Array.isArray(observedSources) ? Object.entries(observedSources) : [];
88
+ const valid = entries.length > 0 && entries.length <= 64 && entries.every(([name, source]) =>
89
+ /^[a-zA-Z0-9_.:-]{1,128}$/.test(name) && source && ["ok", "degraded"].includes(source.status));
90
+ const sources = valid ? Object.fromEntries(entries.map(([name, source]) => [name, source.status]).sort()) : {};
91
+ pi.appendEntry(EYES_ENTRY, { ...data, ownerCwd, observerEvidence: {
92
+ process: identity, observedAt: observedAt ?? null, sources
93
+ } });
94
+ },
50
95
  status: (state) => {
51
- ctx.ui?.setStatus?.("ace-eyes", `eyes ${state.retired ? "retired" : state.breaker?.reason || (state.enabled ? "observing" : "off")} pending:${state.pending}`);
96
+ ctx.ui?.setStatus?.("ace-eyes", `eyes ${state.retired ? "retired" : state.breaker?.reason || (state.observationUnavailable ? "observation-unavailable" : state.enabled ? "observing" : "off")} pending:${state.pending}`);
52
97
  if (state.breaker || state.retired) stopTimer();
53
98
  },
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;
99
+ observe: (config) => observe(ctx.cwd, config),
100
+ // A result is evidence only after Eyes validated it and confirmed that
101
+ // the observer generation is still current.
102
+ onObserved: (result) => {
103
+ if (generation === bindingGeneration) { observedSources = result.sources; observedAt = now(); }
60
104
  },
61
- canDeliver: () => !arming && !compacting && (ctx.isIdle() || running),
105
+ onObservationUnavailable: () => {
106
+ if (generation === bindingGeneration) clearEvidence();
107
+ },
108
+ // Do not queue a follow-up while the current turn can still handle and
109
+ // acknowledge the same revision. Polling retains it until the agent is
110
+ // idle; already handled changes then require no extra model turn. Unlike
111
+ // eyes revisions, loop/watch messages cannot be acknowledged this way.
112
+ canDeliver: () => !arming && !compacting && !running && ctx.isIdle() && !ctx.hasPendingMessages(),
62
113
  deliveryStatus: () => {
63
114
  if (attempt?.accepted) return "accepted";
64
115
  // sendUserMessage is a void wrapper. Busy/queued is uncertain, not
@@ -72,12 +123,14 @@ export function registerEyes(pi, { observe = observeHitl, now = Date.now,
72
123
  "Read ace-overseer observe and the original state owners; adopt reports through ace-overseer process-reports and existing task/assignment gates. " +
73
124
  "Reconcile uncertain effects; never repeat external actions on wake alone. After handling each exact revision, " +
74
125
  "acknowledge with the ace_eyes tool (action ack, key, revision). Settlement alone is not acknowledgement.";
126
+ const previous = attempt;
75
127
  attempt = { text, accepted: false };
76
128
  const result = pi.sendUserMessage(text, { deliverAs: "followUp" });
77
129
  // Some hosts expose a promise, the standard ExtensionAPI exposes void.
78
130
  // Neither completion nor void is proof of message consumption.
79
- if (result?.then) await result;
80
- return result !== false;
131
+ const submitted = await result;
132
+ if (submitted === false) attempt = previous;
133
+ return submitted !== false;
81
134
  } });
82
135
  arm();
83
136
  if (eyes.s.enabled) void eyes.tick();
@@ -85,7 +138,7 @@ export function registerEyes(pi, { observe = observeHitl, now = Date.now,
85
138
  pi.on("session_start", async (_event, ctx) => bind(ctx));
86
139
  pi.on("session_tree", async (_event, ctx) => bind(ctx));
87
140
  pi.on("agent_start", async () => { running = true; });
88
- pi.on("agent_settled", async () => { running = false; });
141
+ pi.on("agent_settled", async () => { running = false; eyes?.persist(); });
89
142
  pi.on("message_start", async (event) => {
90
143
  if (event.message?.role !== "user" || !attempt) return;
91
144
  const text = typeof event.message.content === "string" ? event.message.content :
@@ -95,7 +148,10 @@ export function registerEyes(pi, { observe = observeHitl, now = Date.now,
95
148
  pi.on("session_before_compact", async (event) => { if (event.reason === "manual") compacting = true; });
96
149
  pi.on("session_compact", async () => { compacting = false; eyes?.persist(); });
97
150
  pi.on("session_compact_failed", async () => { compacting = false; });
98
- pi.on("session_shutdown", async () => { stopTimer(); eyes?.dispose(); });
151
+ pi.on("session_shutdown", async () => {
152
+ bindingGeneration++; stopTimer(); clearEvidence();
153
+ eyes?.persist(); eyes?.dispose(); eyes = undefined;
154
+ });
99
155
  pi.on("message_end", async (event) => {
100
156
  const message = event.message;
101
157
  if (message?.role === "assistant" && message.stopReason === "error") eyes?.quota(message.errorMessage);
@@ -117,11 +173,13 @@ export function registerEyes(pi, { observe = observeHitl, now = Date.now,
117
173
  throw new Error("Eyes start requires configPath and the current session context");
118
174
  }
119
175
  const config = JSON.parse(fs.readFileSync(path.resolve(ctx.cwd, args.configPath), "utf8"));
120
- eyes.start(config); arm();
176
+ const current = eyes, generation = bindingGeneration;
177
+ clearEvidence(); current.start(config); arm();
121
178
  // Observe now, but do not enqueue a redundant model turn inside the
122
179
  // caller's turn. Pending revisions are returned to the caller below.
123
180
  arming = true;
124
- try { await eyes.tick(); } finally { arming = false; }
181
+ try { await current.tick(); } finally { if (current === eyes && generation === bindingGeneration) arming = false; }
182
+ if (current !== eyes || generation !== bindingGeneration) throw new Error("Eyes session changed during start");
125
183
  }
126
184
  else if (args.action === "ack") eyes.ack(args.key, args.revision);
127
185
  else if (args.action === "deadline") eyes.deadline(args.key, args.at, args.revision);
@@ -143,7 +201,10 @@ export function registerEyes(pi, { observe = observeHitl, now = Date.now,
143
201
  case "start": {
144
202
  if (!a || b) throw new Error("Use eyes start CONFIG_JSON");
145
203
  const config = JSON.parse(fs.readFileSync(path.resolve(ctx.cwd, a), "utf8"));
146
- eyes.start(config); arm(); await eyes.tick(); break;
204
+ const current = eyes, generation = bindingGeneration;
205
+ clearEvidence(); current.start(config); arm(); await current.tick();
206
+ if (current !== eyes || generation !== bindingGeneration) throw new Error("Eyes session changed during start");
207
+ break;
147
208
  }
148
209
  case "status": ctx.ui?.notify?.(JSON.stringify({ ...eyes.summary(), pending: eyes.s.pending, deadlines: eyes.s.deadlines }), "info"); break;
149
210
  case "ack": eyes.ack(a, b); await eyes.tick(); break;
@@ -153,7 +214,13 @@ export function registerEyes(pi, { observe = observeHitl, now = Date.now,
153
214
  case "cancel": eyes.cancelDeadline(a); break;
154
215
  case "resume":
155
216
  if (a !== "quota-verified" || b) throw new Error("Explicit owner verification required: eyes resume quota-verified");
156
- await eyes.resume(); arm(); break;
217
+ {
218
+ const current = eyes, generation = bindingGeneration;
219
+ clearEvidence(); await current.resume();
220
+ if (current !== eyes || generation !== bindingGeneration) throw new Error("Eyes session changed during resume");
221
+ arm();
222
+ }
223
+ break;
157
224
  case "retire": eyes.retire(); stopTimer(); break;
158
225
  default: throw new Error("Unknown eyes command; use start, status, ack, deadline, cancel, resume or retire");
159
226
  }
@@ -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.3.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.3.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-10 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