@eyeauras/insight-cli 0.6.6 → 0.8.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.
Files changed (122) hide show
  1. package/.cli-package-build.json +1 -1
  2. package/SKILL.md +1 -1
  3. package/dist/src/activity-audit.d.ts +130 -0
  4. package/dist/src/activity-audit.js +320 -0
  5. package/dist/src/analysis-storage.d.ts +5 -1
  6. package/dist/src/analysis-storage.js +9 -2
  7. package/dist/src/audit-commands.d.ts +10 -0
  8. package/dist/src/audit-commands.js +85 -0
  9. package/dist/src/audit-retention.d.ts +44 -0
  10. package/dist/src/audit-retention.js +167 -0
  11. package/dist/src/cli.js +28 -6
  12. package/dist/src/context-diagnostics.d.ts +1 -1
  13. package/dist/src/context-diagnostics.js +10 -2
  14. package/dist/src/contexts.d.ts +118 -10
  15. package/dist/src/contexts.js +851 -199
  16. package/dist/src/debugger.js +2 -1
  17. package/dist/src/diagnostic-error.d.ts +12 -0
  18. package/dist/src/diagnostic-error.js +82 -0
  19. package/dist/src/inline-script.js +3 -4
  20. package/dist/src/internal-timing.d.ts +8 -2
  21. package/dist/src/internal-timing.js +50 -7
  22. package/dist/src/lifecycle.d.ts +12 -1
  23. package/dist/src/lifecycle.js +34 -6
  24. package/dist/src/native-inputs.d.ts +6 -0
  25. package/dist/src/native-inputs.js +30 -6
  26. package/dist/src/native-queries.js +1 -6
  27. package/dist/src/native-service.d.ts +40 -0
  28. package/dist/src/native-service.js +406 -0
  29. package/dist/src/research.d.ts +30 -2
  30. package/dist/src/research.js +106 -27
  31. package/dist/src/server.d.ts +38 -1
  32. package/dist/src/server.js +160 -12
  33. package/dist/src/storage-gc.js +374 -341
  34. package/dist/src/sync-policy.js +2 -1
  35. package/dist/src/timed-backend.js +8 -0
  36. package/dist/src/timing-report.d.ts +32 -0
  37. package/dist/src/timing-report.js +74 -0
  38. package/dist/src/tool-runtime/identity.js +86 -1
  39. package/dist/src/tool-runtime/supervisor.js +6 -5
  40. package/dist/src/transport.d.ts +35 -0
  41. package/dist/src/transport.js +95 -16
  42. package/dist/src/unresolved-guidance.d.ts +46 -0
  43. package/dist/src/unresolved-guidance.js +55 -0
  44. package/dist/src/windbg.d.ts +1 -1
  45. package/dist/src/worker-lease.d.ts +17 -0
  46. package/dist/src/worker-lease.js +50 -0
  47. package/dist/src/workspace.d.ts +5 -9
  48. package/dist/src/workspace.js +34 -41
  49. package/package.json +1 -1
  50. package/references/native/InsightHeadlessMain.java +9 -2
  51. package/references/native/InsightNativeCheckout.java +113 -43
  52. package/references/native/InsightNativeFingerprint.java +28 -1
  53. package/references/native/InsightNativeRead.java +32 -9
  54. package/references/native/InsightNativeService.java +43 -0
  55. package/references/native/InsightNativeView.java +17 -6
  56. package/references/native/InsightOwnedScripts.java +170 -0
  57. package/references/native/InsightWorkerLease.java +132 -0
  58. package/references/recovery.md +68 -3
  59. package/references/research.md +71 -6
  60. package/references/setup.md +5 -1
  61. package/skill-bundle/insight-artifacts/SKILL.md +1 -1
  62. package/skill-bundle/insight-artifacts/references/recovery.md +68 -3
  63. package/skill-bundle/insight-binary/SKILL.md +1 -1
  64. package/skill-bundle/insight-capture/SKILL.md +1 -1
  65. package/skill-bundle/insight-cli/SKILL.md +1 -1
  66. package/skill-bundle/insight-cli/references/recovery.md +68 -3
  67. package/skill-bundle/insight-cli/references/setup.md +5 -1
  68. package/skill-bundle/insight-die/SKILL.md +1 -1
  69. package/skill-bundle/insight-dnspy/SKILL.md +1 -1
  70. package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
  71. package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
  72. package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
  73. package/skill-bundle/insight-frida/SKILL.md +1 -1
  74. package/skill-bundle/insight-ghidra/SKILL.md +1 -1
  75. package/skill-bundle/insight-ghidra/references/recovery.md +68 -3
  76. package/skill-bundle/insight-ghidra/references/research.md +71 -6
  77. package/skill-bundle/insight-ghidra/references/setup.md +5 -1
  78. package/skill-bundle/insight-ilspy/SKILL.md +1 -1
  79. package/skill-bundle/insight-interop/SKILL.md +1 -1
  80. package/skill-bundle/insight-lldb/SKILL.md +1 -1
  81. package/skill-bundle/insight-llvm/SKILL.md +1 -1
  82. package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
  83. package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
  84. package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
  85. package/skill-bundle/insight-overview/SKILL.md +1 -1
  86. package/skill-bundle/insight-procmon/SKILL.md +1 -1
  87. package/skill-bundle/insight-re/SKILL.md +7 -1
  88. package/skill-bundle/insight-re/references/recovery.md +68 -3
  89. package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
  90. package/skill-bundle/insight-strace/SKILL.md +1 -1
  91. package/skill-bundle/insight-tshark/SKILL.md +1 -1
  92. package/skill-bundle/insight-windbg/SKILL.md +1 -1
  93. package/skill-bundle/manifest.json +1 -1
  94. package/skills/insight-artifacts/SKILL.md +1 -1
  95. package/skills/insight-artifacts/references/recovery.md +68 -3
  96. package/skills/insight-binary/SKILL.md +1 -1
  97. package/skills/insight-capture/SKILL.md +1 -1
  98. package/skills/insight-die/SKILL.md +1 -1
  99. package/skills/insight-dnspy/SKILL.md +1 -1
  100. package/skills/insight-dotnet-dump/SKILL.md +1 -1
  101. package/skills/insight-dotnet-stack/SKILL.md +1 -1
  102. package/skills/insight-dotnet-trace/SKILL.md +1 -1
  103. package/skills/insight-frida/SKILL.md +1 -1
  104. package/skills/insight-ghidra/SKILL.md +1 -1
  105. package/skills/insight-ghidra/references/recovery.md +68 -3
  106. package/skills/insight-ghidra/references/research.md +71 -6
  107. package/skills/insight-ghidra/references/setup.md +5 -1
  108. package/skills/insight-ilspy/SKILL.md +1 -1
  109. package/skills/insight-interop/SKILL.md +1 -1
  110. package/skills/insight-lldb/SKILL.md +1 -1
  111. package/skills/insight-llvm/SKILL.md +1 -1
  112. package/skills/insight-managed-heap/SKILL.md +1 -1
  113. package/skills/insight-managed-metadata/SKILL.md +1 -1
  114. package/skills/insight-mitmproxy/SKILL.md +1 -1
  115. package/skills/insight-overview/SKILL.md +1 -1
  116. package/skills/insight-procmon/SKILL.md +1 -1
  117. package/skills/insight-re/SKILL.md +7 -1
  118. package/skills/insight-re/references/recovery.md +68 -3
  119. package/skills/insight-sevenzip/SKILL.md +1 -1
  120. package/skills/insight-strace/SKILL.md +1 -1
  121. package/skills/insight-tshark/SKILL.md +1 -1
  122. package/skills/insight-windbg/SKILL.md +1 -1
