jg-agent-hq 4.0.1 → 4.0.2

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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 4.0.2
4
+
5
+ - Read Claude sessions whose transcript holds a hidden record written before the record it follows, such as an instructions attachment or a scheduled-task event. The reader rejected the whole session, so HQ couldn't name or show it; it now holds the record back until its parent is indexed.
6
+ - Accept Claude transcript records up to 8 MiB, such as tool results holding images, instead of 1 MiB. Indexing reads up to 16 MiB per batch so the largest record fits, and a page always reads its first record.
7
+ - Re-index every Claude transcript once after the upgrade, so sessions the previous version rejected become readable.
8
+
3
9
  ## 4.0.1
4
10
 
5
11
  - Report an interactive Claude session that waits on a question or permission prompt as waiting. Claude Code lists it as `waiting`, which was recorded as an unknown state and reported as a disappearance.
package/api/README.md CHANGED
@@ -150,7 +150,7 @@ Text chunks contain at most 32,768 UTF-8 bytes and shrink when escaping or metad
150
150
 
151
151
  `HistoryItemSchema` and evidence fragments expose `provenance: { origin, source, nativeInputId, actionId, contentBoundary: 'untrusted', grantsAuthority: false }`. Origins are operator, agent, tool, system or unknown. Native assistant/tool kinds establish only their observed category. A native user role, quoted operator text or an imported message cannot establish an operator. HQ correlates a submitted input only when its exact native message/client identity, thread/turn and complete normalized text hash match the acknowledged action ledger. Programmatic host submissions have source `host-action` and unknown actor. An authenticated browser submission additionally requires the same selected thread and text fingerprint, yielding `authenticated-host-action` and operator provenance. Unverifiable, modified, attachment-expanded or skill-expanded content stays unknown. Provenance remains historical evidence and grants no current approval, execution authority or tool permission; quotations remain inside its untrusted content boundary.
152
152
 
153
- Codex uses its native descending item API with unloaded thread metadata. It never reads Codex transcript files. Claude uses indexed current-chain byte locations, exact UUID lookups and separate bounded seeks per selected kind. Its cold index retains the existing 4 MiB batches and 30-second operation budget; selected evidence reads parse at most 4 MiB of records. Continuation revalidates and rereads one bounded native page to detect content changes rather than caching transcript bodies. Work and memory per read are bounded independently of history growth; reconstructing a large body may reread that source page. No conversation-body cache is maintained.
153
+ Codex uses its native descending item API with unloaded thread metadata. It never reads Codex transcript files. Claude uses indexed current-chain byte locations, exact UUID lookups and separate bounded seeks per selected kind. Its cold index uses 16 MiB batches and a 30-second operation budget; selected evidence reads parse at most 4 MiB of records beyond the first. Continuation revalidates and rereads one bounded native page to detect content changes rather than caching transcript bodies. Work and memory per read are bounded independently of history growth; reconstructing a large body may reread that source page. No conversation-body cache is maintained.
154
154
 
155
155
  ## Native accounts and extensions
156
156
 
