Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/core/src/id/id.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { create as createIdentifier } from "@opencode-ai/schema/identifier"
import { create as createIdentifier, timeChars } from "@opencode-ai/schema/identifier"

const prefixes = {
job: "job",
Expand Down Expand Up @@ -39,7 +39,7 @@ export function create(prefix: string, direction: "descending" | "ascending", ti
/** Extract timestamp from an ascending ID. Does not work with descending IDs. */
export function timestamp(id: string): number {
const prefix = id.split("_")[0]
const hex = id.slice(prefix.length + 1, prefix.length + 13)
const hex = id.slice(prefix.length + 1, prefix.length + 1 + timeChars)
const encoded = BigInt("0x" + hex)
return Number(encoded / BigInt(0x1000))
}
Expand Down
16 changes: 16 additions & 0 deletions packages/core/test/id.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { describe, expect, test } from "bun:test"
import { Identifier } from "../src/id/id"

describe("Identifier.timestamp", () => {
test("round-trips the time an ascending id was minted", () => {
const before = Date.now()
const decoded = Identifier.timestamp(Identifier.ascending("session"))
expect(decoded).toBeGreaterThanOrEqual(before)
expect(decoded).toBeLessThanOrEqual(Date.now())
})

test("round-trips an explicit timestamp", () => {
const stamp = Date.parse("2026-09-03T04:39:56.208Z")
expect(Identifier.timestamp(Identifier.create("ses", "ascending", stamp))).toBe(stamp)
})
})
14 changes: 9 additions & 5 deletions packages/opencode/src/id/id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ const prefixes = {
} as const

const LENGTH = 26
// See packages/schema/src/identifier.ts: a 6-byte time field truncates
// Date.now() * 0x1000 and wraps every ~795 days. 7 bytes hold it until 2527.
const TIME_BYTES = 7
const TIME_CHARS = TIME_BYTES * 2

// State for monotonic ID generation
let lastTimestamp = 0
Expand Down Expand Up @@ -61,18 +65,18 @@ export function create(prefix: string, direction: "descending" | "ascending", ti

now = direction === "descending" ? ~now : now

const timeBytes = Buffer.alloc(6)
for (let i = 0; i < 6; i++) {
timeBytes[i] = Number((now >> BigInt(40 - 8 * i)) & BigInt(0xff))
const timeBytes = Buffer.alloc(TIME_BYTES)
for (let i = 0; i < TIME_BYTES; i++) {
timeBytes[i] = Number((now >> BigInt(8 * (TIME_BYTES - 1 - i))) & BigInt(0xff))
}

return prefix + "_" + timeBytes.toString("hex") + randomBase62(LENGTH - 12)
return prefix + "_" + timeBytes.toString("hex") + randomBase62(LENGTH - TIME_CHARS)
}

/** Extract timestamp from an ascending ID. Does not work with descending IDs. */
export function timestamp(id: string): number {
const prefix = id.split("_")[0]
const hex = id.slice(prefix.length + 1, prefix.length + 13)
const hex = id.slice(prefix.length + 1, prefix.length + 1 + TIME_CHARS)
const encoded = BigInt("0x" + hex)
return Number(encoded / BigInt(0x1000))
}
Expand Down
13 changes: 10 additions & 3 deletions packages/schema/src/identifier.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
const length = 26
// Date.now() * 0x1000 needs 53 bits. A 6-byte time field holds 48, so the top
// bits were dropped and the sortable prefix wrapped every 2^36 ms, about 795
// days. The last wrap was 2026-08-14T11:19:55Z, which sorted every id minted
// after it below the preceding two years of history. 7 bytes hold the encoding
// until 2527. Ids stay 26 characters.
const timeBytes = 7
export const timeChars = timeBytes * 2
const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
let lastTimestamp = 0
let counter = 0
Expand All @@ -20,11 +27,11 @@ export function create(descending: boolean, timestamp = Date.now()) {

const current = BigInt(timestamp) * 0x1000n + BigInt(counter)
const value = descending ? ~current : current
const time = Array.from({ length: 6 }, (_, index) =>
Number((value >> BigInt(40 - 8 * index)) & 0xffn)
const time = Array.from({ length: timeBytes }, (_, index) =>
Number((value >> BigInt(8 * (timeBytes - 1 - index))) & 0xffn)
.toString(16)
.padStart(2, "0"),
).join("")
const bytes = crypto.getRandomValues(new Uint8Array(length - 12))
const bytes = crypto.getRandomValues(new Uint8Array(length - timeChars))
return time + Array.from(bytes, (byte) => chars[byte % 62]).join("")
}
33 changes: 33 additions & 0 deletions packages/schema/test/identifier.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { describe, expect, test } from "bun:test"
import { create } from "../src/identifier"

// The most recent 48-bit wrap, 2026-08-14T11:19:55Z. Ids either side of it
// must still sort in time order.
const WRAP = 2 ** 36 * Math.floor(Date.now() / 2 ** 36)
const DAY = 86_400_000

describe("identifier", () => {
test("ids are 26 characters", () => {
expect(create(false)).toHaveLength(26)
expect(create(true)).toHaveLength(26)
})

test("ascending ids sort in time order across the wrap", () => {
expect(create(false, WRAP - DAY) < create(false, WRAP + DAY)).toBe(true)
})

test("descending ids sort in reverse time order across the wrap", () => {
expect(create(true, WRAP + DAY) < create(true, WRAP - DAY)).toBe(true)
})

test("ascending ids sort in time order over four centuries", () => {
const stamps = [0, 1_000_000_000_000, WRAP - 1, WRAP + 1, Date.parse("2400-01-01T00:00:00Z")]
const ids = stamps.map((stamp) => create(false, stamp))
expect(ids).toEqual([...ids].sort())
})

test("ids minted in the same millisecond stay ordered", () => {
const ids = Array.from({ length: 32 }, () => create(false, WRAP))
expect(ids).toEqual([...ids].sort())
})
})
Loading