@@ -4,12 +4,39 @@ import db.buffers.InsightBlockTransfer;
4
4
  import ghidra.program.database.ProgramDB;
5
5
  import ghidra.program.model.listing.Program;
6
6
 
7
- /** Saved native buffers only; never fabricates or replaces native ancestry/change sets. */
7
+ /**
8
+ * `of` and `content` read a whole database and are for the two places where the coordinator itself copies or
9
+ * converts one (initial publication, legacy migration). Native checkouts are identified by `saved` and `version`.
10
+ */
8
11
  public final class InsightNativeFingerprint {
9
12
  public static String of(Program p)throws Exception {
10
13
  if(p.isChanged())throw new IllegalStateException("Program has unsaved changes");
11
14
  return InsightBlockTransfer.fingerprint(((ProgramDB)p).getDBHandle().getBufferMgr().getSourceFile());
12
15
  }
16
+ /**
17
+ * Identity of one saved state of a local file, from what Ghidra itself keeps: the file, its base version and
18
+ * the version of its local buffer file, which Ghidra advances on every save. No bytes are read.
19
+ * It names a saved state so that a later request can tell whether it still looks at the same one; it says
20
+ * nothing about content, and whether a checkout holds work is Ghidra's own `modifiedSinceCheckout()`.
21
+ */
22
+ public static String saved(Program p)throws Exception {
23
+ if(p.isChanged())throw new IllegalStateException("Program has unsaved changes");
24
+ var file=p.getDomainFile();Object source=((ProgramDB)p).getDBHandle().getBufferMgr().getSourceFile();
25
+ // A repository item (no local file) is one immutable version; the database is never read to name a state.
26
+ if(!(source instanceof db.buffers.LocalManagedBufferFile local))return version(file.getFileID(),file.getVersion());
27
+ // Only what the local project knows: a worker's project is not connected to the repository server.
28
+ return identity("local|"+file.getFileID()+"|"+(file.isCheckedOut()?"base "+file.getVersion():"private")+"|"+local.getVersion());
29
+ }
30
+ /** The version of a program's local buffer file, which Ghidra advances on every save; -1 without a local file. */
31
+ public static long localVersion(Program p){
32
+ Object source=((ProgramDB)p).getDBHandle().getBufferMgr().getSourceFile();
33
+ return source instanceof db.buffers.LocalManagedBufferFile local?local.getVersion():-1;
34
+ }
35
+ /** Identity of one immutable version of a repository item. */
36
+ public static String version(String fileId,int version)throws Exception {return identity("server|"+fileId+"|"+version);}
37
+ private static String identity(String value)throws Exception {
38
+ return java.util.HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(("insight-saved-state-v1|"+value).getBytes(java.nio.charset.StandardCharsets.UTF_8)));
39
+ }
13
40
  /**
14
41
  * Every saved record except what opening a program writes by itself: the derived Metadata table, rebuilt
15
42
  * from options on save, and the GUI's "Should Ask To Analyze" flag. Stored file bytes are included; memory
@@ -13,17 +13,29 @@ import java.util.*;
13
13
 
14
14
  /** Independent read authority, immutable exact-version native database; never checks out. */
