@karmaniverous/jeeves-meta 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { z } from 'zod';
2
2
  import pino, { Logger } from 'pino';
3
- import { FastifyInstance } from 'fastify';
3
+ import * as fastify from 'fastify';
4
+ import { FastifyInstance, FastifyBaseLogger } from 'fastify';
5
+ import * as node_http from 'node:http';
4
6
 
5
7
  /**
6
8
  * List archive snapshot files in chronological order.
@@ -183,6 +185,20 @@ declare function readLatestArchive(metaPath: string): MetaJson | null;
183
185
  */
184
186
  declare function createSnapshot(metaPath: string, meta: MetaJson): string;
185
187
 
188
+ /**
189
+ * Shared constants for the jeeves-meta service package.
190
+ *
191
+ * @module constants
192
+ */
193
+ /** Default HTTP port for the jeeves-meta service. */
194
+ declare const DEFAULT_PORT = 1938;
195
+ /** Default port as a string (for Commander CLI defaults). */
196
+ declare const DEFAULT_PORT_STR: string;
197
+ /** Service name identifier. */
198
+ declare const SERVICE_NAME = "jeeves-meta";
199
+ /** Service version, read from package.json at startup. */
200
+ declare const SERVICE_VERSION: string;
201
+
186
202
  /**
187
203
  * Load and resolve jeeves-meta service config.
188
204
  *
@@ -369,6 +385,34 @@ interface WatcherClient {
369
385
  unregisterRules(source: string): Promise<void>;
370
386
  }
371
387
 
388
+ /**
389
+ * Pino logger factory.
390
+ *
391
+ * @module logger
392
+ */
393
+
394
+ /** Minimal logger interface accepted by library functions. */
395
+ interface MinimalLogger {
396
+ debug: (obj: Record<string, unknown>, msg: string) => void;
397
+ info: (obj: Record<string, unknown>, msg: string) => void;
398
+ warn: (obj: Record<string, unknown>, msg: string) => void;
399
+ error: (obj: Record<string, unknown>, msg: string) => void;
400
+ }
401
+ /** Logger configuration options. */
402
+ interface LoggerConfig {
403
+ /** Log level (default: 'info'). */
404
+ level?: string;
405
+ /** Optional file path to write logs to. */
406
+ file?: string;
407
+ }
408
+ /**
409
+ * Create a pino logger instance.
410
+ *
411
+ * @param config - Optional logger configuration.
412
+ * @returns Configured pino logger.
413
+ */
414
+ declare function createLogger(config?: LoggerConfig): pino.Logger;
415
+
372
416
  /**
373
417
  * Discover .meta/ directories via watcher scan.
374
418
  *
@@ -399,7 +443,7 @@ declare function buildMetaFilter(config: MetaConfig): Record<string, unknown>;
399
443
  * @param watcher - WatcherClient for scan queries.
400
444
  * @returns Array of normalized .meta/ directory paths.
401
445
  */
402
- declare function discoverMetas(config: MetaConfig, watcher: WatcherClient): Promise<string[]>;
446
+ declare function discoverMetas(config: MetaConfig, watcher: WatcherClient, logger?: MinimalLogger): Promise<string[]>;
403
447
 
404
448
  /**
405
449
  * Types for meta discovery and ownership tree.
@@ -499,7 +543,7 @@ interface MetaListResult {
499
543
  * @param watcher - Watcher HTTP client for discovery.
500
544
  * @returns Enriched meta list with summary statistics and ownership tree.
501
545
  */
502
- declare function listMetas(config: MetaConfig, watcher: WatcherClient): Promise<MetaListResult>;
546
+ declare function listMetas(config: MetaConfig, watcher: WatcherClient, logger?: MinimalLogger): Promise<MetaListResult>;
503
547
 
