ace-wake 0.4.0 → 0.6.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.
@@ -1,4 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { clip, describeEvent, HEX64, MAX_NOTE_CHARS } from "./eyes-digest.js";
2
3
 
3
4
  const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
4
5
  export const EYES_ENTRY = "ace-wake-eyes";
@@ -7,7 +8,7 @@ export const defaults = { intervalSeconds: 30, maxEvents: 500, maxObservationsPe
7
8
 
8
9
  export function validateConfig(input) {
9
10
  if (!input || typeof input !== "object" || Array.isArray(input) ||
10
- Object.keys(input).some(key => !(key in defaults))) throw new Error("Invalid eyes configuration");
11
+ Object.keys(input).some(key => !Object.hasOwn(defaults, key))) throw new Error("Invalid eyes configuration");
11
12
  const config = { ...defaults, ...input };
12
13
  for (const [key, min, max] of [["intervalSeconds", 1, 3600], ["maxEvents", 1, 2000],
13
14
  ["maxObservationsPerHour", 1, 3600], ["maxWakesPerHour", 1, 1000], ["timeoutMs", 100, 120000], ["maxErrors", 1, 10], ["maxPending", 1, 10000]]) {
@@ -30,6 +31,20 @@ export class Eyes {
30
31
  this.s.config = validateConfig(this.s.config);
31
32
  for (const key of ["pending", "acknowledged", "deadlines"])
32
33
  if (!this.s[key] || typeof this.s[key] !== "object" || Array.isArray(this.s[key])) throw new Error("Invalid persisted eyes state");
34
+ // Migrate legacy (pre-0.5.0) pending entries: they carry no descriptors,
35
+ // so no id form could ever address them and they would accumulate toward
36
+ // the retention breaker. Give each a unique synthetic ref and a note that
37
+ // names it, keeping the restored session operable without exposing hashes.
38
+ const takenRefs = new Set(Object.values(this.s.pending)
39
+ .filter((entry) => entry.ref !== undefined).flatMap((entry) => [entry.ref, `${entry.kind}:${entry.ref}`]));
40
+ let restored = 0;
41
+ for (const entry of Object.values(this.s.pending)) {
42
+ if (entry.ref !== undefined) continue;
43
+ do { restored += 1; entry.ref = `restored-${restored}`; } while (takenRefs.has(entry.ref) || takenRefs.has(`${entry.kind ?? "event"}:${entry.ref}`));
44
+ takenRefs.add(entry.ref); takenRefs.add(`${entry.kind ?? "event"}:${entry.ref}`);
45
+ entry.kind = entry.kind ?? "event";
46
+ entry.note = clip(`${entry.note ?? "unrecognized event from an older session"} — ack id ${entry.ref}`, MAX_NOTE_CHARS);
47
+ }
33
48
  if (typeof this.s.enabled !== "boolean" || typeof this.s.retired !== "boolean" ||
34
49
  !Number.isInteger(this.s.errors) || this.s.errors < 0) throw new Error("Invalid persisted eyes state");
35
50
  this.save = save; this.observe = observe; this.deliver = deliver; this.now = now; this.status = status;
@@ -40,15 +55,38 @@ export class Eyes {
40
55
  // same pending revisions; business-effect idempotence remains with .5.4.
41
56
  this.inflight = false;
42
57
  this.sent = new Map();
58
+ // Revisions actually rendered to the model this session (wake prefix and
59
+ // status details). Ref-based acknowledgement is held to them: a stale view
60
+ // can never discard a newer revision it has not seen. In-memory by design:
61
+ // after a restart nothing is considered presented until re-rendered.
62
+ this.presented = new Map();
43
63
  this.lastDelivery = new Map();
44
64
  this.generation = 0;
45
65
  }
66
+ /** Record the revisions the model was just shown (wake prefix or status). */
67
+ markPresented(entries) {
68
+ for (const { key, revision } of Array.isArray(entries) ? entries : []) {
69
+ if (typeof key === "string" && key && typeof revision === "string" && revision) this.presented.set(key, revision);
70
+ }
71
+ }
72
+ /** Bind raw receipt rows to current pending entries: only a row whose
73
+ * exact revision is still pending becomes presented, so a report digest
74
+ * authorizes nothing beyond the outcomes it actually names. */
75
+ markReceiptPresented(rows) {
76
+ for (const { key, revision } of Array.isArray(rows) ? rows : []) {
77
+ if (typeof key === "string" && key && typeof revision === "string" && revision &&
78
+ this.s.pending[key]?.revision === revision) {
79
+ this.presented.set(key, this.s.pending[key].revision);
80
+ }
81
+ }
82
+ }
46
83
  persist() { this.save(structuredClone(this.s)); this.status(this.summary()); }
47
84
  summary() { return { enabled: this.s.enabled, retired: this.s.retired, pending: Object.keys(this.s.pending).length,
85
+ deadlines: Object.keys(this.s.deadlines).length,
48
86
  breaker: this.s.breaker, errors: this.s.errors + Number(this.s.observationUnavailable === true),
49
87
  observationUnavailable: this.s.observationUnavailable === true,
50
88
  observations: this.s.window?.count || 0, wakes: this.s.window?.wakes || 0,
51
- wakeLimitedUntil: this.wakeLimitedUntil() }; }
89
+ wakeLimit: this.s.config.maxWakesPerHour, wakeLimitedUntil: this.wakeLimitedUntil() }; }
52
90
  wakeLimitedUntil() {
53
91
  const window = this.s.window;
54
92
  if (!window || (window.wakes || 0) < this.s.config.maxWakesPerHour) return null;
@@ -104,6 +142,7 @@ export class Eyes {
104
142
  this.s.deadlines[name] = { at, operationRevision }; this.persist();
105
143
  }
106
144
  cancelDeadline(name) {
145
+ if (!Object.hasOwn(this.s.deadlines, name)) throw new Error(`No deadline named ${clip(name, 64)} is registered`);
107
146
  delete this.s.deadlines[name]; delete this.s.pending[`deadline:${name}`];
108
147
  this.sent.delete(`deadline:${name}`); this.inflight = this.sent.size > 0; this.persist();
109
148
  }
@@ -115,6 +154,54 @@ export class Eyes {
115
154
  this.sent.delete(key);
116
155
  this.inflight = this.sent.size > 0; this.persist();
117
156
  }
157
+ /** Resolve a short id from the digest to exactly one pending event. Exact
158
+ * keys (deadline:<name>, composite kind:ref) win over bare refs; a restored
159
+ * entry's non-hash persisted id is accepted as a last resort. Ambiguity and
160
+ * unknown ids are refused without side effects, and an ambiguous id names
161
+ * its bounded candidates instead of advising the form that was refused. */
162
+ /** Resolve a short id to exactly one pending event and acknowledge it.
163
+ * Model-facing paths (ace_eyes tool) require the revision to have been
164
+ * presented this session and hold stale views to the presented revision.
165
+ * The operator /eyes ack command runs under explicit human authority: it
166
+ * acknowledges the current pending revision the operator just viewed. */
167
+ ackByRef(ref, { presentationRequired = true } = {}) {
168
+ if (typeof ref !== "string" || !ref.trim()) throw new Error("Ack requires a pending event id from ace_eyes status");
169
+ const wanted = ref.trim();
170
+ const candidates = Object.entries(this.s.pending).filter(([, value]) =>
171
+ value.ref === wanted || `${value.kind}:${value.ref}` === wanted ||
172
+ (typeof value.id === "string" && value.id && !HEX64.test(value.id) && value.id === wanted));
173
+ if (candidates.length === 0) {
174
+ throw new Error(`No pending event matches ${clip(wanted, 64)}; run ace_eyes action status for current pending ids`);
175
+ }
176
+ if (candidates.length > 1) {
177
+ const named = candidates.slice(0, 3).map(([, value]) => clip(value.note ?? `${value.kind ?? "event"}:${value.ref ?? ""}`, 60));
178
+ const more = candidates.length > named.length ? ` (+${candidates.length - named.length} more)` : "";
179
+ const advice = wanted.includes(":")
180
+ ? "no id form disambiguates identical identities; handle one at its owner, the other stays pending"
181
+ : "ack each by its unique kind:id";
182
+ throw new Error(`Ambiguous id ${clip(wanted, 64)} matches ${candidates.length} pending events — ${named.join(" | ")}${more}; ${advice}`);
183
+ }
184
+ const [key, value] = candidates[0];
185
+ if (presentationRequired) {
186
+ const presented = this.presented.get(key);
187
+ if (presented === undefined) {
188
+ throw new Error(`No revision of ${clip(wanted, 64)} was presented in this session; run ace_eyes action status for the current note, then ack`);
189
+ }
190
+ // The stale branch requires pending to be NEWER than presented: revisions
191
+ // only advance (observed revisions overwrite, acknowledged suppress older).
192
+ if (presented !== value.revision) {
193
+ // Stale view: acknowledge exactly the presented revision and keep the
194
+ // newer unseen revision pending so it re-reports on the next delivery.
195
+ this.s.acknowledged[key] = presented;
196
+ if (this.sent.get(key) === presented) this.sent.delete(key);
197
+ this.inflight = this.sent.size > 0;
198
+ this.persist();
199
+ return { ...value, stale: true };
200
+ }
201
+ }
202
+ this.ack(key, value.revision);
203
+ return { ...value };
204
+ }
118
205
  validate(result) {
119
206
  if (result?.schema !== "ace.hitl.observation/v1" || !Array.isArray(result.events) || result.events.length > this.s.config.maxEvents)
120
207
  throw new Error("Invalid or over-budget HITL observation");
@@ -176,7 +263,33 @@ export class Eyes {
176
263
  }
177
264
  if (this.inflight && this.sent.size === 0) this.inflight = false;
178
265
  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 };
266
+ if (this.s.acknowledged[e.key] !== e.revision) {
267
+ const described = describeEvent(e);
268
+ // Keep kind:ref unique across pending entries: a colliding second
269
+ // event gets a numbered ref (named in its note) so the kind:id
270
+ // form stays resolvable instead of dead-ending in ambiguity.
271
+ if (described.ref !== undefined) {
272
+ const original = described.ref;
273
+ let candidate = original;
274
+ let sequence = 2;
275
+ while (Object.entries(this.s.pending).some(([k, v]) => k !== e.key && (v.ref === candidate || `${v.kind}:${v.ref}` === `${described.kind}:${candidate}`))) {
276
+ candidate = `${original}#${sequence++}`;
277
+ }
278
+ if (candidate !== original) {
279
+ described.note = clip(described.note.replace(original, candidate), MAX_NOTE_CHARS);
280
+ described.ref = candidate;
281
+ }
282
+ } else {
283
+ // An unknown or malformed event shape derives no ref; without one
284
+ // it could never be acknowledged and would only feed the breaker.
285
+ let sequence = 1;
286
+ let candidate;
287
+ do { candidate = `event-${sequence++}`; } while (Object.entries(this.s.pending).some(([k, v]) => k !== e.key && (v.ref === candidate || `${v.kind}:${v.ref}` === `event:${candidate}`)));
288
+ described.ref = candidate;
289
+ described.note = clip(`${described.note} — ack id ${candidate}`, MAX_NOTE_CHARS);
290
+ }
291
+ this.s.pending[e.key] = { id: e.id, revision: e.revision, ...described };
292
+ }
180
293
  }
181
294
  observed = true;
182
295
  }