@@ -211,15 +211,15 @@ Selected action receipts expose nullable `result: { state, format, text, structu
211
211
 
212
212
  Claude connects on its first read through `claude --print --input-format stream-json --output-format stream-json --verbose`. No user prompt, bare mode, permission bypass or SDK dependency is used. Runtime status reports this adapter as `idle`, `ready` or `unavailable`, with its observed CLI version. An unavailable native lane requires restarting the host after resolving the native problem.
213
213
 
214
- The structured CLI interface has no session-history listing operation. The Claude-owned reader therefore uses direct UUID JSONL files in the native project's directory beneath `CLAUDE_CONFIG_DIR`, or the normal `.claude` directory. CLI and transcript version labels do not gate reads. Required session identity, workspace, parent links, timestamps and message roles are validated, while additive fields and mixed version labels are tolerated. Encoded project keys longer than 200 characters, directory/file links, malformed required fields and records larger than 1 MiB report unavailable. Discovery never recurses into subdirectories, including excluded directories. Unsupported discovered sessions have `historyState: unavailable`; they do not prevent supported sessions from being listed.
214
+ The structured CLI interface has no session-history listing operation. The Claude-owned reader therefore uses direct UUID JSONL files in the native project's directory beneath `CLAUDE_CONFIG_DIR`, or the normal `.claude` directory. CLI and transcript version labels do not gate reads. Required session identity, workspace, parent links, timestamps and message roles are validated, while additive fields and mixed version labels are tolerated. Claude Code can write a hidden record, such as an attachment or a scheduled-task event, a few lines before the record it follows; the reader holds it back until that parent is indexed, and one whose parent the read doesn't reach starts a turn of its own. A message whose parent is unknown is never accepted. Encoded project keys longer than 200 characters, directory/file links, malformed required fields and records larger than 8 MiB report unavailable. Discovery never recurses into subdirectories, including excluded directories. Unsupported discovered sessions have `historyState: unavailable`; they do not prevent supported sessions from being listed.
215
215
 
216
216
  Discovery verifies the workspace recorded inside each transcript before returning its identity or title. A matching native directory name alone is insufficient because punctuation replacement can produce colliding directory keys. Native working directories may be the selected workspace or its subdirectories, including removed subdirectories. The nearest existing path ancestor must resolve inside the workspace without excluded segments; sibling paths and symlink escapes are rejected. Foreign workspaces are omitted. If a file's workspace cannot be established, discovery reports unavailable rather than inventing an empty result.
217
217
 
218
- The existing SQLite worker incrementally records file identity, complete-line offsets, message identities and parent links. It does not save message bodies. File identity includes the current reader projection revision and a native prefix hash, so source changes invalidate the derived projection. Each worker batch inspects at most 128 directory entries and reads at most 4 MiB of new transcript bytes, one file at a time. The adapter continues batches with a host-event-loop yield between them, within a 30-second operation budget. If that budget is reached, the read reports unavailable and subsequent reads continue indexing. At most four incomplete discovery iterators remain open. Shutdown closes them. Discovery continuations use that projection without starting another directory scan; start a fresh first page to refresh discovery. Removed files are discarded from the projection after a complete refresh. No additional cache infrastructure or browser cache is used.
218
+ The existing SQLite worker incrementally records file identity, complete-line offsets, message identities and parent links. It does not save message bodies. File identity includes the current reader projection revision and a native prefix hash, so source changes invalidate the derived projection. Each worker batch inspects at most 128 directory entries and reads at most 16 MiB of new transcript bytes, one file at a time, which fits the largest record. The adapter continues batches with a host-event-loop yield between them, within a 30-second operation budget. If that budget is reached, the read reports unavailable and subsequent reads continue indexing. At most four incomplete discovery iterators remain open. Shutdown closes them. Discovery continuations use that projection without starting another directory scan; start a fresh first page to refresh discovery. Removed files are discarded from the projection after a complete refresh. No additional cache infrastructure or browser cache is used.
219
219
 
220
220
  Current-chain membership and turn starts are indexed as metadata. Ordinary item and turn continuations seek those indexes; they do not walk the full chain per page. A changed branch rebuilds membership before exposing that revision. Repeated native message identities can replace content while retaining their parent; a changed parent for the same identity is an unsupported format.
221
221
 
222
- Selected history reads refresh only that file, retain incomplete tails, and detect truncation or replaced identity. Changed branch/file revisions invalidate item and turn continuations. Only the current parent-linked conversation chain is returned. Text is reread from the native file for the selected page and normalized as plain text. Tool calls show their native name and input; tool results have kind `tool`. Other non-text content has explicit native block labels. An unknown record containing content is returned as an `unsupported` item when its identity and chain are trustworthy; it cannot imply an agent response, idle state or completion. Each selected page reads at most 4 MiB of record bytes and returns at most 4 MiB of serialized item presentation, so a large-text page can contain fewer rows than its requested limit.
222
+ Selected history reads refresh only that file, retain incomplete tails, and detect truncation or replaced identity. Changed branch/file revisions invalidate item and turn continuations. Only the current parent-linked conversation chain is returned. Text is reread from the native file for the selected page and normalized as plain text. Tool calls show their native name and input; tool results have kind `tool`. Other non-text content has explicit native block labels. An unknown record containing content is returned as an `unsupported` item when its identity and chain are trustworthy; it cannot imply an agent response, idle state or completion. Each selected page reads at most 4 MiB of record bytes beyond its first record and returns at most 4 MiB of serialized item presentation, so a large-text page can contain fewer rows than its requested limit.
223
223
 
224
224
  File timestamps and records do not prove that a native process is idle or a turn completed. Claude file-backed thread and turn states are therefore `unknown`, with no invented completion timestamp. Explicit native custom titles are preserved; a missing title remains null. File-backed grouping follows native user records and parent links, including generated user-record markers; it is not an authoritative execution boundary.
225
225
 
@@ -28,6 +28,15 @@ export declare class ClaudeHistoryModel {
28
28
  private __identity;
29
29
  private __refresh;
30
30
  private __inspect;
31
+ /**
32
+ * Indexes one transcript record. Claude Code can write a hidden record, such as an attachment
33
+ * or a scheduled-task event, a few lines before the record it follows; such a record is held
34
+ * back unless `isOrphanAllowed`, and the caller retries it once its parent is indexed.
35
+ * @returns Null once the record is indexed, or the UUID of the parent a held-back record awaits.
36
+ * @throws
37
+ * - JG_AGENT_HQ_CLAUDE_HISTORY_UNAVAILABLE: The Claude history is unavailable
38
+ */
31
39
  private __record;
40
+ private __hasEntry;
32
41
  private __unavailable;
33
42
  }
@@ -8,9 +8,14 @@ import { evidencePosition, buildEvidencePage, EVIDENCE_SOURCE_PAGE_SIZE, } from
8
8
  import { EntryRowSchema, EntrySeekSchema, FileRowSchema, RecordSchema, ApiRequestMetadataSchema, SeekSchema, } from './types.js';
9
9
  import { isClaudeWorkspaceCwd, openTranscript, projectDirectory, toClaudeItem, } from './utilities.js';
10
10
  // identifies the path and record interpretation used by persisted projection entries
11
- const HISTORY_PROJECTION_VERSION = 3;
12
- const MAX_RECORD_BYTES = 1_048_576;
13
- const MAX_REFRESH_BYTES = 4_194_304;
11
+ const HISTORY_PROJECTION_VERSION = 4;
12
+ // one record, such as a tool result holding images, and an indexing read, which fits the largest
13
+ const MAX_RECORD_BYTES = 8_388_608;
14
+ const MAX_REFRESH_BYTES = 16_777_216;
15
+ // the record bytes and serialized items of one page, which stays inside the 8 MiB IPC frame
16
+ const MAX_PAGE_BYTES = 4_194_304;
17
+ // hidden records awaiting a parent later in the file; Claude Code writes them a few lines early
18
+ const MAX_HELD_BACK_RECORDS = 64;
14
19
  const CHAIN = `WITH RECURSIVE current_chain AS (
15
20
  SELECT workspace_root, native_id, uuid, parent_uuid, turn_id, byte_offset, byte_length, created_at, is_visible
16
21
  FROM hq_claude_entry WHERE workspace_root = ? AND native_id = ? AND uuid = ?
@@ -174,7 +179,8 @@ export class ClaudeHistoryModel {
174
179
  let readBytes = 0;
175
180
  let lastOffset = offset;
176
181
  for (const entry of page) {
177
- if (readBytes + entry.byte_length > MAX_REFRESH_BYTES)
182
+ // a page always reads its first record, which can be larger than the page budget
183
+ if (readBytes > 0 && readBytes + entry.byte_length > MAX_PAGE_BYTES)
178
184
  break;
179
185
  readBytes += entry.byte_length;
180
186
  const bytes = Buffer.alloc(entry.byte_length);
@@ -185,7 +191,7 @@ export class ClaudeHistoryModel {
185
191
  this.__unavailable();
186
192
  const item = toClaudeItem(record, entry.turn_id);
187
193
  const itemSize = Buffer.byteLength(JSON.stringify(item));
188
- if (size + itemSize > MAX_REFRESH_BYTES)
194
+ if (size + itemSize > MAX_PAGE_BYTES)
189
195
  break;
190
196
  size += itemSize;
191
197
  lastOffset = entry.byte_offset;
@@ -255,7 +261,7 @@ export class ClaudeHistoryModel {
255
261
  if (this.__identity(fd) !== row.identity || fstatSync(fd).size < row.file_size)
256
262
  this.__unavailable();
257
263
  for (const entry of entries.slice(0, EVIDENCE_SOURCE_PAGE_SIZE)) {
258
- if (readBytes + entry.byte_length > MAX_REFRESH_BYTES)
264
+ if (readBytes > 0 && readBytes + entry.byte_length > MAX_PAGE_BYTES)
259
265
  break;
260
266
  const bytes = Buffer.alloc(entry.byte_length);
261
267
  if (readSync(fd, bytes, 0, bytes.length, entry.byte_offset) !== bytes.length)
@@ -396,6 +402,31 @@ export class ClaudeHistoryModel {
396
402
  let lineStart = position;
397
403
  let tail = Buffer.alloc(0);
398
404
  const chunk = Buffer.alloc(65_536);
405
+ // hidden records whose parent comes later in the file, by location and awaited parent
406
+ const heldBack = [];
407
+ const reread = (offset, length) => {
408
+ const bytes = Buffer.alloc(length);
409
+ if (readSync(fd, bytes, 0, length, offset) !== length)
410
+ this.__unavailable();
411
+ return bytes;
412
+ };
413
+ const isReleasable = ({ parentUuid }) => this.__hasEntry(root, nativeId, parentUuid);
414
+ const indexRecord = (bytes, offset) => {
415
+ const parentUuid = this.__record(root, nativeId, row, bytes, offset, false);
416
+ if (parentUuid !== null) {
417
+ if (heldBack.length >= MAX_HELD_BACK_RECORDS)
418
+ this.__unavailable();
419
+ heldBack.push({ offset, length: bytes.length, parentUuid });
420
+ return;
421
+ }
422
+ // a released record can be the parent of another held-back one
423
+ for (let held = heldBack.findIndex(isReleasable); held !== -1;) {
424
+ const [record] = heldBack.splice(held, 1);
425
+ if (record)
426
+ this.__record(root, nativeId, row, reread(record.offset, record.length), record.offset, false);
427
+ held = heldBack.findIndex(isReleasable);
428
+ }
429
+ };
399
430
  this.__database.exec('BEGIN IMMEDIATE');
400
431
  try {
401
432
  while (position < stat.size && remaining() > 0) {
@@ -409,13 +440,20 @@ export class ClaudeHistoryModel {
409
440
  if (end > MAX_RECORD_BYTES)
410
441
  this.__unavailable();
411
442
  if (end > 0)
412
- this.__record(root, nativeId, row, tail.subarray(0, end), lineStart);
443
+ indexRecord(tail.subarray(0, end), lineStart);
413
444
  lineStart += end + 1;
414
445
  tail = tail.subarray(end + 1);
415
446
  }
416
447
  if (tail.length > MAX_RECORD_BYTES)
417
448
  this.__unavailable();
418
449
  }
450
+ /*
451
+ * A parent this read didn't reach is indexed as the root of its own turn: the projection
452
+ * keeps no position before byte_offset to retry from, and a hidden record only groups
453
+ * the records that follow it.
454
+ */
455
+ for (const record of heldBack)
456
+ this.__record(root, nativeId, row, reread(record.offset, record.length), record.offset, true);
419
457
  row.byte_offset = lineStart;
420
458
  this.__database
421
459
  .prepare(`UPDATE hq_claude_file SET byte_offset = ?, file_size = ?, leaf_id = ?, name = ?,
@@ -440,14 +478,22 @@ export class ClaudeHistoryModel {
440
478
  closeSync(fd);
441
479
  }
442
480
  }
443
- __record(root, nativeId, row, bytes, offset) {
481
+ /**
482
+ * Indexes one transcript record. Claude Code can write a hidden record, such as an attachment
483
+ * or a scheduled-task event, a few lines before the record it follows; such a record is held
484
+ * back unless `isOrphanAllowed`, and the caller retries it once its parent is indexed.
485
+ * @returns Null once the record is indexed, or the UUID of the parent a held-back record awaits.
486
+ * @throws
487
+ * - JG_AGENT_HQ_CLAUDE_HISTORY_UNAVAILABLE: The Claude history is unavailable
488
+ */
489
+ __record(root, nativeId, row, bytes, offset, isOrphanAllowed) {
444
490
  const input = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
445
491
  const metadata = ApiRequestMetadataSchema.safeParse(input);
446
492
  if (metadata.success) {
447
493
  if (metadata.data.sessionId !== nativeId ||
448
494
  (metadata.data.cwd !== undefined && !isClaudeWorkspaceCwd(metadata.data.cwd, root)))
449
495
  this.__unavailable();
450
- return;
496
+ return null;
451
497
  }
452
498
  const record = RecordSchema.parse(input);
453
499
  if (record.cwd !== undefined) {
@@ -461,14 +507,14 @@ export class ClaudeHistoryModel {
461
507
  if (record.sessionId !== nativeId || record.customTitle === undefined)
462
508
  this.__unavailable();
463
509
  row.name = record.customTitle;
464
- return;
510
+ return null;
465
511
  }
466
512
  if (record.isSidechain)
467
- return;
513
+ return null;
468
514
  if (!record.uuid) {
469
515
  if (record.message !== undefined || record.type === 'user' || record.type === 'assistant')
470
516
  this.__unavailable();
471
- return;
517
+ return null;
472
518
  }
473
519
  if ((record.type === 'user' || record.type === 'assistant') &&
474
520
  record.message?.role !== record.type)
@@ -485,6 +531,15 @@ export class ClaudeHistoryModel {
485
531
  WHERE workspace_root = ? AND native_id = ? AND uuid = ?`)
486
532
  .get(root, nativeId, record.parentUuid)
487
533
  : undefined;
534
+ const visible = record.message !== undefined && !record.isMeta;
535
+ if (record.parentUuid === record.uuid)
536
+ this.__unavailable();
537
+ if (record.parentUuid && !parent) {
538
+ if (visible)
539
+ this.__unavailable();
540
+ if (!isOrphanAllowed)
541
+ return record.parentUuid;
542
+ }
488
543
  const textPrompt = record.type === 'user' &&
489
544
  !record.isMeta &&
490
545
  (typeof record.message?.content === 'string' ||
@@ -495,11 +550,6 @@ export class ClaudeHistoryModel {
495
550
  : typeof parent?.turn_id === 'string'
496
551
  ? parent.turn_id
497
552
  : record.uuid;
498
- const visible = record.message !== undefined && !record.isMeta;
499
- if (record.parentUuid === record.uuid)
500
- this.__unavailable();
501
- if (record.parentUuid && !parent)
502
- this.__unavailable();
503
553
  const previous = this.__database
504
554
  .prepare('SELECT parent_uuid FROM hq_claude_entry WHERE workspace_root = ? AND native_id = ? AND uuid = ?')
505
555
  .get(root, nativeId, record.uuid);
@@ -542,6 +592,12 @@ export class ClaudeHistoryModel {
542
592
  }
543
593
  row.created_at = Math.min(row.created_at, createdAt);
544
594
  row.updated_at = Math.max(row.updated_at, createdAt);
595
+ return null;
596
+ }
597
+ __hasEntry(root, nativeId, uuid) {
598
+ return (this.__database
599
+ .prepare('SELECT 1 FROM hq_claude_entry WHERE workspace_root = ? AND native_id = ? AND uuid = ?')
600
+ .get(root, nativeId, uuid) !== undefined);
545
601
  }
546
602
  __unavailable() {
547
603
  throw new Exception('The Claude history is unavailable', {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jg-agent-hq",
3
- "version": "4.0.1",
3
+ "version": "4.0.2",
4
4
  "description": "Native coding-agent session control, agent streams and durable collaboration for Node.js apps.",
5
5
  "type": "module",
6
6
  "license": "MIT",