504
548
  /**
505
549
  * Build the ownership tree from discovered .meta/ paths.
@@ -530,31 +574,27 @@ declare function findNode(tree: OwnershipTree, targetPath: string): MetaNode | u
530
574
  /**
531
575
  * Compute the file scope owned by a meta node.
532
576
  *
533
- * A meta owns: parent dir + all descendants, minus child .meta/ subtrees.
534
- * For child subtrees, it consumes the child's .meta/meta.json as a rollup input.
577
+ * A meta owns: parent dir + all descendants, minus:
578
+ * - Its own .meta/ subtree (outputs, not inputs)
579
+ * - Child meta ownerPath subtrees (except their .meta/meta.json for rollups)
580
+ *
581
+ * Uses filesystem walks instead of watcher scans for performance.
535
582
  *
536
583
  * @module discovery/scope
537
584
  */
538
585
 
539
586
  /**
540
587
  * Get the scope path prefix for a meta node.
541
- *
542
- * This is the ownerPath — all files under this path are in scope,
543
- * except subtrees owned by child metas.
544
- *
545
- * @param node - The meta node to compute scope for.
546
- * @returns The scope path prefix.
547
588
  */
548
589
  declare function getScopePrefix(node: MetaNode): string;
549
590
  /**
550
591
  * Filter a list of file paths to only those in scope for a meta node.
551
592
  *
552
- * Includes files under ownerPath, excludes files under child meta ownerPaths,
553
- * but includes child .meta/meta.json files as rollup inputs.
593
+ * Excludes:
594
+ * - The node's own .meta/ subtree (synthesis outputs are not scope inputs)
595
+ * - Child meta ownerPath subtrees (except child .meta/meta.json for rollups)
554
596
  *
555
- * @param node - The meta node.
556
- * @param files - Array of file paths to filter.
557
- * @returns Filtered array of in-scope file paths.
597
+ * walkFiles already returns normalized forward-slash paths.
558
598
  */
559
599
  declare function filterInScope(node: MetaNode, files: string[]): string[];
560
600
 
@@ -690,7 +730,7 @@ declare function normalizePath(p: string): string;
690
730
  * @param params - Base scan parameters (cursor is managed internally).
691
731
  * @returns All matching files across all pages.
692
732
  */
693
- declare function paginatedScan(watcher: WatcherClient, params: Omit<ScanParams, 'cursor'>): Promise<ScanFile[]>;
733
+ declare function paginatedScan(watcher: WatcherClient, params: Omit<ScanParams, 'cursor'>, logger?: MinimalLogger): Promise<ScanFile[]>;
694
734
 
695
735
  /**
696
736
  * Compute a structure hash from a sorted file listing.
@@ -708,6 +748,32 @@ declare function paginatedScan(watcher: WatcherClient, params: Omit<ScanParams,
708
748
  */
709
749
  declare function computeStructureHash(filePaths: string[]): string;
710
750
 
751
+ /**
752
+ * Recursive filesystem walker for file enumeration.
753
+ *
754
+ * Replaces paginated watcher scans for scope/delta/staleness checks.
755
+ * Returns normalized forward-slash paths.
756
+ *
757
+ * @module walkFiles
758
+ */
759
+ /** Options for walkFiles. */
760
+ interface WalkFilesOptions {
761
+ /** Directory names to exclude (in addition to defaults). */
762
+ exclude?: string[];
763
+ /** Only include files modified after this Unix timestamp (seconds). */
764
+ modifiedAfter?: number;
765
+ /** Maximum recursion depth. Default: 50. */
766
+ maxDepth?: number;
767
+ }
768
+ /**
769
+ * Recursively walk a directory and return all file paths.
770
+ *
771
+ * @param root - Root directory to walk.
772
+ * @param options - Walk options.
773
+ * @returns Array of normalized file paths.
774
+ */
775
+ declare function walkFiles(root: string, options?: WalkFilesOptions): string[];
776
+
711
777
  /**
712
778
  * MetaExecutor implementation using the OpenClaw gateway HTTP API.
713
779
  *
@@ -726,6 +792,8 @@ interface GatewayExecutorOptions {
726
792
  apiKey?: string;
727
793
  /** Polling interval in ms. Default: 5000. */
728
794
  pollIntervalMs?: number;
