@glyphier/cli 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright (c) 2026 Glyphier. All rights reserved.
2
+
3
+ This software and its documentation are proprietary and confidential. No
4
+ license is granted to use, copy, modify, distribute, reverse engineer, or
5
+ create derivative works except under a written commercial agreement with
6
+ Glyphier. Authorized users may run the unmodified software solely with a valid
7
+ Glyphier API key and an active paid subscription.
package/README.md ADDED
@@ -0,0 +1,48 @@
1
+ # Glyphier CLI
2
+
3
+ Glyphier is a paid, local-first context compiler for engineering agents. Raw
4
+ repository source remains on your machine. The managed service verifies your
5
+ license and can synchronize only policy-scoped, redacted receipts.
6
+
7
+ ## Install with your agent
8
+
9
+ Start at [glyphier.com/agent.md](https://glyphier.com/agent.md). Your agent
10
+ will ask for an email address and personal organization name, ask you for the
11
+ email OTP, open Stripe Checkout for your seven-day trial, and install the MCP
12
+ entry after activation.
13
+
14
+ It should pipe the short-lived installation grant directly to the CLI:
15
+
16
+ ```sh
17
+ npx -y @glyphier/cli@0.1.0 install --agent codex --onboarding-token-stdin
18
+ glyphier doctor --agent codex
19
+ ```
20
+
21
+ The grant is single-use. The resulting paid API key is written only into the
22
+ selected user-level MCP configuration with restrictive permissions; it is never
23
+ printed by the installer or returned to an agent conversation.
24
+
25
+ Verified automatic adapters: Codex, Claude Code, Cursor, Gemini CLI, and
26
+ Windsurf. Any MCP-compatible host can use a standards-compliant template:
27
+
28
+ ```sh
29
+ npx -y @glyphier/cli@0.1.0 config --universal
30
+ ```
31
+
32
+ Use `glyphier install --agent <host> --dry-run` before changing an existing
33
+ configuration. The installer preserves unrelated entries, backs up modified
34
+ files, rejects repository locations, and `glyphier uninstall --agent <host>`
35
+ removes only the Glyphier-owned entry.
36
+
37
+ ## Security and billing
38
+
39
+ Glyphier requires an active Dev trial, Dev subscription, or Enterprise
40
+ entitlement. Do not commit literal API keys or host configuration files.
41
+
42
+ Jev provider egress is disabled by default and requires explicit consent for
43
+ each repository. The TypeSafe credential is held only by Glyphier's private
44
+ broker; it is never present in this package, local receipts, or MCP responses.
45
+
46
+ This package is compiled proprietary software. It intentionally contains no
47
+ source TypeScript, tests, fixtures, source maps, credentials, or development
48
+ artifacts.
@@ -0,0 +1 @@
1
+ import{a,b,c,d}from"./chunk-WJT5SDKF.js";export{a as SOURCE_AUTHORITY,d as admitMemoryRecord,c as canTaskOutcomeValidateRecord,b as computeEvidenceAuthority};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e}from"./chunk-JJMQEAIJ.js";export{e as formatContextForAgent,c as renderForAntigravity,a as renderForClaudeCode,b as renderForCursor,d as renderForText};
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env node
2
+ import{a as ke}from"../chunk-I6N5RRFT.js";import{a as Ee}from"../chunk-ZOFLEGRO.js";import{a as $e}from"../chunk-B6KCBY3J.js";import{a as Ae,c as Ie,j as De,k as Ne}from"../chunk-Z4N35S7K.js";import{d as Te}from"../chunk-WJT5SDKF.js";import{a as L,b as Ve,c as Je}from"../chunk-NZULHZGK.js";import{a as y,n as Ce}from"../chunk-MCPBJALB.js";import{a as Re,b as _e,c as Fe}from"../chunk-BJ2IE33Q.js";import{A as fe,B as ge,C as ue,D as he,F as ye,G as Se,H as ve,L as be,R as we,V as Pe,j as Q,k as ee,l as oe,m as te,n as _,o as re,p as ne,q as ie,r as G,s as V,t as se,u as ae,v as ce,w as le,x as pe,y as de,z as me}from"../chunk-VOGFZYFC.js";import{a as J,b as xe}from"../chunk-QYSMWA6Y.js";import{a as je,d as $}from"../chunk-PCRAPKFZ.js";import{e as F}from"../chunk-JJMQEAIJ.js";import{a as I}from"../chunk-H6T36TY5.js";import{c as Oe}from"../chunk-FOZKI4M3.js";import{b as h,g as Z,h as A}from"../chunk-NIXOREHQ.js";import{Command as lt}from"commander";import Ge from"path";async function Le(t,o={}){let e=Ge.resolve(o.root||t||process.cwd()),r=Ge.resolve(t||o.root||process.cwd()),n=o.depth?parseInt(o.depth,10):void 0,i=o.level?parseInt(o.level,10):0,a=o.ignore?[o.ignore]:void 0;if(o.budget){let c=parseInt(o.budget,10),s=await de({budget:c,rootPath:r});o.json?console.log(y(s.plan)):console.log(s.formattedOutput);return}if(i===0){let c=await Q(r,{depth:n,rootPath:e,ignore:a});o.json?console.log(y(c)):console.log(G(c))}else{let c=await _(r,{level:1,rootPath:e,depth:n,ignore:a,noCache:o.noCache});if(o.json)console.log(y({tree:c.tree,files:Object.fromEntries(c.files)}));else{console.log(G(c.tree)),console.log();let s=Array.from(c.files.entries()),p=15,m=s.slice(0,p);for(let[l,u]of m)console.log(`--- ${l} ---`),console.log(V(u,{level:1})),console.log();s.length>p&&console.log(`... (${s.length-p} more files omitted; use 'glyphier view <file>' or specify a subdirectory)`)}}}import H from"path";async function He(t,o={}){let e=o.root?H.resolve(o.root):process.cwd(),r=H.isAbsolute(t)?t:H.resolve(e,t),n=o.level?parseInt(o.level,10):2,i=await te(r,{level:n,rootPath:e,noCache:o.noCache});if(i||(console.error(`[glyphier] Error: could not parse file ${t}`),process.exit(1)),o.session){let a=he(o.session,r,i);if(a.status==="unchanged"){console.log(pe(a));return}}o.json?console.log(y(i)):console.log(V(i,{level:n}))}import M from"path";async function Me(t,o,e){let r=typeof o=="string"?o:void 0,n=(typeof o=="object"?o:e)||{},i=r?M.resolve(r):M.resolve(n.root||process.cwd()),a=n.root?M.resolve(n.root):i,c=n.ignore?[n.ignore]:void 0,s=await _(i,{level:2,rootPath:a,ignore:c,noCache:n.noCache}),p=Array.from(s.files.values()),m=ee(p,t,{kind:n.kind});n.json?console.log(y(m)):console.log(oe(t,m))}import Io from"path";function ze(t,o={}){let e=Io.resolve(t),r,n;if(o.lines){let a=o.lines.split("-").map(c=>parseInt(c.trim(),10));a.length===2&&!isNaN(a[0])&&!isNaN(a[1])?(r=a[0],n=a[1]):a.length===1&&!isNaN(a[0])&&(r=a[0])}let i=re(e,{startLine:r,endLine:n});i===null&&(console.error(`[glyphier] Error: file not found: ${t}`),process.exit(1)),console.log(i)}import Do from"path";async function Ue(t,o={}){let e=Do.resolve(o.root||process.cwd()),r=o.depth?parseInt(o.depth,10):2;try{let n=await ne(t,{rootPath:e,depth:r});o.json?console.log(y(n)):console.log(se(n))}catch(n){console.error(`Error analyzing impact: ${String(n)}`),process.exit(1)}}import No from"path";async function qe(t,o={}){let e=No.resolve(o.root||process.cwd()),r=o.since||"HEAD";try{let n=await ie(t,{since:r,rootPath:e});o.json?console.log(y(n)):console.log(ae(n))}catch(n){console.error(`Error diffing file: ${String(n)}`),process.exit(1)}}import z from"fs";import To from"path";async function Be(t,o={}){let e=To.resolve(o.root||process.cwd()),r=o.patch||"";!r&&!process.stdin.isTTY?r=z.readFileSync(0,"utf-8"):r&&z.existsSync(r)&&(r=z.readFileSync(r,"utf-8")),r||(console.error("Error: patch or code content is required via --patch <file|string> or stdin."),process.exit(1));try{let n=await me(t,r,{rootPath:e});o.json?console.log(y(n)):console.log(ce(n)),n.valid||process.exit(1)}catch(n){console.error(`Error checking patch: ${String(n)}`),process.exit(1)}}import Ye from"path";async function Ke(t,o={}){let e=Ye.resolve(o.root||process.cwd()),r=Ye.resolve(e,t);try{let n=await fe(r,{rootPath:e});o.json?console.log(y(n)):console.log(ge(n))}catch(n){console.error(`Error analyzing module graph: ${String(n)}`),process.exit(1)}}import _o from"path";async function We(t,o,e={}){let r=e.depth?parseInt(e.depth,10):2,n=_o.resolve(o||process.cwd());try{let i=await ue(n,t,{depth:r,targetSymbol:e.target});e.json?console.log(JSON.stringify(i,null,2)):console.log(le(i))}catch(i){console.error(`Error computing program slice: ${i.message}`),process.exit(1)}}import Vo from"path";async function Xe(t,o,e={}){let r=Vo.resolve(t);try{let n=await ye(r,o,{dryRun:e.dryRun});e.json?console.log(JSON.stringify(n,null,2)):n.success?console.log(`\u2713 Applied ${n.appliedOps} patch operation(s) to ${n.file}`):(console.error(`\u2717 Patch failed: ${n.error}`),process.exit(1))}catch(n){console.error(`Error applying patch: ${n.message}`),process.exit(1)}}function Ze(){console.log("Glyphier v3.0.0 \u2014 The Code Representation Engine for AI Agents"),console.log("https://glyphier.com"),console.log(),console.log("Supported Language Grammars (Tree-sitter WASM):");let t=Z();console.log(` ${t.join(", ")}`),console.log(),console.log("MCP Tools: glyphier_explore, glyphier_view, glyphier_search, glyphier_read_raw ")}import Jo from"path";async function Qe(t,o={}){let e=Jo.resolve(o.root||process.cwd()),r=t||".",n=o.top?parseInt(o.top,10):5;try{let i=await Se(r,{rootPath:e,topN:n});o.json?console.log(JSON.stringify(i,null,2)):console.log(ve(i))}catch(i){console.error(`Error computing stats: ${String(i)}`),process.exit(1)}}import j from"fs";import Fo from"os";import b from"path";var Go=["codex","claude-code","cursor","gemini-cli","windsurf"];function eo(){return process.env.GLYPHIER_CONFIG_HOME||Fo.homedir()}function q(t){let o=eo();return{codex:{host:t,path:b.join(o,".codex","config.toml"),format:"toml"},"claude-code":{host:t,path:b.join(o,".claude.json"),format:"json"},cursor:{host:t,path:b.join(o,".cursor","mcp.json"),format:"json"},"gemini-cli":{host:t,path:b.join(o,".gemini","settings.json"),format:"json"},windsurf:{host:t,path:b.join(o,".codeium","windsurf","mcp_config.json"),format:"json"},universal:{host:t,path:b.join(o,".config","glyphier","mcp.json"),format:"json"}}[t]}function B(t){let e={claude:"claude-code",claude_code:"claude-code",gemini:"gemini-cli",gemini_cli:"gemini-cli"}[t.toLowerCase()]??t.toLowerCase();if(![...Go,"universal"].includes(e))throw new Error(`Unsupported agent host: ${t}`);return e}function oo(t){let o=b.resolve(eo()),e=b.resolve(t),r=b.resolve(process.cwd());if(e!==o&&!e.startsWith(`${o}${b.sep}`))throw new Error("Glyphier configuration must be written in the user-level configuration directory.");if(e===r||e.startsWith(`${r}${b.sep}`))throw new Error("Glyphier refuses to write API credentials into the current repository or workspace.");for(let n=b.dirname(e);n!==b.dirname(n);n=b.dirname(n))if(j.existsSync(b.join(n,".git")))throw new Error("Glyphier refuses to write credentials into a source-controlled directory.")}function Lo(t){return{command:"npx",args:["-y",`@glyphier/cli@${A}`,"mcp"],env:{GLYPHIER_API_KEY:t,GLYPHIER_API_URL:"https://glyphier.com"}}}function Ho(t,o){let e={};if(t.trim())try{e=JSON.parse(t)}catch{throw new Error("Existing host configuration is not valid JSON; Glyphier will not overwrite it.")}let r=e.mcpServers&&typeof e.mcpServers=="object"&&!Array.isArray(e.mcpServers)?e.mcpServers:{};return`${JSON.stringify({...e,mcpServers:{...r,glyphier:Lo(o)}},null,2)}
3
+ `}function to(t){return`# BEGIN GLYPHIER MCP \u2014 managed by glyphier install
4
+ [mcp_servers.glyphier]
5
+ command = "npx"
6
+ args = ["-y", "@glyphier/cli@${A}", "mcp"]
7
+ env = { GLYPHIER_API_KEY = "${t}", GLYPHIER_API_URL = "https://glyphier.com" }
8
+ # END GLYPHIER MCP
9
+ `}function Mo(t,o){let e=/# BEGIN GLYPHIER MCP — managed by glyphier install[\s\S]*?# END GLYPHIER MCP\n?/g;return`${t.replace(e,"").trimEnd()}${t.trim()?`
10
+
11
+ `:""}${to(o)}`}function ro(t,o){if(oo(t.path),j.mkdirSync(b.dirname(t.path),{recursive:!0,mode:448}),j.existsSync(t.path)){let r=`${t.path}.glyphier-backup-${Date.now()}`;j.copyFileSync(t.path,r),j.chmodSync(r,384)}let e=`${t.path}.glyphier-tmp-${process.pid}`;j.writeFileSync(e,o,{encoding:"utf8",mode:384}),j.renameSync(e,t.path),j.chmodSync(t.path,384)}function no(t){return oo(t.path),j.existsSync(t.path)?j.readFileSync(t.path,"utf8"):""}function U(){return JSON.stringify({mcpServers:{glyphier:{command:"npx",args:["-y",`@glyphier/cli@${A}`,"mcp"],env:{GLYPHIER_API_KEY:"<your-paid-api-key>",GLYPHIER_API_URL:"https://glyphier.com"}}}},null,2)}async function zo(t){let o=await fetch("https://glyphier.com/api/v1/agent/onboarding/exchange",{method:"POST",headers:{"content-type":"application/json","cache-control":"no-store"},body:JSON.stringify({installationToken:t})});if(!o.ok)throw new Error("Installation grant was rejected. Request a new grant from Glyphier onboarding.");let e=await o.json();if(!e.apiKey||!e.apiUrl)throw new Error("Installation grant response was invalid.");return{apiKey:e.apiKey,apiUrl:e.apiUrl}}async function io(t){if(t.universal){process.stdout.write(`${U()}
12
+ `);return}let o=B(t.agent),e=q(o),r=no(e);if(t.dryRun){process.stdout.write(`Glyphier would update ${e.path} (${e.format}) with its MCP entry only. Existing configuration will be backed up.
13
+ `);return}if(!t.onboardingTokenStdin)throw new Error("glyphier install requires --onboarding-token-stdin; grants must never be supplied as command arguments.");let n=j.readFileSync(0,"utf8").trim();if(!n)throw new Error("No installation grant was provided on stdin.");let{apiKey:i}=await zo(n),a=e.format==="json"?Ho(r,i):Mo(r,i);ro(e,a),process.stdout.write(`Glyphier installed for ${o}. The paid API key was stored only in ${e.path}. Run: glyphier doctor --agent ${o}
14
+ `)}function so(t){if(t.universal)return process.stdout.write(`${U()}
15
+ `);let o=B(t.agent);if(q(o).format==="toml"){process.stdout.write(to("<your-paid-api-key>"));return}process.stdout.write(`${U()}
16
+ `)}function ao(t){let o=q(B(t.agent)),e=no(o);if(!e)return process.stdout.write(`No Glyphier configuration found for ${o.host}.
17
+ `);let r;if(o.format==="toml")r=e.replace(/# BEGIN GLYPHIER MCP — managed by glyphier install[\s\S]*?# END GLYPHIER MCP\n?/g,"");else{let n;try{n=JSON.parse(e)}catch{throw new Error("Existing host configuration is not valid JSON; Glyphier will not modify it.")}let i={...n.mcpServers};delete i.glyphier,r=`${JSON.stringify({...n,mcpServers:i},null,2)}
18
+ `}ro(o,r),process.stdout.write(`Removed only the Glyphier MCP entry from ${o.path}.
19
+ `)}import Uo from"path";async function co(t,o){let e=Uo.resolve(o.root||process.cwd()),r=h(e),n=o.depth?parseInt(o.depth,10):2,i=o.direction||"both",a=J(t,{storage:r,direction:i,depth:n});o.json?console.log(JSON.stringify(a,null,2)):console.log(xe(a))}import qo from"path";async function lo(t,o){let e=qo.resolve(o.root||process.cwd()),r=h(e),n=o.budget?parseInt(o.budget,10):2500;if(o.format){let a=t.toLowerCase().replace(/[^a-z0-9_\-]/g," ").split(/\s+/).filter(p=>p.length>2),c=[];for(let p of a){let m=r.findSymbols(p);c.push(...m)}let s=$({task:t,rootPath:e,tokenBudget:n,candidateSymbols:c});console.log(F(s.contextArtifact,o.format));return}let i=await Pe({task:t,budget:n,rootPath:e,sessionId:o.session,storage:r});o.json?console.log(JSON.stringify(i,null,2)):console.log(i.renderedContext)}import Bo from"path";async function po(t,o={}){let e=Bo.resolve(o.root||process.cwd()),r=h(e),n=new I(r);if(o.record){let i=o.record,a=o.category||(t&&t!=="record"?t:"invariant"),c=o.confidence?parseFloat(o.confidence):.9,s={start:1,end:1};if(o.lines){let l=o.lines.split("-");s={start:parseInt(l[0],10),end:parseInt(l[1]||l[0],10)}}let p=o.file?[{file:o.file,startLine:s.start,endLine:s.end}]:[],m=n.addFact({statement:i,category:a,confidence:c,provenance:p});o.json?console.log(JSON.stringify(m,null,2)):(console.log(`\u2713 Recorded fact in memory [${m.category}] (${(m.confidence*100).toFixed(0)}%):`),console.log(` "${m.statement}"`));return}if(o.query){let i=n.findFacts(o.query);if(o.json)console.log(JSON.stringify(i,null,2));else if(i.length===0)console.log(`No memory facts matched query: "${o.query}"`);else for(let a of i)console.log(`[${a.category}] (${(a.confidence*100).toFixed(0)}%) "${a.statement}"`);return}o.json?console.log(JSON.stringify(n.getFacts(t),null,2)):console.log(n.formatMemorySExpr(t))}import Yo from"path";async function mo(t,o){let e=Yo.resolve(o.root||t||process.cwd()),r=h(e),n=await we(e,{storage:r,force:o.force});o.json?console.log(JSON.stringify(n,null,2)):console.log(`\u2713 Indexed ${n.indexedFiles} files, skipped ${n.skippedFiles} unchanged, pruned ${n.deletedFiles} in ${n.durationMs}ms.`)}import Ko from"path";async function fo(t,o,e={}){let r=Ko.resolve(e.root||process.cwd()),n=await Re(t,{filePath:o,rootPath:r});if(e.json){console.log(JSON.stringify(n,null,2)),n.success||process.exit(1);return}if(n.success&&n.symbol&&n.content!==void 0){let i=n.symbol;console.log(`// [${i.kind}] ${i.qualifiedName||i.name} (${i.filePath}:${i.startLine}-${i.endLine})`),console.log(n.content);return}if(n.ambiguous&&n.candidates){console.error(`Found ${n.candidates.length} symbols matching "${t}":`);for(let i of n.candidates)console.error(` - [${i.kind}] ${i.qualifiedName||i.name} (${i.filePath}:${i.startLine}-${i.endLine})`);console.error(`
20
+ To read a specific symbol, provide the file path:`),console.error(` glyphier read-symbol "${t}" <filePath>`),process.exit(1)}console.error(n.message||`Symbol "${t}" not found.`),process.exit(1)}import{execSync as So}from"child_process";import{createHash as K}from"crypto";import T from"path";import{z as d}from"zod";import{createHash as et}from"crypto";import{z as w}from"zod";var Wo=w.object({patterns:w.array(w.string()),gitignoreApplied:w.boolean(),configuredPaths:w.array(w.string()).optional()}),Xo=w.enum(["clean","dirty","untracked","generated","unknown"]),Y=w.object({repositoryId:w.string(),repositoryName:w.string(),rootPath:w.string(),headRef:w.string().nullable(),baseRef:w.string().nullable().optional(),indexState:Xo,ignorePolicy:Wo,capturedAt:w.string().datetime(),schemaVersion:w.literal("1.0.0")});import{z as x}from"zod";var Zo=x.object({language:x.string(),grammarVersion:x.string(),wasmChecksum:x.string().optional()}),go=x.object({cliVersion:x.string(),parserVersions:x.array(Zo),rankingVersion:x.string(),riskPolicyVersion:x.string(),budgetPolicyVersion:x.string(),capabilityFlags:x.record(x.string(),x.boolean()),fingerprintHash:x.string(),schemaVersion:x.literal("1.0.0")});import{z as S}from"zod";var Qo=S.object({symbol:S.string(),reason:S.enum(["dynamic_dispatch","macro_expansion","reflection","external_module","parse_failure","timeout"]),originPath:S.string()}),uo=S.object({parseCoverage:S.number().min(0).max(1),parseFailures:S.array(S.object({path:S.string(),reason:S.string()})),unresolvedEdges:S.array(Qo),skippedPaths:S.array(S.object({path:S.string(),reason:S.enum(["ignored","too_large","binary","generated","permission_denied","external"])})),hasDynamicBoundaries:S.boolean(),coverageTier:S.enum(["high","medium","low","minimal"]),schemaVersion:S.literal("1.0.0")});var ot=d.enum(["added","modified","deleted","renamed"]),ho=d.enum(["public_api","internal_logic","test_surface","config_surface","schema_surface","docs_surface"]),tt=d.object({id:d.string(),name:d.string(),filePath:d.string(),changeKind:ot,surface:ho,startLine:d.number().int().positive(),endLine:d.number().int().positive(),signatureBefore:d.string().optional(),signatureAfter:d.string().optional(),isBreaking:d.boolean().default(!1),evidenceRefId:d.string().optional()}),rt=d.object({sourceSymbolId:d.string(),targetSymbolId:d.string(),targetFilePath:d.string(),depth:d.number().int().positive(),confidence:d.number().min(0).max(1),isTransitive:d.boolean(),evidenceRefId:d.string().optional()}),nt=d.object({pairedTestPaths:d.array(d.string()).default([]),affectedIntegrationTests:d.array(d.string()).default([]),untestedChangedSymbols:d.array(d.string()).default([]),coverageGapDetected:d.boolean().default(!1)}),yn=d.object({reviewId:d.string(),baseSnapshot:Y,headSnapshot:Y,diffDigest:d.string(),compilerFingerprint:go,changedSymbols:d.array(tt),impactEdges:d.array(rt),affectedSurfaces:d.array(ho),testCoverage:nt,riskAssessment:je,coverage:uo,evidenceRefs:d.array(Ae),ciReceiptHash:d.string(),compiledAt:d.string().datetime(),schemaVersion:d.literal("1.0.0").default("1.0.0")});function yo(t){let e=JSON.stringify(t,(r,n)=>{if(n&&typeof n=="object"&&!Array.isArray(n)){let i={};for(let a of Object.keys(n).sort())i[a]=n[a];return i}return n});return et("sha256").update(e).digest("hex")}function vo(t){let o=process.cwd(),e=t.base,r=t.head||"HEAD",n="",i=[];try{n=So(`git diff ${e}...${r}`,{cwd:o,encoding:"utf8",maxBuffer:10*1024*1024}),i=So(`git diff --name-status ${e}...${r}`,{cwd:o,encoding:"utf8"}).trim().split(`
21
+ `).filter(Boolean)}catch(C){console.error(`Error calculating git diff between ${e} and ${r}:`,String(C)),process.exit(1)}let a=K("sha256").update(n).digest("hex"),c=[],s=new Set,p=[];for(let C of i){let[X,v]=C.split(/\s+/);if(!v)continue;let O="internal_logic";v.endsWith(".test.ts")||v.endsWith(".spec.ts")||v.includes("test/")?(O="test_surface",p.push(v)):v.includes("config")||v.endsWith(".json")||v.endsWith(".yaml")?O="config_surface":v.endsWith(".md")?O="docs_surface":v.includes("schema")||v.includes("migrations/")?O="schema_surface":(v.includes("index.ts")||v.includes("public/"))&&(O="public_api"),s.add(O),c.push({id:`sym-${K("sha256").update(v).digest("hex").slice(0,12)}`,name:T.basename(v),filePath:v,changeKind:X==="A"?"added":X==="D"?"deleted":"modified",surface:O,startLine:1,endLine:1,isBreaking:O==="public_api"||O==="schema_surface"})}let m=c.some(C=>C.isBreaking),l=m?"high":c.length>10?"medium":"low",u=l,N={reviewId:`review-${K("sha256").update(`${e}:${r}:${a}`).digest("hex").slice(0,16)}`,baseSnapshot:{repositoryId:T.basename(o),repositoryName:T.basename(o),rootPath:o,headRef:e,indexState:"clean",ignorePolicy:{patterns:["node_modules"],gitignoreApplied:!0},capturedAt:new Date().toISOString(),schemaVersion:"1.0.0"},headSnapshot:{repositoryId:T.basename(o),repositoryName:T.basename(o),rootPath:o,headRef:r,indexState:"clean",ignorePolicy:{patterns:["node_modules"],gitignoreApplied:!0},capturedAt:new Date().toISOString(),schemaVersion:"1.0.0"},diffDigest:a,compilerFingerprint:{cliVersion:"4.1.0",parserVersions:[{language:"typescript",grammarVersion:"0.23.0"}],rankingVersion:"1.0.0",riskPolicyVersion:"1.0.0",budgetPolicyVersion:"1.0.0",capabilityFlags:{corpus_compiler:!0,memory:!0},fingerprintHash:"sha256:review-compiler",schemaVersion:"1.0.0"},changedSymbols:c,impactEdges:[],affectedSurfaces:Array.from(s),testCoverage:{pairedTestPaths:p,affectedIntegrationTests:[],untestedChangedSymbols:c.filter(C=>C.surface==="public_api"&&p.length===0).map(C=>C.id),coverageGapDetected:p.length===0&&c.length>0},riskAssessment:{intrinsicRisk:l,effectiveRisk:u,affectedSurfaces:Array.from(s).map(C=>({type:C==="public_api"?"public_api":"internal",path:o})),policyDecision:m?"review_required":"proceed",requiresHumanReview:m,reviewDomains:m?["api_review","qa"]:[],schemaVersion:"1.0.0"},coverage:{parseCoverage:1,parseFailures:[],unresolvedEdges:[],skippedPaths:[],hasDynamicBoundaries:!1,coverageTier:"high",schemaVersion:"1.0.0"},evidenceRefs:[],compiledAt:new Date().toISOString(),schemaVersion:"1.0.0"},R=yo(N),P={...N,ciReceiptHash:R};if(t.json){console.log(JSON.stringify(P,null,2));return}console.log(`
22
+ \u{1F4CB} Glyphier Review (${e}...${r})`),console.log(`Review ID: ${P.reviewId}`),console.log(`CI Receipt Hash: ${P.ciReceiptHash}
23
+ `),console.log(`Risk Assessment: ${P.riskAssessment.effectiveRisk.toUpperCase()} (Decision: ${P.riskAssessment.policyDecision})`),console.log(`Changed Files: ${P.changedSymbols.length}`),console.log(`Surfaces Affected: ${P.affectedSurfaces.join(", ")||"none"}`),console.log(`Test Coverage: ${P.testCoverage.coverageGapDetected?"\u26A0\uFE0F Coverage gap detected":"\u2705 Paired tests identified"}`),console.log()}import it from"path";async function bo(t,o){let e=it.resolve(o.root||process.cwd()),r=h(e),n=o.budget?parseInt(o.budget,10):2500,i=t.toLowerCase().replace(/[^a-z0-9_\-]/g," ").split(/\s+/).filter(s=>s.length>2),a=[];for(let s of i){let p=r.findSymbols(s);a.push(...p)}let c=$({task:t,rootPath:e,tokenBudget:n,candidateSymbols:a});o.format?console.log(F(c.contextArtifact,o.format)):o.json?console.log(JSON.stringify(c,null,2)):console.log(c.renderedPlan)}import st from"path";async function wo(t,o){let e=st.resolve(o.root||process.cwd()),r=o.budget?parseInt(o.budget,10):2500,n=$({task:t,rootPath:e,tokenBudget:r}),i=ke({priorArtifact:n.contextArtifact,feedback:o.feedback,failedVerification:o.failedVerification});o.json?console.log(JSON.stringify(i,null,2)):console.log(i.renderedDeltaSummary)}import xo from"path";async function Po(t,o){let e=xo.resolve(o.root||process.cwd()),r=h(e),n=new I(r),i=J(t,{storage:r,direction:"both",depth:1}),a=i.nodes.filter(l=>l.depth===1&&l.symbol.name!==t).map(l=>l.symbol.name),c=i.nodes.filter(l=>l.depth===-1).map(l=>l.symbol.name),p=n.getFacts().filter(l=>l.statement.toLowerCase().includes(t.toLowerCase())).map(l=>({id:l.id,statement:l.statement,claimType:l.category==="decision"?"decision":"fact",repositoryId:xo.basename(e),branchScope:null,evidenceRefs:[],validationStatus:l.verifiedAt?"validated":"unvalidated",expiresAt:null,lastValidatedAt:null,createdAt:new Date(l.createdAt).toISOString(),schemaVersion:"1.0.0"})),m=Ee({symbolName:t,callers:a,callees:c,memoryRecords:p,docAssertions:[]});o.json?console.log(JSON.stringify(m,null,2)):console.log(m.renderedExplanation)}import D from"fs";import E from"path";async function Co(t,o={}){let e=E.resolve(o.root||process.cwd()),r=t?E.resolve(e,t):E.join(e,"docs"),n=[];if(D.existsSync(r)){let c=D.statSync(r).isDirectory()?D.readdirSync(r,{recursive:!0}).filter(s=>String(s).endsWith(".md")).map(s=>E.join(r,String(s))):[r];for(let s of c){if(!D.existsSync(s))continue;let p=D.readFileSync(s,"utf8"),m=E.relative(e,s),l=De(m),u=[];p.split(`
24
+ `).forEach((R,P)=>{(R.includes("Invariant I-")||R.includes("ADR ")||R.includes("MUST ")||R.includes("Rule:"))&&u.push({id:`assert-${P+1}`,statement:R.trim().replace(/^[-*#>\s]+/,""),assertionType:"invariant",rationaleLink:"EXTRACTED",status:"verified",docStartLine:P+1,docEndLine:P+1,evidenceRefs:[],confidence:1})}),n.push({documentId:Ne(E.basename(e),m,"digest"),repositoryId:E.basename(e),path:m,title:E.basename(s),authorityTier:l,authorityScore:Ie[l],digest:"content-digest",sections:[],assertions:u,snapshotRef:"HEAD",capturedAt:new Date().toISOString(),schemaVersion:"1.0.0"})}}let i=$e(n,e,D.existsSync);o.json?console.log(JSON.stringify(i,null,2)):console.log(i.renderedReport)}import W from"path";import{createHash as at}from"crypto";async function jo(t,o={}){let e=W.resolve(o.root||process.cwd()),r=h(e),n=new I(r),i=o.type||"fact",a=o.confidence?parseFloat(o.confidence):i==="inference"?.8:void 0,c={id:`mem-${at("sha256").update(`${i}:${t}`).digest("hex").slice(0,12)}`,statement:t,claimType:i,repositoryId:W.basename(e),branchScope:null,evidenceRefs:o.evidencePath?[{id:"ev-1",sourceType:"source_file",path:o.evidencePath,snapshotRef:`${W.basename(e)}:HEAD`,retrievalReason:"User specified evidence path",freshness:"fresh",schemaVersion:"1.0.0"}]:[],confidence:a,validationStatus:"unvalidated",expiresAt:null,createdAt:new Date().toISOString(),lastValidatedAt:null,schemaVersion:"1.0.0"},s=Te(c);if(!s.admitted){console.error("\u274C Memory admission rejected:");for(let p of s.errors)console.error(` - ${p}`);process.exit(1)}if(n.addFact({category:o.category||(i==="decision"?"decision":"architecture"),statement:t,confidence:a??1,provenance:[{file:o.evidencePath||"manual-entry",startLine:1,endLine:1}]}),console.log(`\u2705 Memory recorded (${i}): "${t}"`),s.warnings.length>0)for(let p of s.warnings)console.log(` \u26A0\uFE0F Warning: ${p}`)}import k from"path";import Ro from"fs";async function Oo(t,o={}){let e=k.resolve(o.root||process.cwd()),r=h(e),n=o.title||`${t.toUpperCase()} Documentation`,a=r.findSymbols(o.scope||"").slice(0,10).map(s=>({name:s.name,filePath:s.filePath,isExported:s.isExported,kind:s.kind,startLine:s.startLine,endLine:s.endLine})),c=L({kind:t||"architecture",title:n,rootPath:e,snapshot:{repositoryId:k.basename(e),repositoryName:k.basename(e),rootPath:e,headRef:"HEAD",indexState:"clean",ignorePolicy:{patterns:["node_modules"],gitignoreApplied:!0},capturedAt:new Date().toISOString(),schemaVersion:"1.0.0"},fingerprint:{cliVersion:A,parserVersions:[{language:"typescript",grammarVersion:"0.23.0"}],rankingVersion:"1.0.0",riskPolicyVersion:"1.0.0",budgetPolicyVersion:"1.0.0",capabilityFlags:{doc_compiler:!0},fingerprintHash:"sha256:doc-compiler",schemaVersion:"1.0.0"},includedSymbols:a});o.json?console.log(JSON.stringify(c,null,2)):(console.log(`
25
+ \u{1F4CB} Documentation Plan: ${c.planId}`),console.log(`Kind: ${c.kind.toUpperCase()} | Title: ${c.title}`),console.log(`Target Symbols (${c.targetSymbols.length}): ${c.targetSymbols.join(", ")||"General"}`),console.log(`Assertions to validate: ${c.assertionsToValidate.length}`),console.log(`
26
+ Sections:
27
+ ${c.outlineSections.map(s=>` - ${s}`).join(`
28
+ `)}
29
+ `))}async function Ao(t,o={}){let e=k.resolve(o.root||process.cwd()),r=h(e),n=o.title||`${t.toUpperCase()} Documentation`,a=r.findSymbols(o.scope||"").slice(0,10).map(l=>({name:l.name,filePath:l.filePath,isExported:l.isExported,kind:l.kind,startLine:l.startLine,endLine:l.endLine})),c={repositoryId:k.basename(e),repositoryName:k.basename(e),rootPath:e,headRef:"HEAD",indexState:"clean",ignorePolicy:{patterns:["node_modules"],gitignoreApplied:!0},capturedAt:new Date().toISOString(),schemaVersion:"1.0.0"},s={cliVersion:A,parserVersions:[{language:"typescript",grammarVersion:"0.23.0"}],rankingVersion:"1.0.0",riskPolicyVersion:"1.0.0",budgetPolicyVersion:"1.0.0",capabilityFlags:{doc_compiler:!0},fingerprintHash:"sha256:doc-compiler",schemaVersion:"1.0.0"},p=L({kind:t||"architecture",title:n,rootPath:e,snapshot:c,fingerprint:s,includedSymbols:a}),m=Ve(p,c,s);o.json?console.log(JSON.stringify(m,null,2)):console.log(m.content)}async function ko(t,o={}){let e=k.resolve(o.root||process.cwd()),r=h(e),n=k.resolve(e,t);if(!Ro.existsSync(n)){console.error(`Error: Documentation file not found: ${n}`),process.exitCode=1;return}let i=Ro.readFileSync(n,"utf8"),a=_e(i,n,e),s=Je(a,{symbolExists(p,m){let l=r.findSymbols(p);return m?l.some(u=>u.name===p&&(u.filePath===m||u.filePath.endsWith(m))):l.some(u=>u.name===p)},isSymbolExported(p,m){let l=r.findSymbols(p);return m?l.some(u=>u.name===p&&u.isExported&&(u.filePath===m||u.filePath.endsWith(m))):l.some(u=>u.name===p&&u.isExported)},callsSymbol(p,m){let l=r.findSymbols(p);for(let u of l){let N=r.getOutgoingEdges(u.id,"calls");for(let R of N)if(R.targetId===m||R.targetId.includes(m))return!0}return!1}});if(o.json)console.log(JSON.stringify(s,null,2));else if(console.log(`
30
+ \u{1F50D} Documentation Validation Report: ${k.basename(n)}`),console.log(`Total Assertions: ${a.assertions?a.assertions.length:0}`),console.log(` \u2713 Valid: ${s.validCount}`),console.log(` \u2717 Outdated: ${s.outdatedCount}`),console.log(` ? Unverified: ${s.unverifiedCount}`),s.outdatedCount>0){console.log(`
31
+ \u26A0\uFE0F Outdated Assertions Detected:`);for(let p of s.updatedAssertions)p.status==="outdated"&&console.log(` - [${p.type.toUpperCase()}] ${p.claim}`)}else console.log(`
32
+ \u2728 All structured assertions passed verification!`)}import ct from"path";async function Eo(t,o){let e=ct.resolve(o.root??t??process.cwd()),r=Ce({rootPath:e});if(o.json){console.log(y(r));return}console.log(["(analysis-snapshot",` :id ${r.snapshotId}`,` :authority ${r.sourceAuthority}`,` :head ${r.headRef??"none"}`,` :freshness ${r.freshness}`,` :schema ${r.schemaVersion})`].join(`
33
+ `))}function $o(){let t=new lt;t.name("glyphier").description("Glyphier 0.1: evidence-governed semantic context for engineering agents.").version(A),t.hook("preAction",async(e,r)=>{["install","config","doctor","uninstall"].includes(r.name())||await be()}),t.command("snapshot [path]").description("Publish an immutable, provenance-bearing AnalysisSnapshot").option("-r, --root <path>","Project root directory").option("--json","Output the typed AnalysisSnapshot as JSON").action(async(e,r)=>{await Eo(e,r)}),t.command("explore [path]").description("Get a compact Prefix-Trie view of the project directory tree, or auto-zoom under a token budget").option("-d, --depth <n>","Maximum directory depth").option("-l, --level <0|1>","Detail level (0 = tree only, 1 = tree + skeletons)","0").option("-b, --budget <tokens>","Strict token budget (e.g. 1500) for adaptive PageRank auto-zoom").option("-r, --root <path>","Project root directory").option("-i, --ignore <glob>","Additional ignore glob pattern").option("--no-cache","Disable mtime cache").option("--json","Output as JSON").action(async(e,r)=>{await Le(e,r)}),t.command("view <file>").description("Get the S-expression intermediate representation of a file").option("-l, --level <1|2>","Detail level (1 = signatures only, 2 = full graph)","2").option("-s, --session <id>","Session identifier for multi-turn delta compression").option("-r, --root <path>","Project root directory").option("--no-cache","Disable mtime cache").option("--json","Output as JSON").action(async(e,r)=>{await He(e,r)}),t.command("search <query> [path]").description("Semantic grep across project IR for functions, types, calls, decorators, or states").option("-k, --kind <calls|fn|type|use|route|var|all>","Filter results by symbol kind (calls, fn, type, use, route, var, all)").option("-r, --root <path>","Project root directory").option("-i, --ignore <glob>","Additional ignore glob pattern").option("--no-cache","Disable mtime cache").option("--json","Output as JSON").action(async(e,r,n)=>{await Me(e,r,n)}),t.command("read-raw <file>").description("Read raw source code with line numbers for a specific line range").option("-l, --lines <start-end>","Line range to read, e.g. 15-45").action((e,r)=>{ze(e,r)}),t.command("read-symbol <symbol> [file]").description("Directly extract the raw source code of a symbol without guessing line numbers").option("-r, --root <path>","Project root directory").option("--json","Output as JSON").action(async(e,r,n)=>{await fo(e,r,n)}),t.command("impact <symbol>").description("Evaluate blast radius / reverse callers of modifying or renaming a symbol").option("-d, --depth <n>","Maximum transitive depth (default: 2)").option("-r, --root <path>","Project root directory").option("--json","Output as JSON").action(async(e,r)=>{await Ue(e,r)}),t.command("diff <file>").description("Get a semantic AST diff of a file against a git revision (85% fewer tokens than git diff)").option("-s, --since <rev>","Git revision to compare against (default: HEAD)").option("-r, --root <path>","Project root directory").option("--json","Output as JSON").action(async(e,r)=>{await qe(e,r)}),t.command("check <file>").description("Pre-flight check: validate proposed code or patch for AST syntax errors before writing").option("-p, --patch <patchOrFile>","Patch string or path to patch file (or via stdin)").option("-r, --root <path>","Project root directory").option("--json","Output as JSON").action(async(e,r)=>{await Be(e,r)}),t.command("graph <path>").description("Analyze subsystem architectural dependency graph (queues, processors, external modules, service calls)").option("-r, --root <path>","Project root directory").option("--json","Output as JSON").action(async(e,r)=>{await Ke(e,r)}),t.command("slice <symbol> [path]").description("Extract a targeted multi-file program slice tracing call paths for a specific symbol").option("-d, --depth <n>","Maximum traversal depth (default: 2)").option("-t, --target <symbol>","Target destination symbol").option("--json","Output as JSON").action(async(e,r,n)=>{await We(e,r,n)}),t.command("patch <file> <expression>").description("Apply an AST-native structural patch with pre-flight syntax validation").option("--dry-run","Validate and preview patch without writing to disk").option("--json","Output as JSON").action(async(e,r,n)=>{await Xe(e,r,n)}),t.command("stats [path]").description("Compute token density, compression ratios, and pricing analytics across codebase").option("-r, --root <path>","Project root directory").option("-t, --top <n>","Number of heaviest files to display","5").option("--json","Output as JSON").action(async(e,r)=>{await Qe(e,r)}),t.command("mcp").description("Start the Model Context Protocol (MCP) server over stdio").option("-r, --root <path>","Project root directory to serve").action(async e=>{await Fe({rootDir:e.root})}),t.command("install").description("Install Glyphier MCP in a user-level agent configuration").option("--agent <host>","codex, claude-code, cursor, gemini-cli, windsurf, or universal").option("--onboarding-token-stdin","Read the one-time installation grant from stdin").option("--dry-run","Preview the exact user-level configuration change").option("--universal","Print standards-compliant MCP configuration without writing files").action(async e=>{await io(e)}),t.command("config").description("Print a host-specific or universal MCP configuration template").option("--agent <host>","Agent host").option("--universal","Print universal MCP configuration").action(e=>{if(!e.universal&&!e.agent)throw new Error("Provide --agent <host> or --universal.");so(e)}),t.command("uninstall").description("Remove only Glyphier-owned MCP configuration from an agent host").requiredOption("--agent <host>","Agent host").action(e=>{ao(e)}),t.command("info").description("Display version and supported language grammars").action(()=>{Ze()}),t.command("trace <symbol>").description("Trace callers and callees of a symbol through the symbol graph").option("-d, --depth <n>","Traversal depth (default: 2)").option("--direction <callers|callees|both>","Direction of traversal (default: both)").option("-r, --root <path>","Project root directory").option("--json","Output as JSON").action(async(e,r)=>{await co(e,r)}),t.command("context <task>").description("Assemble a minimally sufficient semantic context for a task under a token budget").option("-b, --budget <tokens>","Strict token budget (default: 2500)").option("-s, --session <id>","Session identifier for deduplication").option("-f, --format <format>","Agent client output format (claude, cursor, antigravity, json, text)").option("-r, --root <path>","Project root directory").option("--json","Output as JSON").action(async(e,r)=>{await lo(e,r)}),t.command("memory [category]").description("Inspect, query, or record persistent repository architectural facts and invariants").option("-q, --query <text>","Search query across memory facts").option("--record <statement>","Record a new architectural fact or invariant into memory").option("-c, --category <cat>","Category for recorded fact (architecture, invariant, convention, integration, decision)").option("--confidence <n>","Confidence score 0.0 to 1.0 (default: 0.9)").option("--file <path>","Associated file provenance").option("-l, --lines <start-end>","Associated line range").option("-r, --root <path>","Project root directory").option("--json","Output as JSON").action(async(e,r)=>{await po(e,r)}),t.command("index [path]").description("Incrementally index repository ASTs, symbol table, and edges into SQLite").option("--force","Force re-indexing all files").option("-r, --root <path>","Project root directory").option("--json","Output as JSON").action(async(e,r)=>{await mo(e,r)}),t.command("doctor").description("Run installation diagnostics, health checks, and generate support bundles").option("--json","Output diagnostics as JSON").option("--bundle","Generate a sanitized, redacted support bundle archive").action(e=>{Oe(e)}),t.command("review").description("Compile a structured, evidence-backed review artifact between base and head refs").requiredOption("-b, --base <ref>","Base git revision (e.g. main, v1.0.0)").option("-h, --head <ref>","Head git revision (defaults to HEAD)").option("--json","Output ReviewArtifact as JSON").action(e=>{vo(e)}),t.command("plan <task>").description("Compile a structured task plan with entrypoints, budget allocation, effective risk, and mutation envelope").option("-b, --budget <tokens>","Token budget (default: 2500)").option("-f, --format <format>","Agent client output format (claude, cursor, antigravity, json, text)").option("-r, --root <path>","Project root directory").option("--json","Output Plan as JSON").action(async(e,r)=>{await bo(e,r)}),t.command("replan <task>").description("Refine an existing plan following test failures, coverage gaps, or agent feedback").option("-f, --feedback <text>","Feedback or correction guidance").option("--failed-verification <reason>","Reason verification or tests failed").option("-b, --budget <tokens>","Token budget (default: 2500)").option("-r, --root <path>","Project root directory").option("--json","Output as JSON").action(async(e,r)=>{await wo(e,r)}),t.command("explain <symbol>").description("Explain symbol behavior, combining AST facts, caller/callee graphs, architectural memory, and ADR assertions").option("-r, --root <path>","Project root directory").option("--json","Output as JSON").action(async(e,r)=>{await Po(e,r)}),t.command("drift [path]").description("Detect drift in documentation assertions against current code evidence and signatures").option("-r, --root <path>","Project root directory").option("--json","Output as JSON").action(async(e,r)=>{await Co(e,r)}),t.command("remember <statement>").description("Explicitly record an architectural fact, decision, or invariant with admission verification").option("-c, --category <category>","Category: architecture, convention, invariant, decision").option("-t, --type <type>","Claim type: fact, inference, decision, outcome, preference").option("--confidence <score>","Confidence score (0.0 to 1.0)").option("-e, --evidence-path <path>","Source file path providing evidence").option("-r, --root <path>","Project root directory").action(async(e,r)=>{await jo(e,r)});let o=t.command("doc").description("Documentation Compiler: plan, generate, and validate provenance-backed documentation");return o.command("plan <kind>").description("Plan a bounded documentation artifact (markdown, openapi, architecture, guide)").option("-t, --title <title>","Document title").option("-s, --scope <query>","Symbol scope query").option("-r, --root <path>","Project root directory").option("--json","Output plan as JSON").action(async(e,r)=>{await Oo(e,r)}),o.command("generate <kind>").description("Generate a provenance-backed DocArtifact with structured assertions").option("-t, --title <title>","Document title").option("-s, --scope <query>","Symbol scope query").option("-r, --root <path>","Project root directory").option("--json","Output DocArtifact as JSON").action(async(e,r)=>{await Ao(e,r)}),o.command("validate <file>").description("Validate structured assertions in a documentation artifact against code evidence").option("-r, --root <path>","Project root directory").option("--json","Output validation report as JSON").action(async(e,r)=>{await ko(e,r)}),t}$o().parseAsync(process.argv).catch(t=>{console.error("[glyphier] Fatal error:",t),process.exit(1)});
@@ -0,0 +1,4 @@
1
+ import l from"path";function v(i,f=process.cwd(),a){let e=[];for(let t of i)for(let s of t.assertions){let c=!1,n;if(s.evidenceRefs.length>0){for(let p of s.evidenceRefs)if(n=l.resolve(f,p.path),a&&!a(n)){c=!0;break}}c?e.push({assertionId:s.id,docPath:t.path,statement:s.statement,status:"drifted",evidencePath:n,driftReason:`Referenced code file '${n}' no longer exists on disk`,suggestedScope:`Update ${t.path} to reference new module structure`}):s.status==="contradicted"?e.push({assertionId:s.id,docPath:t.path,statement:s.statement,status:"contradicted",evidencePath:n,driftReason:s.driftDetails||"Contradicted by code signatures or tests",suggestedScope:`Review statement in ${t.path}`}):e.push({assertionId:s.id,docPath:t.path,statement:s.statement,status:"verified",evidencePath:n,driftReason:"Backed by verified source evidence"})}let d=e.filter(t=>t.status==="verified").length,r=e.filter(t=>t.status==="drifted").length,o=e.filter(t=>t.status==="contradicted").length,u=["# Glyphier Documentation Drift Report",`Evaluated ${e.length} assertions across ${i.length} document artifacts`,`Verified: ${d} | Drifted: ${r} | Contradicted: ${o}`,"","## Findings:",...e.map(t=>`${t.status==="verified"?"\u2705":t.status==="drifted"?"\u26A0\uFE0F":"\u274C"} [${t.status.toUpperCase()}] ${t.docPath}#${t.assertionId}: "${t.statement}"
2
+ Reason: ${t.driftReason}${t.suggestedScope?`
3
+ Scope: ${t.suggestedScope}`:""}`),e.length===0?"- (No document assertions found to evaluate)":""].filter(Boolean).join(`
4
+ `);return{totalEvaluated:e.length,verifiedCount:d,driftedCount:r,contradictedCount:o,hasDrift:r>0||o>0,items:e,renderedReport:u}}export{v as a};
@@ -0,0 +1,49 @@
1
+ import{A as J,B as W,C as Y,D as X,F as K,G as Z,H as Q,L as ee,R as te,V as ne,j as F,k as V,l as M,m as R,n as T,o as w,p as j,q as N,r as I,s as L,t as C,u as H,v as U,w as G,x as q,y as z,z as B}from"./chunk-VOGFZYFC.js";import{a as re,b as oe}from"./chunk-QYSMWA6Y.js";import{a as ie}from"./chunk-H6T36TY5.js";import{b,h as S}from"./chunk-NIXOREHQ.js";import{McpServer as ue}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as ge}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as i}from"zod";import f from"path";import k from"path";import pe from"fs";async function ae(y,x={}){let n=k.resolve(x.rootPath||process.cwd()),d=b(n).findSymbols(y);if(x.filePath){let e=x.filePath.replace(/\\/g,"/");d=d.filter(r=>r.filePath.replace(/\\/g,"/").includes(e))}let t=d.filter(e=>e.name===y||e.qualifiedName===y),o=t.length>0?t:d;if(o.length===1){let e=o[0],r=k.isAbsolute(e.filePath)?e.filePath:k.resolve(n,e.filePath),s=w(r,{startLine:e.startLine,endLine:e.endLine});return s===null?{success:!1,message:`File not found on disk: ${e.filePath}`}:{success:!0,symbol:e,content:s}}if(o.length>1)return{success:!1,ambiguous:!0,candidates:o,message:`Found ${o.length} symbols matching "${y}". Specify a file path to disambiguate.`};if(x.filePath){let e=k.isAbsolute(x.filePath)?x.filePath:k.resolve(n,x.filePath);if(pe.existsSync(e))try{let r=await R(e,{level:2,rootPath:n});if(r){let s=r.module,c=s.functions.find(p=>p.name===y||p.name.endsWith(`.${y}`));if(c){let p=w(e,{startLine:c.lines.start,endLine:c.lines.end});return{success:!0,symbol:{id:`${e}:${c.name}`,filePath:x.filePath,name:c.name,qualifiedName:c.name,kind:"fn",startLine:c.lines.start,endLine:c.lines.end,signature:`(fn ${c.name})`,isExported:c.isExported??!1,hash:"",language:r.metadata.language},content:p||""}}let a=s.types.find(p=>p.name===y);if(a){let p=w(e,{startLine:a.lines.start,endLine:a.lines.end});return{success:!0,symbol:{id:`${e}:${a.name}`,filePath:x.filePath,name:a.name,qualifiedName:a.name,kind:"type",startLine:a.lines.start,endLine:a.lines.end,signature:`(type ${a.name})`,isExported:a.isExported??!1,hash:"",language:r.metadata.language},content:p||""}}}}catch{}}return{success:!1,message:`Symbol "${y}" not found in index. Run "glyphier index" to update symbol graph.`}}import P from"path";function se(y,x,n){try{return JSON.parse(y)}catch{let d=y.match(/<!--\s*glyphier-doc:\s*(\{[\s\S]*?\})\s*-->/);if(d)return JSON.parse(d[1])}let v=y.split(`
2
+ `).flatMap((d,t)=>/Invariant I-|ADR |MUST |Verify /.test(d)?[{id:`assert-${t+1}`,documentPath:P.relative(n,x),claim:d.trim().replace(/^[-*#>\s]+/,""),type:"architecture",verificationMethod:"source_relation",anchors:[],status:"unverified"}]:[]);return{id:`doc-${P.basename(x)}`,kind:"architecture",title:P.basename(x),repository:{repositoryId:P.basename(n),repositoryName:P.basename(n),rootPath:n,headRef:"HEAD",indexState:"clean",ignorePolicy:{patterns:["node_modules"],gitignoreApplied:!0},capturedAt:new Date().toISOString(),schemaVersion:"1.0.0"},compiler:{cliVersion:S,parserVersions:[{language:"typescript",grammarVersion:"0.23.0"}],rankingVersion:"1.0.0",riskPolicyVersion:"1.0.0",budgetPolicyVersion:"1.0.0",capabilityFlags:{},fingerprintHash:"sha256:doc",schemaVersion:"1.0.0"},planEvidence:[],assertions:v,content:y,humanReviewState:"pending_review",createdAt:new Date().toISOString(),schemaVersion:"1.0.0"}}function ce(y,x=process.cwd()){let n=f.resolve(x),v=y.tool.bind(y),d=((t,...o)=>v(t.replace(/^glyphier_/,"glyphier_"),...o));d("glyphier_explore","Get a compact Prefix-Trie view of the project file tree with line and function counts, or auto-zoom under a token budget. Use this first to orient yourself without reading raw code.",{path:i.string().optional().describe("Subdirectory to explore relative to project root"),depth:i.number().int().positive().optional().describe("Maximum directory depth"),budget:i.number().int().positive().optional().describe("Strict token budget for auto-zooming (e.g. 1500). Packs maximum semantic information within token limit."),level:i.number().int().min(0).max(1).optional().describe("0 = tree only (ultra-compact, ~25 tokens), 1 = tree + function skeletons (~80 tokens)")},async({path:t,depth:o,budget:e,level:r=0})=>{try{let s=t?f.resolve(n,t):n;if(e)return{content:[{type:"text",text:(await z({budget:e,rootPath:s})).formattedOutput}]};if(r===0){let p=await F(s,{depth:o,rootPath:n});return{content:[{type:"text",text:I(p)}]}}let c=await T(s,{level:1,rootPath:n}),a=[I(c.tree),""];for(let[p,m]of c.files)a.push(`--- ${p} ---`),a.push(L(m,{level:1})),a.push("");return{content:[{type:"text",text:a.join(`
3
+ `)}]}}catch(s){return{isError:!0,content:[{type:"text",text:`Error exploring codebase: ${String(s)}`}]}}}),d("glyphier_view","Get the compact S-expression intermediate representation of a file (signatures, types, and L2 call graph). Use this to understand file logic without reading raw code.",{file:i.string().describe("File path relative to project root"),level:i.number().int().min(1).max(2).optional().describe("1 = signatures only, 2 = signatures + call graph + validates + throws (default: 2)"),session:i.string().optional().describe("Session ID to enable multi-turn delta compression (returns unchanged/delta summary instead of full text)")},async({file:t,level:o=2,session:e})=>{try{let r=f.resolve(n,t),s=await R(r,{level:o,rootPath:n});if(!s)return{isError:!0,content:[{type:"text",text:`File not found or cannot be parsed: ${t}`}]};if(e){let a=X(e,r,s);if(a.status==="unchanged")return{content:[{type:"text",text:q(a)}]}}return{content:[{type:"text",text:L(s,{level:o})}]}}catch(r){return{isError:!0,content:[{type:"text",text:`Error parsing file ${t}: ${String(r)}`}]}}}),d("glyphier_search",'Semantic grep across project IR. Search for functions by name, call targets (e.g. "db.users.create"), types, or imports across all parsed files.',{query:i.string().describe("Search query string"),kind:i.enum(["calls","fn","type","use"]).optional().describe('Filter results by kind: "calls" (call graph), "fn" (functions), "type" (types/interfaces), "use" (imports)'),path:i.string().optional().describe("Subdirectory or root path to search within")},async({query:t,kind:o,path:e})=>{try{let r=e?f.resolve(n,e):n,s=await T(r,{level:2,rootPath:r}),c=Array.from(s.files.values()),a=V(c,t,{kind:o});return{content:[{type:"text",text:M(t,a)}]}}catch(r){return{isError:!0,content:[{type:"text",text:`Error searching IR: ${String(r)}`}]}}}),d("glyphier_read_raw","Read raw source code lines for a specific line range. ONLY call this when you have already identified the exact function to modify using the IR tools.",{file:i.string().describe("File path relative to project root"),start_line:i.number().int().positive().optional().describe("Start line number (1-indexed)"),end_line:i.number().int().positive().optional().describe("End line number (1-indexed)")},async({file:t,start_line:o,end_line:e})=>{try{let r=f.resolve(n,t),s=w(r,{startLine:o,endLine:e});return s===null?{isError:!0,content:[{type:"text",text:`File not found: ${t}`}]}:{content:[{type:"text",text:s}]}}catch(r){return{isError:!0,content:[{type:"text",text:`Error reading file ${t}: ${String(r)}`}]}}}),d("glyphier_read_symbol","Directly extract the raw source code of a symbol (function, method, class, type, route) without manual line calculations. Uses SQLite index for instant lookup.",{symbol:i.string().describe("Name or qualified name of the symbol to read"),file:i.string().optional().describe("Optional file path or substring to disambiguate if multiple symbols share the name")},async({symbol:t,file:o})=>{try{let e=await ae(t,{filePath:o,rootPath:n});if(!e.success){if(e.ambiguous&&e.candidates){let c=e.candidates.map(a=>` - [${a.kind}] ${a.qualifiedName||a.name} (${a.filePath}:${a.startLine}-${a.endLine})`).join(`
4
+ `);return{isError:!0,content:[{type:"text",text:`Ambiguous symbol "${t}". Found ${e.candidates.length} candidates:
5
+ ${c}
6
+
7
+ Specify the "file" argument to disambiguate.`}]}}return{isError:!0,content:[{type:"text",text:e.message||`Symbol "${t}" not found.`}]}}let r=e.symbol;return{content:[{type:"text",text:`// [${r.kind}] ${r.qualifiedName||r.name} (${r.filePath}:${r.startLine}-${r.endLine})
8
+ `+e.content}]}}catch(e){return{isError:!0,content:[{type:"text",text:`Error reading symbol ${t}: ${String(e)}`}]}}}),d("glyphier_impact","Evaluate the blast radius of modifying or renaming a symbol. Finds all direct and transitive callers, importers, and calculates risk score.",{symbol:i.string().describe("Function, method, class, or type name to evaluate blast radius for"),depth:i.number().int().positive().optional().describe("Maximum transitive caller depth (default: 2)"),path:i.string().optional().describe("Subdirectory or scope to evaluate within")},async({symbol:t,depth:o=2,path:e})=>{try{let r=e?f.resolve(n,e):n,s=await j(t,{rootPath:r,depth:o});return{content:[{type:"text",text:C(s)}]}}catch(r){return{isError:!0,content:[{type:"text",text:`Error analyzing impact for ${t}: ${String(r)}`}]}}}),d("glyphier_diff","Get a semantic AST diff of a file against a git revision. Returns declaration-level changes (added/removed/modified functions, param changes, call graph deltas) in 85% fewer tokens than git diff.",{file:i.string().describe("File path relative to project root to compute semantic diff for"),since:i.string().optional().describe('Git revision to compare against (e.g. "HEAD", "HEAD~1", "main"). Default: "HEAD"')},async({file:t,since:o="HEAD"})=>{try{let e=await N(t,{since:o,rootPath:n});return{content:[{type:"text",text:H(e)}]}}catch(e){return{isError:!0,content:[{type:"text",text:`Error diffing file ${t}: ${String(e)}`}]}}}),d("glyphier_check","Pre-flight validator: checks proposed agent code or unified diff patch for AST syntax errors, missing delimiters, and unresolved imports BEFORE writing to disk.",{file:i.string().describe("File path to validate proposed patch or code for"),patch:i.string().describe("Proposed code snippet or unified diff patch to validate")},async({file:t,patch:o})=>{try{let e=await B(t,o,{rootPath:n});return{content:[{type:"text",text:U(e)}]}}catch(e){return{isError:!0,content:[{type:"text",text:`Error validating check on ${t}: ${String(e)}`}]}}}),d("glyphier_graph","Subsystem architectural dependency graph: maps BullMQ message queues to processors, background jobs, external module boundaries, and cross-service calls in ultra-dense S-expressions.",{path:i.string().describe('Directory path of the subsystem/module to analyze (e.g. "apps/api/src/modules/exchange-sync")')},async({path:t})=>{try{let o=f.resolve(n,t),e=await J(o,{rootPath:n});return{content:[{type:"text",text:W(e)}]}}catch(o){return{isError:!0,content:[{type:"text",text:`Error generating module graph for ${t}: ${String(o)}`}]}}}),d("glyphier_slice","Extract a targeted, multi-file program slice tracing caller/callee execution paths for a symbol in a single compact S-expression (~200 tokens).",{symbol:i.string().describe("Root symbol name (function, method, or type) to slice around"),path:i.string().optional().describe("Subsystem directory or project path to search within"),depth:i.number().int().min(1).max(5).optional().describe("Traversal depth (default: 2)"),target:i.string().optional().describe("Optional destination symbol to find shortest path to")},async({symbol:t,path:o,depth:e=2,target:r})=>{try{let s=o?f.resolve(n,o):n,c=await Y(s,t,{depth:e,targetSymbol:r,rootPath:n});return{content:[{type:"text",text:G(c)}]}}catch(s){return{isError:!0,content:[{type:"text",text:`Error generating program slice for ${t}: ${String(s)}`}]}}}),d("glyphier_patch","Apply an AST-native structural patch (add-call, add-field, replace-call, add-fn) with automatic pre-flight Tree-sitter syntax validation before writing to disk.",{file:i.string().describe("File path to patch relative to project root"),expression:i.string().describe('S-expression patch command, e.g. "(add-call (State).Plan telemetry.Record)"'),dryRun:i.boolean().optional().describe("Validate without saving to disk")},async({file:t,expression:o,dryRun:e=!1})=>{try{let r=f.resolve(n,t),s=await K(r,o,{dryRun:e});return s.success?{content:[{type:"text",text:`\u2713 Successfully applied ${s.appliedOps} patch operation(s) to ${t}`}]}:{isError:!0,content:[{type:"text",text:`\u2717 Patch rejected: ${s.error}`}]}}catch(r){return{isError:!0,content:[{type:"text",text:`Error applying patch to ${t}: ${String(r)}`}]}}}),d("glyphier_stats","Compute token density, compression ratios, language breakdown, and pricing analytics across codebase.",{path:i.string().optional().describe("Directory or file path relative to project root")},async({path:t})=>{try{let o=t?f.resolve(n,t):n,e=await Z(o,{rootPath:n});return{content:[{type:"text",text:Q(e)}]}}catch(o){return{isError:!0,content:[{type:"text",text:`Error computing stats: ${String(o)}`}]}}}),d("glyphier_trace","Trace caller and callee relationships of a symbol through the persistent symbol graph.",{symbol:i.string().describe("Target function or symbol name to trace"),direction:i.enum(["callers","callees","both"]).optional().describe("Traversal direction (default: both)"),depth:i.number().int().min(1).max(5).optional().describe("Traversal depth (default: 2)")},async({symbol:t,direction:o="both",depth:e=2})=>{try{let r=b(n),s=re(t,{storage:r,direction:o,depth:e});return{content:[{type:"text",text:oe(s)}]}}catch(r){return{isError:!0,content:[{type:"text",text:`Error tracing symbol ${t}: ${String(r)}`}]}}}),d("glyphier_context","Assemble a minimally sufficient, budget-optimized semantic context for a task with automatic deduplication.",{task:i.string().describe("Natural language description of the coding task or question"),budget:i.number().int().positive().optional().describe("Strict token budget (default: 2500 tokens)"),session:i.string().optional().describe("Optional conversation session ID for deduplication")},async({task:t,budget:o=2500,session:e})=>{try{let r=b(n);return{content:[{type:"text",text:(await ne({task:t,budget:o,rootPath:n,sessionId:e,storage:r})).renderedContext}]}}catch(r){return{isError:!0,content:[{type:"text",text:`Error generating optimized context: ${String(r)}`}]}}}),d("glyphier_memory","Query, inspect, or record persistent repository architectural facts and invariants with source provenance.",{action:i.enum(["query","record"]).optional().describe('Action to perform: "query" (default) or "record" to store a new fact'),category:i.enum(["architecture","convention","invariant","integration","decision"]).optional().describe("Filter or assign memory category"),query:i.string().optional().describe("Search keywords across memory facts"),statement:i.string().optional().describe('Fact statement to record into repository memory (required when action is "record")'),file:i.string().optional().describe("Optional source file for provenance when recording"),confidence:i.number().min(0).max(1).optional().describe("Confidence score 0.0 to 1.0 (default: 0.9)")},async({action:t="query",category:o,query:e,statement:r,file:s,confidence:c=.9})=>{try{let a=b(n),p=new ie(a);if(t==="record"||r){if(!r)return{isError:!0,content:[{type:"text",text:'Must provide "statement" to record into memory.'}]};let m=p.addFact({statement:r,category:o||"invariant",confidence:c,provenance:s?[{file:s,startLine:1,endLine:1}]:[]});return{content:[{type:"text",text:`\u2713 Recorded invariant in repository memory [${m.category}] (${(m.confidence*100).toFixed(0)}%): "${m.statement}"`}]}}if(e){let h=p.findFacts(e).map(u=>`(${u.category}) "${u.statement}" [conf: ${u.confidence.toFixed(2)}]`);return{content:[{type:"text",text:h.length>0?h.join(`
9
+ `):"(no matching facts)"}]}}return{content:[{type:"text",text:p.formatMemorySExpr(o)}]}}catch(a){return{isError:!0,content:[{type:"text",text:`Error with repository memory: ${String(a)}`}]}}}),d("glyphier_index","Incrementally index the repository ASTs, symbol table, and dependency edges into persistent SQLite storage.",{force:i.boolean().optional().describe("Force full re-indexing of all files")},async({force:t=!1})=>{try{let o=b(n),e=await te(n,{storage:o,force:t});return{content:[{type:"text",text:`\u2713 Indexed ${e.indexedFiles} files, skipped ${e.skippedFiles} unchanged, pruned ${e.deletedFiles} deleted in ${e.durationMs}ms.`}]}}catch(o){return{isError:!0,content:[{type:"text",text:`Error indexing project: ${String(o)}`}]}}}),d("glyphier_review","Compile a structured, evidence-backed review artifact between base and head git revisions.",{base:i.string().describe("Base git revision to compare against (e.g. main, HEAD~1)"),head:i.string().optional().describe("Head git revision (default: HEAD)")},async({base:t,head:o="HEAD"})=>{try{let{execSync:e}=await import("child_process"),{createHash:r}=await import("crypto"),s=e(`git diff ${t}...${o}`,{cwd:n,encoding:"utf8",maxBuffer:10*1024*1024}),a=e(`git diff --name-status ${t}...${o}`,{cwd:n,encoding:"utf8"}).trim().split(`
10
+ `).filter(Boolean),p=r("sha256").update(s).digest("hex"),m=a.length;return{content:[{type:"text",text:[`Review (${t}...${o})`,`Diff digest: ${p.slice(0,16)}...`,`Changed files: ${m}`,...a.slice(0,15).map(u=>` ${u}`),a.length>15?` ... and ${a.length-15} more files`:""].filter(Boolean).join(`
11
+ `)}]}}catch(e){return{isError:!0,content:[{type:"text",text:`Error generating review: ${String(e)}`}]}}}),d("glyphier_doctor","Run diagnostics on Glyphier environment, parsers, SQLite index, and workspace security.",{},async()=>{try{let{runDiagnostics:t}=await import("./doctor-6OEYEF3A.js"),o=t(n);return{content:[{type:"text",text:JSON.stringify(o,null,2)}]}}catch(t){return{isError:!0,content:[{type:"text",text:`Error running doctor diagnostics: ${String(t)}`}]}}}),d("glyphier_plan","Produce a task, evidence, risk, and verification plan before edits.",{task:i.string().describe("Natural language task description"),budget:i.number().int().positive().optional().describe("Token budget (default: 2500)"),format:i.enum(["claude","cursor","antigravity","json","text"]).optional().describe("Output formatting for specific agent client")},async({task:t,budget:o=2500,format:e})=>{try{let{compileTaskPlan:r}=await import("./task-planner-JPPFKAG5.js"),{formatContextForAgent:s}=await import("./agent-adapters-2VCI4NIX.js"),c=b(n),a=t.toLowerCase().replace(/[^a-z0-9_\-]/g," ").split(/\s+/).filter(u=>u.length>2),p=[];for(let u of a){let l=c.findSymbols(u);p.push(...l)}let m=r({task:t,rootPath:n,tokenBudget:o,candidateSymbols:p});return{content:[{type:"text",text:e?s(m.contextArtifact,e):m.renderedPlan}]}}catch(r){return{isError:!0,content:[{type:"text",text:`Error compiling plan: ${String(r)}`}]}}}),d("glyphier_replan","Iteratively expand, correct, or refine context following feedback or verification failures.",{task:i.string().describe("Task description"),feedback:i.string().optional().describe("Feedback or correction instructions"),failedVerification:i.string().optional().describe("Verification failure message if any"),budget:i.number().int().positive().optional().describe("Token budget (default: 2500)")},async({task:t,feedback:o,failedVerification:e,budget:r=2500})=>{try{let{compileTaskPlan:s}=await import("./task-planner-JPPFKAG5.js"),{executeReplan:c}=await import("./replanner-NZ3A5THM.js"),a=s({task:t,rootPath:n,tokenBudget:r});return{content:[{type:"text",text:c({priorArtifact:a.contextArtifact,feedback:o,failedVerification:e}).renderedDeltaSummary}]}}catch(s){return{isError:!0,content:[{type:"text",text:`Error replanning: ${String(s)}`}]}}}),d("glyphier_explain","Explain symbol behavior, combining AST facts, call graph, architectural memory, and ADR assertions.",{symbol:i.string().describe("Target function or symbol name to explain")},async({symbol:t})=>{try{let o=b(n),{traceSymbol:e}=await import("./trace-ZLOFETDM.js"),{RepositoryMemory:r}=await import("./store-T3OGOKTC.js"),{explainSymbol:s}=await import("./explainer-N5B56KNI.js"),c=e(t,{storage:o,direction:"both",depth:1}),a=c.nodes.filter(l=>l.depth===1&&l.symbol.name!==t).map(l=>l.symbol.name),p=c.nodes.filter(l=>l.depth===-1).map(l=>l.symbol.name),h=new r(o).getFacts().filter(l=>l.statement.toLowerCase().includes(t.toLowerCase())).map(l=>({id:l.id,statement:l.statement,claimType:l.category==="decision"?"decision":"fact",repositoryId:f.basename(n),branchScope:null,evidenceRefs:[],validationStatus:l.verifiedAt?"validated":"unvalidated",expiresAt:null,lastValidatedAt:null,createdAt:new Date(l.createdAt).toISOString(),schemaVersion:"1.0.0"}));return{content:[{type:"text",text:s({symbolName:t,callers:a,callees:p,memoryRecords:h}).renderedExplanation}]}}catch(o){return{isError:!0,content:[{type:"text",text:`Error explaining symbol ${t}: ${String(o)}`}]}}}),d("glyphier_drift","Detect drift in documentation assertions against current code evidence and signatures.",{path:i.string().optional().describe("Documentation path to evaluate (defaults to docs/)")},async({path:t})=>{try{let o=await import("fs"),{detectDocumentationDrift:e}=await import("./drift-detector-BY6RWGWP.js"),{classifyDocumentTier:r,DOCUMENT_TIER_AUTHORITY:s,computeDocumentId:c}=await import("./document-artifact-RJPU3IRZ.js"),a=t?f.resolve(n,t):f.join(n,"docs"),p=[];if(o.existsSync(a)){let u=o.statSync(a).isDirectory()?o.readdirSync(a,{recursive:!0}).filter(l=>String(l).endsWith(".md")).map(l=>f.join(a,String(l))):[a];for(let l of u){if(!o.existsSync(l))continue;let g=o.readFileSync(l,"utf8"),E=f.relative(n,l),$=r(E),O=[];g.split(`
12
+ `).forEach((D,de)=>{(D.includes("Invariant I-")||D.includes("ADR ")||D.includes("MUST "))&&O.push({id:`assert-${de+1}`,statement:D.trim().replace(/^[-*#>\s]+/,""),assertionType:"invariant",rationaleLink:"EXTRACTED",status:"verified",evidenceRefs:[],confidence:1})}),p.push({documentId:c(f.basename(n),E,"digest"),repositoryId:f.basename(n),path:E,title:f.basename(l),authorityTier:$,authorityScore:s[$],digest:"digest",sections:[],assertions:O,snapshotRef:"HEAD",capturedAt:new Date().toISOString(),schemaVersion:"1.0.0"})}}return{content:[{type:"text",text:e(p,n,o.existsSync).renderedReport}]}}catch(o){return{isError:!0,content:[{type:"text",text:`Error detecting drift: ${String(o)}`}]}}}),d("glyphier_remember","Safely record an architectural fact, decision, or invariant into repository memory with admission verification.",{statement:i.string().describe("The statement to remember"),category:i.enum(["architecture","convention","invariant","decision"]).optional().describe("Memory category"),type:i.enum(["fact","inference","decision","outcome","preference"]).optional().describe("Claim type"),evidencePath:i.string().optional().describe("Source file providing evidence for this claim"),confidence:i.number().min(0).max(1).optional().describe("Confidence score (default: 0.9)")},async({statement:t,category:o="architecture",type:e="fact",evidencePath:r,confidence:s=.9})=>{try{let{createHash:c}=await import("crypto"),{admitMemoryRecord:a}=await import("./admission-Q3FJHJAY.js"),{RepositoryMemory:p}=await import("./store-T3OGOKTC.js"),m=b(n),h={id:`mem-${c("sha256").update(`${e}:${t}`).digest("hex").slice(0,12)}`,statement:t,claimType:e,repositoryId:f.basename(n),branchScope:null,evidenceRefs:r?[{id:"ev-1",sourceType:"source_file",path:r,snapshotRef:`${f.basename(n)}:HEAD`,retrievalReason:"Evidence for memory record",freshness:"fresh",schemaVersion:"1.0.0"}]:[],confidence:s,validationStatus:"unvalidated",createdAt:new Date().toISOString(),schemaVersion:"1.0.0"},u=a(h);return u.admitted?(new p(m).addFact({category:o,statement:t,confidence:s,provenance:[{file:r||"mcp-entry",startLine:1,endLine:1}]}),{content:[{type:"text",text:`\u2713 Memory recorded (${e}): "${t}"`}]}):{isError:!0,content:[{type:"text",text:`Memory admission rejected:
13
+ ${u.errors.map(g=>` - ${g}`).join(`
14
+ `)}`}]}}catch(c){return{isError:!0,content:[{type:"text",text:`Error recording memory: ${String(c)}`}]}}}),d("glyphier_doc_plan","Plan a bounded documentation artifact (markdown, openapi, architecture, guide) with structured assertions.",{kind:i.enum(["markdown","openapi","architecture","guide"]).describe("Type of documentation to plan"),title:i.string().optional().describe("Document title"),scope:i.string().optional().describe("Symbol scope filter")},async({kind:t,title:o,scope:e})=>{try{let{planDocumentation:r}=await import("./doc-compiler-6H72TGND.js"),a=b(n).findSymbols(e||"").slice(0,10).map(m=>({name:m.name,filePath:m.filePath,isExported:m.isExported,kind:m.kind,startLine:m.startLine,endLine:m.endLine})),p=r({kind:t,title:o||`${t.toUpperCase()} Documentation`,rootPath:n,snapshot:{repositoryId:f.basename(n),repositoryName:f.basename(n),rootPath:n,headRef:"HEAD",indexState:"clean",ignorePolicy:{patterns:["node_modules"],gitignoreApplied:!0},capturedAt:new Date().toISOString(),schemaVersion:"1.0.0"},fingerprint:{cliVersion:S,parserVersions:[{language:"typescript",grammarVersion:"0.23.0"}],rankingVersion:"1.0.0",riskPolicyVersion:"1.0.0",budgetPolicyVersion:"1.0.0",capabilityFlags:{doc_compiler:!0},fingerprintHash:"sha256:doc-compiler",schemaVersion:"1.0.0"},includedSymbols:a});return{content:[{type:"text",text:JSON.stringify(p,null,2)}]}}catch(r){return{isError:!0,content:[{type:"text",text:`Error planning documentation: ${String(r)}`}]}}}),d("glyphier_doc_generate","Generate a provenance-backed DocArtifact with structured assertions and human-review gate.",{kind:i.enum(["markdown","openapi","architecture","guide"]).describe("Type of documentation to generate"),title:i.string().optional().describe("Document title"),scope:i.string().optional().describe("Symbol scope filter")},async({kind:t,title:o,scope:e})=>{try{let{planDocumentation:r,generateDocumentation:s}=await import("./doc-compiler-6H72TGND.js"),p=b(n).findSymbols(e||"").slice(0,10).map(g=>({name:g.name,filePath:g.filePath,isExported:g.isExported,kind:g.kind,startLine:g.startLine,endLine:g.endLine})),m={repositoryId:f.basename(n),repositoryName:f.basename(n),rootPath:n,headRef:"HEAD",indexState:"clean",ignorePolicy:{patterns:["node_modules"],gitignoreApplied:!0},capturedAt:new Date().toISOString(),schemaVersion:"1.0.0"},h={cliVersion:S,parserVersions:[{language:"typescript",grammarVersion:"0.23.0"}],rankingVersion:"1.0.0",riskPolicyVersion:"1.0.0",budgetPolicyVersion:"1.0.0",capabilityFlags:{doc_compiler:!0},fingerprintHash:"sha256:doc-compiler",schemaVersion:"1.0.0"},u=r({kind:t,title:o||`${t.toUpperCase()} Documentation`,rootPath:n,snapshot:m,fingerprint:h,includedSymbols:p}),l=s(u,m,h);return{content:[{type:"text",text:JSON.stringify(l,null,2)}]}}catch(r){return{isError:!0,content:[{type:"text",text:`Error generating documentation: ${String(r)}`}]}}}),d("glyphier_doc_validate","Validate structured assertions in a documentation artifact against code evidence.",{file:i.string().describe("Path to documentation artifact JSON or markdown file")},async({file:t})=>{try{let o=await import("fs"),{validateDocAssertions:e}=await import("./doc-compiler-6H72TGND.js"),r=f.resolve(n,t);if(!o.existsSync(r))return{isError:!0,content:[{type:"text",text:`File not found: ${r}`}]};let s=o.readFileSync(r,"utf8"),c=se(s,r,n),a=b(n),m=e(c,{symbolExists(h,u){let l=a.findSymbols(h);return u?l.some(g=>g.name===h&&(g.filePath===u||g.filePath.endsWith(u))):l.some(g=>g.name===h)},isSymbolExported(h,u){let l=a.findSymbols(h);return u?l.some(g=>g.name===h&&g.isExported&&(g.filePath===u||g.filePath.endsWith(u))):l.some(g=>g.name===h&&g.isExported)},callsSymbol(h,u){let l=a.findSymbols(h);for(let g of l){let E=a.getOutgoingEdges(g.id,"calls");for(let $ of E)if($.targetId===u||$.targetId.includes(u))return!0}return!1}});return{content:[{type:"text",text:JSON.stringify(m,null,2)}]}}catch(o){return{isError:!0,content:[{type:"text",text:`Error validating documentation: ${String(o)}`}]}}})}var me=`# Glyphier 0.1 \u2014 Evidence-Governed Code Navigation
15
+
16
+ You have access to Glyphier semantic tools for token-efficient codebase exploration, provenance-aware context compilation, and repository memory.
17
+ Always follow the 5-Step Progressive Workflow:
18
+
19
+ ## \u{1F9ED} The 5-Step Progressive Workflow
20
+
21
+ ### Step 1: Task Context Retrieval (<350 tokens)
22
+ - Use \`glyphier_context\` to retrieve connected symbols, dependencies, paired tests, and evidence under a strict token budget.
23
+ - Example: \`glyphier_context(task="Fix duplicate Stripe charges", budget=2500)\`
24
+
25
+ ### Step 2: High-Level Exploration & Search (<200 tokens)
26
+ - Use \`glyphier_explore\` (level=0 or level=1) to inspect directory topology, file lengths, and exported signatures without reading raw source code.
27
+ - Use \`glyphier_search\` to semantically find functions, types, calls, or states.
28
+ - Example: \`glyphier_explore(path="src", level=1)\`, \`glyphier_search(query="handleAuth", kind="fn")\`
29
+
30
+ ### Step 3: Graph Tracing & Program Slicing (<250 tokens)
31
+ - Use \`glyphier_trace\` to inspect incoming and outgoing call graph neighborhood around any symbol.
32
+ - Use \`glyphier_slice\` to extract multi-file execution paths between symbols.
33
+ - Example: \`glyphier_trace(symbol="PaymentService.charge")\`, \`glyphier_slice(symbol="PaymentService.charge")\`
34
+
35
+ ### Step 4: Blast Radius & Impact Analysis (<150 tokens)
36
+ - Use \`glyphier_impact\` before refactoring to calculate reverse callers, affected tests, and risk category.
37
+ - Example: \`glyphier_impact(symbol="PaymentService.charge")\`
38
+
39
+ ### Step 5: Surgical Modification (Only when writing code)
40
+ - Use \`glyphier_read_raw\` with exact line ranges (e.g. lines="45-65") to read only the lines to modify.
41
+ - Never dump entire files with cat/view_file.
42
+ - Use \`glyphier_patch\` or AST-aware tools to apply modifications safely.
43
+
44
+ ## \u{1F4BE} Architecture & Invariant Memory
45
+ - Use \`glyphier_memory\` to query recorded repository invariants, decisions, and architectural rules.
46
+
47
+ ## \u{1F504} Index Maintenance
48
+ - If files were changed, use \`glyphier_index\` to incrementally sync the local AST cache and symbol graph.
49
+ `;function le(y){y.resource("instructions","glyphier://instructions",{description:"Instructions for AI coding agents on how to navigate code efficiently using Glyphier 0.1"},async()=>({contents:[{uri:"glyphier://instructions",mimeType:"text/markdown",text:me}]}))}async function fe(y={}){let x=y.rootDir||process.env.GLYPHIER_ROOT||process.cwd();(x==="/"||x==="")&&(x=process.env.PWD||process.env.GLYPHIER_ROOT||process.cwd()),await ee();let n=new ue({name:"glyphier",version:S});ce(n,x),le(n);let v=new ge;await n.connect(v),process.on("SIGINT",async()=>{await n.close(),process.exit(0)}),process.on("SIGTERM",async()=>{await n.close(),process.exit(0)})}import.meta.url===`file://${process.argv[1]}`&&fe().catch(y=>{console.error("[glyphier-mcp] Fatal server error:",y),process.exit(1)});export{ae as a,se as b,fe as c};
@@ -0,0 +1,13 @@
1
+ import{a as k,g as y,h as b}from"./chunk-NIXOREHQ.js";import c from"fs";import i from"path";import p from"os";import{createHash as D}from"crypto";import{createHash as I}from"crypto";import{copyFileSync as P,existsSync as j}from"fs";function x(t){t.exec(`
2
+ CREATE TABLE IF NOT EXISTS schema_migrations (
3
+ version INTEGER PRIMARY KEY,
4
+ description TEXT NOT NULL,
5
+ checksum TEXT NOT NULL,
6
+ applied_at REAL NOT NULL,
7
+ duration_ms REAL NOT NULL
8
+ );
9
+ `)}function _(t){x(t);try{return t.prepare("SELECT MAX(version) as v FROM schema_migrations").get()?.v??0}catch{return 0}}var $="[REDACTED]",T=[{name:"aws_access_key_id",pattern:/\bAKIA[0-9A-Z]{16}\b/g},{name:"aws_secret_access_key",pattern:/(?:aws[_\-.]?secret[_\-.]?(?:access[_\-.]?)?key\s*[=:]\s*)([A-Za-z0-9/+]{40})/gi},{name:"github_token",pattern:/\bghp_[A-Za-z0-9]{36}\b/g},{name:"github_oauth_token",pattern:/\bgho_[A-Za-z0-9]{36}\b/g},{name:"github_app_token",pattern:/\bghs_[A-Za-z0-9]{36}\b/g},{name:"github_fine_grained_token",pattern:/\bgithub_pat_[A-Za-z0-9_]{82}\b/g},{name:"bearer_token",pattern:/\bBearer\s+[A-Za-z0-9\-._~+/]+=*\b/gi,minLength:30},{name:"private_key_block",pattern:/-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----/g},{name:"connection_string_password",pattern:/(?:postgresql|mysql|mongodb|redis|amqp):\/\/[^:@\s]+:([^@\s]{8,})@/gi},{name:"password_assignment",pattern:/(?:password|passwd|secret|api[_\-.]?key|auth[_\-.]?token)\s*[=:]\s*["']([^"'\s]{8,})["']/gi,minLength:8},{name:"stripe_secret_key",pattern:/\bsk_(?:live|test)_[A-Za-z0-9]{24,}\b/g},{name:"stripe_restricted_key",pattern:/\brk_(?:live|test)_[A-Za-z0-9]{24,}\b/g},{name:"openai_api_key",pattern:/\bsk-[A-Za-z0-9]{48}\b/g},{name:"anthropic_api_key",pattern:/\bsk-ant-[A-Za-z0-9\-]{90,}\b/g},{name:"npm_token",pattern:/\bnpm_[A-Za-z0-9]{36}\b/g},{name:"high_entropy_assignment",pattern:/(?:SECRET|TOKEN|KEY|CREDENTIAL)\s*[=:]\s*["']([A-Za-z0-9+/]{32,}={0,2})["']/gi,minLength:32}];function S(t){let n=t,e=0,r=[];for(let{name:o,pattern:u,minLength:a=0}of T)u.lastIndex=0,n=n.replace(u,s=>s.length<a?s:(e++,r.includes(o)||r.push(o),$));return{content:n,redactedCount:e,patternsMatched:r}}function w(t,n){let e=t,r=process.env.HOME||process.env.USERPROFILE||"";return r&&e.startsWith(r)&&(e=e.replace(r,"~")),n&&e.startsWith(n)&&(e=e.replace(n,"<root>")),e}import{realpathSync as C,existsSync as M}from"fs";import{resolve as N,sep as L}from"path";var d=class extends Error{constructor(e,r,o){super(e);this.path=r;this.rootPath=o;this.name="WorkspaceGuardError"}path;rootPath};function E(t){if(t.includes("\0"))throw new d("Path contains null bytes",t,"");let n=t.replace(/\\/g,"/"),e=N(n);if(M(e))try{return C(e)}catch{return e}return e}function A(t,n){try{let e=E(t),r=E(n);return e===r||e.startsWith(r+"/")||e.startsWith(r+L)}catch{return!1}}function R(t=process.cwd()){let n=[],e=process.version,r=typeof globalThis.Bun<"u";n.push({name:"runtime",category:"runtime",status:"ok",message:`Running on ${r?"Bun "+(globalThis.Bun?.version||""):"Node "+e}`,details:{nodeVersion:e,isBun:r,platform:p.platform(),arch:p.arch()}});try{let s=y();n.push({name:"tree-sitter-grammars",category:"parser",status:s.length>=4?"ok":"warning",message:`${s.length} supported language grammars registered`,details:{languages:s}})}catch(s){n.push({name:"tree-sitter-grammars",category:"parser",status:"error",message:`Failed to load grammar registry: ${String(s)}`})}let o=i.join(t,".glyphier","index.db");if(c.existsSync(o))try{let s=c.statSync(o),h=new k(o),v=h.db,f=_(v);h.close(),n.push({name:"sqlite-storage",category:"storage",status:"ok",message:`Index database active (schema v${f}, ${(s.size/1024).toFixed(1)} KB)`,details:{schemaVersion:f,dbSizeKb:s.size/1024}})}catch(s){n.push({name:"sqlite-storage",category:"storage",status:"warning",message:`Storage found but check failed: ${String(s)}`})}else n.push({name:"sqlite-storage",category:"storage",status:"ok",message:"No local index database initialized yet (will initialize on first run)"});try{let s=A(t,t);n.push({name:"workspace-guard",category:"security",status:s?"ok":"error",message:s?"Workspace guard root validated":"Workspace root fails canonical check"})}catch(s){n.push({name:"workspace-guard",category:"security",status:"error",message:`Workspace guard check failed: ${String(s)}`})}let a=[{name:"Cursor Rules",path:i.join(t,".cursorrules")},{name:"AGENTS.md",path:i.join(t,"AGENTS.md")},{name:"GEMINI.md",path:i.join(t,"GEMINI.md")},{name:"Claude Config",path:i.join(t,".claude.json")}].filter(s=>c.existsSync(s.path)).map(s=>s.name);n.push({name:"agent-integrations",category:"integrations",status:a.length>0?"ok":"warning",message:a.length>0?`Active agent integrations: ${a.join(", ")}`:"No agent configuration files found in current directory",details:{detected:a}});let g=n.every(s=>s.status==="ok");return{timestamp:new Date().toISOString(),version:b,system:{os:`${p.type()} ${p.release()}`,arch:p.arch(),nodeVersion:process.version,bunVersion:globalThis.Bun?.version},checks:n,allOk:g}}function O(t=process.cwd()){let n=R(t),e=JSON.stringify(n,null,2),r=S(e).content,o=w(r,t),u=D("sha256").update(o).digest("hex"),a=i.join(t,".glyphier");c.existsSync(a)||c.mkdirSync(a,{recursive:!0});let g=i.join(a,`support-bundle-${Date.now()}.json`);return c.writeFileSync(g,o,"utf8"),{bundleJson:o,checksum:u,outPath:g}}function ae(t){let n=process.cwd(),e=R(n);if(t.bundle){let{checksum:r,outPath:o}=O(n);console.log(`\u2705 Support bundle created: ${o}`),console.log(`SHA-256 Checksum: ${r}`),console.log("All paths and secrets have been automatically sanitized.");return}if(t.json){console.log(JSON.stringify(e,null,2));return}console.log(`
10
+ \u{1F50D} Glyphier Doctor (v${e.version})`),console.log(`System: ${e.system.os} (${e.system.arch}) | Node ${e.system.nodeVersion}
11
+ `);for(let r of e.checks){let o=r.status==="ok"?"\u2705":r.status==="warning"?"\u26A0\uFE0F":"\u274C";console.log(`${o} [${r.category}] ${r.name}: ${r.message}`)}console.log(),e.allOk?console.log(`\u2728 All system and security checks passed.
12
+ `):console.log(`\u26A0\uFE0F Some checks reported warnings or errors. Run with --bundle to export diagnostic info.
13
+ `)}export{R as a,O as b,ae as c};
@@ -0,0 +1,2 @@
1
+ import c from"crypto";var a=class{storage;constructor(e){this.storage=e}addFact(e){let t={id:c.createHash("sha256").update(`${e.category}:${e.statement}`).digest("hex").slice(0,16),statement:e.statement,provenance:e.provenance,confidence:e.confidence,category:e.category,createdAt:Date.now(),verifiedAt:Date.now(),dependencies:e.dependencies||[]};return this.storage.upsertFact(t),t}getFacts(e){return this.storage.getFacts(e)}findFacts(e){let n=this.storage.getFacts(),t=e.toLowerCase();return n.filter(r=>r.statement.toLowerCase().includes(t)||r.category.toLowerCase().includes(t)||r.dependencies.some(s=>s.toLowerCase().includes(t)))}invalidateStaleFacts(e){let n=this.storage.getFacts(),t=0;for(let r of n)r.provenance.some(o=>e.includes(o.file))&&(r.confidence>.5?(r.confidence-=.3,r.verifiedAt=Date.now(),this.storage.upsertFact(r)):(this.storage.deleteFact(r.id),t++));return t}formatMemorySExpr(e){let n=this.getFacts(e);if(n.length===0)return"(memory :status empty)";let t=[];t.push("(memory");for(let r of n){let s=r.provenance.map(o=>`${o.file}:L${o.startLine}-${o.endLine}`).join(" ");t.push(` (fact :category ${r.category} :conf ${r.confidence.toFixed(2)}`),t.push(` "${r.statement}"`),s&&t.push(` :source (${s})`),t.push(" )")}return t.push(")"),t.join(`
2
+ `)}};export{a};
@@ -0,0 +1,2 @@
1
+ import{createHash as x}from"crypto";function P(h){let{priorArtifact:t,feedback:n,failedVerification:d,newEvidenceSymbols:I=[],invalidatedPaths:u=[]}=h,r=new Set(u),l=t.selectedContext.filter(e=>!r.has(e.path)),s=t.selectedContext.filter(e=>r.has(e.path)).map(e=>e.path),c=[],i=[];for(let e of I)if(!l.some(a=>a.path===e.filePath&&a.symbol===e.symbolName)){let a={path:e.filePath,symbol:e.symbolName,level:1,selectionReason:n?`Replanned following feedback: ${n}`:"Expanded candidate evidence",costTokens:e.costTokens,evidenceId:e.evidenceId};c.push(a),i.push(e.filePath)}let f=[...l,...c],p=f.reduce((e,a)=>e+a.costTokens,120),A=t.lineage?.iteration??1,b=t.lineage?.rootArtifactId??t.artifactId,m={...t,selectedContext:f,budgetAllocation:{...t.budgetAllocation,tokensUsed:p},lineage:{parentArtifactId:t.artifactId,rootArtifactId:b,iteration:A+1},compiledAt:new Date().toISOString()},k=x("sha256").update(JSON.stringify(m)).digest("hex"),o={...m,artifactId:k},g={priorArtifactId:t.artifactId,snapshotChanged:!1,compilerChanged:!1,additions:i,removals:s,invalidations:Array.from(r),replanReason:d?`Verification failure: ${d}`:n?`Feedback: ${n}`:"Context refinement",schemaVersion:"1.0.0"},v=[`# Glyphier Replan Delta (${t.artifactId.slice(0,8)} \u2192 ${o.artifactId.slice(0,8)})`,`Iteration: ${o.lineage?.iteration} | Reason: ${g.replanReason}`,`Added (${i.length}): ${i.join(", ")||"None"}`,`Removed/Invalidated (${s.length}): ${s.join(", ")||"None"}`,`Current Context Budget: ${p}/${o.budgetAllocation.tokenBudget} tokens`].join(`
2
+ `);return{newArtifact:o,delta:g,renderedDeltaSummary:v}}export{P as a};
@@ -0,0 +1,5 @@
1
+ function $(s){let{artifactId:a,taskSpec:d,riskAssessment:u,budgetAllocation:c,selectedContext:l,excludedContext:r,claimLedger:n}=s,o=[`<glyphier-context artifactId="${a}" risk="${u.effectiveRisk}" budget="${c.tokensUsed}/${c.tokenBudget}">`,` <task id="${d.taskId}" intent="${d.normalizedIntent}">`,` <raw-prompt>${f(d.rawPrompt)}</raw-prompt>`," </task>",` <selected-context count="${l.length}">`];for(let e of l)o.push(` <item path="${f(e.path)}" symbol="${f(e.symbol||"")}" reason="${f(e.selectionReason)}" />`);o.push(" </selected-context>"),o.push(` <exclusions count="${r.length}">`);for(let e of r)o.push(` <exclusion path="${f(e.path)}" symbol="${f(e.symbol||"")}" reason="${f(e.exclusionReason)}" />`);if(o.push(" </exclusions>"),n.length>0){o.push(` <claim-ledger count="${n.length}">`);for(let e of n)o.push(` <claim id="${e.claimId}" contradicted="${e.isContradicted}">${f(e.statement)}</claim>`);o.push(" </claim-ledger>")}return o.push(` <policy-envelope review-required="${u.requiresHumanReview}">`,...u.affectedSurfaces.map(e=>` <affected-surface type="${e.type}">${f(e.path)}</affected-surface>`)," </policy-envelope>","</glyphier-context>"),o.join(`
2
+ `)}function g(s){let{artifactId:a,taskSpec:d,riskAssessment:u,budgetAllocation:c,selectedContext:l,claimLedger:r}=s,n=[`[GLYPHIER::CONTEXT id=${a} risk=${u.effectiveRisk} budget=${c.tokensUsed}/${c.tokenBudget}]`,`@intent: ${d.normalizedIntent}`];if(l.length>0){n.push("@symbols:");let i=new Map;for(let p of l){let t=i.get(p.path)||[];p.symbol&&t.push(p.symbol),i.set(p.path,t)}for(let[p,t]of i.entries())n.push(` ${p} -> {${t.join(", ")||"*"}}`)}let o=r.filter(i=>i.statement.includes("[INVARIANT]"));if(o.length>0){n.push("@invariants:");for(let i of o)n.push(` ! ${i.statement.replace("[INVARIANT]","").trim()}`)}let e=r.filter(i=>i.statement.includes("[DEAD_END]"));if(e.length>0){n.push("@dead_ends:");for(let i of e)n.push(` X ${i.statement.replace("[DEAD_END]","").trim()}`)}return n.push("[END_GLYPHIER]"),n.join(`
3
+ `)}function k(s){let{artifactId:a,taskSpec:d,riskAssessment:u,budgetAllocation:c,selectedContext:l,excludedContext:r,claimLedger:n,repositorySnapshot:o}=s,e=[`# \u26A1 Glyphier Context: \`${a}\``,"",`> **Task Intent:** \`${d.normalizedIntent.toUpperCase()}\` | **Risk:** \`${u.effectiveRisk.toUpperCase()}\` | **Budget:** \`${c.tokensUsed}/${c.tokenBudget}\` tokens`,""];if(u.requiresHumanReview&&e.push("> [!IMPORTANT]","> **Human Review Required:** Intrinsic risk is elevated. Proposed modifications require explicit verification review.",""),e.push("## \u{1F3AF} Selected Context & Entrypoints"),l.length===0)e.push("- *(No direct candidate symbols matched)*");else for(let t of l){let m=`[${t.path}](file://${o.rootPath}/${t.path})`,h=t.symbol?` \u2014 \`${t.symbol}\``:"";e.push(`- ${m}${h}: ${t.selectionReason}`)}e.push("");let i=n.filter(t=>t.statement.includes("[INVARIANT]")),p=n.filter(t=>t.statement.includes("[DEAD_END]"));if(i.length>0||p.length>0){e.push("## \u{1F9E0} Active Architectural Memory & Invariants");for(let t of i)e.push("> [!NOTE]"),e.push(`> **${t.claimId}**: ${t.statement}`),e.push("");for(let t of p)e.push("> [!WARNING]"),e.push(`> **Avoid Dead End (${t.claimId})**: ${t.statement}`),e.push("")}if(r.length>0){e.push(`## \u{1F6AB} Explicit Exclusions (${r.length})`);for(let t of r.slice(0,5))e.push(`- \`${t.path}\` (${t.symbol||"file"}): *${t.exclusionReason}*`);r.length>5&&e.push(`- *(and ${r.length-5} more budget/unrelated exclusions)*`),e.push("")}return e.join(`
4
+ `)}function x(s){let{artifactId:a,taskSpec:d,riskAssessment:u,budgetAllocation:c,selectedContext:l,excludedContext:r}=s;return[`Context Artifact: ${a}`,`Intent: ${d.normalizedIntent.toUpperCase()} | Risk: ${u.effectiveRisk.toUpperCase()} | Budget: ${c.tokensUsed}/${c.tokenBudget}`,`Selected: ${l.length} item(s)`,...l.map(n=>` - ${n.path} (${n.symbol||"all"}): ${n.selectionReason}`),`Excluded: ${r.length} item(s)`].join(`
5
+ `)}function I(s,a="text"){switch(a){case"claude":return $(s);case"cursor":return g(s);case"antigravity":return k(s);case"json":return JSON.stringify(s,null,2);default:return x(s)}}function f(s){return s.replace(/[<>&'"]/g,a=>{switch(a){case"<":return"&lt;";case">":return"&gt;";case"&":return"&amp;";case"'":return"&apos;";case'"':return"&quot;";default:return a}})}export{$ as a,g as b,k as c,x as d,I as e};
@@ -0,0 +1,2 @@
1
+ import{i as o}from"./chunk-NIXOREHQ.js";function V(n,t=!0){return JSON.stringify(n,null,t?2:0)}import{createHash as D}from"crypto";import{z as e}from"zod";var I=e.enum(["worktree","committed","generated"]),h=e.enum(["fresh","stale_source","stale_compiler","partially_fresh","unknown"]),w=e.object({snapshotId:e.string().regex(/^[a-f0-9]{64}$/),repositoryId:e.string().min(1),headRef:e.string().nullable(),worktreeDigest:e.string().regex(/^[a-f0-9]{64}$/),sourceAuthority:I,dirtyPathsDigest:e.string().regex(/^[a-f0-9]{64}$/).nullable(),generatedPathsDigest:e.string().regex(/^[a-f0-9]{64}$/).nullable(),compilerFingerprint:e.string().regex(/^[a-f0-9]{64}$/),coverageDigest:e.string().regex(/^[a-f0-9]{64}$/),freshness:h,capturedAt:e.string().datetime(),schemaVersion:e.literal("0.1")}),A=e.object({path:e.string().min(1),startLine:e.number().int().positive().optional(),endLine:e.number().int().positive().optional(),symbol:e.string().min(1).optional()}),R=e.object({evidenceId:e.string().min(1),snapshotId:e.string().regex(/^[a-f0-9]{64}$/),sourceKind:e.enum(["source","symbol","edge","test","document","configuration","inference"]),anchor:A,excerptDigest:e.string().regex(/^[a-f0-9]{64}$/),freshness:h,authority:e.number().int().min(0).max(100),schemaVersion:e.literal("0.1")}),M=e.object({artifactId:e.string().regex(/^[a-f0-9]{64}$/),snapshot:w,taskDigest:e.string().regex(/^[a-f0-9]{64}$/),riskTier:e.enum(["low","medium","high","critical"]),evidence:e.array(R),selectedEvidenceIds:e.array(e.string().min(1)),excludedEvidence:e.array(e.object({evidenceId:e.string().min(1),reason:e.string().min(1)})),tokenBudget:e.number().int().positive(),tokensUsed:e.number().int().nonnegative(),claimLedger:e.array(e.object({claimId:e.string().min(1),kind:e.enum(["fact","inference","unknown"]),evidenceIds:e.array(e.string().min(1)),supported:e.boolean()})),schemaVersion:e.literal("0.1")}),_=e.enum(["verification","review","knowledge_promotion","invalidation","provider_decision","sync_delivery"]),W=e.object({receiptId:e.string().regex(/^[a-f0-9]{64}$/),kind:_,repositoryId:e.string().min(1),snapshotId:e.string().regex(/^[a-f0-9]{64}$/),principalId:e.string().min(1),policyRevision:e.string().min(1),subjectDigest:e.string().regex(/^[a-f0-9]{64}$/),evidenceDigests:e.array(e.string().regex(/^[a-f0-9]{64}$/)),issuedAt:e.string().datetime(),schemaVersion:e.literal("0.1")}),j=e.enum(["evidence_disposition","sufficiency_routing","documentation_assertion_support","prompt_injection_signal"]),$=e.object({packetId:e.string().regex(/^[a-f0-9]{64}$/),repositoryId:e.string().min(1),snapshotId:e.string().regex(/^[a-f0-9]{64}$/),principalId:e.string().min(1),policyRevision:e.string().min(1),decisionClass:j,riskTier:e.enum(["low","medium","high","critical"]),contextDigest:e.string().regex(/^[a-f0-9]{64}$/),evidenceDigests:e.array(e.string().regex(/^[a-f0-9]{64}$/)).max(64),inputBytes:e.number().int().nonnegative().max(65536),model:e.string().min(1),schemaVersion:e.literal("0.1")});function a(n){return D("sha256").update(JSON.stringify(n,C)).digest("hex")}function C(n,t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([i],[r])=>i.localeCompare(r))):t}function K(n){if(n.riskTier!=="low")throw new Error("Provider egress is limited to low-risk decision packets");$.parse(n)}import{execFileSync as E}from"child_process";import{createHash as u}from"crypto";import{readdirSync as P,readFileSync as F,statSync as O}from"fs";import c from"path";var T=new Set([".git",".glyphier","node_modules","dist",".next","coverage"]);function te(n){let t=c.resolve(n.rootPath),i=y(t),r=z(t,i),s=x(t,["status","--porcelain"]),p=i.filter(f),S=N(t,["rev-parse","HEAD"]),b=a({compiler:"glyphier-0.1.0",supportedFileCount:i.length}),v=a({files:i.map(d=>({path:d,generated:f(d)}))}),k=s.length>0?"worktree":"committed",g={repositoryId:a(t),headRef:S,worktreeDigest:r,sourceAuthority:k,dirtyPathsDigest:s.length>0?a(s.sort()):null,generatedPathsDigest:p.length>0?a(p.sort()):null,compilerFingerprint:b,coverageDigest:v};return{snapshotId:a(g),...g,freshness:"fresh",capturedAt:(n.now??new Date).toISOString(),schemaVersion:"0.1"}}function y(n,t=""){let i=c.join(n,t);return P(i,{withFileTypes:!0}).flatMap(r=>{let s=c.join(t,r.name);return r.isDirectory()?T.has(r.name)?[]:y(n,s):r.isFile()?[s]:[]})}function z(n,t){let i=u("sha256");for(let r of[...t].sort()){let s=c.join(n,r),p=O(s);i.update(r),i.update("\0"),i.update(String(p.size)),i.update("\0"),i.update(u("sha256").update(F(s)).digest("hex")),i.update("\0")}return i.digest("hex")}function N(n,t){return x(n,t)[0]??null}function x(n,t){try{return E("git",t,{cwd:n,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).split(`
2
+ `).map(i=>i.trim()).filter(Boolean)}catch{return[]}}function f(n){let t=c.basename(n).toLowerCase();return n.split(c.sep).includes("generated")||t.endsWith(".generated.ts")||t.endsWith(".generated.js")||t.endsWith(".gen.ts")}export{V as a,I as b,h as c,w as d,A as e,R as f,M as g,_ as h,W as i,j,$ as k,a as l,K as m,te as n};
@@ -0,0 +1,139 @@
1
+ import p from"fs";import c from"path";import{createRequire as b}from"module";function u(s){if(s==null)return[];try{let e=typeof s=="string"?JSON.parse(s):s;return Array.isArray(e)?e:[]}catch{return[]}}function y(s){let e=b(import.meta.url);if(typeof globalThis.Bun<"u")try{let{Database:t}=e("bun:sqlite");return new t(s)}catch{}try{let{DatabaseSync:t}=e("node:sqlite");return new t(s)}catch{}return R()}function R(){let s=new Map;return{exec(e){},prepare(e){return{run(...t){return{changes:1}},get(...t){},all(...t){return[]}}},close(){s.clear()}}}var o=class{db;dbPath;constructor(e=":memory:"){if(this.dbPath=e,e!==":memory:"){let t=c.dirname(e);p.existsSync(t)||p.mkdirSync(t,{recursive:!0})}this.db=y(e),this.initSchema()}initSchema(){try{this.db.exec("PRAGMA journal_mode = WAL;"),this.db.exec("PRAGMA synchronous = NORMAL;")}catch{}this.db.exec(`
2
+ CREATE TABLE IF NOT EXISTS files (
3
+ path TEXT PRIMARY KEY,
4
+ mtime REAL,
5
+ hash TEXT,
6
+ language TEXT,
7
+ classification TEXT,
8
+ line_count INT,
9
+ token_count INT
10
+ );
11
+
12
+ CREATE TABLE IF NOT EXISTS symbols (
13
+ id TEXT PRIMARY KEY,
14
+ file_path TEXT,
15
+ name TEXT,
16
+ qualified_name TEXT,
17
+ kind TEXT,
18
+ start_line INT,
19
+ end_line INT,
20
+ signature TEXT,
21
+ is_exported INT,
22
+ hash TEXT,
23
+ language TEXT
24
+ );
25
+
26
+ CREATE TABLE IF NOT EXISTS edges (
27
+ source_id TEXT,
28
+ target_id TEXT,
29
+ kind TEXT,
30
+ file_path TEXT,
31
+ line INT,
32
+ confidence REAL
33
+ );
34
+
35
+ CREATE TABLE IF NOT EXISTS ir_cache (
36
+ file_path TEXT,
37
+ level INT,
38
+ content_hash TEXT,
39
+ ir_blob TEXT,
40
+ PRIMARY KEY (file_path, level)
41
+ );
42
+
43
+ CREATE TABLE IF NOT EXISTS sessions (
44
+ session_id TEXT,
45
+ file_path TEXT,
46
+ fingerprint TEXT,
47
+ created_at REAL,
48
+ expires_at REAL,
49
+ PRIMARY KEY (session_id, file_path)
50
+ );
51
+
52
+ CREATE TABLE IF NOT EXISTS memory_facts (
53
+ id TEXT PRIMARY KEY,
54
+ statement TEXT,
55
+ provenance_json TEXT,
56
+ confidence REAL,
57
+ category TEXT,
58
+ created_at REAL,
59
+ verified_at REAL,
60
+ dependencies_json TEXT
61
+ );
62
+
63
+ CREATE TABLE IF NOT EXISTS meta (
64
+ key TEXT PRIMARY KEY,
65
+ value TEXT
66
+ );
67
+
68
+ CREATE INDEX IF NOT EXISTS idx_symbols_name ON symbols(name);
69
+ CREATE INDEX IF NOT EXISTS idx_symbols_file ON symbols(file_path);
70
+ CREATE INDEX IF NOT EXISTS idx_symbols_qname ON symbols(qualified_name);
71
+ CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source_id, kind);
72
+ CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target_id, kind);
73
+ CREATE INDEX IF NOT EXISTS idx_edges_file ON edges(file_path);
74
+ CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at);
75
+ `)}upsertFile(e){this.db.prepare(`
76
+ INSERT INTO files (path, mtime, hash, language, classification, line_count, token_count)
77
+ VALUES (?, ?, ?, ?, ?, ?, ?)
78
+ ON CONFLICT(path) DO UPDATE SET
79
+ mtime = excluded.mtime,
80
+ hash = excluded.hash,
81
+ language = excluded.language,
82
+ classification = excluded.classification,
83
+ line_count = excluded.line_count,
84
+ token_count = excluded.token_count
85
+ `).run(e.path,e.mtime,e.hash,e.language,e.classification,e.lineCount,e.tokenCount)}getFile(e){let t=this.db.prepare("SELECT * FROM files WHERE path = ?").get(e);return t?{path:t.path,mtime:t.mtime,hash:t.hash,language:t.language,classification:t.classification,lineCount:t.line_count,tokenCount:t.token_count}:null}getAllFiles(){return this.db.prepare("SELECT * FROM files").all().map(t=>({path:t.path,mtime:t.mtime,hash:t.hash,language:t.language,classification:t.classification,lineCount:t.line_count,tokenCount:t.token_count}))}deleteFile(e){this.db.prepare("DELETE FROM files WHERE path = ?").run(e),this.deleteSymbolsByFile(e),this.deleteEdgesByFile(e),this.invalidateIR(e)}upsertSymbols(e){let t=this.db.prepare(`
86
+ INSERT INTO symbols (id, file_path, name, qualified_name, kind, start_line, end_line, signature, is_exported, hash, language)
87
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
88
+ ON CONFLICT(id) DO UPDATE SET
89
+ file_path = excluded.file_path,
90
+ name = excluded.name,
91
+ qualified_name = excluded.qualified_name,
92
+ kind = excluded.kind,
93
+ start_line = excluded.start_line,
94
+ end_line = excluded.end_line,
95
+ signature = excluded.signature,
96
+ is_exported = excluded.is_exported,
97
+ hash = excluded.hash,
98
+ language = excluded.language
99
+ `);for(let n of e)t.run(n.id,n.filePath,n.name,n.qualifiedName,n.kind,n.startLine,n.endLine,n.signature,n.isExported?1:0,n.hash,n.language)}getSymbolsByFile(e){return this.db.prepare("SELECT * FROM symbols WHERE file_path = ? ORDER BY start_line ASC").all(e).map(this.mapSymbolRow)}getSymbol(e){let t=this.db.prepare("SELECT * FROM symbols WHERE id = ?").get(e);return t?this.mapSymbolRow(t):null}findSymbols(e,t){return t?this.db.prepare(`
100
+ SELECT * FROM symbols
101
+ WHERE (name = ? OR qualified_name = ? OR name LIKE ? OR qualified_name LIKE ?)
102
+ AND kind = ?
103
+ LIMIT 50
104
+ `).all(e,e,`%${e}%`,`%${e}%`,t).map(this.mapSymbolRow):this.db.prepare(`
105
+ SELECT * FROM symbols
106
+ WHERE name = ? OR qualified_name = ? OR name LIKE ? OR qualified_name LIKE ?
107
+ LIMIT 50
108
+ `).all(e,e,`%${e}%`,`%${e}%`).map(this.mapSymbolRow)}deleteSymbolsByFile(e){this.db.prepare("DELETE FROM symbols WHERE file_path = ?").run(e)}mapSymbolRow(e){return{id:e.id,filePath:e.file_path,name:e.name,qualifiedName:e.qualified_name,kind:e.kind,startLine:e.start_line,endLine:e.end_line,signature:e.signature,isExported:!!e.is_exported,hash:e.hash,language:e.language}}upsertEdges(e){let t=this.db.prepare(`
109
+ INSERT INTO edges (source_id, target_id, kind, file_path, line, confidence)
110
+ VALUES (?, ?, ?, ?, ?, ?)
111
+ `);for(let n of e)t.run(n.sourceId,n.targetId,n.kind,n.filePath,n.line,n.confidence)}getOutgoingEdges(e,t){return t?this.db.prepare("SELECT * FROM edges WHERE source_id = ? AND kind = ?").all(e,t).map(this.mapEdgeRow):this.db.prepare("SELECT * FROM edges WHERE source_id = ?").all(e).map(this.mapEdgeRow)}getIncomingEdges(e,t){return t?this.db.prepare("SELECT * FROM edges WHERE target_id = ? AND kind = ?").all(e,t).map(this.mapEdgeRow):this.db.prepare("SELECT * FROM edges WHERE target_id = ?").all(e).map(this.mapEdgeRow)}deleteEdgesByFile(e){this.db.prepare("DELETE FROM edges WHERE file_path = ?").run(e)}mapEdgeRow(e){return{sourceId:e.source_id,targetId:e.target_id,kind:e.kind,filePath:e.file_path,line:e.line,confidence:e.confidence}}getIR(e,t,n){let i=this.db.prepare(`
112
+ SELECT content_hash, ir_blob FROM ir_cache
113
+ WHERE file_path = ? AND level = ?
114
+ `).get(e,t);return!i||n&&i.content_hash!==n?null:i.ir_blob}setIR(e,t,n,i){this.db.prepare(`
115
+ INSERT INTO ir_cache (file_path, level, content_hash, ir_blob)
116
+ VALUES (?, ?, ?, ?)
117
+ ON CONFLICT(file_path, level) DO UPDATE SET
118
+ content_hash = excluded.content_hash,
119
+ ir_blob = excluded.ir_blob
120
+ `).run(e,t,n,i)}invalidateIR(e){this.db.prepare("DELETE FROM ir_cache WHERE file_path = ?").run(e)}getSession(e,t){let n=this.db.prepare(`
121
+ SELECT * FROM sessions WHERE session_id = ? AND file_path = ?
122
+ `).get(e,t);return n?{sessionId:n.session_id,filePath:n.file_path,fingerprint:n.fingerprint,createdAt:n.created_at,expiresAt:n.expires_at}:null}setSession(e,t,n,i=24){let l=Date.now(),S=l+i*3600*1e3;this.db.prepare(`
123
+ INSERT INTO sessions (session_id, file_path, fingerprint, created_at, expires_at)
124
+ VALUES (?, ?, ?, ?, ?)
125
+ ON CONFLICT(session_id, file_path) DO UPDATE SET
126
+ fingerprint = excluded.fingerprint,
127
+ created_at = excluded.created_at,
128
+ expires_at = excluded.expires_at
129
+ `).run(e,t,n,l,S)}cleanExpiredSessions(){let e=Date.now();return this.db.prepare("DELETE FROM sessions WHERE expires_at < ?").run(e)?.changes||0}clearSession(e){this.db.prepare("DELETE FROM sessions WHERE session_id = ?").run(e)}upsertFact(e){this.db.prepare(`
130
+ INSERT INTO memory_facts (id, statement, provenance_json, confidence, category, created_at, verified_at, dependencies_json)
131
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
132
+ ON CONFLICT(id) DO UPDATE SET
133
+ statement = excluded.statement,
134
+ provenance_json = excluded.provenance_json,
135
+ confidence = excluded.confidence,
136
+ category = excluded.category,
137
+ verified_at = excluded.verified_at,
138
+ dependencies_json = excluded.dependencies_json
139
+ `).run(e.id,e.statement,JSON.stringify(e.provenance),e.confidence,e.category,e.createdAt,e.verifiedAt,JSON.stringify(e.dependencies))}getFacts(e){let t;return e?t=this.db.prepare("SELECT * FROM memory_facts WHERE category = ? ORDER BY confidence DESC").all(e):t=this.db.prepare("SELECT * FROM memory_facts ORDER BY confidence DESC").all(),t.map(n=>({id:n.id,statement:n.statement,provenance:u(n.provenance_json),confidence:n.confidence,category:n.category,createdAt:n.created_at,verifiedAt:n.verified_at,dependencies:u(n.dependencies_json)}))}deleteFact(e){this.db.prepare("DELETE FROM memory_facts WHERE id = ?").run(e)}close(){try{this.db.close()}catch{}}},a=new Map;function v(s){if(!s||s===":memory:"){let i=":memory:";return a.has(i)||a.set(i,new o(":memory:")),a.get(i)}let e=c.resolve(s);if(a.has(e))return a.get(e);let t=c.join(e,".glyphier","0.1.sqlite"),n=new o(t);return a.set(e,n),n}import T from"web-tree-sitter";import d from"fs";import r from"path";import{createRequire as I}from"module";var _=I(import.meta.url),h=!1,E=new Map,f={".ts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".rs":"rust",".go":"go",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"c_sharp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".lua":"lua",".zig":"zig",".elm":"elm",".ex":"elixir",".exs":"elixir",".sh":"bash",".bash":"bash"};async function x(){if(h)return;let s;try{let e=_.resolve("web-tree-sitter/package.json");s=r.join(r.dirname(e),"tree-sitter.wasm")}catch{s=r.resolve("node_modules/web-tree-sitter/tree-sitter.wasm")}await T.init({locateFile:e=>e==="tree-sitter.wasm"?s:e}),h=!0}function O(s){let e=r.resolve(`assets/grammars/tree-sitter-${s}.wasm`);if(d.existsSync(e))return e;try{let t=_.resolve("tree-sitter-wasms/package.json"),n=r.join(r.dirname(t),"out",`tree-sitter-${s}.wasm`);if(d.existsSync(n))return n}catch{}return null}function P(s){let e=r.extname(s).toLowerCase();return f[e]||null}async function j(s){if(await x(),E.has(s))return E.get(s);let e=O(s);if(!e||!d.existsSync(e))return null;let t=d.readFileSync(e),n=await T.Language.load(t);return E.set(s,n),n}function q(){return Array.from(new Set(Object.values(f))).sort()}var B="0.1.0",Y="0.1";export{o as a,v as b,f as c,x as d,P as e,j as f,q as g,B as h,Y as i};
@@ -0,0 +1,2 @@
1
+ import{createHash as p}from"crypto";function h(t){let{kind:o,title:a,rootPath:s,snapshot:d,includedSymbols:n=[]}=t,c=`docplan-${p("sha256").update(`${o}:${a}`).digest("hex").slice(0,12)}`,r=n.map((e,m)=>({id:`ev-doc-${m+1}`,sourceType:"symbol_definition",path:e.filePath,snapshotRef:`${d.repositoryId}:${d.headRef}`,startLine:e.startLine,endLine:e.endLine,symbolName:e.name,retrievalReason:`Documented symbol for ${o}`,freshness:"fresh",schemaVersion:"1.0.0"})),i=n.filter(e=>e.isExported).map((e,m)=>({id:`assert-${m+1}`,documentPath:`docs/${o}/${a.toLowerCase().replace(/\s+/g,"-")}.md`,claim:`Exported symbol ${e.name} is defined in ${e.filePath}`,type:"api",predicate:{id:`pred-${m+1}`,kind:"exports_symbol",targetPath:e.filePath,targetSymbol:e.name,description:`Verify ${e.name} is exported from ${e.filePath}`},verificationMethod:"source_relation",anchors:[{symbolName:e.name,path:e.filePath,startLine:e.startLine,endLine:e.endLine}],status:"unverified"})),l=["Overview & Intent","Architecture & Responsibilities","Exported Surface & Contracts","Verification & Invariants"];return{planId:c,kind:o,title:a,targetSymbols:n.map(e=>e.name),outlineSections:l,plannedEvidence:r,assertionsToValidate:i}}function b(t,o,a){let s=[`# ${t.title}`,"",`> Generated by Glyphier Documentation Compiler (Kind: \`${t.kind}\`)`,"> **Status:** Pending Human Review (Invariant: No auto-merge without review)","","## Overview & Intent",`This document provides formal, provenance-backed documentation for repository \`${o.repositoryName}\`.`,"","## Architecture & Responsibilities",`Documented symbols (${t.targetSymbols.length}):`,...t.targetSymbols.map(n=>`- \`${n}\``),t.targetSymbols.length===0?"- (General architecture overview)":"","","## Structured Assertions & Invariants",...t.assertionsToValidate.map(n=>`- **[${n.type.toUpperCase()}]** ${n.claim}`)].join(`
2
+ `);return{id:`doc-${p("sha256").update(`${t.planId}:${s}`).digest("hex").slice(0,16)}`,kind:t.kind,title:t.title,repository:o,compiler:a,planEvidence:t.plannedEvidence,assertions:t.assertionsToValidate,content:s,humanReviewState:"pending_review",createdAt:new Date().toISOString(),schemaVersion:"1.0.0"}}function g(t,o){let a=[],s=0,d=0,n=0;for(let c of t.assertions){let r="unverified";if(c.predicate){let i=c.predicate;switch(i.kind){case"symbol_exists":{r=(i.targetSymbol?o.symbolExists(i.targetSymbol,i.targetPath):!1)?"valid":"outdated";break}case"exports_symbol":{r=(i.targetSymbol?o.isSymbolExported(i.targetSymbol,i.targetPath):!1)?"valid":"outdated";break}case"calls_symbol":{i.targetSymbol&&i.calleeSymbol&&o.callsSymbol&&(r=o.callsSymbol(i.targetSymbol,i.calleeSymbol)?"valid":"outdated");break}default:r="unverified"}}r==="valid"?s++:r==="outdated"?d++:n++,a.push({...c,status:r,lastValidatedRevision:t.repository.headRef??void 0})}return{validCount:s,outdatedCount:d,unverifiedCount:n,updatedAssertions:a}}export{h as a,b,g as c};
@@ -0,0 +1,2 @@
1
+ import{createHash as E}from"crypto";import A from"path";import{z as l}from"zod";var O=l.object({type:l.enum(["public_api","mcp_tool","cli_command","exported_type","database_schema","config","test","internal"]),path:l.string(),symbol:l.string().optional()}),ee=l.object({intrinsicRisk:l.enum(["critical","high","medium","low","minimal"]),effectiveRisk:l.enum(["critical","high","medium","low","minimal"]),riskElevationReason:l.string().optional(),affectedSurfaces:l.array(O),policyDecision:l.enum(["proceed","review_required","block","abstain"]),requiresHumanReview:l.boolean(),reviewDomains:l.array(l.string()),schemaVersion:l.literal("1.0.0")});function D(s,t,r){let n=["minimal","low","medium","high","critical"],o=n.indexOf(s);return t&&(o=Math.max(o,n.indexOf("medium"))),r==="minimal"&&(o=Math.max(o,n.indexOf("high"))),r==="low"&&(o=Math.max(o,n.indexOf("medium"))),n[o]}import{z as i}from"zod";var W=i.enum(["fact","inference","decision","outcome","preference","invariant","dead_end"]),B=i.enum(["candidate","observed","corroborated","trusted","stale","superseded","invalidated"]),j=i.enum(["MEMORY_ABOUT","SUPERSEDES","CONTRADICTS","VALIDATED_BY"]),F=i.object({relationType:j,targetEventId:i.string()}),G=i.object({symbolName:i.string().optional(),path:i.string().optional(),startLine:i.number().int().positive().optional(),endLine:i.number().int().positive().optional()}),H=i.object({source:i.string(),authorRef:i.string().optional(),capturedAtRevision:i.string(),contextArtifactId:i.string().optional()}),U=i.object({id:i.string(),statement:i.string().min(3),claimType:W,lifecycleState:B,anchors:i.array(G).default([]),provenance:H,confidence:i.number().min(0).max(1),relations:i.array(F).default([]),validationMetadata:i.object({validatedByRule:i.string(),validatedAt:i.string()}).optional(),createdAt:i.string(),schemaVersion:i.literal("1.0.0").default("1.0.0")});function Y(s){return U.parse(s)}var x=class{events=new Map;constructor(t=[]){for(let r of t)this.addEvent(r)}addEvent(t){let r=Y(t);this.events.set(r.id,r)}getEvent(t){return this.events.get(t)}getAllEvents(){return Array.from(this.events.values())}getActiveInvariants(t){return Array.from(this.events.values()).filter(r=>r.claimType!=="invariant"&&r.claimType!=="decision"||r.lifecycleState!=="trusted"&&r.lifecycleState!=="corroborated"?!1:t?r.anchors.some(n=>n.symbolName&&n.symbolName.toLowerCase()===t.toLowerCase()||n.path&&n.path.includes(t)):!0)}getDeadEnds(t=[]){let r=t.map(n=>n.toLowerCase());return Array.from(this.events.values()).filter(n=>{if(n.claimType!=="dead_end"||n.lifecycleState==="invalidated"||n.lifecycleState==="superseded")return!1;if(r.length===0)return!0;let o=n.statement.toLowerCase();return r.some(m=>o.includes(m))})}relate(t,r,n){let o=this.events.get(t),m=this.events.get(n);return!o||!m?!1:(o.relations.push({relationType:r,targetEventId:n}),r==="SUPERSEDES"&&(m.lifecycleState="superseded"),!0)}};var K=new Set(["a","an","the","in","on","at","to","for","with","from","of","by","and","or","is","are","was","were","it","this","that","we","i","how","does","do","can","should","would","could","what","where"]);function J(s){let t=s.toLowerCase();return t.includes("fix")||t.includes("bug")||t.includes("issue")||t.includes("error")||t.includes("fail")||t.includes("crash")?"bug_fix":t.includes("refactor")||t.includes("clean")||t.includes("modularize")||t.includes("restructure")||t.includes("extract")?"refactor":t.includes("test")||t.includes("spec")||t.includes("coverage")||t.includes("benchmark")?"test":t.includes("how")||t.includes("explain")||t.includes("why")||t.includes("where")||t.includes("understand")||t.includes("audit")?"investigation":t.includes("version")||t.includes("release")||t.includes("bump")||t.includes("deploy")||t.includes("format")?"chore":"feature"}function Q(s,t){let r=J(s),n=s.toLowerCase().replace(/[^a-z0-9_\-\.\/]/g," ").split(/\s+/).filter(c=>c.length>1&&!K.has(c)),o=Array.from(new Set(n)),m=n.filter(c=>c.includes("/")||c.endsWith(".ts")||c.endsWith(".js")||c.endsWith(".py")||c.endsWith(".go")||c.endsWith(".rs"));return{taskId:`task-${E("sha256").update(s).digest("hex").slice(0,12)}`,rawPrompt:s,normalizedIntent:r,requestedPaths:m,requestedSymbols:o.filter(c=>!m.includes(c)&&c.length>2),constraints:["Evidence-backed selection","Preserve existing test coverage","Respect workspace boundaries"],acceptanceSignals:[r==="bug_fix"?"Regression test passes":"Target behavior verified","No lint or typecheck regressions"],confidence:.95,schemaVersion:"1.0.0"}}function de(s){let t=A.resolve(s.rootPath),r=s.tokenBudget||2500,n=Q(s.task,t),o={repositoryId:A.basename(t),repositoryName:A.basename(t),rootPath:t,headRef:"HEAD",indexState:"clean",ignorePolicy:{patterns:["node_modules",".git"],gitignoreApplied:!0},capturedAt:new Date().toISOString(),schemaVersion:"1.0.0",...s.snapshot},m={cliVersion:"4.1.0",parserVersions:[{language:"typescript",grammarVersion:"0.23.0"}],rankingVersion:"1.0.0",riskPolicyVersion:"1.0.0",budgetPolicyVersion:"1.0.0",capabilityFlags:{context_compiler:!0,memory:!0,review_compiler:!0},fingerprintHash:"sha256:compiler-fp-4.1.0",schemaVersion:"1.0.0",...s.fingerprint},c={parseCoverage:1,parseFailures:[],unresolvedEdges:[],skippedPaths:[],hasDynamicBoundaries:!1,coverageTier:"high",schemaVersion:"1.0.0",...s.coverage},I=(s.candidateSymbols||[]).map(e=>{let a=0,d=(e.qualifiedName||e.name).toLowerCase();for(let f of n.requestedSymbols)d===f.toLowerCase()?a+=10:d.includes(f.toLowerCase())&&(a+=5);for(let f of n.requestedPaths)e.filePath.toLowerCase().includes(f.toLowerCase())&&(a+=8);return e.isExported&&(a+=2),(e.kind==="fn"||e.kind==="class")&&(a+=2),{sym:e,score:a}});I.sort((e,a)=>a.score-e.score);let u=[],p=[],P=[],h=new Set,y=120,_=0;for(let{sym:e,score:a}of I){let d=Math.max(30,(e.endLine-e.startLine)*4);if(a===0){p.push({path:e.filePath,symbol:e.name,exclusionReason:"unrelated"});continue}if(y+d>r){p.push({path:e.filePath,symbol:e.name,exclusionReason:"budget_limited"});continue}let f=`ev-${E("sha256").update(`${e.filePath}:${e.name}:${e.startLine}`).digest("hex").slice(0,10)}`;P.push({id:f,sourceType:"symbol_definition",path:e.filePath,snapshotRef:`${o.repositoryId}:${o.headRef}`,startLine:e.startLine,endLine:e.endLine,retrievalReason:`Matched task intent: ${n.normalizedIntent}`,freshness:"fresh",schemaVersion:"1.0.0"}),u.push({path:e.filePath,symbol:e.name,level:1,selectionReason:`Candidate score: ${a}`,costTokens:d,evidenceId:f}),h.add(e.filePath),y+=d}let w=n.normalizedIntent==="bug_fix"||h.size>3?"medium":"low",v=D(w,c.unresolvedEdges.length>0,c.coverageTier),g=v==="critical"||v==="high",q={intrinsicRisk:w,effectiveRisk:v,affectedSurfaces:Array.from(h).map(e=>({type:e.includes("test")?"test":"internal",path:e})),policyDecision:g?"review_required":"proceed",requiresHumanReview:g,reviewDomains:g?["architecture_review"]:[],schemaVersion:"1.0.0"},k=new x(s.memoryEvents||[]),R=[];for(let e of n.requestedSymbols)R.push(...k.getActiveInvariants(e));for(let e of u)e.symbol&&R.push(...k.getActiveInvariants(e.symbol));let S=Array.from(new Map(R.map(e=>[e.id,e])).values()),b=k.getDeadEnds(n.requestedSymbols),V=[...S.map((e,a)=>({claimId:`mem-inv-${a+1}`,statement:`[INVARIANT] ${e.statement}`,evidenceIds:e.anchors.map(d=>d.symbolName||d.path).filter(Boolean),isContradicted:!1})),...b.map((e,a)=>({claimId:`mem-deadend-${a+1}`,statement:`[DEAD_END] ${e.statement}`,evidenceIds:[],isContradicted:!1}))],C={repositorySnapshot:o,compilerFingerprint:m,taskSpec:n,selectedContext:u,excludedContext:p,budgetAllocation:{tokenBudget:r,tokensUsed:y,tokensSaved:_},riskAssessment:q,coverage:c,claimLedger:[...u.map((e,a)=>({claimId:`claim-${a+1}`,statement:`Target symbol ${e.symbol||e.path} in scope for ${n.normalizedIntent}`,evidenceIds:e.evidenceId?[e.evidenceId]:[],isContradicted:!1})),...V],evidenceRefs:P,compiledAt:new Date().toISOString(),schemaVersion:"1.0.0"},T=E("sha256").update(JSON.stringify(C)).digest("hex"),z={...C,artifactId:T},M=`plan-${T.slice(0,12)}`,N=[`# Glyphier Task Plan: ${M}`,`Intent: ${n.normalizedIntent.toUpperCase()} | Budget: ${y}/${r} tokens | Risk: ${v.toUpperCase()}`,"","## Entrypoints & Candidates:",...u.map(e=>`- ${e.path} (${e.symbol||"file"}) \u2014 ${e.selectionReason}`),u.length===0?"- (No direct candidates found matching keywords)":"","",S.length>0||b.length>0?"## \u{1F9E0} Memory & Constraints (TM-06):":"",...S.map(e=>`- **[INVARIANT]** (${e.id}): ${e.statement}`),...b.map(e=>`- \u26A0\uFE0F **[DEAD END]** (${e.id}): ${e.statement}`),(S.length>0||b.length>0,""),"## Mutation Envelope:",`- Allowed paths: ${Array.from(h).join(", ")||"None (read-only plan)"}`,`- Human review required: ${g?"YES":"NO"}`,"",`## Exclusions (${p.length}):`,...p.slice(0,5).map(e=>`- ${e.path} (${e.symbol||"file"}): ${e.exclusionReason}`),p.length>5?` ... and ${p.length-5} more items`:"","","## Verification Plan:",...n.acceptanceSignals.map(e=>`- [ ] ${e}`)].filter(Boolean).join(`
2
+ `);return{planId:M,taskSpec:n,contextArtifact:z,mutationPolicy:{allowedPaths:Array.from(h),requireDryRun:!0,requireHumanReview:g},renderedPlan:N}}export{ee as a,J as b,Q as c,de as d};
@@ -0,0 +1,2 @@
1
+ function I(s,o){let{storage:r}=o,c=o.direction||"both",a=Math.min(Math.max(o.depth||2,1),5),t=r.findSymbols(s);if(t.length===0)return{rootSymbol:s,direction:c,depth:a,nodes:[],edges:[]};let d=t[0],n=new Map;n.set(d.id,{symbol:d,depth:0});let i=[],f=new Set,h=[d.id];for(let m=1;m<=a;m++){let u=[];for(let b of h){if(c==="callees"||c==="both"){let p=r.getOutgoingEdges(b);for(let e of p){let l=`${e.sourceId}->${e.targetId}:${e.kind}`;if(f.has(l)||(f.add(l),i.push(e)),!n.has(e.targetId)){let g=r.getSymbol(e.targetId);g&&(n.set(e.targetId,{symbol:g,depth:m}),u.push(e.targetId))}}}if(c==="callers"||c==="both"){let p=r.getIncomingEdges(b,"calls");for(let e of p){let l=`${e.sourceId}->${e.targetId}:${e.kind}`;if(f.has(l)||(f.add(l),i.push(e)),!n.has(e.sourceId)){let g=r.getSymbol(e.sourceId);g&&(n.set(e.sourceId,{symbol:g,depth:m}),u.push(e.sourceId))}}}}if(h=u,h.length===0)break}return{rootSymbol:d.qualifiedName||d.name,direction:c,depth:a,nodes:Array.from(n.values()),edges:i}}function $(s){if(s.nodes.length===0)return`(trace ${s.rootSymbol} :status not-found)`;let o=[];o.push(`(trace ${s.rootSymbol} :direction ${s.direction} :depth ${s.depth}`);let r=s.nodes.find(t=>t.depth===0);r&&o.push(` (root ${r.symbol.qualifiedName} :kind ${r.symbol.kind} :file ${r.symbol.filePath}:${r.symbol.startLine})`);let c=s.edges.filter(t=>t.sourceId===r?.symbol.id);if(c.length>0){o.push(" (callees");for(let t of c){let d=s.nodes.find(i=>i.symbol.id===t.targetId)?.symbol,n=d?d.qualifiedName:t.targetId;o.push(` (calls ${n} :conf ${t.confidence.toFixed(2)})`)}o.push(" )")}let a=s.edges.filter(t=>t.targetId===r?.symbol.id);if(a.length>0){o.push(" (callers");for(let t of a){let d=s.nodes.find(i=>i.symbol.id===t.sourceId)?.symbol,n=d?d.qualifiedName:t.sourceId;o.push(` (called_by ${n} :conf ${t.confidence.toFixed(2)})`)}o.push(" )")}return o.push(")"),o.join(`
2
+ `)}export{I as a,$ as b};