@codua/codeoutline-win32-x64 0.1.4 → 0.1.8

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.
@@ -0,0 +1,221 @@
1
+ -- The shared background HTTP service: one per user, started at login and by
2
+ -- installation. It runs the newest installed version and restarts itself into
3
+ -- an update, so MCP clients connect to one URL and nothing else stays running.
4
+ local u = require('xutils')
5
+ local M = {}
6
+ M.PORT = 19876
7
+ local windows = package.config:sub(1, 1) == '\\'
8
+ local LABEL = 'io.github.1dao.codeoutline'
9
+
10
+ local function home() return (os.getenv('USERPROFILE') or os.getenv('HOME') or '.'):gsub('\\', '/') end
11
+ function M.state_dir() return home() .. '/.codeoutline' end
12
+ function M.logs_dir() return M.state_dir() .. '/logs' end
13
+ -- Created to ask the service on that port to exit (uninstall, reinstall).
14
+ function M.stop_file(port) return M.state_dir() .. '/service-' .. port .. '.stop' end
15
+
16
+ local function read(path)
17
+ local f = io.open(path, 'rb'); if not f then return nil end
18
+ local data = f:read('a'); f:close(); return data
19
+ end
20
+ local function write(path, data)
21
+ assert(u.mkdir_p(assert(path:match('^(.*)/[^/]+$'))))
22
+ local f = assert(io.open(path, 'wb'))
23
+ assert(f:write(data)); assert(f:close())
24
+ end
25
+ local function same_path(a, b)
26
+ local function norm(p) p = p:gsub('\\', '/'):gsub('/+$', ''); return windows and p:lower() or p end
27
+ return norm(a) == norm(b)
28
+ end
29
+ local function sequence(root)
30
+ local info = u.json_unpack(read(root .. '/build-info.json') or '')
31
+ return type(info) == 'table' and tonumber(info.updateSequence) or nil
32
+ end
33
+
34
+ -- Files root of the newest verified version: an installed update, or install
35
+ -- itself when it is newer (an npm upgrade) or nothing is installed. A source
36
+ -- checkout (no build-info.json) runs itself.
37
+ function M.current_root(install)
38
+ local own = sequence(install)
39
+ if not own then return install end
40
+ local ok, current = pcall(function()
41
+ return require('xupgate.client').open(require('codeoutline.updater').config()).current()
42
+ end)
43
+ if ok and current and current.sequence >= own then return current.root end
44
+ return install
45
+ end
46
+ function M.is_current(install) return same_path(M.current_root(install), install) end
47
+
48
+ -- argv of the service run from root. Paths reach a shell, the registry or a
49
+ -- unit file, so characters that would need escaping there are refused.
50
+ local function argv(root, port)
51
+ root = root:gsub('\\', '/'):gsub('/+$', '')
52
+ local runtime = root .. (windows and '/bin/xnet.exe' or '/bin/xnet')
53
+ local entry = root .. '/scripts/codeoutline/command.lua'
54
+ local logs = M.logs_dir()
55
+ for _, path in ipairs({ runtime, entry, logs }) do
56
+ assert(not path:find('[%%"\'`$\\!&|<>^;\r\n]'), 'unsupported characters in path: ' .. path)
57
+ end
58
+ if windows then runtime = runtime:gsub('/', '\\') end
59
+ return { runtime, entry, 'LOG_STDERR=0', 'LOG_LEVEL=WARN', 'LOG_DIR=' .. logs, 'daemon', '--port', tostring(port) }
60
+ end
61
+ local function quoted(args)
62
+ local out = {}
63
+ for i, a in ipairs(args) do out[i] = a:find('[%s=]') and '"' .. a .. '"' or a end
64
+ return table.concat(out, ' ')
65
+ end
66
+ local function sh_quote(s) return "'" .. s:gsub("'", "'\\''") .. "'" end
67
+ local function command_ok(command) local ok = os.execute(command); return ok == true or ok == 0 end
68
+
69
+ -- Start the service from root, detached: it must outlive the process that
70
+ -- starts it and must not inherit its stdio. A second instance exits by itself.
71
+ function M.spawn(root, port)
72
+ local args = argv(root, port or M.PORT)
73
+ local logs = M.logs_dir()
74
+ assert(u.mkdir_p(logs))
75
+ if windows then
76
+ -- Arguments travel through the environment, keeping the script ASCII.
77
+ local list = {}
78
+ for i = 2, #args do list[#list + 1] = "('\"'+$env:CO_ARG" .. i .. "+'\"')" end
79
+ local script = "$ProgressPreference='SilentlyContinue';Start-Process -WindowStyle Hidden -WorkingDirectory $env:CO_LOGS "
80
+ .. '-FilePath $env:CO_ARG1 -ArgumentList ' .. table.concat(list, ',')
81
+ local encoded = {}
82
+ for i = 1, #script do encoded[#encoded + 1] = script:sub(i, i) .. '\0' end
83
+ local env = { 'set "CO_LOGS=' .. logs .. '"' }
84
+ for i, a in ipairs(args) do env[#env + 1] = 'set "CO_ARG' .. i .. '=' .. a .. '"' end
85
+ return command_ok(table.concat(env, ' && ') .. ' && powershell -NoProfile -NonInteractive -WindowStyle Hidden -EncodedCommand '
86
+ .. u.base64_encode(table.concat(encoded)) .. ' >NUL 2>&1')
87
+ end
88
+ local parts = {}
89
+ for i, a in ipairs(args) do parts[i] = sh_quote(a) end
90
+ return command_ok('cd ' .. sh_quote(logs) .. ' && S=; command -v setsid >/dev/null 2>&1 && S=setsid; $S nohup '
91
+ .. table.concat(parts, ' ') .. ' </dev/null >/dev/null 2>&1 &')
92
+ end
93
+
94
+ -- Login entries. Each runs the service once per login; it then keeps itself
95
+ -- current, so entries only change when the installation moves.
96
+ local function entry_paths()
97
+ local h = home()
98
+ return {
99
+ darwin = h .. '/Library/LaunchAgents/' .. LABEL .. '.plist',
100
+ systemd = (os.getenv('XDG_CONFIG_HOME') or h .. '/.config') .. '/systemd/user/codeoutline.service',
101
+ }
102
+ end
103
+ local RUN_KEY = [[HKCU\Software\Microsoft\Windows\CurrentVersion\Run]]
104
+
105
+ -- The text of a login entry, by kind.
106
+ local function render(kind, args)
107
+ if kind == 'windows' then
108
+ -- conhost --headless gives the console runtime no window at all.
109
+ return 'conhost.exe --headless ' .. quoted(args)
110
+ elseif kind == 'darwin' then
111
+ local items = {}
112
+ for i, a in ipairs(args) do items[i] = ' <string>' .. a:gsub('&', '&amp;'):gsub('<', '&lt;') .. '</string>' end
113
+ return table.concat({ '<?xml version="1.0" encoding="UTF-8"?>',
114
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
115
+ '<plist version="1.0">', '<dict>', ' <key>Label</key><string>' .. LABEL .. '</string>',
116
+ ' <key>ProgramArguments</key>', ' <array>', table.concat(items, '\n'), ' </array>',
117
+ ' <key>RunAtLoad</key><true/>',
118
+ -- The service restarts itself as a new process; keep that one alive.
119
+ ' <key>AbandonProcessGroup</key><true/>', '</dict>', '</plist>', '' }, '\n')
120
+ elseif kind == 'systemd' then
121
+ return table.concat({ '[Unit]', 'Description=CodeOutline shared MCP service', '', '[Service]', 'Type=simple',
122
+ 'ExecStart=' .. quoted(args),
123
+ -- The service restarts itself as a new process; stopping this unit's
124
+ -- first process must not take the replacement with it.
125
+ 'KillMode=process', '', '[Install]', 'WantedBy=default.target', '' }, '\n')
126
+ end
127
+ error('unknown entry kind ' .. tostring(kind))
128
+ end
129
+
130
+ local function platform()
131
+ if windows then return 'windows' end
132
+ local p = io.popen('uname -s 2>/dev/null')
133
+ local name = p and p:read('a') or ''
134
+ if p then p:close() end
135
+ return name:match('^Darwin') and 'darwin' or 'linux'
136
+ end
137
+
138
+ -- Register the login entry for the service run from root. Returns a description.
139
+ function M.register(root, port)
140
+ port = port or M.PORT
141
+ local args = argv(root, port)
142
+ local kind = platform()
143
+ if kind == 'windows' then
144
+ local value = render('windows', args):gsub('"', '\\"')
145
+ assert(command_ok('reg add "' .. RUN_KEY .. '" /v CodeOutline /t REG_SZ /d "' .. value .. '" /f >NUL 2>&1'),
146
+ 'cannot write ' .. RUN_KEY)
147
+ kind = RUN_KEY .. '\\CodeOutline'
148
+ elseif kind == 'darwin' then
149
+ write(entry_paths().darwin, render('darwin', args))
150
+ kind = entry_paths().darwin
151
+ else
152
+ -- Systems without a systemd user manager (WSL, containers) rarely run
153
+ -- a login session that would start anything else either.
154
+ assert(command_ok('systemctl --user show-environment >/dev/null 2>&1'),
155
+ 'no systemd user manager; start "codeoutline daemon" at login yourself')
156
+ local path = entry_paths().systemd
157
+ write(path, render('systemd', args))
158
+ assert(command_ok('systemctl --user daemon-reload >/dev/null 2>&1 && systemctl --user enable codeoutline.service >/dev/null 2>&1'),
159
+ 'cannot enable ' .. path)
160
+ kind = path
161
+ end
162
+ return kind
163
+ end
164
+
165
+ function M.unregister()
166
+ local removed = {}
167
+ if windows then
168
+ if command_ok('reg query "' .. RUN_KEY .. '" /v CodeOutline >NUL 2>&1') then
169
+ assert(command_ok('reg delete "' .. RUN_KEY .. '" /v CodeOutline /f >NUL 2>&1'), 'cannot remove ' .. RUN_KEY .. '\\CodeOutline')
170
+ removed[#removed + 1] = RUN_KEY .. '\\CodeOutline'
171
+ end
172
+ else
173
+ local paths = entry_paths()
174
+ if u.stat(paths.systemd).exists then
175
+ os.execute('systemctl --user disable codeoutline.service >/dev/null 2>&1')
176
+ os.remove(paths.systemd)
177
+ os.execute('systemctl --user daemon-reload >/dev/null 2>&1')
178
+ removed[#removed + 1] = paths.systemd
179
+ end
180
+ if u.stat(paths.darwin).exists then os.remove(paths.darwin); removed[#removed + 1] = paths.darwin end
181
+ end
182
+ return removed
183
+ end
184
+
185
+ -- Calls done(true) once a connection to the port succeeds, done(false) when
186
+ -- refused. Needs an initialized xnet.
187
+ function M.probe(port, done)
188
+ local connected, finished = false, false
189
+ local function finish(value) if not finished then finished = true; done(value) end end
190
+ local conn = xnet.connect('127.0.0.1', port, {
191
+ on_connect = function(c) connected = true; c:close('probe') end,
192
+ on_packet = function(_, data) return #data end,
193
+ on_close = function() finish(connected) end,
194
+ })
195
+ if not conn then xtimer.add(1, function() finish(false) end, 1) end
196
+ end
197
+
198
+ -- Poll the port until it is listening (want true) or closed (want false), up
199
+ -- to timeout_ms; done(reached). Needs an initialized xnet and xtimer.
200
+ local function poll(port, want, timeout_ms, done)
201
+ local deadline = xtimer.now_ms() + timeout_ms
202
+ local function check()
203
+ M.probe(port, function(listening)
204
+ if listening == want then done(true)
205
+ elseif xtimer.now_ms() >= deadline then done(false)
206
+ else xtimer.add(200, check, 1) end
207
+ end)
208
+ end
209
+ check()
210
+ end
211
+ function M.wait(port, timeout_ms, done) poll(port, true, timeout_ms, done) end
212
+
213
+ -- Ask the service on port to exit and wait up to timeout_ms for the port to
214
+ -- close; done(stopped). Needs an initialized xnet and xtimer.
215
+ function M.stop(port, timeout_ms, done)
216
+ local path = M.stop_file(port)
217
+ write(path, 'stop\n')
218
+ poll(port, false, timeout_ms, function(stopped) os.remove(path); done(stopped) end)
219
+ end
220
+
221
+ return M
@@ -117,9 +117,8 @@ end
117
117
 
118
118
  -- Rank one candidate node for a query term.
119
119
  local function seed_score(G, id, exact)
120
- local n = G.nodes[id]
121
- local s = (KIND_WEIGHT[n.node.kind] or 1) + (exact and 20 or 0)
122
- if vendored(G.files[n.f].path) then s = s - 6 end
120
+ local s = (KIND_WEIGHT[G.nodes[id].kind] or 1) + (exact and 20 or 0)
121
+ if vendored(G.files[G.node_file[id]].path) then s = s - 6 end
123
122
  return s
124
123
  end
125
124
 
@@ -151,11 +150,11 @@ local function find_seeds(G, query)
151
150
  local last = t.text:match('([%w_]+)$')
152
151
  local first = t.text:match('^([%w_]+)')
153
152
  for _, id in ipairs(G.by_name[last] or {}) do
154
- local q = G.nodes[id].node.qualified:gsub('[:]+', '.')
153
+ local q = G.nodes[id].qualified:gsub('[:]+', '.')
155
154
  if q == t.text or q:sub(-(#t.text + 1)) == '.' .. t.text then
156
155
  consider(id, seed_score(G, id, true) + 10)
157
156
  elseif select(2, t.text:gsub('%.', '')) == 1
158
- and G.files[G.nodes[id].f].path:match('([^/]+)%.[^./]+$') == first then
157
+ and G.files[G.node_file[id]].path:match('([^/]+)%.[^./]+$') == first then
159
158
  -- module.func where the module is the file: Lua's `local M`
160
159
  -- tables and Python modules are named by their file
161
160
  consider(id, seed_score(G, id, true) + 8)
@@ -205,15 +204,17 @@ local function path_between(G, a, b, depth)
205
204
  for _ = 1, depth do
206
205
  local next_frontier = {}
207
206
  for _, x in ipairs(frontier) do
208
- for _, e in ipairs(G.out[x] or {}) do
209
- if not prev[e.id] then
210
- prev[e.id] = x
211
- if e.id == b then
207
+ local out = G.out[x] or {}
208
+ for i = 1, #out, graph.EDGE do
209
+ local dst = out[i]
210
+ if not prev[dst] then
211
+ prev[dst] = x
212
+ if dst == b then
212
213
  local path, y = { b }, b
213
214
  while y ~= a do y = prev[y]; table.insert(path, 1, y) end
214
215
  return path
215
216
  end
216
- next_frontier[#next_frontier + 1] = e.id
217
+ next_frontier[#next_frontier + 1] = dst
217
218
  end
218
219
  end
219
220
  end
@@ -246,9 +247,8 @@ end
246
247
  -- Source block for one node, cut to `full` lines (head + tail beyond).
247
248
  -- Classes/structs over the limit collapse to their member outline.
248
249
  local function node_block(G, idx, id, full)
249
- local n = G.nodes[id]
250
- local node = n.node
251
- local lines = file_lines(idx, G.files[n.f].path)
250
+ local node = G.nodes[id]
251
+ local lines = file_lines(idx, G.files[G.node_file[id]].path)
252
252
  local a, b = node.line, math.max(node.end_line, node.line)
253
253
  local out = {}
254
254
  local span = b - a + 1
@@ -264,7 +264,7 @@ local function node_block(G, idx, id, full)
264
264
  -- one line and the later signature covers both
265
265
  local rows, row_lines = {}, {}
266
266
  for _, k in ipairs(kids) do
267
- local kn = G.nodes[k].node
267
+ local kn = G.nodes[k]
268
268
  if not rows[kn.line] then row_lines[#row_lines + 1] = kn.line end
269
269
  rows[kn.line] = kn.sig or kn.name
270
270
  end
@@ -282,8 +282,8 @@ local function node_block(G, idx, id, full)
282
282
  end
283
283
 
284
284
  local function label(G, id)
285
- local n = G.nodes[id]
286
- return string.format('%s %s (%s)', n.node.kind, n.node.qualified, graph.where(G, id))
285
+ local node = G.nodes[id]
286
+ return string.format('%s %s (%s)', node.kind, node.qualified, graph.where(G, id))
287
287
  end
288
288
 
289
289
  -- Run a query. Returns the text and a table with what was selected.
@@ -299,12 +299,12 @@ function M.run(G, idx, query, opts)
299
299
  -- among the matches (the definition's source is what the caller wants).
300
300
  local defined = {}
301
301
  for _, c in ipairs(ranked) do
302
- local node = G.nodes[c.id].node
302
+ local node = G.nodes[c.id]
303
303
  if node.kind ~= 'prototype' and not node.decl then defined[node.name] = true end
304
304
  end
305
305
  local seeds, per_name = {}, {}
306
306
  for _, c in ipairs(ranked) do
307
- local node = G.nodes[c.id].node
307
+ local node = G.nodes[c.id]
308
308
  local name = node.name
309
309
  if not ((node.kind == 'prototype' or node.decl) and defined[name]) then
310
310
  per_name[name] = (per_name[name] or 0) + 1
@@ -323,7 +323,7 @@ function M.run(G, idx, query, opts)
323
323
  if p then
324
324
  local names = {}
325
325
  for _, id in ipairs(p) do
326
- names[#names + 1] = G.nodes[id].node.name
326
+ names[#names + 1] = G.nodes[id].name
327
327
  if not is_seed[id] and not on_spine[id] then
328
328
  on_spine[id] = true
329
329
  spine[#spine + 1] = id
@@ -348,8 +348,8 @@ function M.run(G, idx, query, opts)
348
348
 
349
349
  -- Section 1: summary + flows.
350
350
  local nfiles = {}
351
- for _, id in ipairs(seeds) do nfiles[G.nodes[id].f] = true end
352
- for _, id in ipairs(spine) do nfiles[G.nodes[id].f] = true end
351
+ for _, id in ipairs(seeds) do nfiles[G.node_file[id]] = true end
352
+ for _, id in ipairs(spine) do nfiles[G.node_file[id]] = true end
353
353
  local nf = 0
354
354
  for _ in pairs(nfiles) do nf = nf + 1 end
355
355
  emit(string.format('Matched %d symbols in %d files, %d more on call paths between them; short ones bring their callees. Source below is verbatim with line numbers; treat it as already Read.',
@@ -369,16 +369,17 @@ function M.run(G, idx, query, opts)
369
369
  local in_order = {}
370
370
  for _, item in ipairs(order) do in_order[item.id] = true end
371
371
  for _, id in ipairs(seeds) do
372
- local node = G.nodes[id].node
372
+ local node = G.nodes[id]
373
373
  if node.end_line - node.line < M.CONTEXT_SEED_LINES then
374
374
  local added = 0
375
- for _, e in ipairs(G.out[id] or {}) do
375
+ local out = G.out[id] or {}
376
+ for i = 1, #out, graph.EDGE do
376
377
  if added >= M.CONTEXT_PER_SEED then break end
377
- local callee = G.nodes[e.id]
378
- local k = callee.node.kind
379
- if not in_order[e.id] and callee.f == G.nodes[id].f and (k == 'function' or k == 'method') then
380
- in_order[e.id] = true
381
- order[#order + 1] = { id = e.id, full = M.SPINE_FULL_LINES }
378
+ local dst = out[i]
379
+ local k = G.nodes[dst].kind
380
+ if not in_order[dst] and G.node_file[dst] == G.node_file[id] and (k == 'function' or k == 'method') then
381
+ in_order[dst] = true
382
+ order[#order + 1] = { id = dst, full = M.SPINE_FULL_LINES }
382
383
  added = added + 1
383
384
  end
384
385
  end
@@ -386,7 +387,7 @@ function M.run(G, idx, query, opts)
386
387
  end
387
388
  local by_file, pointers = {}, {}
388
389
  for _, item in ipairs(order) do
389
- local f = G.nodes[item.id].f
390
+ local f = G.node_file[item.id]
390
391
  if not by_file[f] then by_file[f] = {}; file_order[#file_order + 1] = f end
391
392
  table.insert(by_file[f], item)
392
393
  end
@@ -401,10 +402,10 @@ function M.run(G, idx, query, opts)
401
402
  -- producing any output. Unrelated project files remain speculative.
402
403
  local selected, changed = {}, false
403
404
  for _, f in ipairs(file_order) do selected[f] = true end
404
- for _, c in ipairs(ranked) do selected[G.nodes[c.id].f] = true end
405
+ for _, c in ipairs(ranked) do selected[G.node_file[c.id]] = true end
405
406
  for _, id in ipairs(seeds) do
406
407
  for _, edges in ipairs({ G.inn[id] or {}, G.out[id] or {} }) do
407
- for _, e in ipairs(edges) do selected[G.nodes[e.id].f] = true end
408
+ for i = 1, #edges, graph.EDGE do selected[G.node_file[edges[i]]] = true end
408
409
  end
409
410
  end
410
411
  for f in pairs(selected) do
@@ -418,7 +419,7 @@ function M.run(G, idx, query, opts)
418
419
  local rec = G.files[f]
419
420
  local header = '\n## ' .. rec.path
420
421
  local items = by_file[f]
421
- table.sort(items, function(a, b) return G.nodes[a.id].node.line < G.nodes[b.id].node.line end)
422
+ table.sort(items, function(a, b) return G.nodes[a.id].line < G.nodes[b.id].line end)
422
423
  local wrote_header = false
423
424
  if items.outline then
424
425
  local ol = {}
@@ -452,21 +453,24 @@ function M.run(G, idx, query, opts)
452
453
  for _, id in ipairs(seeds) do
453
454
  local callers, callees = {}, {}
454
455
  local seen_in, seen_out = {}, {}
455
- for _, e in ipairs(G.inn[id] or {}) do
456
- if not seen_in[e.id] and #callers < M.LIST_CAP then
457
- seen_in[e.id] = true
458
- callers[#callers + 1] = string.format('%s (%s:%d)', G.nodes[e.id].node.name, G.files[G.nodes[e.id].f].path, e.line)
456
+ local inn, out = G.inn[id] or {}, G.out[id] or {}
457
+ for i = 1, #inn, graph.EDGE do
458
+ local src = inn[i]
459
+ if not seen_in[src] and #callers < M.LIST_CAP then
460
+ seen_in[src] = true
461
+ callers[#callers + 1] = string.format('%s (%s:%d)', G.nodes[src].name, G.files[G.node_file[src]].path, inn[i + 1])
459
462
  end
460
463
  end
461
- for _, e in ipairs(G.out[id] or {}) do
462
- if not seen_out[e.id] and #callees < M.LIST_CAP then
463
- seen_out[e.id] = true
464
- callees[#callees + 1] = G.nodes[e.id].node.name .. ' (' .. graph.where(G, e.id) .. ')'
464
+ for i = 1, #out, graph.EDGE do
465
+ local dst = out[i]
466
+ if not seen_out[dst] and #callees < M.LIST_CAP then
467
+ seen_out[dst] = true
468
+ callees[#callees + 1] = G.nodes[dst].name .. ' (' .. graph.where(G, dst) .. ')'
465
469
  end
466
470
  end
467
471
  if #callers > 0 or #callees > 0 then
468
- local nsites = G.inn[id] and #G.inn[id] or 0
469
- rel[#rel + 1] = string.format('%s:\n called by%s: %s\n calls: %s', G.nodes[id].node.qualified,
472
+ local nsites = math.floor(#inn / graph.EDGE)
473
+ rel[#rel + 1] = string.format('%s:\n called by%s: %s\n calls: %s', G.nodes[id].qualified,
470
474
  nsites > #callers and string.format(' (%d call sites)', nsites) or '',
471
475
  #callers > 0 and table.concat(callers, ', ') or '-',
472
476
  #callees > 0 and table.concat(callees, ', ') or '-')