795
+ /** Workspace directory for output staging. Default: OS temp dir + /jeeves-meta. */
796
+ workspaceDir?: string;
729
797
  }
730
798
  /**
731
799
  * MetaExecutor that spawns OpenClaw sessions via the gateway's
@@ -739,33 +807,15 @@ declare class GatewayExecutor implements MetaExecutor {
739
807
  private readonly gatewayUrl;
740
808
  private readonly apiKey;
741
809
  private readonly pollIntervalMs;
810
+ private readonly workspaceDir;
742
811
  constructor(options?: GatewayExecutorOptions);
743
812
  /** Invoke a gateway tool via the /tools/invoke HTTP endpoint. */
744
813
  private invoke;
814
+ /** Look up totalTokens for a session via sessions_list. */
815
+ private getSessionTokens;
745
816
  spawn(task: string, options?: MetaSpawnOptions): Promise<MetaSpawnResult>;
746
817
  }
747
818
 
748
- /**
749
- * Pino logger factory.
750
- *
751
- * @module logger
752
- */
753
-
754
- /** Logger configuration options. */
755
- interface LoggerConfig {
756
- /** Log level (default: 'info'). */
757
- level?: string;
758
- /** Optional file path to write logs to. */
759
- file?: string;
760
- }
761
- /**
762
- * Create a pino logger instance.
763
- *
764
- * @param config - Optional logger configuration.
765
- * @returns Configured pino logger.
766
- */
767
- declare function createLogger(config?: LoggerConfig): pino.Logger;
768
-
769
819
  /**
770
820
  * Build task prompts for each synthesis step.
771
821
  *
@@ -817,7 +867,7 @@ declare function buildCriticTask(ctx: MetaContext, meta: MetaJson, config: MetaC
817
867
  * @param watcher - WatcherClient for scope enumeration.
818
868
  * @returns The computed context package.
819
869
  */
820
- declare function buildContextPackage(node: MetaNode, meta: MetaJson, watcher: WatcherClient): Promise<MetaContext>;
870
+ declare function buildContextPackage(node: MetaNode, meta: MetaJson): MetaContext;
821
871
 
822
872
  /**
823
873
  * Parse subprocess outputs for each synthesis step.
@@ -918,7 +968,8 @@ declare function mergeAndWrite(options: MergeOptions): MetaJson;
918
968
  type ProgressPhase = 'architect' | 'builder' | 'critic';
919
969
  type ProgressEvent = {
920
970
  type: 'synthesis_start' | 'phase_start' | 'phase_complete' | 'synthesis_complete' | 'error';
921
- metaPath: string;
971
+ /** Owner path (not .meta path) of the entity being synthesized. */
972
+ path: string;
922
973
  phase?: ProgressPhase;
923
974
  tokens?: number;
924
975
  durationMs?: number;
