ace-wake 0.5.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.
@@ -0,0 +1,105 @@
1
+ import fs from "node:fs";
2
+ import { execFileSync } from "node:child_process";
3
+ import { createWatchPort, nodeWatchFactory, nodeStatFn } from "./wake/watch-subscription.js";
4
+ import { armPendingAskWatches, requestsDirFor } from "./wake/ask-bridge.js";
5
+
6
+ const config = JSON.parse(process.argv[2]);
7
+ const parentPid = process.ppid;
8
+ const prefix = [...config.cli.slice(1), "--actor", config.actor, "--target", config.target, "--json", "--defer-confirm"];
9
+ let stopping = false, lastEyes = 0, lastFlush = 0, lastAsk = 0;
10
+ const errors = new Map();
11
+ const watches = new Map();
12
+ const signatureOf = ({ baseline, error, ...definition }) => JSON.stringify(definition);
13
+ const port = createWatchPort({ watchFactory: nodeWatchFactory, statFn: nodeStatFn, baseDir: config.cwd,
14
+ onDeactivate: () => {} });
15
+
16
+ function read() { return JSON.parse(fs.readFileSync(config.path, "utf8")); }
17
+ function call(args, input) {
18
+ const out = execFileSync(config.cli[0], [...prefix, ...args], {
19
+ cwd: config.cwd, encoding: "utf8", maxBuffer: 16 * 1024 * 1024, timeout: 130000,
20
+ input, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
21
+ });
22
+ return JSON.parse(out);
23
+ }
24
+ function emit(result) {
25
+ if (!result.events?.length) return;
26
+ // Confirm only after the OS accepts the complete output. Async stdout.write
27
+ // can report EPIPE after a premature confirmation has already cleared work.
28
+ const bytes = Buffer.from(config.json ? JSON.stringify(result) + "\n" : result.text + "\n");
29
+ for (let offset = 0; offset < bytes.length;) offset += fs.writeSync(1, bytes, offset, bytes.length - offset);
30
+ if (config.target === "terminal") {
31
+ for (const event of result.events) call(["delivery", "confirm", event.id]);
32
+ call(["delivery", "settle"]);
33
+ }
34
+ }
35
+ function error(key, message) {
36
+ if (errors.get(key) === message) return;
37
+ errors.set(key, message);
38
+ process.stderr.write(`ace-watch ${key}: ${message}; inspect ace-watch status\n`);
39
+ }
40
+ function guarded(key, action) {
41
+ try { const result = action(); errors.delete(key); return result; }
42
+ catch { error(key, "operation unavailable or refused by its owner"); }
43
+ }
44
+ function notify(definition, delta) {
45
+ const safe = definition.redact ? delta.map(({ excerpt, ...reference }) => reference) : delta;
46
+ const result = guarded(`watch:${definition.name}`, () => call(["watch", "notify", definition.name,
47
+ "--revision", definition.generation ?? "", "--delta-stdin"], JSON.stringify(safe)));
48
+ if (!result) return { delivered: false, reason: "rejected" };
49
+ emit(result);
50
+ return { delivered: true };
51
+ }
52
+ function reconcile() {
53
+ if (stopping) return;
54
+ if (process.ppid !== parentPid) { stop(); return; }
55
+ const state = read();
56
+ const definitions = state.subscriptions?.watches ?? [];
57
+ for (const [name, signature] of watches) {
58
+ const next = definitions.find(row => row.name === name);
59
+ if (!next || signatureOf(next) !== signature) { port.stop(name); watches.delete(name); }
60
+ }
61
+ for (const definition of definitions) {
62
+ if (watches.has(definition.name)) {
63
+ const failed = port.errorOf(definition.name);
64
+ if (failed && definition.error !== failed)
65
+ guarded(`watch:${definition.name}`, () => emit(call(["watch", "fail", definition.name,
66
+ "--revision", definition.generation ?? "", "--message", failed])));
67
+ continue;
68
+ }
69
+ if (definition.error) { watches.set(definition.name, signatureOf(definition)); continue; }
70
+ guarded(`watch:${definition.name}`, () => {
71
+ try { port.start(definition, (_def, delta) => notify(definition, delta)); }
72
+ catch (error) { port.fail(definition.name, String(error.message ?? "watch unavailable")); }
73
+ watches.set(definition.name, signatureOf(definition));
74
+ });
75
+ }
76
+ if (Date.now() - lastAsk >= 1000) guarded("ask", () => {
77
+ lastAsk = Date.now();
78
+ return armPendingAskWatches({ requestsDir: requestsDirFor(config.cwd), registry: {
79
+ list: () => [...(read().subscriptions?.watches ?? [])],
80
+ addWatch: (definition) => call(["watch", "add", definition.name, "--path", definition.path,
81
+ "--message", definition.message, ...(definition.redact ? ["--redact"] : [])]),
82
+ } }); });
83
+ for (const loop of state.subscriptions?.loops ?? []) {
84
+ if (Date.now() - loop.lastTick >= loop.intervalSeconds * 1000)
85
+ guarded(`loop:${loop.name}`, () => emit(call(["loop", "tick", loop.name])));
86
+ }
87
+ if (state.eyes?.enabled && !state.eyes.retired && !state.eyes.breaker &&
88
+ Date.now() - lastEyes >= state.eyes.config.intervalSeconds * 1000) {
89
+ lastEyes = Date.now();
90
+ guarded("eyes", () => emit(call(["eyes", "observe", "--scheduled"])));
91
+ }
92
+ if (Object.keys(state.subscriptions?.pending ?? {}).length)
93
+ guarded("delivery", () => emit(call(["delivery", "drain"])));
94
+ if (Date.now() - lastFlush >= 1000) { lastFlush = Date.now(); port.flushDirty(notify); }
95
+ }
96
+ const timer = setInterval(() => guarded("runner", reconcile), 250);
97
+ function stop() {
98
+ if (stopping) return;
99
+ stopping = true; clearInterval(timer); port.stopAll(); process.exitCode = 0;
100
+ process.stdin.pause();
101
+ }
102
+ for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, stop);
103
+ if (config.attached) { process.stdin.on("end", stop); process.stdin.resume(); }
104
+ for (const loop of read().subscriptions?.loops ?? []) guarded(`loop:${loop.name}`, () => call(["loop", "reset", loop.name]));
105
+ guarded("runner", reconcile);
@@ -0,0 +1,32 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ const execute = promisify(execFile);
4
+
5
+ export async function observeHitl(cwd, config) {
6
+ const options = { cwd, timeout: config.timeoutMs, maxBuffer: 1024 * 1024, encoding: "utf8" };
7
+ for (const source of config.syncRoutes) {
8
+ // One source per project: each entry names the project hitl config and,
9
+ // when several hermes_native routes exist there, the route to reconcile.
10
+ const argv = ["sync", "--config", source.config];
11
+ if (source.route !== undefined) argv.push("--route", source.route);
12
+ const { stdout } = await execute("ace-hitl-hermes", argv, options);
13
+ const result = JSON.parse(stdout);
14
+ if (!Array.isArray(result.errors) || result.errors.length) throw new Error("Native synchronization incomplete");
15
+ }
16
+ const { stdout } = await execute("ace-overseer", ["observe", "--owner", config.recipient, "--scope", config.scope, "--limit", String(config.maxEvents)], options);
17
+ const result = JSON.parse(stdout);
18
+ if (!result?.sources || typeof result.sources !== "object" || Array.isArray(result.sources) ||
19
+ Object.keys(result.sources).length === 0) throw new Error("Observation source health is missing");
20
+ return result;
21
+ }
22
+
23
+ export async function processReports(cwd, config, signal) {
24
+ const { stdout } = await execute("ace-overseer", ["process-reports", "--json",
25
+ "--owner", config.recipient, "--scope", config.scope],
26
+ { cwd, signal, maxBuffer: 8 * 1024 * 1024, encoding: "utf8" });
27
+ const result = JSON.parse(stdout);
28
+ if (!Array.isArray(result?.outcomes) || result.dry_run !== false)
29
+ throw new Error("Invalid report-processing receipt");
30
+ return result;
31
+ }
32
+
@@ -37,17 +37,27 @@ const TRUNCATION_MARKER = "… [ace-eyes: truncated]";
37
37
  /** Enforce the hard character bound, reserving room for the marker. */