@@ -184,7 +297,8 @@ export class Eyes {
184
297
  for (const [name, deadline] of Object.entries(this.s.deadlines)) {
185
298
  const { at, operationRevision } = deadline;
186
299
  const key = `deadline:${name}`, revision = hash([name, at, operationRevision]);
187
- if (this.now() >= at && this.s.acknowledged[key] !== revision) this.s.pending[key] = { id: name, revision };
300
+ if (this.now() >= at && this.s.acknowledged[key] !== revision)
301
+ this.s.pending[key] = { id: name, revision, kind: "deadline", ref: name, note: `deadline:${name} reached` };
188
302
  }
189
303
  if (Object.keys(this.s.pending).length + Object.keys(this.s.acknowledged).length > this.s.config.maxPending) {
190
304
  this.block("retention-budget"); return;
@@ -74,7 +74,7 @@ function usage(kind) {
74
74
  * @param {string} raw
75
75
  * @returns {Array<{text: string, quoted: boolean}>}
76
76
  */
77
- function tokenize(raw) {
77
+ export function tokenize(raw) {
78
78
  const tokens = [];
79
79
  let index = 0;
80
80
  while (index < raw.length) {
@@ -153,7 +153,11 @@ export function createWatchPort({ watchFactory, statFn, readFn = nodeReadFn, bas
153
153
  // created between the proof and this recomputation stays a change
154
154
  // (the scheduled reconcile below delivers it).
155
155
  const provenAbsent = new Set(watchers.filter((each) => each.watchPath !== each.path).map((each) => each.path));
156
- const fingerprint = aggregateFingerprint(paths, canonicalPath, provenAbsent);
156
+ const current = aggregateFingerprint(paths, canonicalPath, provenAbsent);
157
+ const restored = typeof definition.baseline === "string" ? segmentMap(definition.baseline) : null;
158
+ const fingerprint = restored
159
+ ? serializeSegments(paths.map(target => [target, restored.get(target) ?? ABSENT_SEGMENT]))
160
+ : current;
157
161
 
158
162
  active.set(definition.name, {
159
163
  watchers,
@@ -173,6 +177,8 @@ export function createWatchPort({ watchFactory, statFn, readFn = nodeReadFn, bas
173
177
  return canonicalPath;
174
178
  },
175
179
 
180
+ baseline(name) { return active.get(name)?.fingerprint; },
181
+
176
182
  stop(name) {
177
183
  stopExisting(name);
178
184
  errors.delete(name);
@@ -670,26 +676,14 @@ export function createWatchPort({ watchFactory, statFn, readFn = nodeReadFn, bas
670
676
  }
671
677
  entry.watchers = remaining;
672
678
  entry.paths = remaining.map((each) => each.path);
673
- // The `=` terminator makes the prefix match the segment of exactly this
674
- // target, never a target whose path merely extends it.
675
- const droppedPrefix = `${target}=`;
676
- entry.fingerprint = withoutSegment(entry.fingerprint, droppedPrefix);
677
- entry.previousFingerprint = withoutSegment(entry.previousFingerprint, droppedPrefix);
679
+ entry.fingerprint = withoutSegment(entry.fingerprint, target);
680
+ entry.previousFingerprint = withoutSegment(entry.previousFingerprint, target);
678
681
  }
679
682
 
680
- /**
681
- * Remove one target's `path=fingerprint` segment from an aggregate
682
- * fingerprint string, keeping every other segment verbatim.
683
- *
684
- * @param {string} fingerprint
685
- * @param {string} segmentPrefix The exact `path=` prefix of the removed target.
686
- * @returns {string}
687
- */
688
- function withoutSegment(fingerprint, segmentPrefix) {
689
- return fingerprint
690
- .split("|")
691
- .filter((segment) => !segment.startsWith(segmentPrefix))
692
- .join("|");
683
+ function withoutSegment(fingerprint, target) {
684
+ const segments = segmentMap(fingerprint);
685
+ segments.delete(target);
686
+ return serializeSegments(segments);
693
687
  }
694
688
 
695
689
  /**
@@ -720,22 +714,19 @@ export function createWatchPort({ watchFactory, statFn, readFn = nodeReadFn, bas
720
714
  * @returns {string}
721
715
  */
722
716
  function aggregateFingerprint(paths, primaryPath, forcedAbsent) {
723
- return [...paths]
724
- .sort()
725
- .map((path) => {
717
+ return serializeSegments([...paths].map((path) => {
726
718
  if (forcedAbsent?.has(path)) {
727
- return `${path}=${ABSENT_SEGMENT}`;
719
+ return [path, ABSENT_SEGMENT];
728
720
  }
729
721
  if (path === primaryPath) {
730
- return `${path}=${fingerprintOf(statFn(path), readFn(path))}`;
722
+ return [path, fingerprintOf(statFn(path), readFn(path))];
731
723
  }
732
724
  try {
733
- return `${path}=${fingerprintOf(statFn(path), readFn(path))}`;
725
+ return [path, fingerprintOf(statFn(path), readFn(path))];
734
726
  } catch {
735
- return `${path}=${ABSENT_SEGMENT}`;
727
+ return [path, ABSENT_SEGMENT];
736
728
  }
737
- })
738
- .join("|");
729
+ }));
739
730
  }
740
731
 
741
732
  /**
@@ -814,17 +805,19 @@ export function nodeStatfsFn(path) {
814
805
  return { type: stats.type };
815
806
  }
816
807
 
817
- /**
818
- * Split an aggregate fingerprint into its per-target `path=signature` map.
819
- *
820
- * @param {string} fingerprint
821
- * @returns {Map<string, string>}
822
- */
808
+ // JSON tuples preserve arbitrary filenames without delimiter ambiguity.
823
809
  function segmentMap(fingerprint) {
824
- return new Map(fingerprint.split("|").map((segment) => {
825
- const at = segment.indexOf("=");
826
- return [segment.slice(0, at), segment.slice(at + 1)];
827
- }));
810
+ return new Map(JSON.parse(fingerprint));
811
+ }
812
+
813
+ function serializeSegments(segments) {
814
+ return JSON.stringify([...segments].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
815
+ }
816
+
817
+ export function updateWatchBaseline(baseline, deltas) {
818
+ const segments = baseline ? segmentMap(baseline) : new Map();
819
+ for (const row of deltas) segments.set(row.path, row.after);
820
+ return serializeSegments(segments);
828
821
  }
829
822
 
830
823
  /**
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ace-wake
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.0
4
+ version: 0.6.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Michal Czyz
8
8
  bindir: exe
9
9
  cert_chain: []
10
- date: 2026-11-12 00:00:00.000000000 Z
10
+ date: 2026-11-17 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: ace-runtime
@@ -29,32 +29,59 @@ dependencies:
29
29
  - - ">="
30
30
  - !ruby/object:Gem::Version
31
31
  version: 0.4.2
32
- description: 'Publishable asset package for the ace-wake Pi harness extension: /loop
33
- timers and /watch file subscriptions that wake idle agents. Ships the extension
34
- through the standard handbook projection (ace-handbook sync --provider pi) and the
35
- ace-lab installer.'
32
+ - !ruby/object:Gem::Dependency
33
+ name: ace-overseer
34
+ requirement: !ruby/object:Gem::Requirement
35
+ requirements:
36
+ - - "~>"
37
+ - !ruby/object:Gem::Version
38
+ version: '0.31'
39
+ - - ">="
40
+ - !ruby/object:Gem::Version
41
+ version: 0.31.5
42
+ type: :runtime
43
+ prerelease: false
44
+ version_requirements: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - "~>"
47
+ - !ruby/object:Gem::Version
48
+ version: '0.31'
49
+ - - ">="
50
+ - !ruby/object:Gem::Version
51
+ version: 0.31.5
52
+ description: Operate watches, timers and semantic Eyes from a terminal or any agent.
53
+ The ace-watch CLI owns private actor state; the optional Pi extension uses the same
54
+ operations.
36
55
  email:
37
56
  - mc@cs3b.com
38
- executables: []
57
+ executables:
58
+ - ace-watch
39
59
  extensions: []
40
60
  extra_rdoc_files: []
41
61
  files:
42
62
  - CHANGELOG.md
43
63
  - README.md
64
+ - exe/ace-watch
44
65
  - handbook/extensions/ace-wake/index.js
45
66
  - handbook/extensions/ace-wake/package.json
46
- - handbook/extensions/ace-wake/wake/ask-bridge.js
47
- - handbook/extensions/ace-wake/wake/eyes-runtime.js
48
- - handbook/extensions/ace-wake/wake/eyes.js
49
- - handbook/extensions/ace-wake/wake/inbox-discovery.js
50
- - handbook/extensions/ace-wake/wake/loop-subscription.js
51
- - handbook/extensions/ace-wake/wake/types.js
52
- - handbook/extensions/ace-wake/wake/wake-command-parser.js
53
- - handbook/extensions/ace-wake/wake/wake-dispatcher.js
54
- - handbook/extensions/ace-wake/wake/wake-registry.js
55
- - handbook/extensions/ace-wake/wake/watch-subscription.js
56
67
  - lib/ace/wake.rb
68
+ - lib/ace/wake/actor_store.rb
69
+ - lib/ace/wake/cli.rb
57
70
  - lib/ace/wake/version.rb
71
+ - libexec/ace-watch/command.js
72
+ - libexec/ace-watch/package.json
73
+ - libexec/ace-watch/runner.js
74
+ - libexec/ace-watch/sources.js
75
+ - libexec/ace-watch/wake/ask-bridge.js
76
+ - libexec/ace-watch/wake/eyes-digest.js
77
+ - libexec/ace-watch/wake/eyes.js
78
+ - libexec/ace-watch/wake/inbox-discovery.js
79
+ - libexec/ace-watch/wake/loop-subscription.js
80
+ - libexec/ace-watch/wake/types.js
81
+ - libexec/ace-watch/wake/wake-command-parser.js
82
+ - libexec/ace-watch/wake/wake-dispatcher.js
83
+ - libexec/ace-watch/wake/wake-registry.js
84
+ - libexec/ace-watch/wake/watch-subscription.js
58
85
  homepage: https://github.com/cs3b/ace
59
86
  licenses:
60
87
  - MIT
@@ -78,5 +105,6 @@ required_rubygems_version: !ruby/object:Gem::Requirement
78
105
  requirements: []
79
106
  rubygems_version: 3.6.9
80
107
  specification_version: 4
81
- summary: Pi agent wake extension assets for ACE (loop timers and watch subscriptions)
108
+ summary: Standalone ace-watch CLI with economical Eyes, file watches, timers and a
109
+ Pi adapter
82
110
  test_files: []