15
15
  public final class InsightNativeRead {
16
+ static final Gson GSON=new GsonBuilder().serializeNulls().create();
17
+ static volatile boolean poisoned;
18
+ /** One-shot helper: one request file, one JSON result line, then exit. */
16
19
  public static void main(String[] args){
17
- var output=System.out;System.setOut(System.err);
20
+ var output=System.out;System.setOut(System.err);Map<String,Object> result;
21
+ try{if(!Application.isInitialized())Application.initializeApplication(new GhidraApplicationLayout(),new HeadlessGhidraApplicationConfiguration());result=handle(Path.of(args[0]));}
22
+ catch(Throwable failure){failure.printStackTrace(System.err);result=unknown(failure);}
23
+ output.println(GSON.toJson(result));System.exit(0);
24
+ }
25
+ static Map<String,Object> unknown(Throwable failure){
26
+ return Map.of("state","unknown","diagnostic",failure.getClass().getSimpleName(),"reason",Objects.toString(failure.getMessage(),failure.toString()),"code",failure instanceof InsightNativeMigration.Required?"migration":"unknown");
27
+ }
28
+ /** One independent read. The server connection is closed after every request, also on failure. */
29
+ static Map<String,Object> handle(Path requestFile){
30
+ GhidraServerManager server=null;
18
31
  try {
19
- JsonObject q=JsonParser.parseString(Files.readString(Path.of(args[0]))).getAsJsonObject();
32
+ JsonObject q=JsonParser.parseString(Files.readString(requestFile)).getAsJsonObject();
20
33
  String repo=q.get("repository").getAsString(),path=q.get("path").getAsString(),sha=q.get("sourceSha").getAsString(),op=q.get("operation").getAsString();
21
34
  if(!path.startsWith("/")||path.indexOf('/',1)>=0)throw new SecurityException();String name=path.substring(1);
22
- Application.initializeApplication(new GhidraApplicationLayout(),new HeadlessGhidraApplicationConfiguration());
23
- var server=new GhidraServerManager();server.connect();var repository=server.server().getRepository(repo);repository.connect();
35
+ server=new GhidraServerManager();server.connect();var repository=server.server().getRepository(repo);repository.connect();
24
36
  if(!repository.getUser().isReadOnly()||!repository.getUser().getName().equals(System.getenv("GHIDRA_SERVER_USER")))throw new SecurityException();
25
37
  var item=repository.getItem("/",name);
26
- if(item==null&&op.equals("migration-probe")){repository.disconnect();server.disconnect();output.println("{\"state\":\"absent\"}");System.exit(0);}
38
+ if(item==null&&op.equals("migration-probe")){repository.disconnect();server.disconnect();server=null;return new LinkedHashMap<>(Map.of("state","absent"));}
27
39
  if(item==null||repository.isCheckinActive("/",name))throw new IllegalStateException("Native item is absent or busy");
28
40
  int version=q.has("version")?q.get("version").getAsInt():item.getVersion();
29
41
  if(q.has("fileId")&&!item.getFileID().equals(q.get("fileId").getAsString()))throw new SecurityException("Native item ID changed");
@@ -31,14 +43,22 @@ public final class InsightNativeRead {
31
43
  var matches=Arrays.stream(repository.getVersions("/",name)).filter(v->q.get("marker").getAsString().equals(v.getComment())).toList();
32
44
  if(matches.size()!=1||matches.getFirst().getVersion()!=version)throw new IllegalStateException("Native history marker is unresolved");
33
45
  }
46
+ // The unique request marker at the expected version is the publication. Nothing more is opened to settle a
47
+ // lost check-in reply; only a migration asks for the bytes.
48
+ if(op.equals("verify")&&!(q.has("bytes")&&q.get("bytes").getAsBoolean())){
49
+ Map<String,Object> settled=new LinkedHashMap<>(Map.of("state","verified","version",version,"fileId",item.getFileID(),"fingerprint",InsightNativeFingerprint.version(item.getFileID(),version)));
50
+ repository.disconnect();server.disconnect();server=null;return settled;
51
+ }
34
52
  DBHandle db=new DBHandle(repository.openDatabase("/",name,version,-1));Object consumer=new Object();ProgramDB program=null;
35
53
  Map<String,Object> result=new LinkedHashMap<>();
36
54
  try {
37
- String fingerprint=InsightNativeFingerprint.of(db);
55
+ // An immutable version is identified by its item and number. Only a migration compares whole databases.
56
+ String fingerprint=op.equals("migration-probe")||q.has("bytes")&&q.get("bytes").getAsBoolean()?InsightNativeFingerprint.of(db):InsightNativeFingerprint.version(item.getFileID(),version);
38
57
  program=new ProgramDB(db,OpenMode.IMMUTABLE,TaskMonitor.DUMMY,consumer);
39
58
  if(!sha.equals(program.getExecutableSHA256()))throw new SecurityException("Native source changed");
40
59
  if(!op.equals("migration-probe")&&!program.getOptions("Insight").getString("Publication Engine","").equals("native-checkout-v1"))throw new InsightNativeMigration.Required();
41
- if(q.has("fingerprint")&&!fingerprint.equals(q.get("fingerprint").getAsString()))throw new SecurityException("Exact native buffers differ");
60
+ // Only a migration compares bytes; a version is otherwise the one that was asked for by item and number.
61
+ if(q.has("bytes")&&q.get("bytes").getAsBoolean()&&q.has("fingerprint")&&!fingerprint.equals(q.get("fingerprint").getAsString()))throw new SecurityException("Exact native buffers differ");
42
62
  result.put("state","verified");result.put("version",version);result.put("fileId",item.getFileID());result.put("fingerprint",fingerprint);
43
63
  if(op.equals("migration-probe")){result.put("content",InsightNativeFingerprint.content(program));result.put("engine",program.getOptions("Insight").getString("Publication Engine",""));result.put("programIdentity",InsightNativeMigration.programIdentity(program));var functions=program.getFunctionManager().getFunctions(true);int samples=0;String sample=null;
44
64
  while(functions.hasNext()&&samples++<1000){var f=functions.next();var block=program.getMemory().getBlock(f.getEntryPoint());if(!f.isThunk()&&block!=null&&block.isInitialized()&&block.isExecute()){if(sample==null)sample=f.getEntryPoint().toString();if(program.getReferenceManager().getReferencesTo(f.getEntryPoint()).hasNext()){sample=f.getEntryPoint().toString();break;}}}result.put("sampleFunction",sample);
@@ -51,7 +71,10 @@ public final class InsightNativeRead {
51
71
  }finally{if(program!=null)program.release(consumer);else db.close();}
52
72
  var after=repository.getItem("/",name);
53
73
  if(after==null||!after.getFileID().equals(item.getFileID())||after.getVersion()<version)throw new SecurityException("Native item changed while reading its exact version");
54
- repository.disconnect();server.disconnect();output.println(new GsonBuilder().serializeNulls().create().toJson(result));System.exit(0);
55
- }catch(Throwable failure){failure.printStackTrace(System.err);output.println(new Gson().toJson(Map.of("state","unknown","diagnostic",failure.getClass().getSimpleName(),"reason",Objects.toString(failure.getMessage(),failure.toString()),"code",failure instanceof InsightNativeMigration.Required?"migration":"unknown")));System.exit(0);}
74
+ repository.disconnect();server.disconnect();server=null;return result;
75
+ }catch(Throwable failure){failure.printStackTrace(System.err);
76
+ if(failure instanceof Error)poisoned=true;
77
+ try{if(server!=null)server.disconnect();}catch(Throwable cleanup){poisoned=true;}
78
+ return unknown(failure);}
56
79
  }
57
80
  }
@@ -0,0 +1,43 @@
1
+ import com.google.gson.*;
2
+ import ghidra.GhidraApplicationLayout;
3
+ import ghidra.framework.*;
4
+ import java.io.*;
5
+ import java.nio.charset.StandardCharsets;
6
+ import java.nio.file.Path;
7
+ import java.util.*;
8
+
9
+ /**
10
+ * Long-lived trusted native service owned by one coordinator process. Ghidra is initialized once; then each
11
+ * stdin line names one owned request file and receives one stdout line with its result, strictly in order.
12
+ * The publisher role runs native checkout operations with publisher credentials, the reader role runs
13
+ * independent reads with reader credentials; agent code never runs here. Each request keeps the one-shot
14
+ * helper's semantics (its own server connection, journals and result shape). End of input stops the service.
15
+ */
16
+ public final class InsightNativeService {
17
+ public static void main(String[] args){
18
+ var output=new PrintStream(new FileOutputStream(FileDescriptor.out),true,StandardCharsets.UTF_8);System.setOut(System.err);
19
+ String role=args.length==1?args[0]:"";
20
+ try{
21
+ if(!role.equals("publisher")&&!role.equals("reader"))throw new IllegalArgumentException("Native service role required");
22
+ if(role.equals("publisher"))InsightNativeCheckout.initialize();
23
+ else if(!Application.isInitialized())Application.initializeApplication(new GhidraApplicationLayout(),new HeadlessGhidraApplicationConfiguration());
24
+ }catch(Throwable failure){failure.printStackTrace(System.err);output.println("{\"state\":\"failed\"}");System.exit(1);}
25
+ output.println("{\"state\":\"ready\",\"role\":\""+role+"\",\"pid\":"+ProcessHandle.current().pid()+"}");
26
+ try(var input=new BufferedReader(new InputStreamReader(System.in,StandardCharsets.UTF_8))){
27
+ for(String line;(line=input.readLine())!=null;){
28
+ String id=null;Path request;
29
+ try{JsonObject q=JsonParser.parseString(line).getAsJsonObject();id=q.get("id").getAsString();request=Path.of(q.get("request").getAsString());}
30
+ catch(RuntimeException malformed){
31
+ // Answer with the id when one was readable, so the caller reports this request instead of waiting.
32
+ output.println(id==null?"{\"error\":\"malformed\"}":InsightNativeCheckout.GSON.toJson(Map.of("id",id,"result",Map.of("state","unknown","diagnostic","Malformed","reason","Malformed native service request","code","unknown"))));continue;}
33
+ Map<String,Object> result=role.equals("publisher")?InsightNativeCheckout.handle(request):InsightNativeRead.handle(request);
34
+ // A doubtful JVM state never serves another request: the reply announces the exit, so the caller
35
+ // never sends a queued request here, and the next one starts a fresh service.
36
+ boolean closing=InsightNativeCheckout.poisoned||InsightNativeRead.poisoned;
37
+ output.println(InsightNativeCheckout.GSON.toJson(closing?Map.of("id",id,"result",result,"closing",true):Map.of("id",id,"result",result)));
38
+ if(closing)break;
39
+ }
40
+ }catch(Throwable failure){failure.printStackTrace(System.err);}
41
+ System.exit(0);
42
+ }
43
+ }
@@ -11,19 +11,30 @@ public class InsightNativeView extends GhidraScript {
11
11
  public void run()throws Exception {
12
12
  JsonObject q=JsonParser.parseString(new String(Base64.getDecoder().decode(getScriptArgs()[0]),java.nio.charset.StandardCharsets.UTF_8)).getAsJsonObject();
13
13
  if(currentProgram==null||currentProgram.isChanged())throw new IllegalStateException("Saved program required");
14
- String fingerprint=InsightNativeFingerprint.of(currentProgram);
14
+ String fingerprint=saved();
15
15
  if(q.has("expected")&&!fingerprint.equals(q.get("expected").getAsString()))throw new IllegalStateException("Saved native view changed");
16
16
  Object value;
17
17
  switch(q.get("operation").getAsString()) {
18
- case "fingerprint":
19
- var c=((ProgramDB)currentProgram).getChanges();
20
- value=Map.of("fingerprint",fingerprint,"version",currentProgram.getDomainFile().getVersion(),"fileId",currentProgram.getDomainFile().getFileID(),
21
- "dataTypeChanges",c.getDataTypeChanges(),"dataTypeAdditions",c.getDataTypeAdditions(),"symbolChanges",c.getSymbolChanges(),"symbolAdditions",c.getSymbolAdditions());break;
18
+ case "fingerprint":value=saved(fingerprint);break;
19
+ // One pass for a save receipt: identity plus the inspected metadata of the same exact bytes.
20
+ case "capture":{
21
+ Map<String,Object> receipt=new LinkedHashMap<>(saved(fingerprint));
22
+ receipt.put("inspected",InsightSnapshotInspect.inspect((ProgramDB)currentProgram,q.getAsJsonObject("parameters")));
23
+ value=receipt;break;
24
+ }
22
25
  case "fields":value=InsightSnapshotFields.inspect((ProgramDB)currentProgram,q.getAsJsonArray("selectors"));break;
23
26
  case "inspect":value=InsightSnapshotInspect.inspect((ProgramDB)currentProgram,q.getAsJsonObject("parameters"));break;
24
27
  default:throw new IllegalArgumentException();
25
28
  }
26
- if(!fingerprint.equals(InsightNativeFingerprint.of(currentProgram)))throw new IllegalStateException("Native view changed while inspecting");
29
+ // Still unchanged and still the same saved source as at the start.
30
+ if(!fingerprint.equals(saved()))throw new IllegalStateException("Native view changed while inspecting");
27
31
  println("INSIGHT_NATIVE:"+new GsonBuilder().serializeNulls().create().toJson(Map.of("value",value)));
28
32
  }
33
+ /** The saved state as Ghidra identifies it. A worker built from other helper sources is replaced before it is used. */
34
+ private String saved()throws Exception{return InsightNativeFingerprint.saved(currentProgram);}
35
+ private Map<String,Object> saved(String fingerprint){
36
+ var c=((ProgramDB)currentProgram).getChanges();
37
+ return Map.of("fingerprint",fingerprint,"modified",currentProgram.getDomainFile().isCheckedOut()&&currentProgram.getDomainFile().modifiedSinceCheckout(),"version",currentProgram.getDomainFile().getVersion(),"fileId",currentProgram.getDomainFile().getFileID(),
38
+ "dataTypeChanges",c.getDataTypeChanges(),"dataTypeAdditions",c.getDataTypeAdditions(),"symbolChanges",c.getSymbolChanges(),"symbolAdditions",c.getSymbolAdditions());
39
+ }
29
40
  }
@@ -0,0 +1,170 @@
1
+ import com.google.gson.Gson;
2
+ import com.google.gson.JsonObject;
3
+ import com.google.gson.JsonParser;
4
+ import com.sun.net.httpserver.HttpExchange;
5
+ import com.xebyte.core.ProgramProvider;
6
+ import com.xebyte.headless.GhidraMCPHeadlessServer;
7
+ import generic.jar.ResourceFile;
8
+ import ghidra.app.script.GhidraScript;
9
+ import ghidra.app.script.GhidraState;
10
+ import ghidra.program.model.listing.Program;
11
+ import ghidra.program.util.ProgramLocation;
12
+ import ghidra.util.task.ConsoleTaskMonitor;
13
+ import java.io.ByteArrayOutputStream;
14
+ import java.io.PrintStream;
15
+ import java.io.PrintWriter;
16
+ import java.io.StringWriter;
17
+ import java.nio.charset.StandardCharsets;
18
+ import java.nio.file.Files;
19
+ import java.nio.file.Path;
20
+ import java.security.MessageDigest;
21
+ import java.util.LinkedHashMap;
22
+ import java.util.Map;
23
+ import java.util.Set;
24
+ import java.util.concurrent.locks.ReentrantLock;
25
+
26
+ /**
27
+ * Runs a fixed helper script of this worker's own compiled helpers in-process.
28
+ *
29
+ * The pinned inline provider compiles a script's source on every call. These helpers are already compiled into
30
+ * the worker's helper directory, so a leased worker runs the same class directly, the way the provider does: a
31
+ * new instance per call with the program's minimum address as its location, executed through
32
+ * GhidraScript.execute while standard output and error are captured. Nothing else is reachable here: only the
33
+ * listed helper names, loaded from that helper directory, for an already open program.
34
+ *
35
+ * A request that cannot be served is refused with 409 and a reason before anything runs. The lease admits each
36
+ * execution: a retiring worker admits none, a worker never retires while one runs, and only a few may wait.
37
+ * Executions are serialized.
38
+ */
39
+ final class InsightOwnedScripts {
40
+ private static final Set<String> SCRIPTS=Set.of("InsightNativeView","InsightResearchQueries","InsightCodeReferences","InsightSdkScript",
41
+ "InsightEmulation","InsightApplyDocumentation","InsightInlineScript","InsightArchivePayloads");
42
+ private static final int MAX_REQUEST_BYTES=8*1024*1024,MAX_CAPTURED_BYTES=64*1024;
43
+ private static final ReentrantLock EXECUTION=new ReentrantLock(true);
44
+ private static volatile GhidraMCPHeadlessServer server;
45
+ private InsightOwnedScripts(){}
46
+
47
+ static void bind(GhidraMCPHeadlessServer headless){server=headless;}
48
+ private static Path helpers()throws Exception{return Path.of(InsightOwnedScripts.class.getProtectionDomain().getCodeSource().getLocation().toURI());}
49
+ private static ProgramProvider programs()throws Exception{
50
+ GhidraMCPHeadlessServer current=server;if(current==null)return null;
51
+ var field=GhidraMCPHeadlessServer.class.getDeclaredField("programProvider");field.setAccessible(true);
52
+ return (ProgramProvider)field.get(current);
53
+ }
54
+ private static void reply(HttpExchange exchange,int status,Map<String,Object> value)throws java.io.IOException{
55
+ byte[] bytes=new Gson().toJson(value).getBytes(StandardCharsets.UTF_8);
56
+ exchange.getResponseHeaders().set("Content-Type","application/json");exchange.sendResponseHeaders(status,bytes.length);
57
+ try(var out=exchange.getResponseBody()){out.write(bytes);}
58
+ }
59
+ private static Map<String,Object> refused(String reason){return Map.of("state","not_executed","reason",reason);}
60
+ /** The deepest cause names the failure, as the inline provider reports it. */
61
+ private static String describe(Throwable failure){
62
+ Throwable cause=failure;for(int depth=0;depth<16&&cause.getCause()!=null&&cause.getCause()!=cause;depth++)cause=cause.getCause();
63
+ String message=cause.getMessage();
64
+ return cause.getClass().getSimpleName()+": "+(message==null?"":message.substring(0,Math.min(message.length(),900)));
65
+ }
66
+ private static final class Bounded extends ByteArrayOutputStream {
67
+ boolean truncated;
68
+ @Override public synchronized void write(int b){if(count<MAX_CAPTURED_BYTES)super.write(b);else truncated=true;}
69
+ @Override public synchronized void write(byte[] b,int offset,int length){
70
+ int kept=Math.max(0,Math.min(length,MAX_CAPTURED_BYTES-count));super.write(b,offset,kept);if(kept<length)truncated=true;
71
+ }
72
+ synchronized boolean truncated(){return truncated;}
73
+ }
74
+
75
+ /**
76
+ * Opens the working program of this worker's project and nothing else. The bridge's own open also clears the
77
+ * "ask to analyze" prompt and saves, which makes Ghidra report an untouched checkout as modified; a private
78
+ * headless checkout has no prompt to suppress.
79
+ */
80
+ static void open(HttpExchange exchange,byte[] expected)throws java.io.IOException{
81
+ try{
82
+ String authorization=exchange.getRequestHeaders().getFirst("Authorization");
83
+ if(!"POST".equals(exchange.getRequestMethod())||authorization==null||!MessageDigest.isEqual(expected,authorization.getBytes(StandardCharsets.UTF_8))){
84
+ exchange.sendResponseHeaders(401,-1);return;
85
+ }
86
+ String refusal=InsightWorkerLease.admitScript();if(refusal!=null){reply(exchange,409,refused(refusal));return;}
87
+ try{
88
+ String path;
89
+ try{path=JsonParser.parseString(new String(exchange.getRequestBody().readNBytes(8192),StandardCharsets.UTF_8)).getAsJsonObject().get("path").getAsString();}
90
+ catch(RuntimeException malformed){exchange.sendResponseHeaders(400,-1);return;}
91
+ EXECUTION.lock();
92
+ try{
93
+ ProgramProvider provider=programs();
94
+ if(!(provider instanceof com.xebyte.core.ProjectProgramProvider project)||project.getProject()==null){reply(exchange,409,refused("provider"));return;}
95
+ ghidra.framework.model.DomainFile file=project.getProject().getProjectData().getFile(path);
96
+ if(file==null){reply(exchange,409,refused("program"));return;}
97
+ Map<String,Object> result=new LinkedHashMap<>();
98
+ // Opening for writing discards Ghidra's recovery snapshot of an interrupted session; such a file is not opened.
99
+ // The reply names only that fact: the caller turns it into its own refusal with the ways out.
100
+ if(file.canRecover()){result.put("recoverable",true);reply(exchange,200,result);return;}
101
+ try{
102
+ Program program=project.openDomainFile(file);
103
+ result.put("success",true);result.put("path",program.getDomainFile().getPathname());result.put("name",program.getName());
104
+ result.put("read_only",!program.getDomainFile().canSave()||!program.isChangeable());
105
+ }catch(Exception failure){result.put("success",false);result.put("error",describe(failure));}
106
+ reply(exchange,200,result);
107
+ }catch(Exception unavailable){reply(exchange,409,refused("unavailable"));}
108
+ finally{EXECUTION.unlock();}
109
+ }finally{InsightWorkerLease.finishScript();}
110
+ }finally{exchange.close();}
111
+ }
112
+ static void handle(HttpExchange exchange,byte[] expected)throws java.io.IOException{
113
+ try{
114
+ String authorization=exchange.getRequestHeaders().getFirst("Authorization");
115
+ if(!"POST".equals(exchange.getRequestMethod())||authorization==null||!MessageDigest.isEqual(expected,authorization.getBytes(StandardCharsets.UTF_8))){
116
+ exchange.sendResponseHeaders(401,-1);return;
117
+ }
118
+ // From admission to release the worker cannot retire or park; a retiring or parked worker admits nothing.
119
+ // Admission precedes the body, so only admitted requests hold a listener thread while they are read.
120
+ String refusal=InsightWorkerLease.admitScript();if(refusal!=null){reply(exchange,409,refused(refusal));return;}
121
+ try{
122
+ byte[] body=exchange.getRequestBody().readNBytes(MAX_REQUEST_BYTES+1);
123
+ JsonObject q;String name,path,caller,text;
124
+ try{
125
+ if(body.length>MAX_REQUEST_BYTES)throw new IllegalArgumentException();
126
+ q=JsonParser.parseString(new String(body,StandardCharsets.UTF_8)).getAsJsonObject();
127
+ name=q.get("script").getAsString();path=q.get("program").getAsString();caller=q.get("helpers").getAsString();
128
+ text=q.has("args")?q.get("args").getAsString().trim():"";
129
+ }catch(RuntimeException malformed){exchange.sendResponseHeaders(400,-1);return;}
130
+ EXECUTION.lock();
131
+ try{
132
+ // Everything up to execute() is a refusal: nothing ran.
133
+ GhidraScript script;GhidraState state;
134
+ try{
135
+ // The caller's helper sources must be the ones these classes were compiled from.
136
+ Path directory=helpers();String compiled=Files.readString(directory.resolve("helper-sources")).trim();
137
+ if(!compiled.matches("[a-f0-9]{64}")||!compiled.equals(caller)){reply(exchange,409,refused("helpers"));return;}
138
+ if(!SCRIPTS.contains(name)){reply(exchange,409,refused("script"));return;}
139
+ ProgramProvider provider=programs();if(provider==null){reply(exchange,409,refused("provider"));return;}
140
+ Program selected=null;int matches=0;
141
+ for(Program p:provider.getAllOpenPrograms())if(p!=null&&!p.isClosed()&&p.getDomainFile()!=null&&path.equals(p.getDomainFile().getPathname())){if(selected!=p)matches++;selected=p;}
142
+ if(matches!=1){reply(exchange,409,refused("program"));return;}
143
+ // Resolved without initialization until its origin is proved to be this helper directory.
144
+ Class<?> type=Class.forName(name,false,InsightOwnedScripts.class.getClassLoader());
145
+ if(!GhidraScript.class.isAssignableFrom(type)||!Path.of(type.getProtectionDomain().getCodeSource().getLocation().toURI()).equals(directory)){reply(exchange,409,refused("script"));return;}
146
+ script=(GhidraScript)type.getDeclaredConstructor().newInstance();
147
+ script.setSourceFile(new ResourceFile(directory.resolve(name+".java").toFile()));
148
+ script.setScriptArgs(text.isEmpty()?new String[0]:text.split("\\s+"));
149
+ var start=selected.getMinAddress();
150
+ state=new GhidraState(null,provider.getProject(),selected,start==null?null:new ProgramLocation(selected,start),null,null);
151
+ }catch(Exception|LinkageError unavailable){reply(exchange,409,refused("unavailable"));return;}
152
+ StringWriter console=new StringWriter();PrintWriter writer=new PrintWriter(console,true);
153
+ Bounded captured=new Bounded();PrintStream originalOut=System.out,originalErr=System.err;
154
+ Map<String,Object> result=new LinkedHashMap<>();
155
+ try{
156
+ PrintStream capture=new PrintStream(captured,true,StandardCharsets.UTF_8);System.setOut(capture);System.setErr(capture);
157
+ script.execute(state,new ConsoleTaskMonitor(),writer);result.put("success",true);
158
+ }catch(Exception failure){result.put("success",false);result.put("error",describe(failure));}
159
+ // An Error is not a script failure: the caller sees a failed request whose effect is unknown.
160
+ catch(Throwable fatal){reply(exchange,500,Map.of("error",describe(fatal)));return;}
161
+ finally{System.setOut(originalOut);System.setErr(originalErr);}
162
+ writer.flush();
163
+ String output=console.toString(),process=captured.toString(StandardCharsets.UTF_8)+(captured.truncated()?"\n[process output truncated]":"");
164
+ result.put("console_output",process.isEmpty()?output:output+"\n--- CONSOLE OUTPUT ---\n"+process+"\n");
165
+ reply(exchange,200,result);
166
+ }finally{EXECUTION.unlock();}
167
+ }finally{InsightWorkerLease.finishScript();}
168
+ }finally{exchange.close();}
169
+ }
170
+ }
@@ -0,0 +1,132 @@
1
+ import com.google.gson.JsonObject;
2
+ import com.google.gson.JsonParser;
3
+ import com.sun.net.httpserver.HttpServer;
4
+ import java.net.InetAddress;
5
+ import java.net.InetSocketAddress;
6
+ import java.nio.charset.StandardCharsets;
7
+ import java.nio.file.Files;
8
+ import java.nio.file.Path;
9
+ import java.nio.file.StandardCopyOption;
10
+ import java.security.MessageDigest;
11
+ import java.time.Instant;
12
+ import java.util.HashMap;
13
+ import java.util.Map;
14
+ import java.util.UUID;
15
+ import java.util.concurrent.Executors;
16
+
17
+ /**
18
+ * Idle cool-down of an owned context worker.
19
+ *
20
+ * A command holds the worker from its first use until it ends: `acquire` registers a holder, `renew` is its
21
+ * heartbeat and `release` ends it. A held worker never retires. Without holders the worker retires once its
22
+ * idle time has passed since the last release or renewal; a holder whose heartbeat stops (its owner died)
23
+ * expires after `HOLD_MS`. `retire` asks an unheld worker to stop now (capacity eviction, runtime change).
24
+ * Every decision is serialized under one monitor and, once retiring, every request is refused (409), so no
25
+ * new command is admitted to a worker that is about to exit. Acknowledged work is saved before acknowledgement,
26
+ * so retirement needs no save. A long gap between watchdog ticks (host suspend) shifts all deadlines by that
27
+ * gap instead of retiring a worker whose holder could not run.
28
+ */
29
+ final class InsightWorkerLease {
30
+ private static final long HOLD_MS=180_000,TICK_MS=1_000,SUSPEND_GAP_MS=10_000;
31
+ private static final Object LOCK=new Object();
32
+ private static final Map<String,Long> holders=new HashMap<>();
33
+ /** Holders released explicitly (bounded): their late heartbeat never re-holds the worker. */
34
+ private static final java.util.LinkedHashSet<String> released=new java.util.LinkedHashSet<>();
35
+ private static long deadline,lastActivity;
36
+ private static String retiring;
37
+ /** Admitted helper-script requests (running or waiting their turn); the worker never retires while any exists. */
38
+ private static int scripts;
39
+ /**
40
+ * The holder whose command closed the project for a native Update or check-in. No helper script is admitted
41
+ * until that command reopens it, or its hold ends (released, or expired because its owner died).
42
+ */
43
+ private static String parkedBy;
44
+ private static final int MAX_SCRIPTS=4;
45
+ private InsightWorkerLease(){}
46
+
47
+ private static long now(){return System.nanoTime();}
48
+ private static long nanos(long millis){return millis*1_000_000L;}
49
+
50
+ /** Admit one helper-script request, or name why not: nothing is admitted to a retiring worker. */
51
+ static String admitScript(){synchronized(LOCK){if(retiring!=null)return "retiring";if(parkedBy!=null&&!holders.containsKey(parkedBy))parkedBy=null;if(parkedBy!=null)return "parked";if(scripts>=MAX_SCRIPTS)return "busy";scripts++;lastActivity=now();return null;}}
52
+ static void finishScript(){synchronized(LOCK){scripts--;lastActivity=now();}}
53
+
54
+ static void start() throws Exception {
55
+ String port=System.getenv("INSIGHT_WORKER_LEASE_PORT");
56
+ if(port==null||port.isEmpty())return;
57
+ long idleMillis=Long.parseLong(System.getenv("INSIGHT_WORKER_IDLE_MS"));
58
+ if(idleMillis<1000)throw new IllegalArgumentException("Worker idle time is too short");
59
+ long idle=nanos(idleMillis);
60
+ byte[] expected=("Bearer "+System.getenv("GHIDRA_MCP_AUTH_TOKEN")).getBytes(StandardCharsets.UTF_8);
61
+ Path root=Path.of(System.getenv("GHIDRA_MCP_FILE_ROOT"));
62
+ long pid=ProcessHandle.current().pid();
63
+ synchronized(LOCK){deadline=now()+idle;lastActivity=now();}
64
+ HttpServer server=HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(),Integer.parseInt(port)),16);
65
+ server.createContext("/insight/lease",exchange->{
66
+ try{
67
+ String authorization=exchange.getRequestHeaders().getFirst("Authorization");
68
+ if(!"POST".equals(exchange.getRequestMethod())||authorization==null||!MessageDigest.isEqual(expected,authorization.getBytes(StandardCharsets.UTF_8))){
69
+ exchange.sendResponseHeaders(401,-1);return;
70
+ }
71
+ JsonObject q;
72
+ try{q=JsonParser.parseString(new String(exchange.getRequestBody().readNBytes(4096),StandardCharsets.UTF_8)).getAsJsonObject();}
73
+ catch(RuntimeException malformed){exchange.sendResponseHeaders(400,-1);return;}
74
+ String action=q.has("action")?q.get("action").getAsString():"",holder=q.has("holder")?q.get("holder").getAsString():"";
75
+ if(!action.matches("acquire|renew|release|status|retire|park_held|unpark")||action.matches("acquire|renew|release|park_held")&&!holder.matches("[a-f0-9-]{36}")){
76
+ exchange.sendResponseHeaders(400,-1);return;
77
+ }
78
+ int status=200;String state;int held,running;long idleFor;
79
+ synchronized(LOCK){
80
+ long t=now();
81
+ if(retiring!=null&&!action.equals("status"))status=409;
82
+ else switch(action){
83
+ case "acquire"->{holders.put(holder,t+nanos(HOLD_MS));lastActivity=t;deadline=Math.max(deadline,t+idle);}
84
+ // A heartbeat restores a hold that merely expired (missed renewals), never one released explicitly.
85
+ case "renew"->{if(!released.contains(holder)){holders.put(holder,t+nanos(HOLD_MS));lastActivity=t;deadline=Math.max(deadline,t+idle);}}
86
+ case "release"->{if(holder.equals(parkedBy))parkedBy=null;holders.remove(holder);released.add(holder);if(released.size()>1024)released.remove(released.iterator().next());lastActivity=t;deadline=t+idle;}
87
+ case "retire"->{if(holders.isEmpty()&&scripts==0)retiring=q.has("reason")&&q.get("reason").getAsString().matches("[a-z_]{1,40}")?q.get("reason").getAsString():"retired";else status=423;}
88
+ // Parking closes the project: refused while a helper script runs or waits, and none is admitted afterwards.
89
+ case "park_held"->{if(scripts==0&&holders.containsKey(holder))parkedBy=holder;else status=423;}
90
+ case "unpark"->parkedBy=null;
91
+ default->{}
92
+ }
93
+ state=retiring!=null?"retiring":holders.isEmpty()?"idle":"held";held=holders.size();running=scripts;idleFor=holders.isEmpty()?Math.max(0,(t-lastActivity)/1_000_000L):0;
94
+ }
95
+ byte[] bytes=("{\"state\":\""+state+"\",\"pid\":"+pid+",\"idleMs\":"+idleMillis+",\"holders\":"+held+",\"scripts\":"+running+",\"idleForMs\":"+idleFor+"}").getBytes(StandardCharsets.UTF_8);
96
+ exchange.getResponseHeaders().set("Content-Type","application/json");
97
+ exchange.sendResponseHeaders(status,bytes.length);
98
+ try(var out=exchange.getResponseBody()){out.write(bytes);}
99
+ }finally{exchange.close();}
100
+ });
101
+ // Owned helper scripts run on this listener too. At most MAX_SCRIPTS requests hold a thread, so a heartbeat
102
+ // always finds one; lease decisions stay serialized under LOCK.
103
+ server.createContext("/insight/script",exchange->InsightOwnedScripts.handle(exchange,expected));
104
+ server.createContext("/insight/open",exchange->InsightOwnedScripts.open(exchange,expected));
105
+ server.setExecutor(Executors.newFixedThreadPool(MAX_SCRIPTS+4,r->{Thread t=new Thread(r,"insight-worker-lease");t.setDaemon(true);return t;}));
106
+ server.start();
107
+ Thread watchdog=new Thread(()->{
108
+ String reason;
109
+ try{
110
+ long previous=now();
111
+ while(true){
112
+ Thread.sleep(TICK_MS);
113
+ synchronized(LOCK){
114
+ long t=now(),gap=t-previous-nanos(TICK_MS);previous=t;
115
+ if(gap>nanos(SUSPEND_GAP_MS)){deadline+=gap;holders.replaceAll((id,expiry)->expiry+gap);}
116
+ holders.values().removeIf(expiry->t-expiry>0);
117
+ // A park ends with its holder, here and not at the next request: a late heartbeat cannot revive it.
118
+ if(parkedBy!=null&&!holders.containsKey(parkedBy))parkedBy=null;
119
+ if(retiring==null&&holders.isEmpty()&&scripts==0&&t-deadline>=0)retiring="idle_timeout";
120
+ if(retiring!=null){reason=retiring;break;}
121
+ }
122
+ }
123
+ server.stop(0);
124
+ Path receipt=root.resolve("idle-exit.json"),temporary=root.resolve("idle-exit.json.new-"+UUID.randomUUID());
125
+ Files.writeString(temporary,"{\"schema\":1,\"pid\":"+pid+",\"at\":\""+Instant.now()+"\",\"idleMs\":"+idleMillis+",\"reason\":\""+reason+"\"}");
126
+ Files.move(temporary,receipt,StandardCopyOption.REPLACE_EXISTING,StandardCopyOption.ATOMIC_MOVE);
127
+ }catch(Throwable ignored){/* Retirement proceeds; the coordinator then records an unknown stop reason. */}
128
+ System.exit(0);
129
+ },"insight-idle-retirement");
130
+ watchdog.setDaemon(true);watchdog.start();
131
+ }
132
+ }
@@ -15,10 +15,19 @@ recovery. Preserve its project and receipts rather than repeating a mutation wit
15
15
 
