agent-office 0.2.2: a same-size sidecar rewrite inside one timestamp tick is read again (#580)
The scanner judged a Grok usage.json / summary.json revision by
"size:mtime:ctime" alone. Linux stamps a write with the coarse kernel
clock: on the WSL2 box 199 of 200 same-size in-place rewrites kept all
three (mote, APFS: 0 of 200). So "midnight and metadata-only changes do
not read JSONL again" was red there (usage 100 -> 200 serialize to the
same length, written ms apart) and green on mote and CI. A user's
usage.json rewritten that way kept the old token count. This is a
product bug, not a test assumption.
A sidecar's revision is now "size:mtime:ctime:ino", plus "#sha1" of
its bytes while its stamp is under 2.5 s old (RACY_MS, git's racy-index
idea). sameSidecar compares the stamps, and the digests where both
carry one, so a stamp aging out of the window is not a new revision and
the same bytes written again are not parsed again. Cost: a sidecar
(<= 256 KiB meta, <= 32 MiB usage) is read and hashed on each tick for
2.5 s after a write. createScanner takes statSync (sidecars only) so a
test can freeze the stamps.
New test: "a same-size usage.json or summary.json rewrite inside one
timestamp tick is read again" (frozen mtime/ctime; in place, temp and
rename, same bytes again with no parse).
Run at this tree (5403c21 + this commit, = origin/main just fetched):
- mote: packages/agent-office HOME=$(mktemp -d) bun test 168 pass 0 fail;
stamp-page.mjs --check 0; bun scripts/check.mjs agent-office 0; full
HOME=$(mktemp -d) bun test 4470 pass 9 skip 0 fail.
- wsl-run (magpie-desktop): packages/agent-office 168 pass 0 fail; full
bun test 4471 pass 8 skip 0 fail.
Broken by hand:
- origin/main's scan.mjs with the new test on WSL: both #580's test
(line 162) and the new one (line 206) red.
- on mote, digest and ino both removed: the new test red at line 206;
ino kept, digest removed: red at 206; digest kept, ino removed: green
(the digest catches the rename too; ino is belt and braces).
Not tried: a real Grok Build session writing usage.json; Windows.
Not changed: the session files themselves (Gemini .json, dsh .zstd,
JSONL, Codex session_index.jsonl) have the same stamp-only check;
filed as #581.
This commit is contained in:
@@ -1,5 +1,11 @@
|
||||
# Changelog
|
||||
|
||||
## 0.2.2 · 2026-11-01
|
||||
|
||||
### Fixed
|
||||
|
||||
- A Grok `usage.json` or `summary.json` rewritten at the same size within one file-system timestamp tick is read again. On Linux a write is stamped with the coarse kernel clock, so such a rewrite kept size, mtime and ctime, and the old token count stood. A sidecar stamped within the last 2.5 s now also carries a digest of its bytes, and its inode is part of its revision (#580).
|
||||
|
||||
## 0.2.1 · 2026-10-31
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -104,7 +104,7 @@ test("the authenticated standalone page, bridge, live data and JSON options work
|
||||
try {
|
||||
const ping = await (await fetch(s.url + "api/ping")).json()
|
||||
expect(ping.name).toBe("agent-office")
|
||||
expect(ping.version).toBe("0.2.1")
|
||||
expect(ping.version).toBe("0.2.2")
|
||||
const page = await fetch(s.url)
|
||||
expect(page.status).toBe(200)
|
||||
expect(await page.text()).toContain('src="_magpie/bridge.js"')
|
||||
|
||||
@@ -185,6 +185,39 @@ test("midnight and metadata-only changes do not read JSONL again",()=>{
|
||||
expect(bytes()).toBe(0)
|
||||
})
|
||||
|
||||
test("a same-size usage.json or summary.json rewrite inside one timestamp tick is read again",()=>{
|
||||
// A coarse-clock file system (Linux stamps a write with the kernel tick):
|
||||
// a rewrite in the same tick keeps size, mtime and ctime. Freeze them, so
|
||||
// the case does not depend on this machine's clock.
|
||||
const root=tmp(),path=join(root,"updates.jsonl"),usage=join(root,"usage.json"),meta=join(root,"summary.json")
|
||||
writeFileSync(path,line({timestamp:time/1000,params:{update:{sessionUpdate:"user_message_chunk",content:{text:"work"}}}}))
|
||||
const use=tokens=>JSON.stringify({turns:[{endedAt:stamp,inputTokens:tokens,outputTokens:10}]})
|
||||
writeFileSync(usage,use(100));writeFileSync(meta,JSON.stringify({title:"title one"}))
|
||||
const frozen=new Map()
|
||||
const statSync2=file=>{
|
||||
const st=statSync(file)
|
||||
if(!frozen.has(file))frozen.set(file,{mtimeMs:st.mtimeMs,ctimeMs:st.ctimeMs})
|
||||
return Object.assign(Object.create(Object.getPrototypeOf(st)),st,frozen.get(file))
|
||||
}
|
||||
const scanner=createScanner({sources:[source(root,"grok",{usage:()=>usage,meta:()=>meta})],statSync:statSync2})
|
||||
expect(scanner.scan(time)[0]).toMatchObject({title:"title one",tokensToday:110})
|
||||
writeFileSync(usage,use(200));writeFileSync(meta,JSON.stringify({title:"title two"}))
|
||||
expect(statSync(usage).size).toBe(Buffer.byteLength(use(100)))
|
||||
expect(scanner.scan(time)[0]).toMatchObject({title:"title two",tokensToday:210})
|
||||
// a temp-and-rename writer: same size and stamps, a new inode
|
||||
const next=join(root,"usage.tmp");writeFileSync(next,use(300));renameSync(next,usage)
|
||||
expect(scanner.scan(time)[0]).toMatchObject({title:"title two",tokensToday:310})
|
||||
// the same bytes written again are not a new revision
|
||||
const original=JSON.parse
|
||||
let usageParses=0
|
||||
JSON.parse=function(text,...args){if(String(text).includes('"endedAt"'))usageParses++;return original.call(this,text,...args)}
|
||||
try {
|
||||
writeFileSync(usage,use(300))
|
||||
expect(scanner.scan(time)[0]).toMatchObject({tokensToday:310})
|
||||
expect(usageParses).toBe(0)
|
||||
}finally{JSON.parse=original}
|
||||
})
|
||||
|
||||
test("changing sources releases cursors and accumulated sessions",()=>{
|
||||
const root=tmp(),other=tmp(),path=join(root,"one.jsonl")
|
||||
writeFileSync(path,line(user("first")))
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// truncation or same-size rewrite starts a fresh replay. Calendar-day usage
|
||||
// is refreshed even when the log has not changed.
|
||||
import { closeSync, existsSync, openSync, fstatSync, readFileSync, readSync, readdirSync, statSync } from "node:fs"
|
||||
import { createHash } from "node:crypto"
|
||||
import { homedir } from "node:os"
|
||||
import { basename, dirname, join } from "node:path"
|
||||
import { StringDecoder } from "node:string_decoder"
|
||||
@@ -18,6 +19,12 @@ const ZSTD_MAX = 8 * 1024 * 1024
|
||||
const ZSTD_EVERY = 4000
|
||||
const META_MAX = 256 * 1024 // state.json / summary.json remain small
|
||||
const USAGE_MAX = 32 * 1024 * 1024 // usage.json grows with every recorded turn
|
||||
// A file system stamps a write with a coarse clock (Linux: one kernel tick,
|
||||
// some file systems a whole second or two), so a same-size rewrite inside one
|
||||
// tick leaves size, mtime, ctime and inode as they were. A sidecar stamped
|
||||
// this recently is told apart by a digest of its bytes as well; one older
|
||||
// than this cannot be rewritten without its stamp moving.
|
||||
const RACY_MS = 2500
|
||||
// Claude Code keeps one file per running process, <config>/sessions/<pid>.json.
|
||||
// A mid-turn session with no live process has stopped, even when the file
|
||||
// ends before a turn-ending event: `claude -p` killed from another agent.
|
||||
@@ -302,16 +309,37 @@ function readMeta(src, path, field = "meta") {
|
||||
} catch { return null }
|
||||
}
|
||||
|
||||
function sidecars(src, path) {
|
||||
// Each sidecar's revision, "size:mtime:ctime:ino", with "#digest" added
|
||||
// while its stamp is too recent to tell a same-size rewrite apart.
|
||||
function sidecars(src, path, stat = statSync) {
|
||||
return ["meta", "usage"].map((field) => {
|
||||
if (typeof src[field] !== "function") return ""
|
||||
try {
|
||||
const st = statSync(src[field](path))
|
||||
return `${st.size}:${st.mtimeMs}:${st.ctimeMs}`
|
||||
const file = src[field](path), st = stat(file)
|
||||
const sig = `${st.size}:${st.mtimeMs}:${st.ctimeMs}:${st.ino}`
|
||||
if (!st.isFile() || st.size > (field === "usage" ? USAGE_MAX : META_MAX)) return sig
|
||||
if (Date.now() - Math.max(st.mtimeMs, st.ctimeMs) >= RACY_MS) return sig
|
||||
return sig + "#" + createHash("sha1").update(readFileSync(file)).digest("hex")
|
||||
} catch { return "missing" }
|
||||
}).join("|")
|
||||
}
|
||||
|
||||
// One sidecar revision is another when their stamps match and, where both
|
||||
// carry a digest, the digests do. A stamp that has aged past RACY_MS drops
|
||||
// its digest, which does not make it a new revision.
|
||||
function sameSidecar(a, b) {
|
||||
if (a === b) return true
|
||||
if (a == null || b == null) return false
|
||||
const [sa, da] = a.split("#"), [sb, db] = b.split("#")
|
||||
return sa === sb && (!da || !db || da === db)
|
||||
}
|
||||
function sameSidecars(a, b) {
|
||||
if (a === b) return true
|
||||
if (a == null || b == null) return false
|
||||
const x = a.split("|"), y = b.split("|")
|
||||
return x.length === y.length && x.every((v, i) => sameSidecar(v, y[i]))
|
||||
}
|
||||
|
||||
// Codex names a thread in session_index.jsonl ({id, thread_name}), the
|
||||
// latest line for an id winning
|
||||
function codexTitles(was, readBytes) {
|
||||
@@ -343,6 +371,7 @@ export function createScanner(opts = {}) {
|
||||
const o = { days: 2, max: 40, zstdMax: ZSTD_MAX, zstdEvery: ZSTD_EVERY, ...opts }
|
||||
const files = new Map() // path -> file identity, JSONL cursor/reader, published session
|
||||
const readBytes = typeof o.readSync === "function" ? o.readSync : readSync
|
||||
const statSidecar = typeof o.statSync === "function" ? o.statSync : statSync
|
||||
const procs = createProcesses()
|
||||
let srcs = o.sources || sources()
|
||||
let titleCache = null
|
||||
@@ -366,8 +395,8 @@ export function createScanner(opts = {}) {
|
||||
let titles = null
|
||||
for (const f of keep) {
|
||||
let c = files.get(f.path)
|
||||
const metadata = sidecars(f.src, f.path)
|
||||
const changed = !c || c.size !== f.size || c.mtime !== f.mtime || c.ctime !== f.ctime || c.dev !== f.dev || c.ino !== f.ino || c.birthtime !== f.birthtime || c.metadata !== metadata || (c.cursor && c.cursor.offset < f.size)
|
||||
const metadata = sidecars(f.src, f.path, statSidecar)
|
||||
const changed = !c || c.size !== f.size || c.mtime !== f.mtime || c.ctime !== f.ctime || c.dev !== f.dev || c.ino !== f.ino || c.birthtime !== f.birthtime || !sameSidecars(c.metadata, metadata) || (c.cursor && c.cursor.offset < f.size)
|
||||
if (changed) {
|
||||
const zstd = f.path.endsWith(".zstd")
|
||||
// Leave size/mtime at the last decoded revision while throttled, so
|
||||
@@ -432,8 +461,8 @@ export function createScanner(opts = {}) {
|
||||
const changes = { now }
|
||||
// Do not retain a whole usage.json snapshot or re-aggregate it on each
|
||||
// append. The reader keeps its daily totals; re-read only a new revision.
|
||||
if (!reusable || before?.[0] !== sig[0]) changes.meta = readMeta(f.src, f.path)
|
||||
if (!reusable || before?.[1] !== sig[1]) changes.usage = readMeta(f.src, f.path, "usage")
|
||||
if (!reusable || !sameSidecar(before?.[0], sig[0])) changes.meta = readMeta(f.src, f.path)
|
||||
if (!reusable || !sameSidecar(before?.[1], sig[1])) changes.usage = readMeta(f.src, f.path, "usage")
|
||||
try { c.reader.update(readAppended(f, c.cursor, readBytes), changes) }
|
||||
catch (error) {
|
||||
if (!(error instanceof ExtendedTail) || !reusable) throw error
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/page-agent-office",
|
||||
"version": "0.2.1",
|
||||
"version": "0.2.2",
|
||||
"description": "我的 Agent 在干嘛:读取本机 Claude Code、Codex、Copilot CLI、Kimi Code、DeepSeek Harness、Gemini CLI、Qwen Code、Pi、omp、Qoder、WorkBuddy、CodeBuddy、Grok Build 的会话文件,把每个会话画成真 3D / 等距 / 2D 办公室里的小人,或分组工作台。Live agent activity dashboard for magpie, with a real WebGL office and six scenes.",
|
||||
"type": "module",
|
||||
"files": [
|
||||
|
||||
Reference in New Issue
Block a user