@aliip/pilah 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/BUILD_STATUS.md +23 -0
- package/LICENSE +21 -0
- package/README.md +108 -2
- package/assets/logo.svg +5 -0
- package/docs/ACCEPTANCE_GATE.md +41 -0
- package/docs/ADAPTIVE_RCA_WORKFLOW.md +93 -0
- package/docs/AGENT_DECISION_REVIEW.md +17 -0
- package/docs/ALWAYS_ON_5_WHYS.md +75 -0
- package/docs/ARCHITECTURE.md +43 -0
- package/docs/BEHAVIORAL_5_WHYS_V2_0_1.md +117 -0
- package/docs/CHECKPOINT_RECOVERY.md +86 -0
- package/docs/CI_EFFICIENCY.md +63 -0
- package/docs/COMPATIBILITY.md +84 -0
- package/docs/CONTRACTS.md +177 -0
- package/docs/CONVERSATION_USAGE.md +52 -0
- package/docs/ENGINEERING_METHOD.md +68 -0
- package/docs/HOST_VALIDATION.md +35 -0
- package/docs/INDEPENDENT_ACCEPTANCE_RUNBOOK.md +72 -0
- package/docs/INTERVENTION_LEDGER.md +25 -0
- package/docs/MAIN_VALIDATION_BACKLOG.md +19 -0
- package/docs/NATIVE_FIRST_WORKFLOW.md +27 -0
- package/docs/OPEN_SOURCE_ENGINEERING_STANDARDS.md +62 -0
- package/docs/ORCHESTRATION_ADVISOR.md +36 -0
- package/docs/PRE_VNEXT_INTEGRATION.md +27 -0
- package/docs/README.md +54 -0
- package/docs/RELEASE.md +33 -0
- package/docs/RELEASE_AUTHORIZATION.md +33 -0
- package/docs/RISK_GUIDANCE.md +18 -0
- package/docs/SECURITY.md +76 -0
- package/docs/SECURITY_RELIABILITY_AUDIT_V2_0_1.md +55 -0
- package/docs/SEMANTIC_EVIDENCE.md +27 -0
- package/docs/SOURCES.md +13 -0
- package/docs/TOKEN_EFFICIENCY.md +71 -0
- package/docs/TOKEN_PROVENANCE.md +15 -0
- package/docs/V2_0_1_TRACEABILITY.md +66 -0
- package/hooks.json +45 -0
- package/mcp_config.json +16 -0
- package/package.json +31 -4
- package/plugin.json +27 -0
- package/rules/AGENTS.md +2 -0
- package/schemas/database.sql +84 -0
- package/schemas/mcp-tools.json +552 -0
- package/scripts/a2a.mjs +344 -0
- package/scripts/check-release.mjs +42 -0
- package/scripts/check-syntax.mjs +30 -0
- package/scripts/checkpoint.mjs +50 -0
- package/scripts/compare-agent-traces.mjs +53 -0
- package/scripts/context-guardian.mjs +132 -0
- package/scripts/evaluate-acceptance.mjs +110 -0
- package/scripts/export-benchmark.mjs +31 -0
- package/scripts/generate-contracts.mjs +6 -0
- package/scripts/hook.mjs +406 -0
- package/scripts/host-check.mjs +40 -0
- package/scripts/intervention-ledger.mjs +94 -0
- package/scripts/pilah.mjs +3 -0
- package/scripts/release-authorization.mjs +137 -0
- package/scripts/review-agent-decisions.mjs +34 -0
- package/scripts/semantic-evidence.mjs +15 -0
- package/scripts/verifykit.mjs +3 -0
- package/skills/pilah/SKILL.md +24 -0
- package/src/acceptance-matrix.mjs +84 -0
- package/src/browser-evidence.mjs +40 -0
- package/src/context-health.mjs +14 -0
- package/src/conversations.mjs +302 -0
- package/src/engine.mjs +494 -0
- package/src/graph.mjs +169 -0
- package/src/mcp-diagnostics.mjs +53 -0
- package/src/mcp.mjs +151 -0
- package/src/model-recovery.mjs +108 -0
- package/src/native-tool-recovery.mjs +45 -0
- package/src/node-runtime.mjs +13 -0
- package/src/orchestration-advisor.mjs +24 -0
- package/src/rca.mjs +174 -0
- package/src/risk-guidance.mjs +95 -0
- package/src/scanner.mjs +303 -0
- package/src/security.mjs +793 -0
- package/src/semantic-evidence.mjs +144 -0
- package/src/skill-discovery.mjs +23 -0
- package/src/sqlite-compat.mjs +11 -0
- package/src/storage.mjs +455 -0
- package/src/tokens.mjs +627 -0
- package/src/tools.mjs +164 -0
- package/src/verification.mjs +567 -0
- package/src/workflow-router.mjs +34 -0
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// Semantic evidence evaluator. All supplied observations remain local and UNATTESTED.
|
|
2
|
+
// It never promotes a caller-asserted witness list to an independently verified pass.
|
|
3
|
+
const BUILTIN={
|
|
4
|
+
'true-concurrency':['parallel_clients','shared_stock_record','atomic_commit','one_winner_asserted'],
|
|
5
|
+
'offline-restart':['network_disconnected','durable_queue_written','browser_closed','browser_reopened','queue_recovered','sync_exactly_once'],
|
|
6
|
+
'lost-response-retry':['first_commit_persisted','response_loss_simulated','same_operation_id_retried','no_duplicate_asserted'],
|
|
7
|
+
'double-refund':['initial_refund_persisted','second_refund_rejected','stock_not_duplicated','money_not_duplicated'],
|
|
8
|
+
'financial-reconciliation':['server_price','item_order_reconcile','payment_reconcile'],
|
|
9
|
+
'tenant-entry-points':['cross_tenant_denials','no_mutations'],
|
|
10
|
+
'refund-duplicate-lines':['duplicate_detected','bounded_refund_and_restock'],
|
|
11
|
+
'refund-amount-only':['partial_refund','no_implicit_restock'],
|
|
12
|
+
'transfer-race':['parallel_transitions','single_final_state'],
|
|
13
|
+
'offline-account-switch':['different_accounts','no_cross_account_cache'],
|
|
14
|
+
'role-matrix':['forbidden_roles_tested','denials_observed','db_unchanged'],
|
|
15
|
+
'relational-ownership':['cross_org_ids_tested','foreign_ids_rejected'],
|
|
16
|
+
'production-credentials':['production_build_observed','no_usable_demo_credentials'],
|
|
17
|
+
'error-sanitization':['failure_injected','private_exception_hidden'],
|
|
18
|
+
'invitation-flow':['expiration_and_acceptance','tenant_scope_enforced'],
|
|
19
|
+
'login-throttling':['invalid_attempts_repeated','rate_limited']
|
|
20
|
+
};
|
|
21
|
+
const valid=x=>typeof x==='string'&&/^[a-z][a-z0-9_-]{2,80}$/.test(x);
|
|
22
|
+
const object=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
|
|
23
|
+
const finite=x=>typeof x==='number'&&Number.isFinite(x);
|
|
24
|
+
const positive=x=>Number.isSafeInteger(x)&&x>=0;
|
|
25
|
+
const eq=x=>x===true;
|
|
26
|
+
const uniq=arr=>[...new Set(arr)];
|
|
27
|
+
function intervalPair(a){
|
|
28
|
+
if(!Array.isArray(a)||a.length!==2)return false;
|
|
29
|
+
const [x,y]=a;
|
|
30
|
+
return x&&y&&x.connection_id&&y.connection_id&&x.connection_id!==y.connection_id&&
|
|
31
|
+
x.resource_id&&x.resource_id===y.resource_id&&
|
|
32
|
+
[x.started_at_ms,x.completed_at_ms,y.started_at_ms,y.completed_at_ms].every(finite)&&
|
|
33
|
+
x.started_at_ms<x.completed_at_ms&&y.started_at_ms<y.completed_at_ms&&
|
|
34
|
+
Math.max(x.started_at_ms,y.started_at_ms)<Math.min(x.completed_at_ms,y.completed_at_ms);
|
|
35
|
+
}
|
|
36
|
+
export function inspectScenarioFacts(name,facts){
|
|
37
|
+
const f=object(facts)?facts:{};
|
|
38
|
+
const checks={
|
|
39
|
+
'true-concurrency':{
|
|
40
|
+
parallel_clients:intervalPair(f.requests),
|
|
41
|
+
shared_stock_record:Array.isArray(f.requests)&&f.requests.length===2&&f.requests[0]?.resource_id===f.requests[1]?.resource_id&&!!f.requests[0]?.resource_id,
|
|
42
|
+
atomic_commit:f.database_dialect!=='sqlite-in-memory'&&f.database_transactions_observed===true,
|
|
43
|
+
one_winner_asserted:Array.isArray(f.requests)&&f.requests.filter(r=>r.outcome==='success').length===1&&f.orders_created===1&&positive(f.stock_after)&&f.stock_after===0
|
|
44
|
+
},
|
|
45
|
+
'offline-restart':{
|
|
46
|
+
network_disconnected:eq(f.network_disconnected_before_checkout),
|
|
47
|
+
durable_queue_written:positive(f.queued_before_restart)&&f.queued_before_restart>=1&&eq(f.queue_written_to_persistent_storage),
|
|
48
|
+
browser_closed:typeof f.process_before==='string'&&f.process_before.length>0&&eq(f.browser_process_terminated),
|
|
49
|
+
browser_reopened:!!f.process_after&&f.process_after!==f.process_before&&!!f.profile_before&&f.profile_before===f.profile_after,
|
|
50
|
+
queue_recovered:positive(f.queued_after_restart)&&f.queued_after_restart>=1&&eq(f.recovered_same_operation_id),
|
|
51
|
+
sync_exactly_once:f.orders_created===1&&f.ledger_movements===1&&f.queue_after_sync===0&&eq(f.backend_assertions_executed)
|
|
52
|
+
},
|
|
53
|
+
'lost-response-retry':{
|
|
54
|
+
first_commit_persisted:eq(f.first_transaction_committed),
|
|
55
|
+
response_loss_simulated:eq(f.response_dropped_after_commit),
|
|
56
|
+
same_operation_id_retried:eq(f.same_operation_id)&&eq(f.same_payload_hash),
|
|
57
|
+
no_duplicate_asserted:f.orders_created===1&&f.ledger_movements===1&&eq(f.different_payload_rejected)&&f.conflict_status===409
|
|
58
|
+
},
|
|
59
|
+
'double-refund':{
|
|
60
|
+
initial_refund_persisted:eq(f.first_refund_committed),
|
|
61
|
+
second_refund_rejected:eq(f.duplicate_refund_rejected),
|
|
62
|
+
stock_not_duplicated:positive(f.total_restocked_qty)&&positive(f.original_sold_qty)&&f.total_restocked_qty<=f.original_sold_qty,
|
|
63
|
+
money_not_duplicated:positive(f.refunded_minor)&&positive(f.original_paid_minor)&&f.refunded_minor<=f.original_paid_minor
|
|
64
|
+
},
|
|
65
|
+
'financial-reconciliation':{
|
|
66
|
+
server_price:f.price_source==='server'&&eq(f.override_policy_checked),
|
|
67
|
+
item_order_reconcile:[f.gross_minor,f.item_discount_minor,f.tax_minor,f.total_minor].every(positive)&&f.gross_minor-f.item_discount_minor+f.tax_minor===f.total_minor,
|
|
68
|
+
payment_reconcile:positive(f.total_minor)&&positive(f.payment_sum_minor)&&f.total_minor===f.payment_sum_minor
|
|
69
|
+
},
|
|
70
|
+
'tenant-entry-points':{
|
|
71
|
+
cross_tenant_denials:Array.isArray(f.denied_entry_points)&&['online','offline-sync','inventory','refund','order-read'].every(x=>f.denied_entry_points.includes(x)),
|
|
72
|
+
no_mutations:eq(f.forbidden_requests_db_unchanged)&&eq(f.cross_org_relations_rejected)
|
|
73
|
+
},
|
|
74
|
+
'refund-duplicate-lines':{
|
|
75
|
+
duplicate_detected:eq(f.same_item_id_appears_twice_in_single_request),
|
|
76
|
+
bounded_refund_and_restock:eq(f.request_rejected_or_aggregated)&&positive(f.restock_qty)&&positive(f.qty_purchased)&&f.restock_qty<=f.qty_purchased
|
|
77
|
+
},
|
|
78
|
+
'refund-amount-only':{
|
|
79
|
+
partial_refund:positive(f.refund_minor)&&positive(f.original_paid_minor)&&f.refund_minor>0&&f.refund_minor<f.original_paid_minor,
|
|
80
|
+
no_implicit_restock:f.explicit_return_items===false&&f.restock_qty===0
|
|
81
|
+
},
|
|
82
|
+
'transfer-race':{
|
|
83
|
+
parallel_transitions:intervalPair(f.requests),
|
|
84
|
+
single_final_state:Array.isArray(f.requests)&&f.requests.filter(x=>x.outcome==='success').length===1&&f.stock_movements===1&&['received','cancelled'].includes(f.final_state)
|
|
85
|
+
},
|
|
86
|
+
'role-matrix':{
|
|
87
|
+
forbidden_roles_tested:Array.isArray(f.forbidden_roles)&&['cashier','auditor','no-member'].every(x=>f.forbidden_roles.includes(x)),
|
|
88
|
+
denials_observed:Array.isArray(f.forbidden_statuses)&&f.forbidden_statuses.length>=3&&f.forbidden_statuses.every(x=>[401,403,404].includes(x)),
|
|
89
|
+
db_unchanged:f.forbidden_db_mutation_count===0&&eq(f.no_protected_data_leaked)
|
|
90
|
+
},
|
|
91
|
+
'relational-ownership':{
|
|
92
|
+
cross_org_ids_tested:eq(f.foreign_store_id_sent)&&eq(f.foreign_supplier_id_sent),
|
|
93
|
+
foreign_ids_rejected:eq(f.relational_constraint_rejected)&&f.cross_org_relations_created===0
|
|
94
|
+
},
|
|
95
|
+
'production-credentials':{
|
|
96
|
+
production_build_observed:eq(f.production_build_tested),
|
|
97
|
+
no_usable_demo_credentials:f.demo_credentials_rendered===false&&f.known_demo_login_accepted===false
|
|
98
|
+
},
|
|
99
|
+
'error-sanitization':{
|
|
100
|
+
failure_injected:eq(f.server_error_injected),
|
|
101
|
+
private_exception_hidden:eq(f.private_message_hidden)&&eq(f.correlation_id_present)
|
|
102
|
+
},
|
|
103
|
+
'invitation-flow':{
|
|
104
|
+
expiration_and_acceptance:eq(f.recipient_acceptance_tested)&&eq(f.expired_token_rejected),
|
|
105
|
+
tenant_scope_enforced:eq(f.cross_tenant_store_invite_rejected)&&eq(f.unauthorized_invite_rejected)
|
|
106
|
+
},
|
|
107
|
+
'login-throttling':{
|
|
108
|
+
invalid_attempts_repeated:Number.isInteger(f.invalid_login_attempts)&&f.invalid_login_attempts>=6,
|
|
109
|
+
rate_limited:eq(f.throttle_returned)&&eq(f.no_credentials_disclosed)
|
|
110
|
+
},
|
|
111
|
+
'offline-account-switch':{
|
|
112
|
+
different_accounts:typeof f.user_before==='string'&&typeof f.user_after==='string'&&f.user_before.length>0&&f.user_after.length>0&&f.user_before!==f.user_after,
|
|
113
|
+
no_cross_account_cache:f.foreign_queue_visible===0&&f.personalized_cache_leaks===0&&eq(f.account_switch_completed)
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
return checks[name]||{};
|
|
117
|
+
}
|
|
118
|
+
export function evaluateSemanticClaims(data){
|
|
119
|
+
if(!object(data)||typeof data.revision!=='string'||!data.revision||data.revision.length>160)throw Error('Code revision required');
|
|
120
|
+
if(!Array.isArray(data.claims)||!data.claims.length||data.claims.length>100)throw Error('Expected 1-100 claims');
|
|
121
|
+
const ids=new Set(),out=[];
|
|
122
|
+
for(const c of data.claims){
|
|
123
|
+
if(!object(c)||!valid(c.id)||ids.has(c.id)||!Array.isArray(c.evidence)||c.evidence.length>30)throw Error('Invalid or duplicate claim');
|
|
124
|
+
ids.add(c.id);
|
|
125
|
+
// Callers may demand MORE checks but cannot remove mandatory scenario checks.
|
|
126
|
+
const builtin=BUILTIN[c.scenario];
|
|
127
|
+
const extra=c.required_capabilities;
|
|
128
|
+
if(extra!==undefined && (!Array.isArray(extra)||extra.length>20||extra.some(x=>!valid(x))))throw Error('Required capabilities must be explicit');
|
|
129
|
+
const required=builtin?uniq([...builtin,...(extra||[])]):extra;
|
|
130
|
+
if(!Array.isArray(required)||required.length<1||required.length>20)throw Error('Required capabilities must be explicit');
|
|
131
|
+
const validReports=c.evidence.filter(e=>object(e)&&e.revision===data.revision&&e.verdict==='passed'&&e.origin==='external-test-harness'&&typeof e.reference==='string'&&/^(?:ci|test|trace|run|evidence)[:/-][A-Za-z0-9._-]{1,100}$/.test(e.reference)&&!e.reference.includes('..')&&typeof e.checked_at==='string'&&!Number.isNaN(Date.parse(e.checked_at)));
|
|
132
|
+
const proven=new Set(),sources=[];
|
|
133
|
+
for(const e of validReports){
|
|
134
|
+
// Only evaluator-computed structured facts can cover a capability; raw witnessed_capabilities is ignored.
|
|
135
|
+
const checks=inspectScenarioFacts(c.scenario,e.observations);
|
|
136
|
+
for(const capability of required)if(checks[capability]===true)proven.add(capability);
|
|
137
|
+
sources.push(e.reference);
|
|
138
|
+
}
|
|
139
|
+
const missing=required.filter(x=>!proven.has(x));
|
|
140
|
+
const status=missing.length?'insufficient-evidence':'evidence-present-unattested';
|
|
141
|
+
out.push({id:c.id,scenario:BUILTIN[c.scenario]?c.scenario:'custom',status,trust:'unattested-local-report',witnessed:required.filter(x=>proven.has(x)),missing,external_evidence_references:uniq(sources).slice(0,20),limitations:['External runner identity and observations are caller-supplied, not cryptographically verified','Capability labels alone are ignored; independently executed artifacts must corroborate facts']});
|
|
142
|
+
}
|
|
143
|
+
return {schema:'a2a-semantic-evidence-v2',revision:data.revision,accepted:0,structurally_supported:out.filter(x=>x.status==='evidence-present-unattested').length,total:out.length,claims:out,report_status:out.every(x=>x.status==='evidence-present-unattested')?'evidence-present-unattested':'insufficient-evidence',release_verified:false,limitations:['Unattested JSON never receives an independently verified release verdict','Reviewer must inspect actual test execution provenance, runtime and database effects']};
|
|
144
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Read-only, bounded skill exclusion diagnostic. Plugin installation does not
|
|
2
|
+
// prove skill inclusion in every Antigravity conversation or subagent.
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {getHomeDir,readSafeJsonFile} from './security.mjs';
|
|
5
|
+
|
|
6
|
+
export function diagnoseSkillDiscovery(){
|
|
7
|
+
const file=path.join(getHomeDir(),'.gemini','config','skills.json');
|
|
8
|
+
const result=readSafeJsonFile(file,{maxBytes:64*1024,checkParentDir:true});
|
|
9
|
+
if(!result.ok)return {
|
|
10
|
+
status:result.reason==='missing'?'no_global_manifest':'manifest_unavailable',
|
|
11
|
+
note:'This does not establish whether the current IDE/CLI agent loaded the pilah skill. Check /skills and project exclusion manifests.'
|
|
12
|
+
};
|
|
13
|
+
const excludes=result.value.exclude;
|
|
14
|
+
if(excludes!==undefined&&(!Array.isArray(excludes)||excludes.some(x=>typeof x!=='string')))
|
|
15
|
+
return {status:'manifest_unavailable',note:'Global skill manifest exclusion format is not readable as a string array.'};
|
|
16
|
+
const excluded=Array.isArray(excludes)&&excludes.some(x=>x==='pilah'||x==='pilah:pilah'||x==='a2a'||x==='a2a:a2a');
|
|
17
|
+
return {
|
|
18
|
+
status:excluded?'excluded_by_global_manifest':'not_excluded_by_global_manifest',
|
|
19
|
+
note:excluded
|
|
20
|
+
?'A global skills.json exclusion names PILAH/A2A. Inspect it in Antigravity; this diagnostic will never alter user preferences.'
|
|
21
|
+
:'Workspace manifests, plugin-level exclusions, session-specific context and model activation remain unverified. Inspect /skills in Antigravity.'
|
|
22
|
+
};
|
|
23
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// Node 22 exposes only DatabaseSync; Node 26.11+ renamed this synchronous
|
|
2
|
+
// class to Database and retains DatabaseSync as a deprecated compatibility alias.
|
|
3
|
+
// Prefer the current API without abandoning users on supported older LTS lines.
|
|
4
|
+
import * as sqlite from 'node:sqlite';
|
|
5
|
+
|
|
6
|
+
export const sqliteApiName = typeof sqlite.Database === 'function' ? 'Database' : 'DatabaseSync';
|
|
7
|
+
export const Database = sqlite[sqliteApiName];
|
|
8
|
+
|
|
9
|
+
if (typeof Database !== 'function') {
|
|
10
|
+
throw new Error('A2A requires the built-in node:sqlite synchronous Database API (Node >=22.13.0)');
|
|
11
|
+
}
|
package/src/storage.mjs
ADDED
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
import { Database } from './sqlite-compat.mjs';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import {dataDir,sha256,safeArtifactPath,MAX_ARTIFACT_BYTES,realpathIfExists,readSafeBytesFile,getHomeDir,isSamePath,requireAuthorizedWorkspace} from './security.mjs';
|
|
6
|
+
|
|
7
|
+
const DDL=fs.readFileSync(new URL('../schemas/database.sql',import.meta.url),'utf8');
|
|
8
|
+
export class Store {
|
|
9
|
+
constructor(base=dataDir()) {
|
|
10
|
+
this.base=path.resolve(base);
|
|
11
|
+
// Never chmod a broad/shared directory if a mistaken environment override
|
|
12
|
+
// points storage at HOME, /tmp, filesystem root or an app configuration root.
|
|
13
|
+
// Treat both the OS account home and overridden HOME/USERPROFILE as protected;
|
|
14
|
+
// never chmod a user's home directory due to an environment override.
|
|
15
|
+
const homes=new Set([os.homedir(),getHomeDir()]);
|
|
16
|
+
const unsafe=[path.parse(this.base).root,os.tmpdir(),...[...homes].flatMap(home=>[
|
|
17
|
+
home,path.join(home,'.config'),path.join(home,'.gemini'),path.join(home,'.gemini','antigravity')
|
|
18
|
+
])];
|
|
19
|
+
if(unsafe.some(p=>isSamePath(p,this.base)))throw new Error('A2A data directory must be a dedicated private directory');
|
|
20
|
+
fs.mkdirSync(this.base,{recursive:true,mode:0o700});
|
|
21
|
+
const dataStat=fs.lstatSync(this.base);
|
|
22
|
+
if(dataStat.isSymbolicLink()||!dataStat.isDirectory())throw new Error('A2A data directory must be a real directory');
|
|
23
|
+
if(process.platform!=='win32'&&(dataStat.mode&0o002)!==0)throw new Error('A2A data directory cannot be world-writable');
|
|
24
|
+
try{fs.chmodSync(this.base,0o700)}catch{}
|
|
25
|
+
const a2aFile=path.join(this.base,'a2a.sqlite');
|
|
26
|
+
const legacyFile=path.join(this.base,'verifykit.sqlite');
|
|
27
|
+
const rejectUnsafeDbPath=(file)=>{
|
|
28
|
+
let st;try{st=fs.lstatSync(file)}catch(e){if(e.code==='ENOENT')return;throw e}
|
|
29
|
+
if(st.isSymbolicLink()||!st.isFile())throw new Error('Unsafe A2A database file type');
|
|
30
|
+
};
|
|
31
|
+
for(const file of [a2aFile,a2aFile+'-wal',a2aFile+'-shm',legacyFile])rejectUnsafeDbPath(file);
|
|
32
|
+
if(!fs.existsSync(a2aFile) && fs.existsSync(legacyFile)){
|
|
33
|
+
try{
|
|
34
|
+
const src=new Database(legacyFile,{readOnly:true});
|
|
35
|
+
try{src.prepare('VACUUM INTO ?').run(a2aFile)}finally{src.close()}
|
|
36
|
+
}catch(e){
|
|
37
|
+
// Raw copies are not WAL-consistent; never silently migrate a partial DB.
|
|
38
|
+
throw new Error('Legacy A2A database migration failed; original database left unchanged');
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
this.file=a2aFile;
|
|
42
|
+
this.db=new Database(this.file);
|
|
43
|
+
this.db.exec('PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL; PRAGMA busy_timeout=4000; PRAGMA trusted_schema=OFF;');
|
|
44
|
+
this.#ensureColumn('workspaces','current_revision_id','TEXT');
|
|
45
|
+
this.#ensureColumn('files','mtime_ms','REAL');
|
|
46
|
+
this.#ensureColumn('artifact_versions','workspace_id','TEXT');
|
|
47
|
+
// Upgrade old v2.0.1 RCA tables BEFORE applying DDL indexes that depend
|
|
48
|
+
// on newly added columns. Other user data and incidents are preserved.
|
|
49
|
+
this.#ensureColumn('incidents','signature_sha','TEXT');
|
|
50
|
+
for(const [column,type] of [
|
|
51
|
+
['revision_id','TEXT'],['parent_hypothesis_id','TEXT'],
|
|
52
|
+
['why_depth','INTEGER NOT NULL DEFAULT 1'],['predicted_observation','TEXT'],
|
|
53
|
+
['disconfirming_test','TEXT'],['expected_criterion_id','TEXT'],
|
|
54
|
+
['plan_id','TEXT'],['assessment_json',"TEXT NOT NULL DEFAULT '{}'"],
|
|
55
|
+
['assessed_revision_id','TEXT'],['updated_at','TEXT']
|
|
56
|
+
])this.#ensureColumn('hypotheses',column,type);
|
|
57
|
+
this.db.exec(DDL);
|
|
58
|
+
// Existing v2.0.1 SQLite databases must upgrade in place, without
|
|
59
|
+
// deleting prior user checkpoints or requiring a new major DB schema.
|
|
60
|
+
this.#ensureColumn('recovery_checkpoints','decisions_json',"TEXT NOT NULL DEFAULT '[]'");
|
|
61
|
+
this.#ensureColumn('recovery_checkpoints','pending_tests_json',"TEXT NOT NULL DEFAULT '[]'");
|
|
62
|
+
try{fs.chmodSync(this.file,0o600)}catch{}
|
|
63
|
+
this.db.prepare("INSERT OR IGNORE INTO meta(key,value) VALUES('schema_version','1')").run();
|
|
64
|
+
const actual=this.db.prepare("SELECT value FROM meta WHERE key='schema_version'").get()?.value;
|
|
65
|
+
if(actual!=='1') throw new Error('Incompatible A2A database schema '+actual);
|
|
66
|
+
}
|
|
67
|
+
#ensureColumn(table,col,type){
|
|
68
|
+
const tableExists=this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(table);
|
|
69
|
+
if(!tableExists) return;
|
|
70
|
+
const cols=this.db.prepare(`PRAGMA table_info(${table})`).all();
|
|
71
|
+
if(!cols.some(c=>c.name===col)) this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${col} ${type}`);
|
|
72
|
+
}
|
|
73
|
+
close(){this.db.close()}
|
|
74
|
+
get(sql,...params){return this.db.prepare(sql).get(...params)}
|
|
75
|
+
all(sql,...params){return this.db.prepare(sql).all(...params)}
|
|
76
|
+
run(sql,...params){return this.db.prepare(sql).run(...params)}
|
|
77
|
+
transaction(fn){
|
|
78
|
+
let active=false;
|
|
79
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
80
|
+
active=true;
|
|
81
|
+
try{
|
|
82
|
+
const result=fn();
|
|
83
|
+
this.db.exec('COMMIT');
|
|
84
|
+
active=false;
|
|
85
|
+
return result;
|
|
86
|
+
}catch(e){
|
|
87
|
+
if(active){try{this.db.exec('ROLLBACK')}catch{}}
|
|
88
|
+
throw e;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
register(ws){const canonical=realpathIfExists(ws);let id=sha256(canonical).slice(0,24);this.run('INSERT OR IGNORE INTO workspaces(id,canonical_path,created_at) VALUES(?,?,?)',id,canonical,new Date().toISOString());return id}
|
|
92
|
+
latest(wsId){
|
|
93
|
+
const active=this.get('SELECT r.* FROM workspaces w JOIN revisions r ON r.id=w.current_revision_id WHERE w.id=? AND r.workspace_id=?',wsId,wsId);
|
|
94
|
+
if(active) return active;
|
|
95
|
+
return this.get('SELECT * FROM revisions WHERE workspace_id=? ORDER BY created_at DESC LIMIT 1',wsId);
|
|
96
|
+
}
|
|
97
|
+
insertRevision(wsId,snapshot,git,env){
|
|
98
|
+
const id=sha256(wsId+':'+snapshot).slice(0,32);
|
|
99
|
+
const now=new Date().toISOString();
|
|
100
|
+
this.run('INSERT INTO revisions(id,workspace_id,git_head,snapshot_sha,environment_json,created_at) VALUES(?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET created_at=excluded.created_at, git_head=excluded.git_head',id,wsId,git||null,snapshot,JSON.stringify(env),now);
|
|
101
|
+
this.run('UPDATE workspaces SET current_revision_id=? WHERE id=?',id,wsId);
|
|
102
|
+
return id;
|
|
103
|
+
}
|
|
104
|
+
persistIndex(wsId,rev,files,nodes,edges){
|
|
105
|
+
this.transaction(()=>{
|
|
106
|
+
const existingFiles=new Map(this.all('SELECT path,content_sha,bytes,mtime_ms FROM files WHERE workspace_id=?',wsId).map(r=>[r.path,r]));
|
|
107
|
+
const incomingFiles=new Map(files.map(f=>[f.path,f]));
|
|
108
|
+
const delFile=this.db.prepare('DELETE FROM files WHERE workspace_id=? AND path=?');
|
|
109
|
+
const upsertFile=this.db.prepare('INSERT INTO files(workspace_id,path,content_sha,language,bytes,revision_id,mtime_ms) VALUES(?,?,?,?,?,?,?) ON CONFLICT(workspace_id,path) DO UPDATE SET content_sha=excluded.content_sha,language=excluded.language,bytes=excluded.bytes,revision_id=excluded.revision_id,mtime_ms=excluded.mtime_ms');
|
|
110
|
+
for(const p of existingFiles.keys()) if(!incomingFiles.has(p)) delFile.run(wsId,p);
|
|
111
|
+
for(const x of files){
|
|
112
|
+
const prev=existingFiles.get(x.path);
|
|
113
|
+
const mtime=x.mtime_ms??null;
|
|
114
|
+
if(!prev || prev.content_sha!==x.hash || prev.bytes!==x.bytes || prev.mtime_ms!==mtime){
|
|
115
|
+
upsertFile.run(wsId,x.path,x.hash,x.language,x.bytes,rev,mtime);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const existingNodes=new Map(this.all('SELECT id,kind,label,file_path,line,basis FROM nodes WHERE workspace_id=?',wsId).map(r=>[r.id,r]));
|
|
120
|
+
const incomingNodes=new Map(nodes.map(n=>[n.id,n]));
|
|
121
|
+
const delNode=this.db.prepare('DELETE FROM nodes WHERE workspace_id=? AND id=?');
|
|
122
|
+
const upsertNode=this.db.prepare('INSERT INTO nodes(workspace_id,id,kind,label,file_path,line,basis,revision_id) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(workspace_id,id) DO UPDATE SET kind=excluded.kind,label=excluded.label,file_path=excluded.file_path,line=excluded.line,basis=excluded.basis,revision_id=excluded.revision_id');
|
|
123
|
+
for(const id of existingNodes.keys()) if(!incomingNodes.has(id)) delNode.run(wsId,id);
|
|
124
|
+
for(const x of nodes){
|
|
125
|
+
const prev=existingNodes.get(x.id);
|
|
126
|
+
const fp=x.path||null, ln=x.line||null, basis=x.basis||'source';
|
|
127
|
+
if(!prev || prev.kind!==x.kind || prev.label!==x.label || prev.file_path!==fp || prev.line!==ln || prev.basis!==basis){
|
|
128
|
+
upsertNode.run(wsId,x.id,x.kind,x.label,fp,ln,basis,rev);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const existingEdgeIds=new Set(this.all('SELECT id FROM edges WHERE workspace_id=?',wsId).map(r=>r.id));
|
|
133
|
+
const incomingEdgeIds=new Set(edges.map(e=>e.id));
|
|
134
|
+
const delEdge=this.db.prepare('DELETE FROM edges WHERE workspace_id=? AND id=?');
|
|
135
|
+
const insEdge=this.db.prepare('INSERT OR IGNORE INTO edges(workspace_id,id,source,target,kind,basis,state,source_file,revision_id) VALUES(?,?,?,?,?,?,?,?,?)');
|
|
136
|
+
for(const id of existingEdgeIds) if(!incomingEdgeIds.has(id)) delEdge.run(wsId,id);
|
|
137
|
+
for(const x of edges){
|
|
138
|
+
if(!existingEdgeIds.has(x.id)){
|
|
139
|
+
insEdge.run(wsId,x.id,x.from,x.to,x.kind,x.basis||'source',x.state||'observed',x.file||null,rev);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
// Local privacy control: only rows associated with an explicitly authorized
|
|
145
|
+
// workspace. Unscoped historical notes and project artifacts on disk remain untouched.
|
|
146
|
+
workspaceDataCounts(workspace){
|
|
147
|
+
const canonical=requireAuthorizedWorkspace(workspace);
|
|
148
|
+
const row=this.get('SELECT id FROM workspaces WHERE canonical_path=?',canonical);
|
|
149
|
+
const tables=['revisions','files','nodes','edges','evidence','runs','incidents','hypotheses',
|
|
150
|
+
'rca_experiments','telemetry','side_questions','artifact_versions','model_recovery_state',
|
|
151
|
+
'recovery_checkpoints','acceptance_plans'];
|
|
152
|
+
const counts={};
|
|
153
|
+
for(const table of tables)counts[table]=row?this.get(`SELECT COUNT(*) AS n FROM ${table} WHERE workspace_id=?`,row.id)?.n||0:0;
|
|
154
|
+
return {registered:!!row,workspace_id:row?.id||null,counts,
|
|
155
|
+
total_rows:Object.values(counts).reduce((a,b)=>a+b,0),
|
|
156
|
+
limits:'Only workspace-scoped SQLite rows; does not delete source files, evidence artifacts on disk, trust grants, or unscoped historical entries.'};
|
|
157
|
+
}
|
|
158
|
+
purgeWorkspaceData(workspace,{confirmed=false}={}){
|
|
159
|
+
if(confirmed!==true)throw Error('Workspace data purge requires explicit confirmation');
|
|
160
|
+
const pre=this.workspaceDataCounts(workspace);
|
|
161
|
+
if(!pre.registered)return {...pre,purged:false,reason:'Workspace has no stored records'};
|
|
162
|
+
const tableOrder=['acceptance_plans','revisions','files','nodes','edges','evidence',
|
|
163
|
+
'runs','hypotheses','rca_experiments','incidents','telemetry','side_questions',
|
|
164
|
+
'artifact_versions','model_recovery_state','recovery_checkpoints'];
|
|
165
|
+
this.transaction(()=>{
|
|
166
|
+
for(const table of tableOrder)this.run(`DELETE FROM ${table} WHERE workspace_id=?`,pre.workspace_id);
|
|
167
|
+
this.run('DELETE FROM workspaces WHERE id=?',pre.workspace_id);
|
|
168
|
+
});
|
|
169
|
+
return {purged:true,deleted_rows:pre.total_rows,workspace_id:pre.workspace_id,
|
|
170
|
+
limits:pre.limits,follow_up:'If necessary, separately delete files you explicitly retained outside the SQLite store.'};
|
|
171
|
+
}
|
|
172
|
+
recordTelemetry(wsId,{toolName,action,rawScopeTokens=0,responseTokens=0}){
|
|
173
|
+
const raw=Math.max(0,Math.round(rawScopeTokens));
|
|
174
|
+
const resp=Math.max(0,Math.round(responseTokens));
|
|
175
|
+
const saved=0; // Deprecated schema column: there is no observed native baseline.
|
|
176
|
+
this.run('INSERT INTO telemetry(workspace_id,tool_name,action,raw_scope_tokens,response_tokens,tokens_saved,created_at) VALUES(?,?,?,?,?,?,?)',wsId,String(toolName||'pilah'),String(action||''),raw,resp,saved,new Date().toISOString());
|
|
177
|
+
try {
|
|
178
|
+
this.run('DELETE FROM telemetry WHERE workspace_id=? AND id NOT IN (SELECT id FROM telemetry WHERE workspace_id=? ORDER BY created_at DESC LIMIT 500)', wsId, wsId);
|
|
179
|
+
} catch {}
|
|
180
|
+
}
|
|
181
|
+
getTelemetrySummary(wsId){
|
|
182
|
+
const row=this.get('SELECT COUNT(*) AS calls, COALESCE(SUM(raw_scope_tokens),0) AS raw_scope_tokens, COALESCE(SUM(response_tokens),0) AS response_tokens FROM telemetry WHERE workspace_id=?',wsId);
|
|
183
|
+
return row||{calls:0,raw_scope_tokens:0,response_tokens:0};
|
|
184
|
+
}
|
|
185
|
+
recordSideQuestion({
|
|
186
|
+
id=null,
|
|
187
|
+
workspaceId=null,
|
|
188
|
+
conversationId,
|
|
189
|
+
parentConversationId=null,
|
|
190
|
+
title=null,
|
|
191
|
+
question,
|
|
192
|
+
summary=null,
|
|
193
|
+
status='resolved',
|
|
194
|
+
transcriptPath=null,
|
|
195
|
+
metadata={}
|
|
196
|
+
}){
|
|
197
|
+
if(!conversationId||!question)throw new Error('conversationId and question are required');
|
|
198
|
+
const sanitizedTitle=title?String(title).slice(0,240):null;
|
|
199
|
+
const sanitizedQuestion=String(question).slice(0,2000);
|
|
200
|
+
const sanitizedSummary=summary?String(summary).slice(0,2000):null;
|
|
201
|
+
const existing=this.get('SELECT * FROM side_questions WHERE conversation_id=? AND workspace_id IS ?',conversationId,workspaceId);
|
|
202
|
+
const sid=id||existing?.id||sha256((workspaceId||'unassigned')+':'+conversationId+':'+(parentConversationId||'')).slice(0,32);
|
|
203
|
+
// Explicit ids never grant ownership of a record in another workspace.
|
|
204
|
+
const byId=this.get('SELECT workspace_id FROM side_questions WHERE id=?',sid);
|
|
205
|
+
if(byId?.workspace_id!=null && byId.workspace_id!==workspaceId)
|
|
206
|
+
throw new Error('Side question ID belongs to another workspace');
|
|
207
|
+
const now=new Date().toISOString();
|
|
208
|
+
const createdAt=existing?.created_at||now;
|
|
209
|
+
const metaJson=JSON.stringify(metadata||{});
|
|
210
|
+
this.run(
|
|
211
|
+
`INSERT INTO side_questions(id,workspace_id,conversation_id,parent_conversation_id,title,question,summary,status,transcript_path,metadata_json,created_at,updated_at)
|
|
212
|
+
VALUES(?,?,?,?,?,?,?,?,?,?,?,?)
|
|
213
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
214
|
+
workspace_id=COALESCE(excluded.workspace_id,side_questions.workspace_id),
|
|
215
|
+
parent_conversation_id=COALESCE(excluded.parent_conversation_id,side_questions.parent_conversation_id),
|
|
216
|
+
title=COALESCE(excluded.title,side_questions.title),
|
|
217
|
+
question=excluded.question,
|
|
218
|
+
summary=COALESCE(excluded.summary,side_questions.summary),
|
|
219
|
+
status=excluded.status,
|
|
220
|
+
transcript_path=COALESCE(excluded.transcript_path,side_questions.transcript_path),
|
|
221
|
+
metadata_json=excluded.metadata_json,
|
|
222
|
+
updated_at=excluded.updated_at
|
|
223
|
+
WHERE side_questions.workspace_id IS excluded.workspace_id OR side_questions.workspace_id IS NULL`,
|
|
224
|
+
sid,workspaceId,conversationId,parentConversationId,sanitizedTitle,sanitizedQuestion,sanitizedSummary,status,transcriptPath,metaJson,createdAt,now
|
|
225
|
+
);
|
|
226
|
+
if(workspaceId){
|
|
227
|
+
try{
|
|
228
|
+
this.run('DELETE FROM side_questions WHERE workspace_id=? AND id NOT IN (SELECT id FROM side_questions WHERE workspace_id=? ORDER BY updated_at DESC LIMIT 100)', workspaceId, workspaceId);
|
|
229
|
+
}catch{}
|
|
230
|
+
}
|
|
231
|
+
const saved=this.get('SELECT * FROM side_questions WHERE id=?',sid);
|
|
232
|
+
if(!saved||(saved.workspace_id!=null&&saved.workspace_id!==workspaceId))
|
|
233
|
+
throw new Error('Side question workspace ownership mismatch');
|
|
234
|
+
return {...saved,metadata:JSON.parse(saved.metadata_json||'{}'),metadata_json:undefined};
|
|
235
|
+
}
|
|
236
|
+
listSideQuestions({workspaceId=null,parentConversationId=null,conversationId=null,limit=20}={}){
|
|
237
|
+
let sql='SELECT * FROM side_questions WHERE 1=1';
|
|
238
|
+
const params=[];
|
|
239
|
+
if(workspaceId){sql+=' AND workspace_id=?';params.push(workspaceId);}
|
|
240
|
+
if(parentConversationId){sql+=' AND parent_conversation_id=?';params.push(parentConversationId);}
|
|
241
|
+
if(conversationId){sql+=' AND conversation_id=?';params.push(conversationId);}
|
|
242
|
+
sql+=' ORDER BY updated_at DESC LIMIT ?';
|
|
243
|
+
params.push(Math.max(1,Math.min(100,Number(limit)||20)));
|
|
244
|
+
return this.all(sql,...params).map(r=>({...r,metadata:JSON.parse(r.metadata_json||'{}'),metadata_json:undefined}));
|
|
245
|
+
}
|
|
246
|
+
getSideQuestion(idOrConvId,{workspaceId=null}={}){
|
|
247
|
+
if(!workspaceId)return null;
|
|
248
|
+
const row=this.get('SELECT * FROM side_questions WHERE workspace_id=? AND (id=? OR conversation_id=?) LIMIT 1',workspaceId,idOrConvId,idOrConvId);
|
|
249
|
+
if(!row)return null;
|
|
250
|
+
return {...row,metadata:JSON.parse(row.metadata_json||'{}'),metadata_json:undefined};
|
|
251
|
+
}
|
|
252
|
+
snapshotArtifact({workspaceId=null,conversationId,artifactPath,content=null,workspaceRoot=null}){
|
|
253
|
+
if(!conversationId||typeof conversationId!=='string'||!/^[a-zA-Z0-9_\-.]{4,64}$/.test(conversationId)){
|
|
254
|
+
throw new Error('Valid conversationId is required for artifact snapshot');
|
|
255
|
+
}
|
|
256
|
+
// A workspace-bound snapshot must not be rebound to another workspace ID.
|
|
257
|
+
if(workspaceRoot && workspaceId && this.register(workspaceRoot)!==workspaceId){
|
|
258
|
+
throw new Error('Artifact workspace identity mismatch');
|
|
259
|
+
}
|
|
260
|
+
const validPath=safeArtifactPath(workspaceRoot,conversationId,artifactPath,{mustExist:content===null});
|
|
261
|
+
const artifactName=path.basename(validPath);
|
|
262
|
+
let rawContent=content;
|
|
263
|
+
if(rawContent===null){
|
|
264
|
+
const read=readSafeBytesFile(validPath,{maxBytes:MAX_ARTIFACT_BYTES});
|
|
265
|
+
if(!read.ok)throw new Error('Artifact file is unsafe or too large');
|
|
266
|
+
rawContent=read.bytes.toString('utf8');
|
|
267
|
+
}
|
|
268
|
+
if(typeof rawContent!=='string'||Buffer.byteLength(rawContent)>MAX_ARTIFACT_BYTES){
|
|
269
|
+
throw new Error(`Artifact content exceeds maximum allowed size (${MAX_ARTIFACT_BYTES/1024} KB)`);
|
|
270
|
+
}
|
|
271
|
+
const contentSha=sha256(rawContent);
|
|
272
|
+
// Serialize version allocation and retention across concurrent processes.
|
|
273
|
+
// The database is the source of truth; filesystem shadows are best-effort.
|
|
274
|
+
let outcome,removedVersions=[];
|
|
275
|
+
this.transaction(()=>{
|
|
276
|
+
const latest=this.get(
|
|
277
|
+
'SELECT * FROM artifact_versions WHERE workspace_id IS ? AND conversation_id=? AND artifact_name=? ORDER BY version_number DESC LIMIT 1',
|
|
278
|
+
workspaceId||null,conversationId,artifactName
|
|
279
|
+
);
|
|
280
|
+
if(latest&&latest.content_sha===contentSha){
|
|
281
|
+
outcome={...latest,changed:false};
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
const versionNumber=latest?latest.version_number+1:1;
|
|
285
|
+
const diff=latest?computeUnifiedDiff(latest.content,rawContent,'v'+latest.version_number,'v'+versionNumber):'';
|
|
286
|
+
const id=sha256((workspaceId||'unassigned')+':'+conversationId+':'+artifactName+':'+versionNumber+':'+contentSha).slice(0,32);
|
|
287
|
+
const now=new Date().toISOString();
|
|
288
|
+
this.run(
|
|
289
|
+
'INSERT INTO artifact_versions(id,workspace_id,conversation_id,artifact_name,version_number,content_sha,content,diff_from_previous,created_at) VALUES(?,?,?,?,?,?,?,?,?)',
|
|
290
|
+
id,workspaceId||null,conversationId,artifactName,versionNumber,contentSha,rawContent,diff,now
|
|
291
|
+
);
|
|
292
|
+
// Keep retention independent of filesystem-shadow write success.
|
|
293
|
+
const excess=this.all(
|
|
294
|
+
'SELECT id,version_number FROM artifact_versions WHERE workspace_id IS ? AND conversation_id=? AND artifact_name=? ORDER BY version_number DESC LIMIT -1 OFFSET 10',
|
|
295
|
+
workspaceId||null,conversationId,artifactName
|
|
296
|
+
);
|
|
297
|
+
for(const oldRow of excess)this.run('DELETE FROM artifact_versions WHERE id=?',oldRow.id);
|
|
298
|
+
removedVersions=excess.map(x=>x.version_number);
|
|
299
|
+
outcome={
|
|
300
|
+
id,workspace_id:workspaceId||null,conversation_id:conversationId,artifact_name:artifactName,
|
|
301
|
+
version_number:versionNumber,content_sha:contentSha,diff_from_previous:diff,created_at:now,
|
|
302
|
+
changed:true,bytes:Buffer.byteLength(rawContent)
|
|
303
|
+
};
|
|
304
|
+
});
|
|
305
|
+
if(!outcome.changed)return outcome;
|
|
306
|
+
try{
|
|
307
|
+
const histDir=path.join(this.base,'artifact_history',workspaceId||'unassigned',conversationId);
|
|
308
|
+
// Create one component at a time; recursive mkdir would follow a
|
|
309
|
+
// pre-existing malicious symlink before we could inspect it.
|
|
310
|
+
let cursor=this.base;
|
|
311
|
+
for(const part of path.relative(this.base,histDir).split(path.sep)){
|
|
312
|
+
cursor=path.join(cursor,part);
|
|
313
|
+
try{fs.mkdirSync(cursor,{mode:0o700})}catch(e){if(e.code!=='EEXIST')throw e}
|
|
314
|
+
const stat=fs.lstatSync(cursor);
|
|
315
|
+
if(stat.isSymbolicLink()||!stat.isDirectory())throw Error('Unsafe artifact shadow path');
|
|
316
|
+
}
|
|
317
|
+
try{fs.chmodSync(histDir,0o700)}catch{}
|
|
318
|
+
const shadowPath=path.join(histDir,artifactName+'.v'+outcome.version_number+'.md');
|
|
319
|
+
try{fs.writeFileSync(shadowPath,rawContent,{encoding:'utf8',mode:0o600,flag:'wx'})}catch{}
|
|
320
|
+
for(const n of removedVersions){
|
|
321
|
+
const oldShadow=path.join(histDir,artifactName+'.v'+n+'.md');
|
|
322
|
+
try{fs.unlinkSync(oldShadow)}catch{}
|
|
323
|
+
}
|
|
324
|
+
}catch{}
|
|
325
|
+
return outcome;
|
|
326
|
+
}
|
|
327
|
+
listArtifactVersions({workspaceId=null,conversationId,artifactName=null,limit=50}={}){
|
|
328
|
+
let sql="SELECT id,workspace_id,conversation_id,artifact_name,version_number,content_sha,created_at,LENGTH(content) AS bytes,(diff_from_previous IS NOT NULL AND diff_from_previous!='') AS has_diff FROM artifact_versions WHERE 1=1";
|
|
329
|
+
const params=[];
|
|
330
|
+
if(conversationId){sql+=' AND conversation_id=?';params.push(conversationId);}
|
|
331
|
+
if(workspaceId){sql+=' AND workspace_id=?';params.push(workspaceId);}
|
|
332
|
+
if(artifactName){sql+=' AND artifact_name=?';params.push(artifactName);}
|
|
333
|
+
sql+=' ORDER BY version_number DESC LIMIT ?';
|
|
334
|
+
params.push(Math.max(1,Math.min(200,Number(limit)||50)));
|
|
335
|
+
return this.all(sql,...params);
|
|
336
|
+
}
|
|
337
|
+
getArtifactVersion({workspaceId=null,conversationId,artifactName,versionNumber=null}={}){
|
|
338
|
+
let sql='SELECT * FROM artifact_versions WHERE conversation_id=? AND artifact_name=?';
|
|
339
|
+
const params=[conversationId,artifactName];
|
|
340
|
+
if(workspaceId){sql+=' AND workspace_id=?';params.push(workspaceId);}
|
|
341
|
+
if(versionNumber!==null&&versionNumber!==undefined){
|
|
342
|
+
sql+=' AND version_number=?';
|
|
343
|
+
params.push(Number(versionNumber));
|
|
344
|
+
}else{
|
|
345
|
+
sql+=' ORDER BY version_number DESC LIMIT 1';
|
|
346
|
+
}
|
|
347
|
+
return this.get(sql,...params)||null;
|
|
348
|
+
}
|
|
349
|
+
getArtifactDiff({workspaceId=null,conversationId,artifactName,v1=null,v2=null}={}){
|
|
350
|
+
if(!v1&&!v2){
|
|
351
|
+
let sql='SELECT * FROM artifact_versions WHERE conversation_id=? AND artifact_name=?';
|
|
352
|
+
const params=[conversationId,artifactName];
|
|
353
|
+
if(workspaceId){sql+=' AND workspace_id=?';params.push(workspaceId);}
|
|
354
|
+
sql+=' ORDER BY version_number DESC LIMIT 1';
|
|
355
|
+
const latest=this.get(sql,...params);
|
|
356
|
+
if(!latest)return null;
|
|
357
|
+
return {
|
|
358
|
+
artifact_name:artifactName,
|
|
359
|
+
v1:latest.version_number>1?latest.version_number-1:0,
|
|
360
|
+
v2:latest.version_number,
|
|
361
|
+
diff:latest.diff_from_previous||''
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
const row1=v1?this.getArtifactVersion({workspaceId,conversationId,artifactName,versionNumber:v1}):null;
|
|
365
|
+
const row2=v2?this.getArtifactVersion({workspaceId,conversationId,artifactName,versionNumber:v2}):null;
|
|
366
|
+
// A nonexistent explicitly requested version is not an empty artifact:
|
|
367
|
+
// returning a diff against empty content could falsely imply a real history.
|
|
368
|
+
const missing_versions=[...(v1&&!row1?[v1]:[]),...(v2&&!row2?[v2]:[])];
|
|
369
|
+
if(missing_versions.length)return {artifact_name:artifactName,v1:v1||0,v2:v2||0,status:'version_not_found',missing_versions,diff:null};
|
|
370
|
+
const content1=row1?.content||'';
|
|
371
|
+
const content2=row2?.content||'';
|
|
372
|
+
return {
|
|
373
|
+
artifact_name:artifactName,
|
|
374
|
+
v1:v1||0,
|
|
375
|
+
v2:v2||0,
|
|
376
|
+
diff:computeUnifiedDiff(content1,content2,`v${v1||0}`,`v${v2||0}`)
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
scanAndSnapshotBrainArtifacts(conversationId,brainDir=null,{workspaceId=null,workspaceRoot=null}={}){
|
|
380
|
+
if(!conversationId)return [];
|
|
381
|
+
const bDir=brainDir||path.join(getHomeDir(),'.gemini','antigravity','brain',conversationId);
|
|
382
|
+
if(!fs.existsSync(bDir))return [];
|
|
383
|
+
const results=[];
|
|
384
|
+
try{
|
|
385
|
+
const files=fs.readdirSync(bDir,{withFileTypes:true});
|
|
386
|
+
for(const entry of files){
|
|
387
|
+
if(entry.isFile()&&entry.name.endsWith('.md')){
|
|
388
|
+
const filePath=path.join(bDir,entry.name);
|
|
389
|
+
const snap=this.snapshotArtifact({workspaceId,workspaceRoot,conversationId,artifactPath:filePath});
|
|
390
|
+
if(snap&&snap.changed)results.push(snap);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}catch{}
|
|
394
|
+
return results;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
export function computeUnifiedDiff(oldStr,newStr,oldLabel='vPrevious',newLabel='vCurrent'){
|
|
399
|
+
if(oldStr===newStr)return '';
|
|
400
|
+
const oldLines=oldStr?oldStr.split('\n'):[];
|
|
401
|
+
const newLines=newStr?newStr.split('\n'):[];
|
|
402
|
+
const diff=[`--- ${oldLabel}`,`+++ ${newLabel}`];
|
|
403
|
+
const m=oldLines.length,n=newLines.length;
|
|
404
|
+
if(m>2500||n>2500){
|
|
405
|
+
diff.push(`@@ -1,${m} +1,${n} @@`,`- (previous content: ${m} lines)`,`+ (updated content: ${n} lines)`);
|
|
406
|
+
return diff.join('\n');
|
|
407
|
+
}
|
|
408
|
+
const dp=Array.from({length:m+1},()=>new Uint16Array(n+1));
|
|
409
|
+
for(let i=0;i<m;i++){
|
|
410
|
+
for(let j=0;j<n;j++){
|
|
411
|
+
dp[i+1][j+1]=oldLines[i]===newLines[j]?dp[i][j]+1:Math.max(dp[i+1][j],dp[i][j+1]);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
let i=m,j=n;
|
|
415
|
+
const script=[];
|
|
416
|
+
while(i>0||j>0){
|
|
417
|
+
if(i>0&&j>0&&oldLines[i-1]===newLines[j-1]){
|
|
418
|
+
script.push({type:' ',text:oldLines[i-1]});
|
|
419
|
+
i--;j--;
|
|
420
|
+
}else if(j>0&&(i===0||dp[i][j-1]>=dp[i-1][j])){
|
|
421
|
+
script.push({type:'+',text:newLines[j-1]});
|
|
422
|
+
j--;
|
|
423
|
+
}else if(i>0&&(j===0||dp[i][j-1]<dp[i-1][j])){
|
|
424
|
+
script.push({type:'-',text:oldLines[i-1]});
|
|
425
|
+
i--;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
script.reverse();
|
|
429
|
+
let hunk=[],inHunk=false;
|
|
430
|
+
for(let idx=0;idx<script.length;idx++){
|
|
431
|
+
const item=script[idx];
|
|
432
|
+
if(item.type!==' '){
|
|
433
|
+
if(!inHunk){
|
|
434
|
+
inHunk=true;
|
|
435
|
+
const start=Math.max(0,idx-2);
|
|
436
|
+
for(let k=start;k<idx;k++){
|
|
437
|
+
if(script[k].type===' ')hunk.push(' '+script[k].text);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
hunk.push(item.type+item.text);
|
|
441
|
+
}else if(inHunk){
|
|
442
|
+
hunk.push(' '+item.text);
|
|
443
|
+
const nextChange=script.slice(idx+1,idx+3).some(x=>x.type!==' ');
|
|
444
|
+
if(!nextChange){
|
|
445
|
+
diff.push(...hunk);
|
|
446
|
+
hunk=[];
|
|
447
|
+
inHunk=false;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
if(hunk.length>0)diff.push(...hunk);
|
|
452
|
+
return diff.join('\n');
|
|
453
|
+
}
|
|
454
|
+
export const uniqueId=(prefix)=>`${prefix}-${cryptoRandom()}`;
|
|
455
|
+
function cryptoRandom(){return globalThis.crypto.randomUUID()}
|