@nessielabs/daemon 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -7,7 +7,7 @@ const program = new Command();
7
7
  program
8
8
  .name("nessie-daemon")
9
9
  .description("Headless Nessie ingestion daemon for Linux agent machines.")
10
- .version("0.2.1");
10
+ .version("0.2.2");
11
11
  program
12
12
  .command("setup")
13
13
  .description("Authenticate, select local sources, and optionally install the user systemd service.")
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { mkdir, readFile, writeFile } from "node:fs/promises";
3
3
  import { hostname } from "node:os";
4
4
  import { dirname } from "node:path";
5
+ import { PARSER_VERSION } from "../parser/types.js";
5
6
  import { getDaemonPaths } from "./paths.js";
6
7
  export function createConfig(input) {
7
8
  const deviceId = input.deviceId ?? randomUUID();
@@ -22,6 +23,8 @@ export function createInitialState() {
22
23
  return {
23
24
  files: {},
24
25
  pushedSourceRootIds: [],
26
+ pushedSessions: {},
27
+ parserVersion: PARSER_VERSION,
25
28
  lastSyncAt: null,
26
29
  };
27
30
  }
@@ -38,6 +41,10 @@ export async function readState(paths = getDaemonPaths()) {
38
41
  return {
39
42
  files: parsed.files ?? {},
40
43
  pushedSourceRootIds: parsed.pushedSourceRootIds ?? [],
44
+ pushedSessions: parsed.pushedSessions ?? {},
45
+ // State written before parser versioning existed predates every
46
+ // versioned parser change, so it always needs the backfill pass.
47
+ parserVersion: parsed.parserVersion ?? 0,
41
48
  lastSyncAt: parsed.lastSyncAt ?? null,
42
49
  };
43
50
  }
@@ -0,0 +1,215 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, isAbsolute, join, resolve } from "node:path";
4
+ /** Directory levels to walk up looking for `.git` before giving up. */
5
+ const MAX_PARENT_TRAVERSAL = 64;
6
+ /**
7
+ * Resolves the git repository identity for a working directory by reading
8
+ * `.git` metadata from disk, without invoking the `git` binary.
9
+ *
10
+ * Resolution is best-effort by design: paths that are not inside a git
11
+ * repository, repositories without remotes, and repositories deleted since
12
+ * the session simply resolve to null.
13
+ */
14
+ export class GitRepoResolver {
15
+ /**
16
+ * Memoized results per workspace path: conversations in the same directory
17
+ * repeat heavily within one sync run.
18
+ */
19
+ cache = new Map();
20
+ resolve(workspacePath) {
21
+ const standardized = resolve(expandTilde(workspacePath));
22
+ const cached = this.cache.get(standardized);
23
+ if (cached !== undefined)
24
+ return cached;
25
+ const resolved = resolveUncached(standardized);
26
+ this.cache.set(standardized, resolved);
27
+ return resolved;
28
+ }
29
+ }
30
+ function expandTilde(path) {
31
+ if (path === "~")
32
+ return homedir();
33
+ if (path.startsWith("~/"))
34
+ return join(homedir(), path.slice(2));
35
+ return path;
36
+ }
37
+ function resolveUncached(workspacePath) {
38
+ let directory = workspacePath;
39
+ for (let level = 0; level < MAX_PARENT_TRAVERSAL; level += 1) {
40
+ const configPath = gitConfigPath(join(directory, ".git"));
41
+ if (configPath) {
42
+ const config = readTextFile(configPath);
43
+ const remoteUrl = config !== null ? remoteUrlFromGitConfig(config) : null;
44
+ if (remoteUrl) {
45
+ return { remoteUrl, repoKey: normalizedRepoKey(remoteUrl) };
46
+ }
47
+ // A repo without a remote keeps the walk going so a nested remoteless
48
+ // checkout attributes to its enclosing repo. Matches NessieCore's
49
+ // GitRepoResolver.resolveUncached, the source of truth for repo
50
+ // identity; both implementations must group conversations identically.
51
+ }
52
+ const parent = dirname(directory);
53
+ if (parent === directory)
54
+ return null;
55
+ directory = parent;
56
+ }
57
+ return null;
58
+ }
59
+ /**
60
+ * Locate the `config` file for a `.git` entry, which is a directory for
61
+ * normal checkouts and a `gitdir:` pointer file for worktrees and submodules.
62
+ */
63
+ function gitConfigPath(gitEntry) {
64
+ const stats = statSync(gitEntry, { throwIfNoEntry: false });
65
+ if (!stats)
66
+ return null;
67
+ if (stats.isDirectory()) {
68
+ return existingFile(join(gitEntry, "config"));
69
+ }
70
+ const pointer = readTextFile(gitEntry);
71
+ const gitDir = pointer !== null ? gitDirPath(pointer) : null;
72
+ if (!gitDir)
73
+ return null;
74
+ const resolvedGitDir = absolutePath(gitDir, dirname(gitEntry));
75
+ // Worktree gitdirs keep shared state (including `config`) in the main
76
+ // repository's git directory, referenced by a `commondir` file.
77
+ const commonDir = readTextFile(join(resolvedGitDir, "commondir"))?.trim();
78
+ if (commonDir) {
79
+ return existingFile(join(absolutePath(commonDir, resolvedGitDir), "config"));
80
+ }
81
+ return existingFile(join(resolvedGitDir, "config"));
82
+ }
83
+ function existingFile(path) {
84
+ return statSync(path, { throwIfNoEntry: false })?.isFile() ? path : null;
85
+ }
86
+ function readTextFile(path) {
87
+ try {
88
+ return readFileSync(path, "utf8");
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ }
94
+ export function gitDirPath(pointerContents) {
95
+ for (const line of pointerContents.split(/\r?\n/)) {
96
+ const trimmed = line.trim();
97
+ if (!trimmed.startsWith("gitdir:"))
98
+ continue;
99
+ const path = trimmed.slice("gitdir:".length).trim();
100
+ return path.length > 0 ? path : null;
101
+ }
102
+ return null;
103
+ }
104
+ function absolutePath(path, base) {
105
+ return isAbsolute(path) ? resolve(path) : resolve(base, path);
106
+ }
107
+ /**
108
+ * Extract a remote URL from raw `.git/config` contents, preferring `origin`
109
+ * and falling back to the first remote with a URL.
110
+ */
111
+ export function remoteUrlFromGitConfig(contents) {
112
+ let currentRemote = null;
113
+ let originUrl = null;
114
+ let firstUrl = null;
115
+ for (const line of contents.split(/\r?\n/)) {
116
+ const trimmed = line.trim();
117
+ if (trimmed.startsWith("[")) {
118
+ currentRemote = remoteNameFromSectionHeader(trimmed);
119
+ continue;
120
+ }
121
+ if (!currentRemote)
122
+ continue;
123
+ const url = configValue(trimmed, "url");
124
+ if (!url)
125
+ continue;
126
+ if (currentRemote === "origin" && originUrl === null) {
127
+ originUrl = url;
128
+ }
129
+ if (firstUrl === null) {
130
+ firstUrl = url;
131
+ }
132
+ }
133
+ return originUrl ?? firstUrl;
134
+ }
135
+ function remoteNameFromSectionHeader(header) {
136
+ // [remote "origin"]
137
+ if (!header.startsWith("[remote "))
138
+ return null;
139
+ const openQuote = header.indexOf('"');
140
+ const closeQuote = header.lastIndexOf('"');
141
+ if (openQuote === -1 || closeQuote <= openQuote)
142
+ return null;
143
+ return header.slice(openQuote + 1, closeQuote);
144
+ }
145
+ function configValue(line, key) {
146
+ const equals = line.indexOf("=");
147
+ if (equals === -1)
148
+ return null;
149
+ if (line.slice(0, equals).trim() !== key)
150
+ return null;
151
+ const value = line.slice(equals + 1).trim();
152
+ return value.length > 0 ? value : null;
153
+ }
154
+ /**
155
+ * Normalize a configured remote URL to a stable `host/path` identity so the
156
+ * same repository matches across protocols, credentials, machines, and
157
+ * clones: `git@github.com:Org/Repo.git` and `https://github.com/org/repo`
158
+ * both become `github.com/org/repo`.
159
+ */
160
+ export function normalizedRepoKey(remoteUrl) {
161
+ let rest = remoteUrl.trim();
162
+ if (rest.length === 0)
163
+ return null;
164
+ const schemeEnd = rest.indexOf("://");
165
+ if (schemeEnd !== -1) {
166
+ const scheme = rest.slice(0, schemeEnd).toLowerCase();
167
+ // Local remotes have no cross-machine identity.
168
+ if (scheme === "file")
169
+ return null;
170
+ rest = rest.slice(schemeEnd + "://".length);
171
+ }
172
+ else if (rest.includes(":") && (rest.includes("@") || !rest.startsWith("/"))) {
173
+ // scp-like syntax: [user@]host:path
174
+ const colon = rest.indexOf(":");
175
+ const hostPart = rest.slice(0, colon);
176
+ const path = rest.slice(colon + 1);
177
+ if (hostPart.length === 0 || path.length === 0 || hostPart.includes("/"))
178
+ return null;
179
+ rest = `${hostPart}/${path}`;
180
+ }
181
+ else {
182
+ // Bare filesystem path remote.
183
+ return null;
184
+ }
185
+ // Strip userinfo.
186
+ const lastAt = rest.lastIndexOf("@");
187
+ const firstSlash = rest.indexOf("/");
188
+ if (lastAt !== -1 && firstSlash !== -1 && lastAt < firstSlash) {
189
+ rest = rest.slice(lastAt + 1);
190
+ }
191
+ else if (rest.includes("@") && !rest.includes("/")) {
192
+ rest = rest.slice(rest.indexOf("@") + 1);
193
+ }
194
+ const components = rest.split("/").filter((component) => component.length > 0);
195
+ if (components.length < 2)
196
+ return null;
197
+ // Lowercase the host and drop any port; path case is preserved except for
198
+ // trailing `.git`.
199
+ let host = components[0].toLowerCase();
200
+ const portColon = host.indexOf(":");
201
+ if (portColon !== -1) {
202
+ host = host.slice(0, portColon);
203
+ }
204
+ if (!host.includes(".") && host !== "localhost")
205
+ return null;
206
+ components[0] = host;
207
+ let last = components[components.length - 1];
208
+ if (last.toLowerCase().endsWith(".git")) {
209
+ last = last.slice(0, -4);
210
+ }
211
+ if (last.length === 0)
212
+ return null;
213
+ components[components.length - 1] = last;
214
+ return components.join("/");
215
+ }
@@ -8,10 +8,15 @@ export async function parseClaudeCodeSession(path) {
8
8
  let title = null;
9
9
  let createdAt = null;
10
10
  let updatedAt = null;
11
+ let cwd = null;
11
12
  for (const value of records) {
12
13
  const record = asRecord(value);
13
14
  if (!record)
14
15
  continue;
16
+ // Every transcript line stamps cwd, including sidechain lines, so capture
17
+ // it before any filtering. The path-encoded project directory name is
18
+ // lossy (dashes vs. path separators), so this is the only reliable source.
19
+ cwd ??= stringValue(record.cwd);
15
20
  if (record.isSidechain === true)
16
21
  continue;
17
22
  sessionId = stringValue(record.sessionId) ?? stringValue(record.session_id) ?? sessionId;
@@ -40,6 +45,7 @@ export async function parseClaudeCodeSession(path) {
40
45
  title: title ?? "Claude Code conversation",
41
46
  createdAt: createdAt ?? now,
42
47
  updatedAt: updatedAt ?? createdAt ?? now,
48
+ cwd,
43
49
  messages,
44
50
  };
45
51
  }
@@ -8,6 +8,7 @@ export async function parseCodexSession(path) {
8
8
  let title = null;
9
9
  let createdAt = null;
10
10
  let updatedAt = null;
11
+ let cwd = null;
11
12
  for (const value of records) {
12
13
  const record = asRecord(value);
13
14
  if (!record)
@@ -21,6 +22,8 @@ export async function parseCodexSession(path) {
21
22
  if (type === "session_meta") {
22
23
  sessionId = stringValue(record.id) ?? stringValue(record.session_id) ?? sessionId;
23
24
  title = redactTitle(stringValue(record.title)) ?? title;
25
+ const meta = asRecord(record.payload) ?? record;
26
+ cwd ??= stringValue(meta.cwd);
24
27
  continue;
25
28
  }
26
29
  if (type !== "event_msg")
@@ -45,6 +48,7 @@ export async function parseCodexSession(path) {
45
48
  title: title ?? "Codex conversation",
46
49
  createdAt: createdAt ?? now,
47
50
  updatedAt: updatedAt ?? createdAt ?? now,
51
+ cwd,
48
52
  messages,
49
53
  };
50
54
  }
@@ -1 +1,9 @@
1
- export {};
1
+ /**
2
+ * Version of the daemon's transcript parsing + enrichment semantics. Bumping
3
+ * it makes the next sync reparse every session file and re-push conversation
4
+ * headers as field-masked merges, so previously synced conversations pick up
5
+ * newly extracted metadata. Messages are append-only and are never re-pushed.
6
+ *
7
+ * 1: workspace/repo metadata (cwd, git remote, repo key) on conversations.
8
+ */
9
+ export const PARSER_VERSION = 1;
@@ -2,6 +2,8 @@ export const secretReplacement = "[REDACTED]";
2
2
  const literalIndicators = [
3
3
  "ghp_",
4
4
  "github_pat_",
5
+ "napi_",
6
+ "npg_",
5
7
  "sk-",
6
8
  ];
7
9
  const caseInsensitiveIndicators = [
@@ -13,22 +15,42 @@ const caseInsensitiveIndicators = [
13
15
  "token=",
14
16
  "key=",
15
17
  "api_key=",
18
+ "connection_string=",
19
+ "database_url=",
20
+ "db_url=",
16
21
  "password=",
22
+ "postgres_url=",
23
+ "postgresql_url=",
24
+ "postgres://",
25
+ "postgresql://",
17
26
  "secret=",
27
+ "supabase",
18
28
  ];
19
29
  const fullReplacementPatterns = [
20
30
  /\bghp_[A-Za-z0-9_]{20,}\b/g,
21
31
  /\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,
32
+ /\bnapi_[A-Za-z0-9_-]{16,}\b/g,
33
+ /\bnpg_[A-Za-z0-9_-]{16,}\b/g,
22
34
  /\bsk-[A-Za-z0-9_-]{16,}\b/g,
35
+ /\bsb_(?:publishable|secret)_[A-Za-z0-9_-]{16,}\b/g,
36
+ /\bsbp_[A-Za-z0-9_-]{16,}\b/g,
37
+ /\bpostgres(?:ql)?:\/\/[^\s'"`<>]+/gi,
23
38
  /\bBearer\s+[A-Za-z0-9._~+/=-]{8,}\b/gi,
24
39
  /-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9 ]+ )?PRIVATE KEY-----/gi,
25
40
  ];
26
- const assignmentPattern = /\b([A-Za-z0-9_]*(?:token|api_key|password|secret)|key)\s*=\s*([^\s&;,'"`]+)/gi;
41
+ const uuidPattern = /\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b/gi;
42
+ const sensitiveKeyNamePattern = String.raw `[A-Za-z0-9_]*(?:token|api[_-]?key|apikey|password|secret|[_-]key|connection[_-]?string|database[_-]?url|db[_-]?url|postgres(?:ql)?[_-]?url)|key`;
43
+ const unquotedAssignmentValuePattern = "[^\\s&;,'\"`}\\[\\]]+";
44
+ const assignmentPattern = new RegExp(String.raw `\b(${sensitiveKeyNamePattern})\b(\s*=\s*)(["']?)(${unquotedAssignmentValuePattern})\3?`, "gi");
45
+ const quotedAssignmentPattern = new RegExp(String.raw `(["'])(${sensitiveKeyNamePattern})\1(\s*:\s*)(["'])([^"']+)\4`, "gi");
27
46
  export function redactSecrets(text) {
28
- if (!mightContainSecret(text))
29
- return text;
30
- const withoutWholeSecrets = fullReplacementPatterns.reduce((result, pattern) => result.replace(pattern, secretReplacement), text);
31
- return withoutWholeSecrets.replace(assignmentPattern, (_match, key) => `${key}=${secretReplacement}`);
47
+ const withoutUuids = text.replace(uuidPattern, secretReplacement);
48
+ if (!mightContainSecret(withoutUuids))
49
+ return withoutUuids;
50
+ const withoutWholeSecrets = fullReplacementPatterns.reduce((result, pattern) => result.replace(pattern, secretReplacement), withoutUuids);
51
+ return withoutWholeSecrets
52
+ .replace(quotedAssignmentPattern, (_match, keyQuote, key, separator, valueQuote) => `${keyQuote}${key}${keyQuote}${separator}${valueQuote}${secretReplacement}${valueQuote}`)
53
+ .replace(assignmentPattern, (_match, key, separator, valueQuote) => `${key}${separator}${valueQuote}${secretReplacement}${valueQuote}`);
32
54
  }
33
55
  export function mightContainSecret(text) {
34
56
  if (literalIndicators.some((indicator) => text.includes(indicator)))
package/dist/sync/loop.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { setTimeout as sleep } from "node:timers/promises";
2
2
  import { AuthRefreshError } from "../auth/tokens.js";
3
3
  import { readConfig, readState, writeState } from "../config/store.js";
4
+ import { GitRepoResolver } from "../git/repoResolver.js";
5
+ import { PARSER_VERSION } from "../parser/types.js";
4
6
  import { runPreflightV3, pushSyncPayload } from "./client.js";
5
7
  import { mapSessionsToPushItems } from "./map.js";
6
8
  import { scanSelectedSources } from "./scan.js";
@@ -8,19 +10,34 @@ export async function runSyncOnce() {
8
10
  let config = await readConfig();
9
11
  const state = await readState();
10
12
  config = await runPreflightV3(config);
11
- const scan = await scanSelectedSources(config.selectedSources, state);
13
+ // A parser version bump reparses everything once and re-pushes conversation
14
+ // headers as field-masked merges so existing conversations pick up newly
15
+ // extracted metadata. The state only records the new version after a
16
+ // successful push, so a failed backfill retries on the next run.
17
+ const backfillParserChanges = state.parserVersion < PARSER_VERSION;
18
+ const scan = await scanSelectedSources(config.selectedSources, state, {
19
+ forceReparse: backfillParserChanges,
20
+ });
21
+ const repoResolver = new GitRepoResolver();
12
22
  const nodes = [];
13
23
  const edges = [];
14
24
  const previouslyPushedRoots = new Set(state.pushedSourceRootIds);
15
25
  const pushedSourceRootIds = new Set(previouslyPushedRoots);
26
+ const pushedSessions = { ...state.pushedSessions };
16
27
  for (const source of config.selectedSources) {
17
28
  const sessions = scan.sessionsBySourceId.get(source.localId) ?? [];
18
29
  const includeRoot = !previouslyPushedRoots.has(source.localId);
19
- const mapped = mapSessionsToPushItems(source, sessions, { includeRoot });
30
+ const mapped = mapSessionsToPushItems(source, sessions, {
31
+ includeRoot,
32
+ pushedSessions: state.pushedSessions,
33
+ repushHeaders: backfillParserChanges,
34
+ resolveRepo: (workspacePath) => repoResolver.resolve(workspacePath),
35
+ });
20
36
  nodes.push(...mapped.nodes);
21
37
  edges.push(...mapped.edges);
22
38
  if (includeRoot)
23
39
  pushedSourceRootIds.add(source.localId);
40
+ Object.assign(pushedSessions, mapped.pushedSessions);
24
41
  }
25
42
  if (nodes.length > 0 || edges.length > 0) {
26
43
  config = await pushSyncPayload(config, { nodes, edges });
@@ -28,6 +45,8 @@ export async function runSyncOnce() {
28
45
  await writeState({
29
46
  ...scan.nextState,
30
47
  pushedSourceRootIds: [...pushedSourceRootIds].sort(),
48
+ pushedSessions,
49
+ parserVersion: PARSER_VERSION,
31
50
  lastSyncAt: new Date().toISOString(),
32
51
  });
33
52
  return { nodes: nodes.length, edges: edges.length };
package/dist/sync/map.js CHANGED
@@ -1,28 +1,52 @@
1
1
  import { redactSecrets } from "../redact/secrets.js";
2
2
  import { contentHash, stableUuidFromString } from "./ids.js";
3
3
  export function mapSessionsToPushItems(source, sessions, options = { includeRoot: true }) {
4
+ const pushedSessions = options.pushedSessions ?? {};
5
+ const nextPushedSessions = {};
4
6
  const nodes = options.includeRoot ? [mapRootNode(source)] : [];
5
7
  const edges = [];
6
8
  for (const session of sessions) {
7
9
  const conversationId = stableUuidFromString(`${source.localId}:session:${session.id}`);
8
- nodes.push({
9
- node: {
10
- id: conversationId,
11
- integrationId: source.localId,
12
- sourceId: session.sourceId,
13
- name: redactSecrets(session.title),
14
- kind: session.sourceKind === "codex" ? "codex_chat" : "claude_code_chat",
15
- originalCreatedAt: session.createdAt,
16
- originalUpdatedAt: session.updatedAt,
17
- },
18
- baseCloudUpdatedAt: null,
19
- slices: [],
20
- aiChatMessage: null,
21
- nessieChatMessage: null,
22
- });
23
- edges.push(mapEdge(source.localId, conversationId, "source_of", 0));
10
+ const stateKey = sessionStateKey(source, session);
11
+ const sessionCursor = pushedSessions[stateKey] ?? {
12
+ conversationPushed: false,
13
+ pushedMessageCount: 0,
14
+ };
15
+ if (!sessionCursor.conversationPushed || options.repushHeaders === true) {
16
+ const repoInfo = session.cwd !== null ? options.resolveRepo?.(session.cwd) ?? null : null;
17
+ // Headers always push as a field-masked merge: new conversations insert
18
+ // normally, and re-pushed headers only touch the workspace metadata
19
+ // columns, never fields other clients own (name, labels, deletion).
20
+ nodes.push({
21
+ node: {
22
+ id: conversationId,
23
+ integrationId: source.localId,
24
+ sourceId: session.sourceId,
25
+ name: redactSecrets(session.title),
26
+ kind: session.sourceKind === "codex" ? "codex_chat" : "claude_code_chat",
27
+ workspacePath: session.cwd,
28
+ repoRemoteUrl: repoInfo?.remoteUrl ?? null,
29
+ repoKey: repoInfo?.repoKey ?? null,
30
+ originalCreatedAt: session.createdAt,
31
+ originalUpdatedAt: session.updatedAt,
32
+ },
33
+ baseCloudUpdatedAt: null,
34
+ slices: [],
35
+ aiChatMessage: null,
36
+ nessieChatMessage: null,
37
+ mergeFields: ["workspacePath", "repoRemoteUrl", "repoKey"],
38
+ });
39
+ }
40
+ if (!sessionCursor.conversationPushed) {
41
+ edges.push(mapEdge(source.localId, conversationId, "source_of", 0));
42
+ }
24
43
  const pushableMessages = session.messages.filter((message) => message.role !== "system");
25
- pushableMessages.forEach((message, index) => {
44
+ nextPushedSessions[stateKey] = {
45
+ conversationPushed: true,
46
+ pushedMessageCount: pushableMessages.length,
47
+ };
48
+ pushableMessages.slice(sessionCursor.pushedMessageCount).forEach((message, offset) => {
49
+ const index = sessionCursor.pushedMessageCount + offset;
26
50
  const messageId = stableUuidFromString(`${conversationId}:message:${index}`);
27
51
  const content = redactSecrets(message.content);
28
52
  const timestamp = message.timestamp ?? session.updatedAt;
@@ -54,7 +78,10 @@ export function mapSessionsToPushItems(source, sessions, options = { includeRoot
54
78
  edges.push(mapEdge(conversationId, messageId, "contains", index));
55
79
  });
56
80
  }
57
- return { nodes, edges };
81
+ return { nodes, edges, pushedSessions: nextPushedSessions };
82
+ }
83
+ export function sessionStateKey(source, session) {
84
+ return `${source.localId}:session:${session.id}`;
58
85
  }
59
86
  function mapRootNode(source) {
60
87
  const now = new Date().toISOString();
@@ -75,9 +102,10 @@ function mapRootNode(source) {
75
102
  };
76
103
  }
77
104
  function mapEdge(fromNodeId, toNodeId, type, sortIndex) {
105
+ const id = stableUuidFromString(`${fromNodeId}:${type}:${toNodeId}`);
78
106
  return {
79
107
  edge: {
80
- id: stableUuidFromString(`${fromNodeId}:${type}:${toNodeId}`),
108
+ id,
81
109
  fromNodeId,
82
110
  toNodeId,
83
111
  type,
package/dist/sync/scan.js CHANGED
@@ -2,10 +2,12 @@ import { readdir, stat } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { parseClaudeCodeSession } from "../parser/claudeCode.js";
4
4
  import { parseCodexSession } from "../parser/codex.js";
5
- export async function scanSelectedSources(sources, state) {
5
+ export async function scanSelectedSources(sources, state, options = {}) {
6
6
  const nextState = {
7
7
  files: { ...state.files },
8
8
  pushedSourceRootIds: [...state.pushedSourceRootIds],
9
+ pushedSessions: { ...state.pushedSessions },
10
+ parserVersion: state.parserVersion,
9
11
  lastSyncAt: state.lastSyncAt,
10
12
  };
11
13
  const sessionsBySourceId = new Map();
@@ -14,7 +16,7 @@ export async function scanSelectedSources(sources, state) {
14
16
  const sessions = [];
15
17
  for (const file of files) {
16
18
  const cursor = await cursorForFile(file);
17
- if (isUnchanged(state.files[file], cursor))
19
+ if (options.forceReparse !== true && isUnchanged(state.files[file], cursor))
18
20
  continue;
19
21
  const session = source.kind === "codex" ? await parseCodexSession(file) : await parseClaudeCodeSession(file);
20
22
  nextState.files[file] = cursor;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nessielabs/daemon",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Headless Linux ingestion daemon for Nessie agent traces.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -18,7 +18,7 @@
18
18
  "node": ">=20"
19
19
  },
20
20
  "scripts": {
21
- "build": "rm -rf dist && tsc -p tsconfig.json",
21
+ "build": "rm -rf dist && tsc -p tsconfig.json && chmod +x dist/cli.js",
22
22
  "check": "tsc -p tsconfig.json --noEmit",
23
23
  "dev": "tsx src/cli.ts",
24
24
  "test": "vitest run"