16
16
  If native `changes discard` loses its response, retry its original request ID or continue
17
17
  the same session/target. Recovery requires a completed native discard journal and matching
18
- new checkout identity/base and saved buffers, followed by independent server readback.
18
+ new checkout identity/base, which Ghidra reports unmodified.
19
19
  It does not repeat discard. An incomplete journal or mismatched checkout stays unknown;
20
20
  preserve the project and any `.keep` file.
21
21
 
22
+ A Ghidra session that ends abruptly can leave unsaved changes as Ghidra recovery data in the
23
+ working copy. Opening the program would delete them, so `ghidra open` and every native
24
+ operation refuse with `blocked` and name the two ways out. Neither needs Ghidra itself:
25
+ `ghidra changes recover-unsaved --session <id> --target <id>` has Ghidra restore those changes
26
+ and save them into the working copy; `ghidra changes discard-unsaved --session <id> --target <id>`
27
+ (Destructive) has Ghidra delete them. Saved work stays in both cases, nothing is published, and
28
+ repeating either command is safe: with nothing left it reports `absent`. Then run the refused
29
+ command again.
30
+
22
31
  First-import recovery uses the same scoped `ghidra open` or the original request ID/input.
23
32
  Import/analysis writes a private snapshot and completion receipt before any initial publication.