38
38
  export function boundText(text, max = MAX_STATUS_CHARS) {
39
39
  const source = String(text ?? "");
40
- return source.length <= max ? source : `${source.slice(0, Math.max(0, max - TRUNCATION_MARKER.length))}${TRUNCATION_MARKER}`;
40
+ if (Buffer.byteLength(source) <= max) return source;
41
+ const limit = Math.max(0, max - Buffer.byteLength(TRUNCATION_MARKER));
42
+ let prefix = "", used = 0;
43
+ for (const character of source) {
44
+ const bytes = Buffer.byteLength(character);
45
+ if (used + bytes > limit) break;
46
+ prefix += character; used += bytes;
47
+ }
48
+ return prefix + TRUNCATION_MARKER;
41
49
  }
42
50
 
43
51
  /** How many of `lines` land fully inside boundText's preserved prefix: a line
44
52
  * cut at the character bound no longer presents what it carries. */
45
53
  function fullyVisibleLines(lines, max = MAX_STATUS_CHARS) {
46
- const limit = Math.max(0, max - TRUNCATION_MARKER.length);
54
+ const joined = lines.join("\n");
55
+ if (Buffer.byteLength(joined) <= max) return lines.length;
56
+ const limit = Math.max(0, max - Buffer.byteLength(TRUNCATION_MARKER));
47
57
  let used = 0;
48
58
  let count = 0;
49
59
  for (const line of lines) {
50
- const add = line.length + (count > 0 ? 1 : 0);
60
+ const add = Buffer.byteLength(line) + (count > 0 ? 1 : 0);
51
61
  if (used + add > limit) break;
52
62
  used += add;
53
63
  count += 1;
@@ -193,6 +203,8 @@ export function describeEntry(entry) {
193
203
 
194
204
  function nextAction(entry) {
195
205
  switch (entry.kind) {
206
+ case "source-health":
207
+ return "inspect ace-overseer observe for this source; repair at its owner before accepting work";
196
208
  case "report":
197
209
  return "run ace_eyes action process-reports to adopt completed reports and acknowledge them";
198
210
  case "question":
@@ -8,7 +8,7 @@ export const defaults = { intervalSeconds: 30, maxEvents: 500, maxObservationsPe
8
8
 
9
9
  export function validateConfig(input) {
10
10
  if (!input || typeof input !== "object" || Array.isArray(input) ||
11
- 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");
12
12
  const config = { ...defaults, ...input };
13
13
  for (const [key, min, max] of [["intervalSeconds", 1, 3600], ["maxEvents", 1, 2000],
14
14
  ["maxObservationsPerHour", 1, 3600], ["maxWakesPerHour", 1, 1000], ["timeoutMs", 100, 120000], ["maxErrors", 1, 10], ["maxPending", 1, 10000]]) {
@@ -142,7 +142,7 @@ export class Eyes {
142
142
  this.s.deadlines[name] = { at, operationRevision }; this.persist();
143
143
  }
144
144
  cancelDeadline(name) {
145
- if (!this.s.deadlines[name]) throw new Error(`No deadline named ${clip(name, 64)} is registered`);
145
+ if (!Object.hasOwn(this.s.deadlines, name)) throw new Error(`No deadline named ${clip(name, 64)} is registered`);
146
146
  delete this.s.deadlines[name]; delete this.s.pending[`deadline:${name}`];
147
147
  this.sent.delete(`deadline:${name}`); this.inflight = this.sent.size > 0; this.persist();
148
148
  }
@@ -193,7 +193,7 @@ export class Eyes {
193
193
  // Stale view: acknowledge exactly the presented revision and keep the
194
194
  // newer unseen revision pending so it re-reports on the next delivery.
195
195
  this.s.acknowledged[key] = presented;
196
- this.sent.delete(key);
196
+ if (this.sent.get(key) === presented) this.sent.delete(key);
197
197
  this.inflight = this.sent.size > 0;
198
198
  this.persist();
199
199
  return { ...value, stale: true };
@@ -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,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ace-wake
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.5.0
4
+ version: 0.6.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Michal Czyz
@@ -29,33 +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-digest.js
48
- - handbook/extensions/ace-wake/wake/eyes-runtime.js
49
- - handbook/extensions/ace-wake/wake/eyes.js
50
- - handbook/extensions/ace-wake/wake/inbox-discovery.js
51
- - handbook/extensions/ace-wake/wake/loop-subscription.js
52
- - handbook/extensions/ace-wake/wake/types.js
53
- - handbook/extensions/ace-wake/wake/wake-command-parser.js
54
- - handbook/extensions/ace-wake/wake/wake-dispatcher.js
55
- - handbook/extensions/ace-wake/wake/wake-registry.js
56
- - handbook/extensions/ace-wake/wake/watch-subscription.js
57
67
  - lib/ace/wake.rb
68
+ - lib/ace/wake/actor_store.rb
69
+ - lib/ace/wake/cli.rb
58
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
59
85
  homepage: https://github.com/cs3b/ace
60
86
  licenses:
61
87
  - MIT
@@ -79,5 +105,6 @@ required_rubygems_version: !ruby/object:Gem::Requirement
79
105
  requirements: []
80
106
  rubygems_version: 3.6.9
81
107
  specification_version: 4
82
- 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
83
110
  test_files: []