@aaac/observability 0.1.17 → 0.2.1
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/README.md +1 -1
- package/dist/{chunk-3DXZNA3E.js → chunk-4PNXLHYZ.js} +125 -35
- package/dist/chunk-4PNXLHYZ.js.map +1 -0
- package/dist/{chunk-EKFRH7PX.js → chunk-D4ZWC5FU.js} +2 -2
- package/dist/cli/global-record.d.ts +1 -1
- package/dist/cli/global-record.js +2 -2
- package/dist/cli/global-record.js.map +1 -1
- package/dist/cli/index.js +17 -11
- package/dist/cli/index.js.map +1 -1
- package/dist/index.d.ts +27 -6
- package/dist/index.js +1 -1
- package/package.json +2 -1
- package/dist/chunk-3DXZNA3E.js.map +0 -1
- /package/dist/{chunk-EKFRH7PX.js.map → chunk-D4ZWC5FU.js.map} +0 -0
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
generateId,
|
|
10
10
|
loadEventMappingConfig,
|
|
11
11
|
worktreeAttributes
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-4PNXLHYZ.js";
|
|
13
13
|
|
|
14
14
|
// src/cli/record-hook.ts
|
|
15
15
|
import { mkdir, rename, unlink, writeFile } from "fs/promises";
|
|
@@ -263,4 +263,4 @@ export {
|
|
|
263
263
|
runRecordHook,
|
|
264
264
|
handleRecordHook
|
|
265
265
|
};
|
|
266
|
-
//# sourceMappingURL=chunk-
|
|
266
|
+
//# sourceMappingURL=chunk-D4ZWC5FU.js.map
|
|
@@ -18,7 +18,7 @@ interface GlobalRecordResult {
|
|
|
18
18
|
fallback: boolean;
|
|
19
19
|
}
|
|
20
20
|
/**
|
|
21
|
-
* Compute a stable repo_id for the user
|
|
21
|
+
* Compute a stable repo_id for the per-user fallback ledger.
|
|
22
22
|
* Prefers a SHA-256 of the canonical git remote URL; falls back to a hash of the
|
|
23
23
|
* resolved cwd so records from a repo with no remote are still grouped.
|
|
24
24
|
*/
|
|
@@ -5,10 +5,10 @@ import {
|
|
|
5
5
|
parseHookInput,
|
|
6
6
|
readStdin,
|
|
7
7
|
runRecordHook
|
|
8
|
-
} from "../chunk-
|
|
8
|
+
} from "../chunk-D4ZWC5FU.js";
|
|
9
9
|
import {
|
|
10
10
|
DEFAULT_DB_PATH
|
|
11
|
-
} from "../chunk-
|
|
11
|
+
} from "../chunk-4PNXLHYZ.js";
|
|
12
12
|
|
|
13
13
|
// src/cli/global-record.ts
|
|
14
14
|
import { createHash } from "crypto";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/global-record.ts","../../src/cli/session-id.ts","../../src/cli/walk-up.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * aaac-observ-global-record — user-global hook recorder (Issue #174 / T-A2).\n *\n * This is the binary wired into the USER-scope Cursor / Claude / Git hooks\n * installed by `aaac observability install --global`. Unlike `record-hook`\n * (which assumes it runs inside a configured repo with a known db path), this\n * wrapper is location-agnostic:\n *\n * 1. parse the hook JSON payload from stdin\n * 2. collect candidate paths (cwd / workspace_roots / file_path + process.cwd)\n * and WALK UP to the nearest enclosing project.yaml\n * 3. resolve session_id through the multi-stage chain (AAAC_* → conversation_id\n * → .observ-context.json → CLAUDE_* → unknown)\n * 4a. RESOLVED → append to <project>/.agent-logs/observability.db\n * 4b. UNRESOLVED → append to ~/.aaac/ledger.db tagged with repo_id (a stable\n * hash of the git remote URL, or the cwd when there is no remote)\n *\n * Strictly fail-open: every walk/IO/exception path still exits 0 so the wrapper\n * can NEVER block the underlying Cursor/Claude/Git operation.\n *\n * Proposal: docs/proposal/observability-integration.md §ローカルグローバル記録.\n */\nimport { createHash } from \"node:crypto\";\nimport { execFileSync } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { DEFAULT_DB_PATH } from \"../index.js\";\nimport type { AttrValue } from \"../types/canonical-event.js\";\nimport {\n contextFilePath,\n defaultMappingConfigPath,\n parseHookInput,\n readStdin,\n runRecordHook,\n} from \"./record-hook.js\";\nimport { resolveSessionId } from \"./session-id.js\";\nimport { collectCandidatePaths, resolveProjectRoot } from \"./walk-up.js\";\n\n/** User-global ledger path, relative to HOME (`~/.aaac/ledger.db`). */\nexport function ledgerDbPath(home: string): string {\n return join(home, \".aaac\", \"ledger.db\");\n}\n\nexport interface GlobalRecordResult {\n /** Where the event was recorded. */\n scope: \"project\" | \"ledger\";\n /** Absolute db path written to. */\n dbPath: string;\n /** Resolved project root, when scope === \"project\". */\n projectRoot?: string;\n /** repo_id attribute, when scope === \"ledger\". */\n repoId?: string;\n /** Resolved session id (may be \"unknown\" provisional). */\n sessionId: string;\n /** Events recorded into the pipeline. */\n recorded: number;\n /** True when the generic fallback was used (no mapping rule matched). */\n fallback: boolean;\n}\n\n/**\n * Compute a stable repo_id for the user-global ledger.\n * Prefers a SHA-256 of the canonical git remote URL; falls back to a hash of the\n * resolved cwd so records from a repo with no remote are still grouped.\n */\nexport function computeRepoId(remoteUrl: string | undefined, fallbackPath: string): string {\n const basis = remoteUrl && remoteUrl.trim().length > 0 ? `remote:${remoteUrl.trim()}` : `path:${fallbackPath}`;\n return createHash(\"sha256\").update(basis).digest(\"hex\").slice(0, 16);\n}\n\n/** Read & parse `.observ-context.json` at the given db dir; fail-open to {}. */\nfunction readContextJson(dbPath: string): Record<string, unknown> {\n try {\n const file = contextFilePath(dbPath);\n if (!existsSync(file)) return {};\n const raw = readFileSync(file, \"utf8\");\n return parseHookInput(raw);\n } catch {\n return {};\n }\n}\n\n/** Best-effort canonical git remote URL for a directory; undefined on any error. */\nexport function gitRemoteUrl(cwd: string): string | undefined {\n try {\n const out = execFileSync(\"git\", [\"-C\", cwd, \"config\", \"--get\", \"remote.origin.url\"], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: 2000,\n });\n const trimmed = out.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport interface RunGlobalRecordArgs {\n hook: string;\n hookInput: Record<string, unknown>;\n source?: string;\n /** Overrides for testability (default to the real environment). */\n env?: Record<string, string | undefined>;\n home?: string;\n processCwd?: string;\n /** Injectable remote-URL resolver (defaults to {@link gitRemoteUrl}). */\n resolveRemote?: (cwd: string) => string | undefined;\n}\n\n/**\n * Core (testable) global-record logic. Never throws — the caller guarantees\n * exit 0 regardless of the outcome.\n */\nexport async function runGlobalRecord(args: RunGlobalRecordArgs): Promise<GlobalRecordResult> {\n const { hook, hookInput } = args;\n const env = args.env ?? process.env;\n const home = args.home ?? homedir();\n const processCwd = args.processCwd ?? process.cwd();\n const source = args.source ?? \"global-hook\";\n const resolveRemote = args.resolveRemote ?? gitRemoteUrl;\n\n const candidates = collectCandidatePaths({\n cwd: hookInput.cwd,\n workspaceRoots: hookInput.workspace_roots,\n filePath: hookInput.file_path,\n processCwd,\n });\n const projectRoot = resolveProjectRoot(candidates);\n\n if (projectRoot) {\n const dbPath = join(projectRoot, DEFAULT_DB_PATH);\n const contextJson = readContextJson(dbPath);\n const { sessionId } = resolveSessionId({ hookInput, env, contextJson });\n const { recorded, fallback } = await runRecordHook({\n hook,\n hookInput,\n dbPath,\n mappingConfigPath: defaultMappingConfigPath(dbPath),\n source,\n sessionId,\n });\n return { scope: \"project\", dbPath, projectRoot, sessionId, recorded, fallback };\n }\n\n // Unresolved → user-global ledger, tagged with repo_id.\n const dbPath = ledgerDbPath(home);\n const contextJson = readContextJson(dbPath);\n const { sessionId } = resolveSessionId({ hookInput, env, contextJson });\n let remote: string | undefined;\n try {\n remote = resolveRemote(processCwd);\n } catch {\n remote = undefined; // fail-open: no remote → cwd-hash repo_id\n }\n const repoId = computeRepoId(remote, processCwd);\n const extraAttributes: Record<string, AttrValue> = { repo_id: repoId };\n const { recorded, fallback } = await runRecordHook({\n hook,\n hookInput,\n dbPath,\n mappingConfigPath: defaultMappingConfigPath(dbPath),\n source,\n sessionId,\n extraAttributes,\n });\n return { scope: \"ledger\", dbPath, repoId, sessionId, recorded, fallback };\n}\n\n// ── CLI argument parsing ─────────────────────────────────────────────────────\n\ninterface ParsedArgs {\n hook: string;\n source?: string;\n}\n\n/** Parse `<hook-name> [--source <s>]` from argv (fail-open: unknown flags ignored). */\nexport function parseGlobalRecordArgs(argv: string[]): ParsedArgs {\n let hook = \"unknown\";\n let source: string | undefined;\n let sawHook = false;\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === \"--source\") {\n source = argv[++i];\n } else if (arg.startsWith(\"--source=\")) {\n source = arg.slice(\"--source=\".length);\n } else if (!arg.startsWith(\"-\") && !sawHook) {\n hook = arg;\n sawHook = true;\n }\n }\n return { hook, source };\n}\n\n// ── Entrypoint ───────────────────────────────────────────────────────────────\n\n/** Run the wrapper end-to-end; always resolves (caller exits 0). */\nexport async function main(argv: string[] = process.argv.slice(2)): Promise<void> {\n let result: GlobalRecordResult | undefined;\n try {\n const { hook, source } = parseGlobalRecordArgs(argv);\n const hookInput = parseHookInput(await readStdin());\n result = await runGlobalRecord({ hook, hookInput, source });\n } catch (err) {\n process.stderr.write(\n `global-record: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n }\n if (result) {\n process.stdout.write(JSON.stringify(result) + \"\\n\");\n }\n}\n\n// Only auto-run when invoked directly as a binary (not when imported by tests).\nif (process.argv[1] && process.argv[1].endsWith(\"global-record.js\")) {\n void main().finally(() => {\n // fail-open: ALWAYS exit 0.\n process.exit(0);\n });\n}\n","/**\n * session_id resolution — multi-stage, fail-open (Issue #174 / T-A6).\n *\n * The user-global hook path runs OUTSIDE the @aaac/runtime process and often\n * outside a configured repo, so the in-process correlation key (conversation_id\n * injected by record-hook) may be absent. To still correlate hook-derived spans\n * we resolve session_id through a fixed priority chain and, when every source\n * fails, fall back to a provisional `unknown` marker rather than dropping the\n * record (records must NEVER be lost — fail-open).\n *\n * Priority (highest first):\n * 1. AAAC_* explicit env override (AAAC_SESSION_ID)\n * 2. conversation_id hook payload field (Cursor / runtime correlation key)\n * 3. .observ-context.json short-lived git-context file written by record-hook\n * 4. CLAUDE_* Claude Code env (CLAUDE_SESSION_ID)\n * 5. unknown provisional marker (provisional = true)\n *\n * Pure and synchronous: the caller is responsible for reading the (optional)\n * .observ-context.json contents and passing the parsed object. This keeps the\n * resolver trivially unit-testable per path (one test per priority level).\n *\n * Proposal: docs/proposal/observability-integration.md §session_id 解決.\n */\n\n/** Provisional marker used when no concrete session_id can be resolved. */\nexport const UNKNOWN_SESSION_ID = \"unknown\";\n\n/** Which priority rung produced the resolved session_id. */\nexport type SessionIdSource =\n | \"env-aaac\"\n | \"conversation_id\"\n | \"observ-context\"\n | \"env-claude\"\n | \"unknown\";\n\nexport interface ResolveSessionIdInput {\n /** Parsed hook payload from stdin (conversation_id, etc.). */\n hookInput?: Record<string, unknown>;\n /** Process environment (defaults to process.env). */\n env?: Record<string, string | undefined>;\n /** Parsed contents of `.observ-context.json` (read fail-open by the caller). */\n contextJson?: Record<string, unknown>;\n}\n\nexport interface ResolvedSessionId {\n /** Resolved session id, or {@link UNKNOWN_SESSION_ID} when unresolvable. */\n sessionId: string;\n /** The priority rung that produced the value. */\n source: SessionIdSource;\n /** True when no concrete source matched (sessionId === UNKNOWN_SESSION_ID). */\n provisional: boolean;\n}\n\n/** Return value when it is a non-empty string, else undefined. */\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim().length > 0 ? value : undefined;\n}\n\n/**\n * Resolve a session_id through the priority chain (1–5). Never throws.\n *\n * @returns the first matching source, or a provisional `unknown` marker.\n */\nexport function resolveSessionId(input: ResolveSessionIdInput = {}): ResolvedSessionId {\n const env = input.env ?? process.env;\n const hookInput = input.hookInput ?? {};\n const contextJson = input.contextJson ?? {};\n\n // 1. AAAC_* explicit override\n const aaac = nonEmptyString(env.AAAC_SESSION_ID);\n if (aaac) {\n return { sessionId: aaac, source: \"env-aaac\", provisional: false };\n }\n\n // 2. conversation_id from the hook payload\n const conversationId = nonEmptyString(hookInput.conversation_id);\n if (conversationId) {\n return { sessionId: conversationId, source: \"conversation_id\", provisional: false };\n }\n\n // 3. .observ-context.json (short-lived git-context file)\n const fromContext = nonEmptyString(contextJson.session_id);\n if (fromContext) {\n return { sessionId: fromContext, source: \"observ-context\", provisional: false };\n }\n\n // 4. CLAUDE_* env\n const claude = nonEmptyString(env.CLAUDE_SESSION_ID);\n if (claude) {\n return { sessionId: claude, source: \"env-claude\", provisional: false };\n }\n\n // 5. provisional unknown\n return { sessionId: UNKNOWN_SESSION_ID, source: \"unknown\", provisional: true };\n}\n","/**\n * project.yaml walk-up resolution (Issue #174 / T-A2).\n *\n * The user-global hook records from any CWD, including repos that never ran\n * `aaac init`. To attribute a hook event to a project we walk UP the directory\n * tree from a set of candidate start paths (the hook payload's cwd /\n * workspace_roots / file_path, plus process.cwd()) until we find a `project.yaml`.\n *\n * Resolution rules:\n * - The nearest enclosing project.yaml wins (innermost in a nested monorepo).\n * - Candidates are tried in priority order; the first that resolves wins.\n * - A file path is reduced to its containing directory before walking.\n * - The walk stops at the filesystem root.\n *\n * Pure and fail-open: any stat/IO error on a candidate is swallowed and the next\n * candidate is tried; an empty/!found result is a normal outcome (the caller\n * then records to the user-global ledger).\n *\n * Proposal: docs/proposal/observability-integration.md §ローカルグローバル記録.\n */\nimport { existsSync, statSync } from \"node:fs\";\nimport { dirname, join, parse as parsePath, resolve } from \"node:path\";\n\n/** The project manifest filename that anchors a project root. */\nexport const PROJECT_MANIFEST = \"project.yaml\";\n\nexport interface CollectCandidatesInput {\n /** Hook payload `cwd` field. */\n cwd?: unknown;\n /** Hook payload `workspace_roots` field (array of paths). */\n workspaceRoots?: unknown;\n /** Hook payload `file_path` field (the edited file). */\n filePath?: unknown;\n /** Process cwd fallback (defaults to process.cwd()). */\n processCwd?: string;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\n/**\n * Collect ordered, de-duplicated candidate start directories from a hook payload.\n * Priority: cwd → workspace_roots (in order) → file_path → process.cwd().\n */\nexport function collectCandidatePaths(input: CollectCandidatesInput): string[] {\n const out: string[] = [];\n const push = (value: unknown): void => {\n if (isNonEmptyString(value)) out.push(value);\n };\n\n push(input.cwd);\n if (Array.isArray(input.workspaceRoots)) {\n for (const root of input.workspaceRoots) push(root);\n }\n push(input.filePath);\n push(input.processCwd ?? process.cwd());\n\n // De-duplicate by resolved absolute path while preserving order.\n const seen = new Set<string>();\n const result: string[] = [];\n for (const p of out) {\n const abs = resolve(p);\n if (!seen.has(abs)) {\n seen.add(abs);\n result.push(abs);\n }\n }\n return result;\n}\n\n/** Reduce a path to a directory: a file → its parent, a dir → itself. */\nfunction toStartDir(candidate: string): string {\n const abs = resolve(candidate);\n try {\n if (existsSync(abs) && statSync(abs).isDirectory()) {\n return abs;\n }\n } catch {\n // fall through — treat as a (possibly non-existent) file path\n }\n return dirname(abs);\n}\n\n/**\n * Walk up from a single start directory to the nearest enclosing project.yaml.\n * @returns the directory containing project.yaml, or undefined.\n */\nexport function walkUpForProject(startDir: string): string | undefined {\n let dir = toStartDir(startDir);\n const { root } = parsePath(dir);\n\n // Bounded by the filesystem root; the loop terminates because dirname()\n // is a fixed point at the root.\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n if (existsSync(join(dir, PROJECT_MANIFEST))) {\n return dir;\n }\n } catch {\n // ignore and keep climbing\n }\n if (dir === root) break;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return undefined;\n}\n\n/**\n * Resolve a project root by walking up from each candidate path in priority\n * order. Returns the first project root found, or undefined when none of the\n * candidates is inside a project.\n */\nexport function resolveProjectRoot(candidates: string[]): string | undefined {\n for (const candidate of candidates) {\n const found = walkUpForProject(candidate);\n if (found) return found;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;AAuBA,SAAS,kBAAkB;AAC3B,SAAS,oBAAoB;AAC7B,SAAS,cAAAA,aAAY,oBAAoB;AACzC,SAAS,eAAe;AACxB,SAAS,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AAS;AAC3C,aAAO;AACP,gBAAU;AAAA,IACZ;AAAA,EACF;AACA,SAAO,EAAE,MAAM,OAAO;AACxB;AAKA,eAAsB,KAAK,OAAiB,QAAQ,KAAK,MAAM,CAAC,GAAkB;AAChF,MAAI;AACJ,MAAI;AACF,UAAM,EAAE,MAAM,OAAO,IAAI,sBAAsB,IAAI;AACnD,UAAM,YAAY,eAAe,MAAM,UAAU,CAAC;AAClD,aAAS,MAAM,gBAAgB,EAAE,MAAM,WAAW,OAAO,CAAC;AAAA,EAC5D,SAAS,KAAK;AACZ,YAAQ,OAAO;AAAA,MACb,kBAAkB,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA;AAAA,IACpE;AAAA,EACF;AACA,MAAI,QAAQ;AACV,YAAQ,OAAO,MAAM,KAAK,UAAU,MAAM,IAAI,IAAI;AAAA,EACpD;AACF;AAGA,IAAI,QAAQ,KAAK,CAAC,KAAK,QAAQ,KAAK,CAAC,EAAE,SAAS,kBAAkB,GAAG;AACnE,OAAK,KAAK,EAAE,QAAQ,MAAM;AAExB,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AACH;","names":["existsSync","join","join","existsSync","dbPath","contextJson","sessionId","recorded","fallback"]}
|
|
1
|
+
{"version":3,"sources":["../../src/cli/global-record.ts","../../src/cli/session-id.ts","../../src/cli/walk-up.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * aaac-observ-global-record — hook recorder (Issue #174 / T-A2).\n *\n * This is the binary wired into the Cursor / Claude / Git hooks `aaac install`\n * writes, at either of its scopes. \"global\" in the name is location-agnosticism\n * rather than an install scope: unlike `record-hook`, which assumes it runs\n * inside a configured repo with a known db path, this wrapper resolves its own\n * destination from where it was invoked:\n *\n * 1. parse the hook JSON payload from stdin\n * 2. collect candidate paths (cwd / workspace_roots / file_path + process.cwd)\n * and WALK UP to the nearest enclosing project.yaml\n * 3. resolve session_id through the multi-stage chain (AAAC_* → conversation_id\n * → .observ-context.json → CLAUDE_* → unknown)\n * 4a. RESOLVED → append to <project>/.agent-logs/observability.db\n * 4b. UNRESOLVED → append to ~/.aaac/ledger.db tagged with repo_id (a stable\n * hash of the git remote URL, or the cwd when there is no remote)\n *\n * Strictly fail-open: every walk/IO/exception path still exits 0 so the wrapper\n * can NEVER block the underlying Cursor/Claude/Git operation.\n *\n * Proposal: docs/proposal/observability-integration.md §ローカルグローバル記録.\n */\nimport { createHash } from \"node:crypto\";\nimport { execFileSync } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { DEFAULT_DB_PATH } from \"../index.js\";\nimport type { AttrValue } from \"../types/canonical-event.js\";\nimport {\n contextFilePath,\n defaultMappingConfigPath,\n parseHookInput,\n readStdin,\n runRecordHook,\n} from \"./record-hook.js\";\nimport { resolveSessionId } from \"./session-id.js\";\nimport { collectCandidatePaths, resolveProjectRoot } from \"./walk-up.js\";\n\n/** User-global ledger path, relative to HOME (`~/.aaac/ledger.db`). */\nexport function ledgerDbPath(home: string): string {\n return join(home, \".aaac\", \"ledger.db\");\n}\n\nexport interface GlobalRecordResult {\n /** Where the event was recorded. */\n scope: \"project\" | \"ledger\";\n /** Absolute db path written to. */\n dbPath: string;\n /** Resolved project root, when scope === \"project\". */\n projectRoot?: string;\n /** repo_id attribute, when scope === \"ledger\". */\n repoId?: string;\n /** Resolved session id (may be \"unknown\" provisional). */\n sessionId: string;\n /** Events recorded into the pipeline. */\n recorded: number;\n /** True when the generic fallback was used (no mapping rule matched). */\n fallback: boolean;\n}\n\n/**\n * Compute a stable repo_id for the per-user fallback ledger.\n * Prefers a SHA-256 of the canonical git remote URL; falls back to a hash of the\n * resolved cwd so records from a repo with no remote are still grouped.\n */\nexport function computeRepoId(remoteUrl: string | undefined, fallbackPath: string): string {\n const basis = remoteUrl && remoteUrl.trim().length > 0 ? `remote:${remoteUrl.trim()}` : `path:${fallbackPath}`;\n return createHash(\"sha256\").update(basis).digest(\"hex\").slice(0, 16);\n}\n\n/** Read & parse `.observ-context.json` at the given db dir; fail-open to {}. */\nfunction readContextJson(dbPath: string): Record<string, unknown> {\n try {\n const file = contextFilePath(dbPath);\n if (!existsSync(file)) return {};\n const raw = readFileSync(file, \"utf8\");\n return parseHookInput(raw);\n } catch {\n return {};\n }\n}\n\n/** Best-effort canonical git remote URL for a directory; undefined on any error. */\nexport function gitRemoteUrl(cwd: string): string | undefined {\n try {\n const out = execFileSync(\"git\", [\"-C\", cwd, \"config\", \"--get\", \"remote.origin.url\"], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: 2000,\n });\n const trimmed = out.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport interface RunGlobalRecordArgs {\n hook: string;\n hookInput: Record<string, unknown>;\n source?: string;\n /** Overrides for testability (default to the real environment). */\n env?: Record<string, string | undefined>;\n home?: string;\n processCwd?: string;\n /** Injectable remote-URL resolver (defaults to {@link gitRemoteUrl}). */\n resolveRemote?: (cwd: string) => string | undefined;\n}\n\n/**\n * Core (testable) global-record logic. Never throws — the caller guarantees\n * exit 0 regardless of the outcome.\n */\nexport async function runGlobalRecord(args: RunGlobalRecordArgs): Promise<GlobalRecordResult> {\n const { hook, hookInput } = args;\n const env = args.env ?? process.env;\n const home = args.home ?? homedir();\n const processCwd = args.processCwd ?? process.cwd();\n const source = args.source ?? \"global-hook\";\n const resolveRemote = args.resolveRemote ?? gitRemoteUrl;\n\n const candidates = collectCandidatePaths({\n cwd: hookInput.cwd,\n workspaceRoots: hookInput.workspace_roots,\n filePath: hookInput.file_path,\n processCwd,\n });\n const projectRoot = resolveProjectRoot(candidates);\n\n if (projectRoot) {\n const dbPath = join(projectRoot, DEFAULT_DB_PATH);\n const contextJson = readContextJson(dbPath);\n const { sessionId } = resolveSessionId({ hookInput, env, contextJson });\n const { recorded, fallback } = await runRecordHook({\n hook,\n hookInput,\n dbPath,\n mappingConfigPath: defaultMappingConfigPath(dbPath),\n source,\n sessionId,\n });\n return { scope: \"project\", dbPath, projectRoot, sessionId, recorded, fallback };\n }\n\n // Unresolved → per-user fallback ledger, tagged with repo_id.\n const dbPath = ledgerDbPath(home);\n const contextJson = readContextJson(dbPath);\n const { sessionId } = resolveSessionId({ hookInput, env, contextJson });\n let remote: string | undefined;\n try {\n remote = resolveRemote(processCwd);\n } catch {\n remote = undefined; // fail-open: no remote → cwd-hash repo_id\n }\n const repoId = computeRepoId(remote, processCwd);\n const extraAttributes: Record<string, AttrValue> = { repo_id: repoId };\n const { recorded, fallback } = await runRecordHook({\n hook,\n hookInput,\n dbPath,\n mappingConfigPath: defaultMappingConfigPath(dbPath),\n source,\n sessionId,\n extraAttributes,\n });\n return { scope: \"ledger\", dbPath, repoId, sessionId, recorded, fallback };\n}\n\n// ── CLI argument parsing ─────────────────────────────────────────────────────\n\ninterface ParsedArgs {\n hook: string;\n source?: string;\n}\n\n/** Parse `<hook-name> [--source <s>]` from argv (fail-open: unknown flags ignored). */\nexport function parseGlobalRecordArgs(argv: string[]): ParsedArgs {\n let hook = \"unknown\";\n let source: string | undefined;\n let sawHook = false;\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === \"--source\") {\n source = argv[++i];\n } else if (arg.startsWith(\"--source=\")) {\n source = arg.slice(\"--source=\".length);\n } else if (!arg.startsWith(\"-\") && !sawHook) {\n hook = arg;\n sawHook = true;\n }\n }\n return { hook, source };\n}\n\n// ── Entrypoint ───────────────────────────────────────────────────────────────\n\n/** Run the wrapper end-to-end; always resolves (caller exits 0). */\nexport async function main(argv: string[] = process.argv.slice(2)): Promise<void> {\n let result: GlobalRecordResult | undefined;\n try {\n const { hook, source } = parseGlobalRecordArgs(argv);\n const hookInput = parseHookInput(await readStdin());\n result = await runGlobalRecord({ hook, hookInput, source });\n } catch (err) {\n process.stderr.write(\n `global-record: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n }\n if (result) {\n process.stdout.write(JSON.stringify(result) + \"\\n\");\n }\n}\n\n// Only auto-run when invoked directly as a binary (not when imported by tests).\nif (process.argv[1] && process.argv[1].endsWith(\"global-record.js\")) {\n void main().finally(() => {\n // fail-open: ALWAYS exit 0.\n process.exit(0);\n });\n}\n","/**\n * session_id resolution — multi-stage, fail-open (Issue #174 / T-A6).\n *\n * The hook path runs OUTSIDE the @aaac/runtime process and often outside a\n * configured repo, so the in-process correlation key (conversation_id\n * injected by record-hook) may be absent. To still correlate hook-derived spans\n * we resolve session_id through a fixed priority chain and, when every source\n * fails, fall back to a provisional `unknown` marker rather than dropping the\n * record (records must NEVER be lost — fail-open).\n *\n * Priority (highest first):\n * 1. AAAC_* explicit env override (AAAC_SESSION_ID)\n * 2. conversation_id hook payload field (Cursor / runtime correlation key)\n * 3. .observ-context.json short-lived git-context file written by record-hook\n * 4. CLAUDE_* Claude Code env (CLAUDE_SESSION_ID)\n * 5. unknown provisional marker (provisional = true)\n *\n * Pure and synchronous: the caller is responsible for reading the (optional)\n * .observ-context.json contents and passing the parsed object. This keeps the\n * resolver trivially unit-testable per path (one test per priority level).\n *\n * Proposal: docs/proposal/observability-integration.md §session_id 解決.\n */\n\n/** Provisional marker used when no concrete session_id can be resolved. */\nexport const UNKNOWN_SESSION_ID = \"unknown\";\n\n/** Which priority rung produced the resolved session_id. */\nexport type SessionIdSource =\n | \"env-aaac\"\n | \"conversation_id\"\n | \"observ-context\"\n | \"env-claude\"\n | \"unknown\";\n\nexport interface ResolveSessionIdInput {\n /** Parsed hook payload from stdin (conversation_id, etc.). */\n hookInput?: Record<string, unknown>;\n /** Process environment (defaults to process.env). */\n env?: Record<string, string | undefined>;\n /** Parsed contents of `.observ-context.json` (read fail-open by the caller). */\n contextJson?: Record<string, unknown>;\n}\n\nexport interface ResolvedSessionId {\n /** Resolved session id, or {@link UNKNOWN_SESSION_ID} when unresolvable. */\n sessionId: string;\n /** The priority rung that produced the value. */\n source: SessionIdSource;\n /** True when no concrete source matched (sessionId === UNKNOWN_SESSION_ID). */\n provisional: boolean;\n}\n\n/** Return value when it is a non-empty string, else undefined. */\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim().length > 0 ? value : undefined;\n}\n\n/**\n * Resolve a session_id through the priority chain (1–5). Never throws.\n *\n * @returns the first matching source, or a provisional `unknown` marker.\n */\nexport function resolveSessionId(input: ResolveSessionIdInput = {}): ResolvedSessionId {\n const env = input.env ?? process.env;\n const hookInput = input.hookInput ?? {};\n const contextJson = input.contextJson ?? {};\n\n // 1. AAAC_* explicit override\n const aaac = nonEmptyString(env.AAAC_SESSION_ID);\n if (aaac) {\n return { sessionId: aaac, source: \"env-aaac\", provisional: false };\n }\n\n // 2. conversation_id from the hook payload\n const conversationId = nonEmptyString(hookInput.conversation_id);\n if (conversationId) {\n return { sessionId: conversationId, source: \"conversation_id\", provisional: false };\n }\n\n // 3. .observ-context.json (short-lived git-context file)\n const fromContext = nonEmptyString(contextJson.session_id);\n if (fromContext) {\n return { sessionId: fromContext, source: \"observ-context\", provisional: false };\n }\n\n // 4. CLAUDE_* env\n const claude = nonEmptyString(env.CLAUDE_SESSION_ID);\n if (claude) {\n return { sessionId: claude, source: \"env-claude\", provisional: false };\n }\n\n // 5. provisional unknown\n return { sessionId: UNKNOWN_SESSION_ID, source: \"unknown\", provisional: true };\n}\n","/**\n * project.yaml walk-up resolution (Issue #174 / T-A2).\n *\n * The hook recorder runs from any CWD, including repos that never ran\n * `aaac init`. To attribute a hook event to a project we walk UP the directory\n * tree from a set of candidate start paths (the hook payload's cwd /\n * workspace_roots / file_path, plus process.cwd()) until we find a `project.yaml`.\n *\n * Resolution rules:\n * - The nearest enclosing project.yaml wins (innermost in a nested monorepo).\n * - Candidates are tried in priority order; the first that resolves wins.\n * - A file path is reduced to its containing directory before walking.\n * - The walk stops at the filesystem root.\n *\n * Pure and fail-open: any stat/IO error on a candidate is swallowed and the next\n * candidate is tried; an empty/!found result is a normal outcome (the caller\n * then records to the per-user fallback ledger).\n *\n * Proposal: docs/proposal/observability-integration.md §ローカルグローバル記録.\n */\nimport { existsSync, statSync } from \"node:fs\";\nimport { dirname, join, parse as parsePath, resolve } from \"node:path\";\n\n/** The project manifest filename that anchors a project root. */\nexport const PROJECT_MANIFEST = \"project.yaml\";\n\nexport interface CollectCandidatesInput {\n /** Hook payload `cwd` field. */\n cwd?: unknown;\n /** Hook payload `workspace_roots` field (array of paths). */\n workspaceRoots?: unknown;\n /** Hook payload `file_path` field (the edited file). */\n filePath?: unknown;\n /** Process cwd fallback (defaults to process.cwd()). */\n processCwd?: string;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\n/**\n * Collect ordered, de-duplicated candidate start directories from a hook payload.\n * Priority: cwd → workspace_roots (in order) → file_path → process.cwd().\n */\nexport function collectCandidatePaths(input: CollectCandidatesInput): string[] {\n const out: string[] = [];\n const push = (value: unknown): void => {\n if (isNonEmptyString(value)) out.push(value);\n };\n\n push(input.cwd);\n if (Array.isArray(input.workspaceRoots)) {\n for (const root of input.workspaceRoots) push(root);\n }\n push(input.filePath);\n push(input.processCwd ?? process.cwd());\n\n // De-duplicate by resolved absolute path while preserving order.\n const seen = new Set<string>();\n const result: string[] = [];\n for (const p of out) {\n const abs = resolve(p);\n if (!seen.has(abs)) {\n seen.add(abs);\n result.push(abs);\n }\n }\n return result;\n}\n\n/** Reduce a path to a directory: a file → its parent, a dir → itself. */\nfunction toStartDir(candidate: string): string {\n const abs = resolve(candidate);\n try {\n if (existsSync(abs) && statSync(abs).isDirectory()) {\n return abs;\n }\n } catch {\n // fall through — treat as a (possibly non-existent) file path\n }\n return dirname(abs);\n}\n\n/**\n * Walk up from a single start directory to the nearest enclosing project.yaml.\n * @returns the directory containing project.yaml, or undefined.\n */\nexport function walkUpForProject(startDir: string): string | undefined {\n let dir = toStartDir(startDir);\n const { root } = parsePath(dir);\n\n // Bounded by the filesystem root; the loop terminates because dirname()\n // is a fixed point at the root.\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n if (existsSync(join(dir, PROJECT_MANIFEST))) {\n return dir;\n }\n } catch {\n // ignore and keep climbing\n }\n if (dir === root) break;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return undefined;\n}\n\n/**\n * Resolve a project root by walking up from each candidate path in priority\n * order. Returns the first project root found, or undefined when none of the\n * candidates is inside a project.\n */\nexport function resolveProjectRoot(candidates: string[]): string | undefined {\n for (const candidate of candidates) {\n const found = walkUpForProject(candidate);\n if (found) return found;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;AAwBA,SAAS,kBAAkB;AAC3B,SAAS,oBAAoB;AAC7B,SAAS,cAAAA,aAAY,oBAAoB;AACzC,SAAS,eAAe;AACxB,SAAS,QAAAC,aAAY;;;ACHd,IAAM,qBAAqB;AA6BlC,SAAS,eAAe,OAAoC;AAC1D,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,IAAI,QAAQ;AACxE;AAOO,SAAS,iBAAiB,QAA+B,CAAC,GAAsB;AACrF,QAAM,MAAM,MAAM,OAAO,QAAQ;AACjC,QAAM,YAAY,MAAM,aAAa,CAAC;AACtC,QAAM,cAAc,MAAM,eAAe,CAAC;AAG1C,QAAM,OAAO,eAAe,IAAI,eAAe;AAC/C,MAAI,MAAM;AACR,WAAO,EAAE,WAAW,MAAM,QAAQ,YAAY,aAAa,MAAM;AAAA,EACnE;AAGA,QAAM,iBAAiB,eAAe,UAAU,eAAe;AAC/D,MAAI,gBAAgB;AAClB,WAAO,EAAE,WAAW,gBAAgB,QAAQ,mBAAmB,aAAa,MAAM;AAAA,EACpF;AAGA,QAAM,cAAc,eAAe,YAAY,UAAU;AACzD,MAAI,aAAa;AACf,WAAO,EAAE,WAAW,aAAa,QAAQ,kBAAkB,aAAa,MAAM;AAAA,EAChF;AAGA,QAAM,SAAS,eAAe,IAAI,iBAAiB;AACnD,MAAI,QAAQ;AACV,WAAO,EAAE,WAAW,QAAQ,Q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","fallback"]}
|
package/dist/cli/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
handleRecordHook
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-D4ZWC5FU.js";
|
|
5
5
|
import {
|
|
6
6
|
DEFAULT_DB_PATH,
|
|
7
7
|
OUTCOME_CHAIN_STAGES,
|
|
@@ -13,11 +13,12 @@ import {
|
|
|
13
13
|
createPipeline,
|
|
14
14
|
generateDiagnosticReport,
|
|
15
15
|
generateId,
|
|
16
|
+
isAttrMap,
|
|
16
17
|
isoToUnixNano,
|
|
17
18
|
mapVendorOtelExport,
|
|
18
19
|
renderReportJson,
|
|
19
20
|
renderReportMarkdown
|
|
20
|
-
} from "../chunk-
|
|
21
|
+
} from "../chunk-4PNXLHYZ.js";
|
|
21
22
|
|
|
22
23
|
// src/cli/index.ts
|
|
23
24
|
import { readFileSync } from "fs";
|
|
@@ -240,10 +241,10 @@ command_sets:
|
|
|
240
241
|
schema:
|
|
241
242
|
type: string
|
|
242
243
|
enum: [trace, span, search, links, issue]
|
|
243
|
-
description: "Query kind: trace | span | search | links | issue"
|
|
244
|
+
description: "Query kind: trace | span | search | links | issue (optional when --issue is set)"
|
|
244
245
|
- name: issue
|
|
245
246
|
schema: { type: string }
|
|
246
|
-
description: "Issue ID
|
|
247
|
+
description: "Issue ID \u2014 implies --kind issue when --kind is omitted"
|
|
247
248
|
- name: trace-id
|
|
248
249
|
schema: { type: string }
|
|
249
250
|
description: Trace ID for trace queries (--kind trace)
|
|
@@ -332,12 +333,12 @@ command_sets:
|
|
|
332
333
|
stderr:
|
|
333
334
|
format: text
|
|
334
335
|
`;
|
|
335
|
-
var CONTRACT_JSON_STR = '{\n "cli_contracts": "0.1.0",\n "info": {\n "title": "AaaC Observability CLI",\n "version": "0.1.0",\n "description": "aaac-observ \u2014 external event registration and query for @aaac/observability"\n },\n "command_sets": {\n "aaac-observ": {\n "summary": "aaac-observ \u2014 register external events and query the observability store",\n "executable": "aaac-observ",\n "commands": {\n "record": {\n "summary": "Register an external event into the observability pipeline (thin entrypoint for EventCollector.registerExternalEvent)",\n "options": [\n {\n "name": "event-type",\n "aliases": [\n "t"\n ],\n "schema": {\n "type": "string"\n },\n "description": "Event type (e.g. promotion.commit, process.edit, agent.session)"\n },\n {\n "name": "lifecycle",\n "aliases": [\n "l"\n ],\n "schema": {\n "type": "string",\n "enum": [\n "open",\n "close",\n "event",\n "instant"\n ]\n },\n "description": "Event lifecycle phase: open | close | event | instant"\n },\n {\n "name": "span-id",\n "aliases": [\n "s"\n ],\n "schema": {\n "type": "string"\n },\n "description": "Span ID (auto-generated if omitted)"\n },\n {\n "name": "parent-span-id",\n "schema": {\n "type": "string"\n },\n "description": "Parent span ID for hierarchy"\n },\n {\n "name": "session-id",\n "schema": {\n "type": "string"\n },\n "description": "Session ID to associate with the event"\n },\n {\n "name": "trace-id",\n "schema": {\n "type": "string"\n },\n "description": "Trace ID for distributed tracing"\n },\n {\n "name": "source",\n "schema": {\n "type": "string"\n },\n "description": "Event source identifier (default: external)"\n },\n {\n "name": "attr",\n "schema": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "description": "Attribute as key=value (repeatable, e.g. --attr git.commit=abc123)"\n },\n {\n "name": "link",\n "schema": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "description": "Cross-axis link as targetSpanId:linkType[:targetTraceId] (repeatable)"\n },\n {\n "name": "db",\n "schema": {\n "type": "string"\n },\n "description": "Path to observability SQLite database (overrides default)"\n }\n ],\n "exits": {\n "0": {\n "description": "Event registered successfully",\n "stdout": {\n "format": "json",\n "schema": {\n "type": "object",\n "properties": {\n "eventId": {\n "type": "string"\n },\n "spanId": {\n "type": "string"\n }\n }\n }\n }\n },\n "1": {\n "description": "Registration failed (validation error or write error)",\n "stderr": {\n "format": "text"\n }\n }\n }\n },\n "record-hook": {\n "summary": "Record a Cursor/git hook event \u2014 parses stdin JSON, resolves event_mapping into 3-axis spans/links, injects session_id, and emits human-events (fail-open)",\n "arguments": [\n {\n "name": "hook-name",\n "index": 0,\n "required": true,\n "schema": {\n "type": "string"\n },\n "description": "Cursor/git hook name (e.g. afterFileEdit, subagentStart, beforeShellExecution)"\n }\n ],\n "options": [\n {\n "name": "mapping-config",\n "schema": {\n "type": "string"\n },\n "description": "Path to event-mapping.json (default: .agent-logs/config/event-mapping.json)"\n },\n {\n "name": "db",\n "schema": {\n "type": "string"\n },\n "description": "Path to observability SQLite database (overrides default)"\n }\n ],\n "exits": {\n "0": {\n "description": "Hook recorded (or no-op when stdin/mapping unavailable) \u2014 always fail-open",\n "stdout": {\n "format": "json",\n "schema": {\n "type": "object",\n "properties": {\n "recorded": {\n "type": "integer"\n },\n "fallback": {\n "type": "boolean"\n }\n }\n }\n }\n }\n }\n },\n "backfill": {\n "summary": "Re-emit historical spans from SQLite to an OTLP backend",\n "description": "Reads closed/instant spans from the local SQLite database and emits them\\nvia OtelEmitter to an OTLP-compatible backend.\\n\\nIMPORTANT \u2014 idempotency: The OTel SDK does not support specifying custom\\nspanIds, so each backfill invocation creates NEW spans in the backend.\\nRepeated invocations will produce DUPLICATE data. Use --from/--to to\\ncontrol scope. See #125 \xA77 for full idempotency guidance.\\n",\n "options": [\n {\n "name": "db",\n "schema": {\n "type": "string"\n },\n "description": "Path to observability SQLite database (overrides default)"\n },\n {\n "name": "endpoint",\n "schema": {\n "type": "string"\n },\n "description": "OTLP HTTP endpoint URL (fallback: OTEL_EXPORTER_OTLP_ENDPOINT)"\n },\n {\n "name": "service-name",\n "schema": {\n "type": "string"\n },\n "description": "OTEL service name reported to backend (default: @aaac/observability)"\n },\n {\n "name": "from",\n "schema": {\n "type": "string"\n },\n "description": "Backfill spans starting at or after this ISO 8601 time"\n },\n {\n "name": "to",\n "schema": {\n "type": "string"\n },\n "description": "Backfill spans starting at or before this ISO 8601 time"\n },\n {\n "name": "event-type",\n "schema": {\n "type": "string"\n },\n "description": "Filter by event type (e.g. agent.session)"\n },\n {\n "name": "dry-run",\n "schema": {\n "type": "boolean"\n },\n "description": "Print span count without emitting to OTLP backend"\n },\n {\n "name": "flush-timeout-ms",\n "schema": {\n "type": "integer"\n },\n "description": "Maximum ms to wait for OTLP flush before exit (default: 2000; use \u226530000 for >5k spans)"\n }\n ],\n "exits": {\n "0": {\n "description": "Backfill completed",\n "stdout": {\n "format": "json",\n "schema": {\n "type": "object",\n "properties": {\n "spansFound": {\n "type": "integer"\n },\n "spansEmitted": {\n "type": "integer"\n },\n "dryRun": {\n "type": "boolean"\n }\n }\n }\n }\n },\n "1": {\n "description": "Backfill failed (missing endpoint, DB error, etc.)",\n "stderr": {\n "format": "text"\n }\n }\n }\n },\n "ingest-vendor-otel": {\n "summary": "Project a vendor OTLP/JSON trace export (e.g. Claude Code token/cost/trace) into the SQLite Ledger",\n "description": "Canonical Projection batch (observability-integration.md \xA79.2 / T-D2).\\n\\nReads a vendor OTLP/JSON trace export from --input (file) or stdin, projects\\neach span into a Canonical Event, and backfills it into the SQLite Ledger.\\n\\nIdempotent: every event carries a deterministic dedup_key\\n(vendor-otel:{traceId}:{spanId}) enforced by UNIQUE + INSERT OR IGNORE, so\\nre-running on the same export inserts nothing new (reported as\\nskippedDuplicate). Hook/runtime records remain the primary source; vendor\\nOTEL is auxiliary evidence.\\n",\n "options": [\n {\n "name": "db",\n "schema": {\n "type": "string"\n },\n "description": "Path to observability SQLite database (overrides default)"\n },\n {\n "name": "input",\n "aliases": [\n "i"\n ],\n "schema": {\n "type": "string"\n },\n "description": "Path to the OTLP/JSON trace export (reads stdin when omitted)"\n },\n {\n "name": "source",\n "schema": {\n "type": "string"\n },\n "description": "Source tag for projected events (default: claude-code-otel)"\n },\n {\n "name": "dry-run",\n "schema": {\n "type": "boolean"\n },\n "description": "Parse and project without writing to the Ledger"\n }\n ],\n "exits": {\n "0": {\n "description": "Ingestion completed",\n "stdout": {\n "format": "json",\n "schema": {\n "type": "object",\n "properties": {\n "found": {\n "type": "integer"\n },\n "inserted": {\n "type": "integer"\n },\n "skippedDuplicate": {\n "type": "integer"\n },\n "skippedInvalid": {\n "type": "integer"\n },\n "dryRun": {\n "type": "boolean"\n }\n }\n }\n }\n },\n "1": {\n "description": "Ingestion failed (unreadable input, invalid JSON, DB error)",\n "stderr": {\n "format": "text"\n }\n }\n }\n },\n "query": {\n "summary": "Query the observability store via QueryAdapter",\n "options": [\n {\n "name": "kind",\n "aliases": [\n "k"\n ],\n "schema": {\n "type": "string",\n "enum": [\n "trace",\n "span",\n "search",\n "links",\n "issue"\n ]\n },\n "description": "Query kind: trace | span | search | links | issue"\n },\n {\n "name": "issue",\n "schema": {\n "type": "string"\n },\n "description": "Issue ID for issue queries (--kind issue)"\n },\n {\n "name": "trace-id",\n "schema": {\n "type": "string"\n },\n "description": "Trace ID for trace queries (--kind trace)"\n },\n {\n "name": "span-id",\n "aliases": [\n "s"\n ],\n "schema": {\n "type": "string"\n },\n "description": "Span ID for span/links queries (--kind span or --kind links)"\n },\n {\n "name": "event-type",\n "schema": {\n "type": "string"\n },\n "description": "Event type filter for search queries (--kind search)"\n },\n {\n "name": "task-id",\n "schema": {\n "type": "string"\n },\n "description": "Task ID filter for search queries (--kind search)"\n },\n {\n "name": "from",\n "schema": {\n "type": "string"\n },\n "description": "Start time in ISO 8601 format for search queries (--kind search)"\n },\n {\n "name": "to",\n "schema": {\n "type": "string"\n },\n "description": "End time in ISO 8601 format for search queries (--kind search)"\n },\n {\n "name": "direction",\n "aliases": [\n "d"\n ],\n "schema": {\n "type": "string",\n "enum": [\n "forward",\n "reverse",\n "both"\n ]\n },\n "description": "Link traversal direction for links queries (default: both)"\n },\n {\n "name": "db",\n "schema": {\n "type": "string"\n },\n "description": "Path to observability SQLite database (overrides default)"\n }\n ],\n "exits": {\n "0": {\n "description": "Query succeeded \u2014 results as JSON array",\n "stdout": {\n "format": "json",\n "schema": {\n "type": "object"\n }\n }\n },\n "1": {\n "description": "Query failed",\n "stderr": {\n "format": "text"\n }\n }\n }\n },\n "report": {\n "summary": "Generate an Observability diagnostic report (Layer 1-3 + link completion + Person Tier) from the SQLite Ledger",\n "description": "Customer-facing Observability diagnostic (#179 WS-F T-F1). Computes the\\nsame Layer 1-3 / link-completion / Person-Tier metrics rendered by the\\n`aaac-diagnostic` Grafana dashboard, over the local SQLite Ledger.\\n\\nOutput is Markdown (default) or JSON. Use --project-id to scope to a\\nsingle project (internal or a cooperating customer project). Supply\\n--baseline-from / --baseline-to to add a Before/After comparison\\nsection against a baseline window; --from / --to bound the current\\n(after) window.\\n",\n "options": [\n {\n "name": "project-id",\n "aliases": [\n "p"\n ],\n "schema": {\n "type": "string"\n },\n "description": "Restrict the report to a single project_id (project.id attr / service.name)"\n },\n {\n "name": "from",\n "schema": {\n "type": "string"\n },\n "description": "Start time (ISO 8601) for the current/after window"\n },\n {\n "name": "to",\n "schema": {\n "type": "string"\n },\n "description": "End time (ISO 8601) for the current/after window"\n },\n {\n "name": "baseline-from",\n "schema": {\n "type": "string"\n },\n "description": "Start time (ISO 8601) of the baseline/before window (enables Before/After comparison)"\n },\n {\n "name": "baseline-to",\n "schema": {\n "type": "string"\n },\n "description": "End time (ISO 8601) of the baseline/before window (enables Before/After comparison)"\n },\n {\n "name": "format",\n "aliases": [\n "f"\n ],\n "schema": {\n "type": "string",\n "enum": [\n "markdown",\n "json"\n ]\n },\n "description": "Output format: markdown (default) | json"\n },\n {\n "name": "db",\n "schema": {\n "type": "string"\n },\n "description": "Path to observability SQLite database (overrides default)"\n }\n ],\n "exits": {\n "0": {\n "description": "Report generated \u2014 Markdown or JSON on stdout",\n "stdout": {\n "format": "text"\n }\n },\n "1": {\n "description": "Report generation failed",\n "stderr": {\n "format": "text"\n }\n }\n }\n }\n }\n }\n }\n}';
|
|
336
|
+
var CONTRACT_JSON_STR = '{\n "cli_contracts": "0.1.0",\n "info": {\n "title": "AaaC Observability CLI",\n "version": "0.1.0",\n "description": "aaac-observ \u2014 external event registration and query for @aaac/observability"\n },\n "command_sets": {\n "aaac-observ": {\n "summary": "aaac-observ \u2014 register external events and query the observability store",\n "executable": "aaac-observ",\n "commands": {\n "record": {\n "summary": "Register an external event into the observability pipeline (thin entrypoint for EventCollector.registerExternalEvent)",\n "options": [\n {\n "name": "event-type",\n "aliases": [\n "t"\n ],\n "schema": {\n "type": "string"\n },\n "description": "Event type (e.g. promotion.commit, process.edit, agent.session)"\n },\n {\n "name": "lifecycle",\n "aliases": [\n "l"\n ],\n "schema": {\n "type": "string",\n "enum": [\n "open",\n "close",\n "event",\n "instant"\n ]\n },\n "description": "Event lifecycle phase: open | close | event | instant"\n },\n {\n "name": "span-id",\n "aliases": [\n "s"\n ],\n "schema": {\n "type": "string"\n },\n "description": "Span ID (auto-generated if omitted)"\n },\n {\n "name": "parent-span-id",\n "schema": {\n "type": "string"\n },\n "description": "Parent span ID for hierarchy"\n },\n {\n "name": "session-id",\n "schema": {\n "type": "string"\n },\n "description": "Session ID to associate with the event"\n },\n {\n "name": "trace-id",\n "schema": {\n "type": "string"\n },\n "description": "Trace ID for distributed tracing"\n },\n {\n "name": "source",\n "schema": {\n "type": "string"\n },\n "description": "Event source identifier (default: external)"\n },\n {\n "name": "attr",\n "schema": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "description": "Attribute as key=value (repeatable, e.g. --attr git.commit=abc123)"\n },\n {\n "name": "link",\n "schema": {\n "type": "array",\n "items": {\n "type": "string"\n }\n },\n "description": "Cross-axis link as targetSpanId:linkType[:targetTraceId] (repeatable)"\n },\n {\n "name": "db",\n "schema": {\n "type": "string"\n },\n "description": "Path to observability SQLite database (overrides default)"\n }\n ],\n "exits": {\n "0": {\n "description": "Event registered successfully",\n "stdout": {\n "format": "json",\n "schema": {\n "type": "object",\n "properties": {\n "eventId": {\n "type": "string"\n },\n "spanId": {\n "type": "string"\n }\n }\n }\n }\n },\n "1": {\n "description": "Registration failed (validation error or write error)",\n "stderr": {\n "format": "text"\n }\n }\n }\n },\n "record-hook": {\n "summary": "Record a Cursor/git hook event \u2014 parses stdin JSON, resolves event_mapping into 3-axis spans/links, injects session_id, and emits human-events (fail-open)",\n "arguments": [\n {\n "name": "hook-name",\n "index": 0,\n "required": true,\n "schema": {\n "type": "string"\n },\n "description": "Cursor/git hook name (e.g. afterFileEdit, subagentStart, beforeShellExecution)"\n }\n ],\n "options": [\n {\n "name": "mapping-config",\n "schema": {\n "type": "string"\n },\n "description": "Path to event-mapping.json (default: .agent-logs/config/event-mapping.json)"\n },\n {\n "name": "db",\n "schema": {\n "type": "string"\n },\n "description": "Path to observability SQLite database (overrides default)"\n }\n ],\n "exits": {\n "0": {\n "description": "Hook recorded (or no-op when stdin/mapping unavailable) \u2014 always fail-open",\n "stdout": {\n "format": "json",\n "schema": {\n "type": "object",\n "properties": {\n "recorded": {\n "type": "integer"\n },\n "fallback": {\n "type": "boolean"\n }\n }\n }\n }\n }\n }\n },\n "backfill": {\n "summary": "Re-emit historical spans from SQLite to an OTLP backend",\n "description": "Reads closed/instant spans from the local SQLite database and emits them\\nvia OtelEmitter to an OTLP-compatible backend.\\n\\nIMPORTANT \u2014 idempotency: The OTel SDK does not support specifying custom\\nspanIds, so each backfill invocation creates NEW spans in the backend.\\nRepeated invocations will produce DUPLICATE data. Use --from/--to to\\ncontrol scope. See #125 \xA77 for full idempotency guidance.\\n",\n "options": [\n {\n "name": "db",\n "schema": {\n "type": "string"\n },\n "description": "Path to observability SQLite database (overrides default)"\n },\n {\n "name": "endpoint",\n "schema": {\n "type": "string"\n },\n "description": "OTLP HTTP endpoint URL (fallback: OTEL_EXPORTER_OTLP_ENDPOINT)"\n },\n {\n "name": "service-name",\n "schema": {\n "type": "string"\n },\n "description": "OTEL service name reported to backend (default: @aaac/observability)"\n },\n {\n "name": "from",\n "schema": {\n "type": "string"\n },\n "description": "Backfill spans starting at or after this ISO 8601 time"\n },\n {\n "name": "to",\n "schema": {\n "type": "string"\n },\n "description": "Backfill spans starting at or before this ISO 8601 time"\n },\n {\n "name": "event-type",\n "schema": {\n "type": "string"\n },\n "description": "Filter by event type (e.g. agent.session)"\n },\n {\n "name": "dry-run",\n "schema": {\n "type": "boolean"\n },\n "description": "Print span count without emitting to OTLP backend"\n },\n {\n "name": "flush-timeout-ms",\n "schema": {\n "type": "integer"\n },\n "description": "Maximum ms to wait for OTLP flush before exit (default: 2000; use \u226530000 for >5k spans)"\n }\n ],\n "exits": {\n "0": {\n "description": "Backfill completed",\n "stdout": {\n "format": "json",\n "schema": {\n "type": "object",\n "properties": {\n "spansFound": {\n "type": "integer"\n },\n "spansEmitted": {\n "type": "integer"\n },\n "dryRun": {\n "type": "boolean"\n }\n }\n }\n }\n },\n "1": {\n "description": "Backfill failed (missing endpoint, DB error, etc.)",\n "stderr": {\n "format": "text"\n }\n }\n }\n },\n "ingest-vendor-otel": {\n "summary": "Project a vendor OTLP/JSON trace export (e.g. Claude Code token/cost/trace) into the SQLite Ledger",\n "description": "Canonical Projection batch (observability-integration.md \xA79.2 / T-D2).\\n\\nReads a vendor OTLP/JSON trace export from --input (file) or stdin, projects\\neach span into a Canonical Event, and backfills it into the SQLite Ledger.\\n\\nIdempotent: every event carries a deterministic dedup_key\\n(vendor-otel:{traceId}:{spanId}) enforced by UNIQUE + INSERT OR IGNORE, so\\nre-running on the same export inserts nothing new (reported as\\nskippedDuplicate). Hook/runtime records remain the primary source; vendor\\nOTEL is auxiliary evidence.\\n",\n "options": [\n {\n "name": "db",\n "schema": {\n "type": "string"\n },\n "description": "Path to observability SQLite database (overrides default)"\n },\n {\n "name": "input",\n "aliases": [\n "i"\n ],\n "schema": {\n "type": "string"\n },\n "description": "Path to the OTLP/JSON trace export (reads stdin when omitted)"\n },\n {\n "name": "source",\n "schema": {\n "type": "string"\n },\n "description": "Source tag for projected events (default: claude-code-otel)"\n },\n {\n "name": "dry-run",\n "schema": {\n "type": "boolean"\n },\n "description": "Parse and project without writing to the Ledger"\n }\n ],\n "exits": {\n "0": {\n "description": "Ingestion completed",\n "stdout": {\n "format": "json",\n "schema": {\n "type": "object",\n "properties": {\n "found": {\n "type": "integer"\n },\n "inserted": {\n "type": "integer"\n },\n "skippedDuplicate": {\n "type": "integer"\n },\n "skippedInvalid": {\n "type": "integer"\n },\n "dryRun": {\n "type": "boolean"\n }\n }\n }\n }\n },\n "1": {\n "description": "Ingestion failed (unreadable input, invalid JSON, DB error)",\n "stderr": {\n "format": "text"\n }\n }\n }\n },\n "query": {\n "summary": "Query the observability store via QueryAdapter",\n "options": [\n {\n "name": "kind",\n "aliases": [\n "k"\n ],\n "schema": {\n "type": "string",\n "enum": [\n "trace",\n "span",\n "search",\n "links",\n "issue"\n ]\n },\n "description": "Query kind: trace | span | search | links | issue (optional when --issue is set)"\n },\n {\n "name": "issue",\n "schema": {\n "type": "string"\n },\n "description": "Issue ID \u2014 implies --kind issue when --kind is omitted"\n },\n {\n "name": "trace-id",\n "schema": {\n "type": "string"\n },\n "description": "Trace ID for trace queries (--kind trace)"\n },\n {\n "name": "span-id",\n "aliases": [\n "s"\n ],\n "schema": {\n "type": "string"\n },\n "description": "Span ID for span/links queries (--kind span or --kind links)"\n },\n {\n "name": "event-type",\n "schema": {\n "type": "string"\n },\n "description": "Event type filter for search queries (--kind search)"\n },\n {\n "name": "task-id",\n "schema": {\n "type": "string"\n },\n "description": "Task ID filter for search queries (--kind search)"\n },\n {\n "name": "from",\n "schema": {\n "type": "string"\n },\n "description": "Start time in ISO 8601 format for search queries (--kind search)"\n },\n {\n "name": "to",\n "schema": {\n "type": "string"\n },\n "description": "End time in ISO 8601 format for search queries (--kind search)"\n },\n {\n "name": "direction",\n "aliases": [\n "d"\n ],\n "schema": {\n "type": "string",\n "enum": [\n "forward",\n "reverse",\n "both"\n ]\n },\n "description": "Link traversal direction for links queries (default: both)"\n },\n {\n "name": "db",\n "schema": {\n "type": "string"\n },\n "description": "Path to observability SQLite database (overrides default)"\n }\n ],\n "exits": {\n "0": {\n "description": "Query succeeded \u2014 results as JSON array",\n "stdout": {\n "format": "json",\n "schema": {\n "type": "object"\n }\n }\n },\n "1": {\n "description": "Query failed",\n "stderr": {\n "format": "text"\n }\n }\n }\n },\n "report": {\n "summary": "Generate an Observability diagnostic report (Layer 1-3 + link completion + Person Tier) from the SQLite Ledger",\n "description": "Customer-facing Observability diagnostic (#179 WS-F T-F1). Computes the\\nsame Layer 1-3 / link-completion / Person-Tier metrics rendered by the\\n`aaac-diagnostic` Grafana dashboard, over the local SQLite Ledger.\\n\\nOutput is Markdown (default) or JSON. Use --project-id to scope to a\\nsingle project (internal or a cooperating customer project). Supply\\n--baseline-from / --baseline-to to add a Before/After comparison\\nsection against a baseline window; --from / --to bound the current\\n(after) window.\\n",\n "options": [\n {\n "name": "project-id",\n "aliases": [\n "p"\n ],\n "schema": {\n "type": "string"\n },\n "description": "Restrict the report to a single project_id (project.id attr / service.name)"\n },\n {\n "name": "from",\n "schema": {\n "type": "string"\n },\n "description": "Start time (ISO 8601) for the current/after window"\n },\n {\n "name": "to",\n "schema": {\n "type": "string"\n },\n "description": "End time (ISO 8601) for the current/after window"\n },\n {\n "name": "baseline-from",\n "schema": {\n "type": "string"\n },\n "description": "Start time (ISO 8601) of the baseline/before window (enables Before/After comparison)"\n },\n {\n "name": "baseline-to",\n "schema": {\n "type": "string"\n },\n "description": "End time (ISO 8601) of the baseline/before window (enables Before/After comparison)"\n },\n {\n "name": "format",\n "aliases": [\n "f"\n ],\n "schema": {\n "type": "string",\n "enum": [\n "markdown",\n "json"\n ]\n },\n "description": "Output format: markdown (default) | json"\n },\n {\n "name": "db",\n "schema": {\n "type": "string"\n },\n "description": "Path to observability SQLite database (overrides default)"\n }\n ],\n "exits": {\n "0": {\n "description": "Report generated \u2014 Markdown or JSON on stdout",\n "stdout": {\n "format": "text"\n }\n },\n "1": {\n "description": "Report generation failed",\n "stderr": {\n "format": "text"\n }\n }\n }\n }\n }\n }\n }\n}';
|
|
336
337
|
|
|
337
338
|
// src/generated/program.ts
|
|
338
|
-
function createProgram(handlers2,
|
|
339
|
+
function createProgram(handlers2, version2) {
|
|
339
340
|
const program2 = new Command();
|
|
340
|
-
program2.name("aaac-observ").version(
|
|
341
|
+
program2.name("aaac-observ").version(version2, "-V, --version").description("aaac-observ \u2014 register external events and query the observability store");
|
|
341
342
|
program2.command("record").description("Register an external event into the observability pipeline (thin entrypoint for EventCollector.registerExternalEvent)").option("-t, --event-type <value>", "Event type (e.g. promotion.commit, process.edit, agent.session)").option("-l, --lifecycle <value>", "Event lifecycle phase: open | close | event | instant").option("-s, --span-id <value>", "Span ID (auto-generated if omitted)").option("--parent-span-id <value>", "Parent span ID for hierarchy").option("--session-id <value>", "Session ID to associate with the event").option("--trace-id <value>", "Trace ID for distributed tracing").option("--source <value>", "Event source identifier (default: external)").option("--attr <value>", "Attribute as key=value (repeatable, e.g. --attr git.commit=abc123)").option("--link <value>", "Cross-axis link as targetSpanId:linkType[:targetTraceId] (repeatable)").option("--db <value>", "Path to observability SQLite database (overrides default)").action(async (opts, cmd) => {
|
|
342
343
|
await handlers2.record(opts, cmd.optsWithGlobals());
|
|
343
344
|
});
|
|
@@ -350,7 +351,7 @@ function createProgram(handlers2, version) {
|
|
|
350
351
|
program2.command("ingest-vendor-otel").description("Project a vendor OTLP/JSON trace export (e.g. Claude Code token/cost/trace) into the SQLite Ledger").option("--db <value>", "Path to observability SQLite database (overrides default)").option("-i, --input <value>", "Path to the OTLP/JSON trace export (reads stdin when omitted)").option("--source <value>", "Source tag for projected events (default: claude-code-otel)").option("--dry-run", "Parse and project without writing to the Ledger").action(async (opts, cmd) => {
|
|
351
352
|
await handlers2.ingestVendorOtel(opts, cmd.optsWithGlobals());
|
|
352
353
|
});
|
|
353
|
-
program2.command("query").description("Query the observability store via QueryAdapter").option("-k, --kind <value>", "Query kind: trace | span | search | links | issue").option("--issue <value>", "Issue ID
|
|
354
|
+
program2.command("query").description("Query the observability store via QueryAdapter").option("-k, --kind <value>", "Query kind: trace | span | search | links | issue (optional when --issue is set)").option("--issue <value>", "Issue ID \u2014 implies --kind issue when --kind is omitted").option("--trace-id <value>", "Trace ID for trace queries (--kind trace)").option("-s, --span-id <value>", "Span ID for span/links queries (--kind span or --kind links)").option("--event-type <value>", "Event type filter for search queries (--kind search)").option("--task-id <value>", "Task ID filter for search queries (--kind search)").option("--from <value>", "Start time in ISO 8601 format for search queries (--kind search)").option("--to <value>", "End time in ISO 8601 format for search queries (--kind search)").option("-d, --direction <value>", "Link traversal direction for links queries (default: both)").option("--db <value>", "Path to observability SQLite database (overrides default)").action(async (opts, cmd) => {
|
|
354
355
|
await handlers2.query(opts, cmd.optsWithGlobals());
|
|
355
356
|
});
|
|
356
357
|
program2.command("report").description("Generate an Observability diagnostic report (Layer 1-3 + link completion + Person Tier) from the SQLite Ledger").option("-p, --project-id <value>", "Restrict the report to a single project_id (project.id attr / service.name)").option("--from <value>", "Start time (ISO 8601) for the current/after window").option("--to <value>", "End time (ISO 8601) for the current/after window").option("--baseline-from <value>", "Start time (ISO 8601) of the baseline/before window (enables Before/After comparison)").option("--baseline-to <value>", "End time (ISO 8601) of the baseline/before window (enables Before/After comparison)").option("-f, --format <value>", "Output format: markdown (default) | json").option("--db <value>", "Path to observability SQLite database (overrides default)").action(async (opts, cmd) => {
|
|
@@ -435,7 +436,8 @@ function parseAttr(attrStr) {
|
|
|
435
436
|
const trimmed = attrStr.trim();
|
|
436
437
|
if (trimmed.startsWith("{")) {
|
|
437
438
|
try {
|
|
438
|
-
|
|
439
|
+
const parsed = JSON.parse(trimmed);
|
|
440
|
+
if (isAttrMap(parsed)) return parsed;
|
|
439
441
|
} catch {
|
|
440
442
|
}
|
|
441
443
|
}
|
|
@@ -944,9 +946,13 @@ var handlers = {
|
|
|
944
946
|
|
|
945
947
|
// src/cli/index.ts
|
|
946
948
|
var __dirname = dirname(fileURLToPath(import.meta.url));
|
|
947
|
-
var
|
|
949
|
+
var manifest = JSON.parse(
|
|
948
950
|
readFileSync(resolve(__dirname, "../../package.json"), "utf8")
|
|
949
951
|
);
|
|
950
|
-
var
|
|
952
|
+
var version = typeof manifest === "object" && manifest !== null ? manifest.version : void 0;
|
|
953
|
+
if (typeof version !== "string") {
|
|
954
|
+
throw new Error("@aaac/observability package.json declares no string `version`");
|
|
955
|
+
}
|
|
956
|
+
var program = createProgram(handlers, version);
|
|
951
957
|
await program.parseAsync();
|
|
952
958
|
//# sourceMappingURL=index.js.map
|