@@ -970,7 +1021,7 @@ interface OrchestrateResult {
970
1021
  * @param targetPath - Optional: specific meta/owner path to synthesize instead of stalest candidate.
971
1022
  * @returns Array with a single result.
972
1023
  */
973
- declare function orchestrate(config: MetaConfig, executor: MetaExecutor, watcher: WatcherClient, targetPath?: string, onProgress?: ProgressCallback): Promise<OrchestrateResult[]>;
1024
+ declare function orchestrate(config: MetaConfig, executor: MetaExecutor, watcher: WatcherClient, targetPath?: string, onProgress?: ProgressCallback, logger?: MinimalLogger): Promise<OrchestrateResult[]>;
974
1025
 
975
1026
  /**
976
1027
  * Weighted staleness formula for candidate selection.
@@ -1042,12 +1093,16 @@ declare function selectCandidate(candidates: StalenessCandidate[]): StalenessCan
1042
1093
  * @param watcher - WatcherClient instance.
1043
1094
  * @returns True if any file in scope was modified after _generatedAt.
1044
1095
  */
1045
- declare function isStale(scopePrefix: string, meta: MetaJson, watcher: WatcherClient): Promise<boolean>;
1096
+ declare function isStale(scopePrefix: string, meta: MetaJson): boolean;
1046
1097
  /**
1047
1098
  * Compute actual staleness in seconds (now minus _generatedAt).
1048
1099
  *
1100
+ * Never-synthesized metas are capped at {@link MAX_STALENESS_SECONDS}
1101
+ * (1 year) so that depth weighting can differentiate them. Without
1102
+ * bounding, `Infinity * depthFactor` = `Infinity` for all depths.
1103
+ *
1049
1104
  * @param meta - Current meta.json content.
1050
- * @returns Staleness in seconds, or Infinity if never synthesized.
1105
+ * @returns Staleness in seconds, capped at 1 year for never-synthesized metas.
1051
1106
  */
1052
1107
  declare function actualStaleness(meta: MetaJson): number;
1053
1108
  /**
@@ -1233,6 +1288,8 @@ interface HttpWatcherClientOptions {
1233
1288
  backoffBaseMs?: number;
1234
1289
  /** Multiplier for backoff. Default: 4 (1s, 4s, 16s). */
1235
1290
  backoffFactor?: number;
1291
+ /** Per-request timeout in ms. Default: 10000. */
1292
+ timeoutMs?: number;
1236
1293
  }
1237
1294
  /**
1238
1295
  * HTTP-based WatcherClient implementation with retry.
@@ -1242,6 +1299,7 @@ declare class HttpWatcherClient implements WatcherClient {
1242
1299
  private readonly maxRetries;
1243
1300
  private readonly backoffBaseMs;
1244
1301
  private readonly backoffFactor;
1302
+ private readonly timeoutMs;
1245
1303
  constructor(options: HttpWatcherClientOptions);
1246
1304
  /** POST JSON with retry. */
1247
1305
  private post;
@@ -1332,12 +1390,6 @@ declare function registerRoutes(app: FastifyInstance, deps: RouteDeps): void;
1332
1390
  /** Sleep for a given number of milliseconds. */
1333
1391
  declare function sleep(ms: number): Promise<void>;
1334
1392
 
1335
- /**
1336
- * Minimal Fastify HTTP server for jeeves-meta service.
1337
- *
1338
- * @module server
1339
- */
1340
-
1341
1393
  /** Options for creating the server. */