24
33
  If its worker is still running, continuation reports busy; wait and continue the same scope.
@@ -75,6 +84,62 @@ edits stay private. A revision change or live checkout blocks adoption. Only an
75
84
  absent path permits a separately journaled preparation under the current verified runtime,
76
85
  using the original lock and conditional creation. An unknown publication still freezes recovery.
77
86
 
87
+ ## Merge or refresh that was never sent
88
+
89
+ A cancellation (or an unusable native service) can stop a merge or refresh before its native
90
+ Update or check-in ever left the CLI. That is provable, so it is not an unknown outcome: the request
91
+ ends as failed with `reason: not_sent`, a prepared publication intent is withdrawn (stored as a
92
+ refused publication), the lane stays open and local work remains pending. The original
93
+ `--request-id` then keeps reporting that terminal refusal (`coordinator.conflict`) with its `phase`,
94
+ `cause` and memory diagnosis (a suggested next command is given only in the first response); run the
95
+ merge or refresh again with a new request ID. The same applies when the worker pool was busy, blocked or
96
+ full, the worker could not be parked or stopped, or its server could not be reached before the step
97
+ was dispatched. Any other failure while the context was reopened or saved (a lost, failed or
98
+ unusable reply, an unacknowledged save) keeps its own unresolved outcome. A cancellation after a native step was sent keeps the
99
+ unknown-outcome rules below.
100
+
101
+ A native helper can also end before its step reached the server, most often because the machine
102
+ ran out of memory (many concurrent sessions or JVMs). The helper writes its operation journal
103
+ before its Update or check-in call (it may already have read from the server), so a helper that ended without an answer (exit, timeout, cancellation or
104
+ memory exhaustion) is reported as not sent (with `memory: exhausted`, `reason: out_of_memory`, the
105
+ concrete JVM cause such as a too-small paging file in `memoryCause` and the message, and the
106
+ original error as `cause`) when that journal is absent from the journal directory the coordinator
107
+ created and identified before dispatch (a moved or replaced checkout or directory proves nothing)
108
+ and no helper or publisher service that could still write it
109
+ remains: each has proved its exit, or is a publisher service the current owner still tracks as
110
+ serving. A helper that answered keeps its own outcome (refusal, migration, binding or unknown), and
111
+ a helper whose termination could not be proved keeps the outcome unknown. These proofs assume the
112
+ profile's single owner process; process records of any other owner must show their exit.
113
+
114
+ Only the live command, which itself observed its helper end, reports a step as not sent. An outcome
115
+ already recorded as unknown (for example after the owner process itself stopped) is never settled
116
+ from an absent journal: on Windows a machine crash can lose a written journal's directory entry,
117
+ and an Update that ran can leave the checkout unchanged (no incoming change, or a conflict). It
118
+ stays unknown until its own journal, or for a check-in the request marker in the server history,
119
+ establish the result; `insight-cli ghidra open --target <target> --session <session>` reconciles it.
120
+
121
+ Every refusal of a research or lifecycle command caused by an unresolved outcome
122
+ (`coordinator.blocked`) names the reconciling
123
+ command in its message and in `next.reconcile`, lists the owning context's unresolved requests
124
+ (ID, caller request ID, operation, state) and, when another session's publication holds the lane,
125
+ that publication. If a proof is missing, the lane stays frozen as described below; once the cause
126
+ (for example low memory or a busy server) is gone, run the reconciling open again. Never repeat the
127
+ unknown operation itself. While it stays frozen the saved project and its journals are retained.
128
+ A context-local outcome leaves the target free: research continues in a new session
129
+ (`next.continueElsewhere`, `insight-cli ghidra open --target <target> --session new`). An
130
+ unresolved publication or shared model holds the whole target (`targetHeld: true`, no
131
+ `continueElsewhere`): a new session of it waits as well, other targets are unaffected. When the
132
+ reconciling open cannot prove an outcome yet, it says so and when to run it again; replay an
133
+ original request ID to see how a reconciled request ended (`sessions status` lists only requests
134
+ that are still unresolved, so keep that ID). An open that failed while setting up (before any
135
+ reconciliation) is a plain failure; its replay reports that failure without running setup again.
136
+ A request settled as not sent is terminal: run the operation again with a new request ID. A merge or refresh
137
+ recorded as unknown keeps its error code and adds the same guidance to its message and result.
138
+ Commands in guidance name the profile (`--profile <name>`); machine-readable follow-ups (`next`)
139
+ always address the context that owns the outcome, never the refused one. `ghidra abandon` applies
140
+ only to legacy detached program attempts; for a native outcome it refuses with the same
141
+ reconciliation command.
142
+
78
143
  ## Interrupted save or close
79
144
 
80
145
  After restoring profile storage, inspect the selected session and target with
@@ -117,8 +182,8 @@ their exception strings or an unchanged program snapshot. File/Python scripts re
117
182
  existing conservative recovery semantics.
118
183
 
119
184
  An unknown or partial effect retains its request intent, receipts and native project. Open the
120
- same tuple to reconcile supported outcomes. A committed merge is verified against its recorded
121
- server version and complete saved buffers through independent read authority; it is never
185
+ same tuple to reconcile supported outcomes. A committed merge is recognised by its unique request
186
+ marker at the expected version in the repository history, read with read-only authority; it is never
122
187
  checked in again merely because its response was lost. Until verification succeeds, publication
123
188
  for this shared target is blocked across sessions. Saved private work remains retained.
124
189