Skip to content

An open-source, faster Devin alternative

TypeScript

filesetdigest: hash a length-prefixed framing, drop the JSON pre-image + hand-rolled ustar

Igor Zalutskidfff900d7ec1
diff --git a/cmd/oc/internal/commands/agent_deploy_flue.go b/cmd/oc/internal/commands/agent_deploy_flue.go
index 8ae56965..94e12a07 100644
--- a/cmd/oc/internal/commands/agent_deploy_flue.go
+++ b/cmd/oc/internal/commands/agent_deploy_flue.go
@@ -76,7 +76,7 @@ func deployFlue(cmd *cobra.Command, sc *client.Client, dir string, m *manifest,
return err
}
digest := filesetdigest.Digest(files)
- tarGz, err := filesetdigest.CanonicalTarGz(files)
+ tarGz, err := filesetdigest.TarGz(files)
if err != nil {
return fmt.Errorf("pack artifact: %w", err)
}
diff --git a/cmd/oc/internal/commands/agent_deploy_flue_test.go b/cmd/oc/internal/commands/agent_deploy_flue_test.go
index 85e2ced7..3dd407c4 100644
--- a/cmd/oc/internal/commands/agent_deploy_flue_test.go
+++ b/cmd/oc/internal/commands/agent_deploy_flue_test.go
@@ -112,7 +112,7 @@ func TestDeployFlueEndToEnd(t *testing.T) {
{Path: "oc.js", Mode: 0o644, Content: []byte(e2eOcBody + "\n")},
}
expectedDigest := filesetdigest.Digest(expectedFiles)
- expectedTarGz, err := filesetdigest.CanonicalTarGz(expectedFiles)
+ expectedTarGz, err := filesetdigest.TarGz(expectedFiles)
if err != nil {
t.Fatal(err)
}
diff --git a/cmd/oc/internal/filesetdigest/filesetdigest.go b/cmd/oc/internal/filesetdigest/filesetdigest.go
index d96f307f..b9670f04 100644
--- a/cmd/oc/internal/filesetdigest/filesetdigest.go
+++ b/cmd/oc/internal/filesetdigest/filesetdigest.go
@@ -1,34 +1,42 @@
// Package filesetdigest is the Go implementation of the OpenComputer bundle
-// fileset digest + canonical tar.gz — the content-addressing scheme shared by
-// skill bundles and Flue framework artifacts.
+// fileset digest — the content-addressing scheme shared by skill bundles and
+// Flue framework artifacts.
//
-// This is the THIRD implementation of one contract (flue-slice.md contract 4).
-// It MUST stay byte-identical to:
-// - TS runtime: oc-runtimes/adapter-core/src/skills.ts (computeFilesetDigest)
-// - TS host: sessions-api/src/v3/core/skill-bundle-canonical.ts
+// This is one of three implementations of a single contract (flue-slice.md
+// contract 4). It MUST stay byte-identical to:
+// - TS host: sessions-api/src/v3/core/skill-bundle-canonical.ts (filesetDigest)
+// - TS box: oc-runtimes/adapter-core/src/skills.ts (filesetDigest)
//
-// A shared golden vector (a fixed fileset → a fixed digest) locks the three in
-// lockstep; see filesetdigest_test.go. If you change anything here, re-run the
-// golden across all three repos.
+// A shared golden vector (a fixed fileset -> a fixed digest) locks the three in
+// lockstep; see testdata/golden-fileset.json + filesetdigest_test.go.
//
-// Digest (contract 4): sha256 over the bytewise-sorted, fixed-order entry list
-// [{"path":…,"mode":…,"sha256":…}, …] serialized as JSON with no whitespace,
-// mode as a bare decimal integer, sha256 the hex of sha256(content). The JSON is
-// hand-built (not encoding/json) so string escaping matches JavaScript's
-// JSON.stringify exactly — the digest is a cross-language content address, and
-// Go's default JSON escaping (HTML entities, /, U+2028/U+2029)
-// diverges from JS.
+// The digest hashes a length-prefixed binary framing, NOT a serialization
+// format. Reproducing it in another language is three primitives with no edge
+// cases — sort paths by UTF-8 bytes, big-endian uint32, sha256 of raw bytes —
+// so there is nothing to escape and no JSON.stringify dialect to match. (An
+// earlier scheme hashed JSON.stringify output, which forced a hand-rolled
+// ECMA-262 string escaper here to match JavaScript; that is what this replaces.)
+//
+// Pre-image:
+//
+// entries sorted by path, compared as raw UTF-8 bytes
+// buf = u32be(len(entries))
+// ‖ for each entry: sha256(content)[32] ‖ u32be(mode) ‖ u32be(len(path)) ‖ path_utf8
+// digest = "sha256:" + lowerhex(sha256(buf))
package filesetdigest
import (
"crypto/sha256"
+ "encoding/binary"
"encoding/hex"
- "fmt"
"sort"
- "strconv"
- "strings"
)
+// DigestScheme is the hash-function prefix on every digest ("sha256:<hex>").
+// The hash is over the canonical framing below, not the raw file bytes — the
+// same "sha256: means sha256 of our canonical form" convention as OCI descriptors.
+const DigestScheme = "sha256:"
+
// File is one entry in a bundle fileset. Mode is the POSIX file mode, normalized
// to 0o644 or 0o755 by the caller (NormalizeMode) — the digest and the tar must
// use the same value.
@@ -48,74 +56,35 @@ func NormalizeMode(mode int) int {
return 0o644
}
-// Digest returns the fileset digest ("sha256:" + hex). Byte-for-byte identical
-// to the TS computeFilesetDigest for the same fileset.
+// Digest returns the fileset digest ("ocfs1:" + hex). Byte-for-byte identical to
+// the TS filesetDigest for the same fileset.
func Digest(files []File) string {
type entry struct {
path string
mode int
- sha string
+ sum [32]byte
}
entries := make([]entry, len(files))
for i, f := range files {
- sum := sha256.Sum256(f.Content)
- entries[i] = entry{path: f.Path, mode: f.Mode, sha: hex.EncodeToString(sum[:])}
+ entries[i] = entry{path: f.Path, mode: f.Mode, sum: sha256.Sum256(f.Content)}
}
- // Bytewise sort by path. Go string comparison is bytewise over the UTF-8
- // bytes, matching Node's Buffer.compare(Buffer.from(path, "utf8"), …).
+ // Bytewise sort by path. Go string comparison is over the raw bytes, matching
+ // Node's Buffer.compare(Buffer.from(path,"utf8"), …) — NOT String.localeCompare
+ // or a default JS Array.sort (which orders by UTF-16 code units).
sort.Slice(entries, func(i, j int) bool { return entries[i].path < entries[j].path })
- var b strings.Builder
- b.WriteByte('[')
- for i, e := range entries {
- if i > 0 {
- b.WriteByte(',')
- }
- b.WriteString(`{"path":`)
- b.WriteString(jsMarshalString(e.path))
- b.WriteString(`,"mode":`)
- b.WriteString(strconv.Itoa(e.mode))
- b.WriteString(`,"sha256":`)
- b.WriteString(jsMarshalString(e.sha))
- b.WriteByte('}')
- }
- b.WriteByte(']')
-
- sum := sha256.Sum256([]byte(b.String()))
- return "sha256:" + hex.EncodeToString(sum[:])
-}
-
-// jsMarshalString serializes s to a JSON string literal byte-for-byte as
-// JavaScript's JSON.stringify would (ECMA-262 QuoteJSONString): escape " and \,
-// the short forms \b \t \n \f \r, other C0 controls as \u00xx (lowercase), and
-// emit everything else — including non-ASCII and U+2028/U+2029 — as raw UTF-8.
-func jsMarshalString(s string) string {
- var b strings.Builder
- b.WriteByte('"')
- for _, r := range s {
- switch r {
- case '"':
- b.WriteString(`\"`)
- case '\\':
- b.WriteString(`\\`)
- case '\b':
- b.WriteString(`\b`)
- case '\f':
- b.WriteString(`\f`)
- case '\n':
- b.WriteString(`\n`)
- case '\r':
- b.WriteString(`\r`)
- case '\t':
- b.WriteString(`\t`)
- default:
- if r < 0x20 {
- fmt.Fprintf(&b, `\u%04x`, r)
- } else {
- b.WriteRune(r)
- }
- }
+ h := sha256.New()
+ var u32 [4]byte
+ binary.BigEndian.PutUint32(u32[:], uint32(len(entries)))
+ h.Write(u32[:])
+ for _, e := range entries {
+ h.Write(e.sum[:])
+ binary.BigEndian.PutUint32(u32[:], uint32(e.mode))
+ h.Write(u32[:])
+ path := []byte(e.path)
+ binary.BigEndian.PutUint32(u32[:], uint32(len(path)))
+ h.Write(u32[:])
+ h.Write(path)
}
- b.WriteByte('"')
- return b.String()
+ return DigestScheme + hex.EncodeToString(h.Sum(nil))
}
diff --git a/cmd/oc/internal/filesetdigest/filesetdigest_test.go b/cmd/oc/internal/filesetdigest/filesetdigest_test.go
index ef050703..81863318 100644
--- a/cmd/oc/internal/filesetdigest/filesetdigest_test.go
+++ b/cmd/oc/internal/filesetdigest/filesetdigest_test.go
@@ -1,14 +1,13 @@
package filesetdigest
import (
+ "archive/tar"
"bytes"
"compress/gzip"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
- "fmt"
"io"
- "strconv"
"strings"
"testing"
)
@@ -16,8 +15,8 @@ import (
// goldenFiles is the SHARED cross-repo golden vector (flue-slice.md contract 4).
// The same fileset must produce goldenDigest in all three implementations:
// this package, oc-runtimes/adapter-core, and sessions-api. It includes a real
-// binary file (logo.png) so a utf8 round-trip in ANY impl would change the digest
-// (finding #13). Kept byte-identical to testdata/golden-fileset.json.
+// binary file (logo.png) so a utf8 round-trip in ANY impl would change the
+// digest. Kept byte-identical to testdata/golden-fileset.json.
var goldenFiles = []File{
{Path: "artifact.json", Mode: 0o644, Content: []byte("{\"entry\":\"oc.js\",\"profile_version\":1}\n")},
{Path: "oc.js", Mode: 0o644, Content: []byte("export const x = 1;\n")},
@@ -34,7 +33,9 @@ func mustB64(s string) []byte {
return b
}
-const goldenDigest = "sha256:fbea3c2455fbec53f75b474924fe38e7e0fc20a67cd69a7942bd5670bc25b501"
+// The ocfs1 fileset digest of goldenFiles. Regenerated across all three repos
+// whenever the algorithm changes (it must not, without a scheme bump).
+const goldenDigest = "sha256:cab805ea6500039cdd09da801f90b1d6aff177710f106acc647a875c2dcdceea"
func TestGoldenDigest(t *testing.T) {
if got := Digest(goldenFiles); got != goldenDigest {
@@ -48,29 +49,29 @@ func TestDigestIndependentOfInputOrder(t *testing.T) {
for i, f := range goldenFiles {
rev[len(goldenFiles)-1-i] = f
}
- if got := Digest(rev); got != goldenDigest {
- t.Fatalf("digest is order-dependent: got %s want %s", got, goldenDigest)
+ if got := Digest(rev); got != Digest(goldenFiles) {
+ t.Fatalf("digest is order-dependent: got %s want %s", got, Digest(goldenFiles))
}
}
-// TestCanonicalTarGzRoundTrip reproduces the SERVER's verify path: unpack the
-// tar.gz with a minimal POSIX-ustar reader (a port of adapter-core parseTar) and
-// recompute the digest from the unpacked bytes. It must equal Digest(files) —
-// this is exactly the check the deploy-verify executor performs before pinning.
-func TestCanonicalTarGzRoundTrip(t *testing.T) {
- tarGz, err := CanonicalTarGz(goldenFiles)
+// TestTarGzRoundTrip reproduces the server/box verify path: pack the fileset,
+// unpack it with a standard tar reader, and recompute the digest from the
+// unpacked bytes. It must equal Digest(files) — the check the deploy-verify
+// executor and the box materializer both perform before pinning.
+func TestTarGzRoundTrip(t *testing.T) {
+ tarGz, err := TarGz(goldenFiles)
if err != nil {
- t.Fatalf("CanonicalTarGz: %v", err)
+ t.Fatalf("TarGz: %v", err)
}
- unpacked, err := parseTarGz(tarGz)
+ unpacked, err := readTarGz(tarGz)
if err != nil {
- t.Fatalf("parse: %v", err)
+ t.Fatalf("read: %v", err)
}
if len(unpacked) != len(goldenFiles) {
t.Fatalf("unpacked %d files, want %d", len(unpacked), len(goldenFiles))
}
- if got := Digest(unpacked); got != goldenDigest {
- t.Fatalf("round-trip digest mismatch: got %s want %s", got, goldenDigest)
+ if got := Digest(unpacked); got != Digest(goldenFiles) {
+ t.Fatalf("round-trip digest mismatch: got %s want %s", got, Digest(goldenFiles))
}
byPath := map[string]File{}
for _, f := range unpacked {
@@ -90,17 +91,22 @@ func TestCanonicalTarGzRoundTrip(t *testing.T) {
}
}
-func TestCanonicalTarGzDeterministic(t *testing.T) {
- a, err := CanonicalTarGz(goldenFiles)
+// TestTarGzLongPath is the case the old hand-rolled ustar codec had to special-
+// case (name/prefix split, "path too long" errors): a path over 100 bytes must
+// round-trip cleanly through the standard tar codec.
+func TestTarGzLongPath(t *testing.T) {
+ long := "skills/" + strings.Repeat("a/", 60) + "SKILL.md" // ~130 bytes
+ files := []File{{Path: long, Mode: 0o644, Content: []byte("x")}}
+ tarGz, err := TarGz(files)
if err != nil {
- t.Fatal(err)
+ t.Fatalf("TarGz long path: %v", err)
}
- b, err := CanonicalTarGz(goldenFiles)
+ unpacked, err := readTarGz(tarGz)
if err != nil {
- t.Fatal(err)
+ t.Fatalf("read long path: %v", err)
}
- if !bytes.Equal(a, b) {
- t.Fatal("CanonicalTarGz is not deterministic")
+ if len(unpacked) != 1 || unpacked[0].Path != long {
+ t.Fatalf("long path did not round-trip: %+v", unpacked)
}
}
@@ -113,86 +119,31 @@ func TestNormalizeMode(t *testing.T) {
}
}
-// TestJSMarshalString locks the JS-faithful escaping (the reason we hand-roll
-// instead of using encoding/json). Expected values are JSON.stringify output.
-func TestJSMarshalString(t *testing.T) {
- cases := []struct{ in, want string }{
- {"abc", `"abc"`},
- {`a"b\c`, `"a\"b\\c"`},
- {"tab\tnl\n", `"tab\tnl\n"`},
- {"\b\f\r", `"\b\f\r"`},
- // / < > & and non-ASCII are emitted RAW (Go's default JSON would escape some).
- {"a<b>&/z", `"a<b>&/z"`},
- {"café/☃", `"café/☃"`},
- }
- for _, c := range cases {
- if got := jsMarshalString(c.in); got != c.want {
- t.Errorf("jsMarshalString(%q) = %s, want %s", c.in, got, c.want)
- }
- }
- // C0 control chars without a short form -> lowercase \u00xx (matches JS
- // JSON.stringify). Checked via the property to avoid hand-typing escapes.
- for _, b := range []byte{0x00, 0x01, 0x1f} {
- got := jsMarshalString(string(rune(b)))
- want := "\"" + fmt.Sprintf("\\u%04x", b) + "\""
- if got != want {
- t.Errorf("jsMarshalString(%#x) = %s, want %s", b, got, want)
- }
- }
-}
-
-// ── minimal ustar reader for the round-trip test (mirror of adapter-core parseTar) ──
-
-func parseTarGz(tarGz []byte) ([]File, error) {
+func readTarGz(tarGz []byte) ([]File, error) {
zr, err := gzip.NewReader(bytes.NewReader(tarGz))
if err != nil {
return nil, err
}
- tar, err := io.ReadAll(zr)
- if err != nil {
- return nil, err
- }
- readStr := func(o, n int) string {
- s := tar[o : o+n]
- if i := bytes.IndexByte(s, 0); i >= 0 {
- s = s[:i]
- }
- return string(s)
- }
+ tr := tar.NewReader(zr)
var out []File
- off := 0
- for off+512 <= len(tar) {
- header := tar[off : off+512]
- if isAllZero(header) {
+ for {
+ hdr, err := tr.Next()
+ if err == io.EOF {
break
}
- name := readStr(off+0, 100)
- prefix := readStr(off+345, 155)
- path := name
- if prefix != "" {
- path = prefix + "/" + name
+ if err != nil {
+ return nil, err
}
- mode, _ := strconv.ParseInt(strings.TrimSpace(readStr(off+100, 8)), 8, 32)
- size, _ := strconv.ParseInt(strings.TrimSpace(readStr(off+124, 12)), 8, 64)
- typeflag := tar[off+156]
- off += 512
- if typeflag == '0' || typeflag == 0 {
- content := make([]byte, size)
- copy(content, tar[off:off+int(size)])
- out = append(out, File{Path: path, Mode: int(mode) & 0o7777, Content: content})
+ if hdr.Typeflag != tar.TypeReg {
+ continue
}
- off += int((size+511)/512) * 512
- }
- return out, nil
-}
-
-func isAllZero(b []byte) bool {
- for _, x := range b {
- if x != 0 {
- return false
+ content, err := io.ReadAll(tr)
+ if err != nil {
+ return nil, err
}
+ out = append(out, File{Path: hdr.Name, Mode: int(hdr.Mode) & 0o7777, Content: content})
}
- return true
+ return out, nil
}
func TestContentShaSanity(t *testing.T) {
diff --git a/cmd/oc/internal/filesetdigest/fixture_test.go b/cmd/oc/internal/filesetdigest/fixture_test.go
index 7f499cf4..36862e66 100644
--- a/cmd/oc/internal/filesetdigest/fixture_test.go
+++ b/cmd/oc/internal/filesetdigest/fixture_test.go
@@ -1,19 +1,16 @@
package filesetdigest
import (
- "compress/gzip"
"encoding/base64"
"encoding/json"
- "io"
"os"
- "strings"
"testing"
)
// goldenFixture mirrors testdata/golden-fileset.json — the SHARED cross-language
// golden vector for contract 4. The same file is consumed by the sessions-api and
-// oc-runtimes test suites; computeFilesetDigest(files) must equal `digest` in all
-// three. Regenerate with scratch gen-fixture.mjs (reference JS) if the vector changes.
+// oc-runtimes test suites; filesetDigest(files) must equal `digest` in all three.
+// Regenerate with scratch gen-fixture.mjs (reference JS) if the vector changes.
type goldenFixture struct {
Digest string `json:"digest"`
Files []struct {
@@ -21,7 +18,6 @@ type goldenFixture struct {
Mode int `json:"mode"`
ContentBase64 string `json:"contentBase64"`
} `json:"files"`
- CanonicalTarGzBase64 string `json:"canonicalTarGzBase64"`
}
func loadFixture(t *testing.T) goldenFixture {
@@ -57,26 +53,3 @@ func TestGoldenFixtureDigest(t *testing.T) {
t.Fatalf("Digest(fixture files) = %s, want %s", got, fx.Digest)
}
}
-
-// TestGoldenFixtureTarballInterop proves the SERVER verify path works on a
-// FOREIGN-produced bundle: unpack the reference (JS)-produced canonical tar.gz
-// with our ustar reader and recompute the digest. Cross-language bundle interop.
-func TestGoldenFixtureTarballInterop(t *testing.T) {
- fx := loadFixture(t)
- tarGz, err := base64.StdEncoding.DecodeString(fx.CanonicalTarGzBase64)
- if err != nil {
- t.Fatalf("decode tar.gz: %v", err)
- }
- // sanity: it really is gzip
- if zr, err := gzip.NewReader(strings.NewReader(string(tarGz))); err == nil {
- _, _ = io.Copy(io.Discard, zr)
- _ = zr.Close()
- }
- files, err := parseTarGz(tarGz)
- if err != nil {
- t.Fatalf("parse reference tar.gz: %v", err)
- }
- if got := Digest(files); got != fx.Digest {
- t.Fatalf("digest of reference tarball = %s, want %s", got, fx.Digest)
- }
-}
diff --git a/cmd/oc/internal/filesetdigest/tar.go b/cmd/oc/internal/filesetdigest/tar.go
index 0c45ce1a..f64b60dd 100644
--- a/cmd/oc/internal/filesetdigest/tar.go
+++ b/cmd/oc/internal/filesetdigest/tar.go
@@ -1,117 +1,45 @@
package filesetdigest
import (
+ "archive/tar"
"bytes"
"compress/gzip"
- "fmt"
- "sort"
- "strconv"
"time"
)
-// CanonicalTarGz builds the deterministic tar.gz transport container for a
-// fileset: entries bytewise-sorted by path, fixed mode/uid/gid/mtime, gzip
-// mtime zeroed. Mirrors buildCanonicalTarGz in
-// sessions-api/src/v3/core/skill-bundle-canonical.ts.
+// TarGz packs a fileset into a gzip-compressed tar for upload. The tar is pure
+// TRANSPORT — the content address is the fileset Digest, which the server and
+// box re-derive from the UNPACKED bytes, so the tar does NOT need to be
+// canonical or byte-reproducible. We therefore use the standard library
+// (archive/tar) on both ends instead of a hand-rolled minimal ustar codec: the
+// reader handles whatever framing the writer emits (ustar or PAX for long
+// paths), so there is no matched-writer/reader pair to keep in lockstep.
//
-// The tar bytes are NOT the content address — the digest is over the fileset
-// (Digest), and the server re-derives it from the UNPACKED bytes with its own
-// minimal POSIX-ustar reader (adapter-core parseTar). This writer emits exactly
-// what that reader consumes: typeflag '0' regular files, ustar name/prefix split
-// for long paths, octal numeric fields. No PAX/GNU extensions (Go's archive/tar
-// would add extension records the minimal reader can't parse), which is why this
-// is hand-rolled.
-func CanonicalTarGz(files []File) ([]byte, error) {
- sorted := append([]File(nil), files...)
- sort.Slice(sorted, func(i, j int) bool { return sorted[i].Path < sorted[j].Path })
-
- var tar bytes.Buffer
- for _, f := range sorted {
- hdr, err := tarHeader(f.Path, f.Mode, len(f.Content))
- if err != nil {
+// ModTime is pinned to the epoch so repeated packs of the same input are stable
+// (nice for caching/diffing), but nothing depends on it.
+func TarGz(files []File) ([]byte, error) {
+ var buf bytes.Buffer
+ zw := gzip.NewWriter(&buf)
+ tw := tar.NewWriter(zw)
+ for _, f := range files {
+ if err := tw.WriteHeader(&tar.Header{
+ Name: f.Path,
+ Mode: int64(f.Mode),
+ Size: int64(len(f.Content)),
+ Typeflag: tar.TypeReg,
+ ModTime: time.Unix(0, 0),
+ }); err != nil {
return nil, err
}
- tar.Write(hdr)
- tar.Write(f.Content)
- if pad := (512 - (len(f.Content) % 512)) % 512; pad > 0 {
- tar.Write(make([]byte, pad))
+ if _, err := tw.Write(f.Content); err != nil {
+ return nil, err
}
}
- tar.Write(make([]byte, 1024)) // two zero blocks = end of archive
-
- var gz bytes.Buffer
- zw, err := gzip.NewWriterLevel(&gz, gzip.BestCompression)
- if err != nil {
- return nil, err
- }
- zw.ModTime = time.Time{} // zero → gzip MTIME field written as 0 (determinism)
- if _, err := zw.Write(tar.Bytes()); err != nil {
+ if err := tw.Close(); err != nil {
return nil, err
}
if err := zw.Close(); err != nil {
return nil, err
}
- return gz.Bytes(), nil
-}
-
-// tarHeader builds a 512-byte POSIX ustar header for a regular file with
-// uid/gid/mtime = 0 (deterministic). Matches tarHeader in skill-bundle-canonical.ts.
-func tarHeader(path string, mode, size int) ([]byte, error) {
- buf := make([]byte, 512)
- pathBytes := []byte(path)
- if len(pathBytes) <= 100 {
- copy(buf[0:100], pathBytes)
- } else {
- // ustar name(100)/prefix(155) split: cut at a '/' in the last 100 bytes.
- cut := -1
- for i := len(pathBytes) - 100; i < len(pathBytes); i++ {
- if pathBytes[i] == '/' {
- cut = i
- break
- }
- }
- if cut < 0 || cut > 155 {
- return nil, fmt.Errorf("path too long for tar: %q", path)
- }
- copy(buf[0:100], pathBytes[cut+1:]) // name
- copy(buf[345:500], pathBytes[:cut]) // prefix
- }
- writeOctal(buf, 100, 8, mode&0o7777)
- writeOctal(buf, 108, 8, 0) // uid
- writeOctal(buf, 116, 8, 0) // gid
- writeOctal(buf, 124, 12, size)
- writeOctal(buf, 136, 12, 0) // mtime
- for i := 148; i < 156; i++ {
- buf[i] = ' ' // checksum field = spaces while summing
- }
- buf[156] = '0' // typeflag '0' (regular file)
- copy(buf[257:263], "ustar\x00") // magic
- copy(buf[263:265], "00") // version
-
- sum := 0
- for i := 0; i < 512; i++ {
- sum += int(buf[i])
- }
- cs := padOctal(sum, 6)
- copy(buf[148:154], cs) // 6 octal digits
- buf[154] = 0
- buf[155] = ' '
- return buf, nil
-}
-
-// writeOctal writes value as octal into buf[off:off+length): (length-1)
-// zero-padded digits, then a NUL. Matches writeOctal in the TS canonicalizer.
-func writeOctal(buf []byte, off, length, value int) {
- s := padOctal(value, length-1)
- copy(buf[off:off+length-1], s)
- buf[off+length-1] = 0
-}
-
-// padOctal renders value in octal, left-padded with '0' to at least width digits.
-func padOctal(value, width int) string {
- s := strconv.FormatInt(int64(value), 8)
- for len(s) < width {
- s = "0" + s
- }
- return s
+ return buf.Bytes(), nil
}
diff --git a/cmd/oc/internal/filesetdigest/testdata/golden-fileset.json b/cmd/oc/internal/filesetdigest/testdata/golden-fileset.json
index 69d5d9c9..97a35569 100644
--- a/cmd/oc/internal/filesetdigest/testdata/golden-fileset.json
+++ b/cmd/oc/internal/filesetdigest/testdata/golden-fileset.json
@@ -1,6 +1,6 @@
{
- "note": "Shared golden vector for the OpenComputer bundle fileset digest (flue-slice.md contract 4). The fileset digest over RAW file bytes MUST equal `digest` in all implementations: cmd/oc filesetdigest (Go), sessions-api skill-bundle-canonical.ts (computeFilesetDigestRaw), oc-runtimes adapter-core skills.ts. `mode` is decimal (0o644=420, 0o755=493). `contentBase64` is base64 of the RAW file bytes — the fileset INCLUDES a binary PNG (skills/triage/logo.png), so any impl that decodes to a utf8 string before hashing diverges (finding #13). `canonicalTarGzBase64` is a reference canonical tar.gz — gzip framing is implementation-specific and NOT a byte-level golden; use it only to verify parseTar(gunzip(x)) recomputes `digest`.",
- "digest": "sha256:fbea3c2455fbec53f75b474924fe38e7e0fc20a67cd69a7942bd5670bc25b501",
+ "note": "Shared golden vector for the OpenComputer bundle fileset digest (flue-slice.md contract 4, sha256 scheme). The fileset digest over RAW file bytes MUST equal `digest` in all implementations: cmd/oc filesetdigest (Go), sessions-api skill-bundle-canonical.ts (filesetDigest), oc-runtimes adapter-core skills.ts. Pre-image = u32be(count) then per entry (sorted by UTF-8 path bytes) sha256(content)[32] ‖ u32be(mode) ‖ u32be(len(path)) ‖ path_utf8; digest = 'sha256:' + hex(sha256(preimage)). `mode` is decimal (0o644=420, 0o755=493). `contentBase64` is base64 of the RAW file bytes — the fileset INCLUDES a binary PNG (skills/triage/logo.png), so any impl that decodes to a utf8 string before hashing diverges. Transport is a plain (non-canonical) tar.gz — the digest is over the unpacked fileset, so no tar bytes are pinned here.",
+ "digest": "sha256:cab805ea6500039cdd09da801f90b1d6aff177710f106acc647a875c2dcdceea",
"files": [
{
"path": "artifact.json",
@@ -27,6 +27,5 @@
"mode": 420,
"contentBase64": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
}
- ],
- "canonicalTarGzBase64": "H4sIAAAAAAACE+2XT0vDMBTAMxCRyvDkxYtdvbr2pesfmHhQJlocY6h3rTVbO2sykk4mIojoYeAX8eJn8ODdu5/Fg3QexIJ4WlCXH4SEB+Fd3u/lJeRZ0gmjzOwJRtFkAADwHGe8A0BxB3C8z3Mex+DUXKQDksBAZCFHICXXL+TSIDTjF0bdYJHZE8aq0eesk6Tk8JxwkTBq1PGVhhT/lOOEWnxATRFPLkcute+63/tv21/9B99zbeW/DFYqVl4CItZIFDM9TpTrU8W46084x4/vv+0U/Pd8AOW/DMiwz3imR4yKTB/q6zpeUx1gihCnSZoKK+NJ2CXW/m7QbJpnJ5L9r9UK8z/2sZr/pVCtVjUanpG6/lECWh6ISZoy1Qamz/+UdZnZp125/mMo/v9t7DnKfxmM2q3tsraUy14Odhp7CKFSvuZmEULLi88jhNB80Ng4GL5Gby9P7QU0c1e6vn24r+S3g61W43Hz6EZ5pFAoFH+Nd1JcnEEAGAAA"
+ ]
}