1342
1394
  interface ServerOptions {
1343
1395
  /** Pino logger instance. */
@@ -1359,7 +1411,9 @@ interface ServerOptions {
1359
1411
  * @param options - Server creation options.
1360
1412
  * @returns Configured Fastify instance (not yet listening).
1361
1413
  */
1362
- declare function createServer(options: ServerOptions): FastifyInstance;
1414
+ declare function createServer(options: ServerOptions): fastify.FastifyInstance<node_http.Server<typeof node_http.IncomingMessage, typeof node_http.ServerResponse>, node_http.IncomingMessage, node_http.ServerResponse<node_http.IncomingMessage>, FastifyBaseLogger, fastify.FastifyTypeProviderDefault> & PromiseLike<fastify.FastifyInstance<node_http.Server<typeof node_http.IncomingMessage, typeof node_http.ServerResponse>, node_http.IncomingMessage, node_http.ServerResponse<node_http.IncomingMessage>, FastifyBaseLogger, fastify.FastifyTypeProviderDefault>> & {
1415
+ __linterBrands: "SafePromiseLike";
1416
+ };
1363
1417
 
1364
1418
  /**
1365
1419
  * Graceful shutdown handler.
@@ -1370,7 +1424,9 @@ declare function createServer(options: ServerOptions): FastifyInstance;
1370
1424
  */
1371
1425
 
1372
1426
  interface ShutdownDeps {
1373
- server: FastifyInstance;
1427
+ server: {
1428
+ close: () => Promise<void>;
1429
+ };
1374
1430
  scheduler: Scheduler | null;
1375
1431
  queue: SynthesisQueue;
1376
1432
  logger: Logger;
@@ -1403,5 +1459,5 @@ declare function registerShutdownHandlers(deps: ShutdownDeps): void;
1403
1459
  */
1404
1460
  declare function startService(config: ServiceConfig, configPath?: string): Promise<void>;
1405
1461
 
1406
- export { GatewayExecutor, HttpWatcherClient, ProgressReporter, RuleRegistrar, Scheduler, SynthesisQueue, acquireLock, actualStaleness, buildArchitectTask, buildBuilderTask, buildContextPackage, buildCriticTask, buildMetaFilter, buildOwnershipTree, cleanupStaleLocks, computeEffectiveStaleness, computeEma, computeStructureHash, createLogger, createServer, createSnapshot, discoverMetas, filterInScope, findNode, formatProgressEvent, getScopePrefix, hasSteerChanged, isArchitectTriggered, isLocked, isStale, listArchiveFiles, listMetas, loadServiceConfig, mergeAndWrite, metaConfigSchema, metaErrorSchema, metaJsonSchema, normalizePath, orchestrate, paginatedScan, parseArchitectOutput, parseBuilderOutput, parseCriticOutput, pruneArchive, readLatestArchive, readLockState, registerRoutes, registerShutdownHandlers, releaseLock, resolveConfigPath, resolveMetaDir, selectCandidate, serviceConfigSchema, sleep, startService, toMetaError };
1407
- export type { BuilderOutput, EnqueueResult, GatewayExecutorOptions, HttpWatcherClientOptions, InferenceRuleSpec, LockState, LoggerConfig, MergeOptions, MetaConfig, MetaContext, MetaEntry, MetaError, MetaExecutor, MetaJson, MetaListResult, MetaListSummary, MetaNode, MetaSpawnOptions, MetaSpawnResult, OrchestrateResult, OwnershipTree, ProgressCallback, ProgressEvent, ProgressPhase, ProgressReporterConfig, QueueItem, QueueState, RouteDeps, ScanFile, ScanParams, ScanResponse, ServerOptions, ServiceConfig, ServiceStats, StalenessCandidate, WatcherClient };
1462
+ export { DEFAULT_PORT, DEFAULT_PORT_STR, GatewayExecutor, HttpWatcherClient, ProgressReporter, RuleRegistrar, SERVICE_NAME, SERVICE_VERSION, Scheduler, SynthesisQueue, acquireLock, actualStaleness, buildArchitectTask, buildBuilderTask, buildContextPackage, buildCriticTask, buildMetaFilter, buildOwnershipTree, cleanupStaleLocks, computeEffectiveStaleness, computeEma, computeStructureHash, createLogger, createServer, createSnapshot, discoverMetas, filterInScope, findNode, formatProgressEvent, getScopePrefix, hasSteerChanged, isArchitectTriggered, isLocked, isStale, listArchiveFiles, listMetas, loadServiceConfig, mergeAndWrite, metaConfigSchema, metaErrorSchema, metaJsonSchema, normalizePath, orchestrate, paginatedScan, parseArchitectOutput, parseBuilderOutput, parseCriticOutput, pruneArchive, readLatestArchive, readLockState, registerRoutes, registerShutdownHandlers, releaseLock, resolveConfigPath, resolveMetaDir, selectCandidate, serviceConfigSchema, sleep, startService, toMetaError, walkFiles };
1463
+ export type { BuilderOutput, EnqueueResult, GatewayExecutorOptions, HttpWatcherClientOptions, InferenceRuleSpec, LockState, LoggerConfig, MergeOptions, MetaConfig, MetaContext, MetaEntry, MetaError, MetaExecutor, MetaJson, MetaListResult, MetaListSummary, MetaNode, MetaSpawnOptions, MetaSpawnResult, MinimalLogger, OrchestrateResult, OwnershipTree, ProgressCallback, ProgressEvent, ProgressPhase, ProgressReporterConfig, QueueItem, QueueState, RouteDeps, ScanFile, ScanParams, ScanResponse, ServerOptions, ServiceConfig, ServiceStats, StalenessCandidate, WatcherClient };