November 29, 2026
Amazing Stories, May 1939 (Volume 13, Number 5). The issue contains a story about a future civilization discovering records deliberately preserved by an earlier generation for its descendants. The story specifically describes scientific and cultural knowledge reduced to microfilm and stored in a time capsule. A future person discovers these records and reads about the achievements of the earlier civilization, including Einstein, Darwin and scientific theories. The story is particularly interesting because it is not simply about discovering an ancient civilization. It is about the preservation of knowledge as a gift to the future. The fictional discovery is based on a real historical event: the Westinghouse Time Capsule buried at the 1939 New York World’s Fair, intended to be opened 5,000 years later. The capsule really did contain microfilm and examples of contemporary technology and culture.
BuriedBits research project: laboratory notebook. Technical record of tests, commands, responses, observations and conclusions. Raw evidence is kept in ~/buriedbits/cdx/raw/ (\\wsl.localhost\Ubuntu\home\alex\buriedbits\cdx\raw)
Tools like wayback_machine_downloader are the usual way to pull a site out of the Wayback Machine, and they work. You give one a website, it asks the Archive for a list of everything saved, then fetches the files and rebuilds the folders on your disk. Our method uses the same source (the Archive’s saved copies; nothing crawls the original sites). What differs is what happens around the download:
--all adds errors, redirects and empty files). We found real software recorded without any status (about 500 addresses on this one site). The README does not say whether --all picks those up, and we have not tested it.What we have not shown: that the method recovers more or better files in practice. So far we’ve downloaded two. A side-by-side test on one folder is the fair comparison, and it’s still to do.
This is the script used in earlier work (wayback.sh, run on a Mac). It reads a list of sites, one per line, and runs the downloader on each. It worked well overall, but some downloads were not the expected size. We have no measurements of its completeness or accuracy, and the cause of the size differences is unknown.
#!/bin/bash
#This script will use a file populated with a list of URLs as an input file and replace the $line with a URL.
# The file filled with URLs in this case is being read by the loop below, via input.file.
while read -r line
# The loop starts with while read -r line In this case, line will refer to each line (a URL) in your file.
# The loop then runs wayback_machine_downloader ... "$line", which means it's running the command against the URL line from your file.
do
wayback_machine_downloader -a -d "$line"_IA -c1 --only "/\.(sit|sea|img|smi|hqx|bin|pkg|cpt|dd|pit)$/i" "$line"
done < /Users/admin/Desktop/_IA/URLs2.txt
# add to tail if you want a log file
# | tee -a log.txt
# *************The final line done < input.file is what's providing your file to the loop. You can replace input.file with the actual path of your file.
What the options do (per the downloader’s README; the version used may differ):
-d: the folder to save into (here, named after the site plus _IA).-c1: one download at a time.-a (--all): also include error and redirect responses and keep empty files, as well as normal “200 OK” captures.--only: keep only addresses matching the pattern, here a list of Mac file extensions.Hypothesis (untested): because -a keeps error pages, redirects and empty files, some saved “files” may have been error pages or zero-byte files, which could explain wrongly sized downloads. Checking an old download folder for tiny or empty files would test this.
Entry numbering: M001, M002… are milestones. T entries are experiments (a command was run and its output recorded). D entries are desk research (documentation or web searches; no experiment). Entries are numbered in order within each milestone, and D entries apply to the milestone they are filed under and to later ones.S entries record tools and scripts: the frozen source, what it does, and how it was tested.
BuriedBits research project: recovering historical software from the Wayback Machine.
This is the laboratory notebook for a research project. The aim is a repeatable, respectful method for discovering historical software (initially classic Macintosh files) in the Internet Archive’s Wayback Machine, using its CDX index to find candidates before anything is downloaded. Discovery and retrieval are deliberately separate steps.
Working principles
raw/).Where we are (status as of 2026 – 11-28) Milestone 001 (M001-T01 to T21, plus D01 and D02) is closed. Tested against one host, archive.info-mac.org, and one file family (mostly .hqx), we found that:
unk and status -), and the length field is not the file size.Not yet done: paged discovery of all captures, the SQLite catalogue, any bulk download, and testing on other hosts or file types. Figures are working estimates unless an entry says otherwise.
How to read this file: entries are numbered in order. Each records the command, result, observations and any corrections to earlier entries. This introduction will be rewritten as the experiments conclude.
Working folder (always the Linux side, never /mnt/c):
~/buriedbits/cdx/raw (full path /home/alex/buriedbits/cdx/raw)\\wsl.localhost\Ubuntu\home\alex\buriedbits\cdx\rawcd ~/buriedbits/cdx/raw && pwd && ls | tail
raw/m002-all-rows.tsv: all 45,089 discovered rows as one tab-separated table (timestamp, original, mimetype, status, digest, length), built from m002-pages/. Also census-triples.tsv, gap-triples.tsv, paged-triples.tsv: derived lists used for the completeness check (M002-T07).~/buriedbits/cdx/build_catalogue.py: catalogue importer (see M003-S01). Run: python3 ~/buriedbits/cdx/build_catalogue.py --host <site> --extensions <list> --pages <folder>~/buriedbits/cdx/catalogue.sqlite: the catalogue. It can always be rebuilt from the saved pages, except for the downloads table, which records download progress and should be kept.Design rule: files are kept exactly as downloaded. A little preamble here: The tool never decodes, unpacks, renames, or converts a file. A .hqx for example, stays a .hqx, verified against the Archive’s digest, because that is the form from which the original Mac file can be faithfully restored. Decoding on a modern system (Linux, Windows, or anything beyond Mac OS 9 or the Classic Environment in early Mac OS X (10.0 – 10.4), which allowed older Mac OS 9 applications to run within Mac OS X by essentially launching the Mac OS 9 system environment alongside OS X on PowerPC Macs) can result in the loss of the Mac’s two-part file structure (data fork and resource fork). Anyone who wants to inspect a file should do so on a copy, never in the download folder.
The downloader only retrieves and verifies files. It never opens them. To look inside one, this project uses unar, a free command-line tool from The Unarchiver project. It opens many old archive formats, including the two this project mostly deals with.
BinHex 4.0 (.hqx). Classic Mac files could not be sent safely over early internet and email systems, which handled only plain text. BinHex wraps a Mac file as plain text so it survives the trip. The file starts with the line (This file must be converted with BinHex 4.0), followed by lines of encoded text. Decoding reverses this and restores the original Mac file.
StuffIt (.sit). The common compression format on the classic Mac, comparable to what .zip is elsewhere. Info-Mac files are often a StuffIt archive that has been wrapped in BinHex, so a .hqx can contain a .sit.
Two forks. A classic Mac file has two parts: a data fork (the ordinary content) and a resource fork (menus, icons, dialogs, and often the program code itself). Other systems have no equivalent, which is another reason BinHex was needed. After decoding you may find a data file, a separate resource file, or only one of them. A very small or odd-looking result is not a sign that the download failed; the digest check already tells us the file arrived intact.
Installing and using it (Ubuntu / WSL):
sudo apt install unar
mkdir -p ~/buriedbits/cdx/test-decode && cd ~/buriedbits/cdx/test-decode
unar -o . ~/buriedbits/cdx/files/AXNRETBF*/eudora-direct-unix-navs-halcyon.hqx
ls -la
Decoding is optional and happens in a separate folder (test-decode). It never changes the verified files in ~/buriedbits/cdx/files/, which stay exactly as downloaded.
Notes file: path: C:\Users\Alex\Sites\Blot\Posts\_CDX_API_Compatibility_Notes.md relative path: Blot\Posts\_CDX_API_Compatibility_Notes.md
File naming in raw/:
mNNN-tNN-headers.txt / mNNN-tNN-body.*: raw response headers and body for each test (the “evidence”).m001-t10-body.json: the master census (29,273 URLs with fields original, timestamp, digest, length). Do not re-request it.m001-t20-body.json: the 672-row gap (non-200, non-revisit).census-digests.txt, gap-*.txt / .tsv: derived lists made locally from those files.m001-t20-bscan-2.hqx and m001-t20-fat-tracker-40.hqx: the two files downloaded in T21 (named t20 because they were saved before the entry was renumbered).x-nid line showing the ISP. Redact it before publishing anything.Discovery script and its output (Milestone 002):
~/buriedbits/cdx/m002-discover.sh: the paged discovery script. A frozen copy is in entry M002-S01 below. Pilot run: cd ~/buriedbits/cdx/raw && MAX_PAGES=1 ~/buriedbits/cdx/m002-discover.shraw/m002-pages/page-NNNN.json: one saved response per request (evidence; never edit or delete). The script’s only state is these files, so after a break, just re-run it and it continues. Deleting the last page makes it request that page again.raw/m002-pages/page-NNNN.headers.txt: that request’s response headers (redact x-nid before publishing).raw/m002-pages/m002-log.txt: one line per request (time, status, rows, bytes). The folder is created on the first run.Tools: WSL Ubuntu with curl, jq, python3. Check with curl --version | head -1; jq --version.
Resuming after a break
cd ~/buriedbits/cdx/rawWayback Machine. The Internet Archive’s collection of saved copies of web pages and files, taken at many points in time.
Capture. One saved copy of one address at one moment. The same file can have many captures, because the Archive may visit an address many times.
CDX API. The Archive’s search index of captures. It answers questions like “list every capture under this website that ends in .hqx”. It lists what exists and does not return the files themselves.
Timestamp. The date and time of a capture, written as YYYYMMDDhhmmss (for example 20130817190433).
Digest. A fingerprint of a file’s contents, computed by the Archive (base32 SHA-1). Two captures with the same digest hold identical bytes, so the digest identifies a file independently of its address, and lets us check that a download is exactly what the Archive holds.
Status code. The server’s one-number reply when asked for something. 200 means “here it is”; 301/302 mean “it has moved, look elsewhere”; 404 means “not found”; 429 means “too many requests, slow down”; 503 means “temporarily unavailable”. Our tools stop at the first reply that isn’t 200 and don’t retry.
Redirect (301/302). A reply that points to another address and carries no file. Tools that save every reply as a file can end up with a tiny file that is only the “moved” note.
Replay URL. The Archive’s address for viewing a capture. Adding id_ after the timestamp (/web/<timestamp>id_/<address>) returns the original bytes with no Wayback additions.
Revisit. A capture that is only a pointer saying “this is the same content as an earlier capture”. It holds no file of its own, and in our test the pointer did not replay as a file.
Record length. The size of the Archive’s stored record for a capture, as listed in the CDX index. It is not the file size. In our tests it is about 0.76 of the real size, probably because it is stored compressed.
Catalogue. Our own database (catalogue.sqlite) that turns the raw list of captures into a list of distinct files, with one row per digest.
Verdict. The catalogue’s classification of each distinct file: candidate (worth downloading), revisit_only (pointer only), not_a_file (only redirects or errors), or empty.
Resume key. A marker the CDX API returns with a page of results, which we send back to get the next page. It lets the Archive give long result lists in small pieces, so we can go slowly.
BinHex (.hqx). A plain-text wrapping that let classic Mac files travel safely over early internet systems. We keep these files exactly as downloaded.
StuffIt (.sit). The common compression format on the classic Mac, comparable to .zip.
Data fork / resource fork. The two parts of a classic Mac file: ordinary content, and structured resources such as icons, menus and often the program code itself. Modern systems have no equivalent, which is why files are not decoded here.
Census. The first count of what exists: a single query to the CDX index listing one line per address for the file types we were after. It gave a rough size for the collection (29,273 addresses for Info-Mac) before we did the slower, complete discovery. The later full discovery found captures that the census had not listed, which is why we compared the two.
Each line below is one experiment (M001-T01 onward). It states the question we asked and the short answer we got. Click the triangle to open an entry and see the exact command, the evidence file, what we observed and our conclusion. T entries are experiments we ran. D entries are desk research: what the documentation says.
Date: 2026 – 11-26 Tools: curl 8.18.0, jq 1.8.2 (WSL) Evidence: raw/m001-t01-headers.txt, raw/m001-t01-body.txt
Command
curl -sG 'https://web.archive.org/cdx/search/cdx' \
--data-urlencode 'url=archive.info-mac.org' \
--data-urlencode 'limit=5' \
-D m001-t01-headers.txt -o m001-t01-body.txt
Result: HTTP/2 200, content-type text/plain, 5 lines.
Observations
org,info-mac,archive)/); it groups :80 and non-:80 variants of the same URL.url= matched only the root URL /.server-timing: exclusion.robots; robots exclusion is evidently checked.Conclusion: Endpoint reachable; format as hypothesised. Wildcard/prefix matching still untested. Redaction note: strip x-nid header before publishing.
Date: 2026 – 11-26 Tools: curl 8.18.0, jq 1.8.2 (WSL) Evidence: raw/m001-t02-headers.txt, raw/m001-t02-body.json
Command
curl -sG 'https://web.archive.org/cdx/search/cdx' \
--data-urlencode 'url=archive.info-mac.org' \
--data-urlencode 'limit=5' \
--data-urlencode 'output=json' \
-D m001-t02-headers.txt -o m001-t02-body.json
jq 'length' m001-t02-body.json
Result: HTTP/2 200. jq 'length' returned 6 (1 header row + 5 records).
Observations
output=json returns an array of arrays; row 0 is the field names, rows 1 – 5 are records.jq 'length' minus 1.length is compressed record size or original body size.Conclusion: JSON output works as hypothesised and is the better format for scripting. Use output=json from here on, keeping the plain-text default for quick eyeballing.
/*) with limit=5, inconclusive/* wildcard list the URLs below the root? Inconclusive: limit=5 never got past the root page.
Date: 2026 – 11-26 Tools: curl 8.18.0, jq 1.8.2 (WSL) Evidence: raw/m001-t03-headers.txt, raw/m001-t03-body.json
Command
curl -sG 'https://web.archive.org/cdx/search/cdx' \
--data-urlencode 'url=archive.info-mac.org/*' \
--data-urlencode 'limit=5' \
--data-urlencode 'output=json' \
-D m001-t03-headers.txt -o m001-t03-body.json
jq 'length' m001-t03-body.json
Result: HTTP/2 200. jq 'length' returned 6 (1 header + 5 records). Records identical to T01/T02 (root URL only).
Observations
/. It did not./ has at least 5 captures, so limit=5 is exhausted before any other URL.Conclusion: Inconclusive. Repeat with collapse=urlkey and a larger limit (M001-T04) so each URL is counted once. Lesson: when results are sorted, a small limit can hide everything but the first URL. Design tests that can show a difference.
collapse=urlkey; but root-page variants crowd the early results.
Date: 2026 – 11-26 Tools: curl 8.18.0, jq 1.8.2 (WSL) Evidence: raw/m001-t04-headers.txt, raw/m001-t04-body.json
Command
curl -sG 'https://web.archive.org/cdx/search/cdx' \
--data-urlencode 'url=archive.info-mac.org/*' \
--data-urlencode 'limit=10' \
--data-urlencode 'collapse=urlkey' \
--data-urlencode 'output=json' \
-D m001-t04-headers.txt -o m001-t04-body.json
jq 'length' m001-t04-body.json
Result: HTTP/2 200. jq 'length' returned 11 (1 header + 10 records), all distinct urlkeys.
Observations
/* works: it returns URLs beyond the exact root. This resolves T03.?C=D;O=A etc.): Apache directory-listing sort links. No file paths reached yet.original preserves case. Use (?i) for extension regexes.__cf_chl_tk), status 403, length 5369. Not real site content. Supports keeping statuscode:200.? sorts after /, so path-based URLs come later in the list.Conclusion: Wildcard matching confirmed. Root-page query variants crowd the early results, so a filter on original is needed to reach files.
.sit|.hqx).hqx files (Disinfectant, Gatekeeper and others).
Date: 2026 – 11-26 Tools: curl 8.18.0, jq 1.8.2 (WSL) Evidence: raw/m001-t05-headers.txt, raw/m001-t05-body.json
Command
curl -sG 'https://web.archive.org/cdx/search/cdx' \
--data-urlencode 'url=archive.info-mac.org/*' \
--data-urlencode 'filter=original:(?i).*\.(sit|hqx)$' \
--data-urlencode 'limit=10' \
--data-urlencode 'collapse=urlkey' \
--data-urlencode 'output=json' \
-D m001-t05-headers.txt -o m001-t05-body.json
jq 'length' m001-t05-body.json
Result: HTTP/2 200. jq 'length' returned 11 (1 header + 10 records). All 10 are .hqx files under /_Anti-Virus/, status 200.
Observations
filter=original: with a Java-style regex works, including (?i) and the $ anchor.application/mac-binhex40 on all rows.length ranges from 5,969 to 3,436,668. Still unknown whether this is compressed or original size (see T02)..sit rows in the first 10: expected from alphabetical sort, not evidence that none exist.Conclusion: Hypothesis supported: CDX can discover software files by extension in this archive. Results are limited by sort order and limit; need pagination or narrower queries to see the full population. Open: length semantics; whether .sit/.sitx/.sea exist here; total count.
Date: 2026 – 11-26 Tools: curl 8.18.0 (WSL) Evidence: raw/m001-t06-headers.txt, raw/m001-t06-body.txt
Command
curl -sG 'https://web.archive.org/cdx/search/cdx' \
--data-urlencode 'url=archive.info-mac.org/*' \
--data-urlencode 'filter=original:(?i).*\.(sit|hqx)$' \
--data-urlencode 'collapse=urlkey' \
--data-urlencode 'showNumPages=true' \
-D m001-t06-headers.txt -o m001-t06-body.txt
Result: HTTP/2 200. Body: 13.
Observations
filter/collapse, so 13 describes the whole archive.info-mac.org/* range, not the matches.Conclusion: Inconclusive on population size. Repeat without filter/collapse (M001-T07) to see whether the number changes. Open: page size; whether filters affect page count; how pagination (page=) combines with filter.
Date: 2026 – 11-26 Tools: curl 8.18.0 (WSL) Evidence: raw/m001-t07-headers.txt, raw/m001-t07-body.txt
Command
curl -sG 'https://web.archive.org/cdx/search/cdx' \
--data-urlencode 'url=archive.info-mac.org/*' \
--data-urlencode 'showNumPages=true' \
-D m001-t07-headers.txt -o m001-t07-body.txt
Result: HTTP/2 200. Body: 13 (identical to T06).
Observations
filter and collapse: it is computed from the URL range, before filtering..sit/.hqx files exist.Conclusion: T06 hypothesis confirmed. To count matches we must fetch results and count rows. Open: page size; behaviour of page= combined with filter; total number of matching URLs.
.hqx, 2 .sit), about three times the expected 9,000.
Date: 2026 – 11-26 Tools: curl 8.18.0, jq 1.8.2 (WSL) Evidence: raw/m001-t08-headers.txt, raw/m001-t08-body.json (2,058,299 bytes)
Command
curl -sG 'https://web.archive.org/cdx/search/cdx' \
--data-urlencode 'url=archive.info-mac.org/*' \
--data-urlencode 'filter=statuscode:200' \
--data-urlencode 'filter=original:(?i).*\.(sit|sitx|hqx|sea)$' \
--data-urlencode 'collapse=urlkey' \
--data-urlencode 'fl=original' \
--data-urlencode 'output=json' \
-D m001-t08-headers.txt -o m001-t08-body.json
jq 'length' m001-t08-body.json
jq -r '.[1:][] | .[0]' m001-t08-body.json | sed -E 's/.*\.([A-Za-z]+)$/\L\1/' | sort | uniq -c
Result: HTTP/2 200, single request, no limit. jq 'length' = 29274 (1 header + 29,273 records). Extension tally: hqx 29,271; sit 2; sitx 0; sea 0.
Observations
.sit.hqx), so the final extension is .hqx. Untested..sitx or .sea URLs under this host with status 200.Corrections to earlier entries
Conclusion: CDX can enumerate the archive’s software files in one request. Next analysis is local (no further requests). Open: meaning of the 29k vs 9k discrepancy; .sit.hqx share; directory distribution; duplicate digests; length semantics; capture history.
Date: 2026 – 11-26 Tools: jq 1.8.2, grep, awk (WSL). No requests to archive.org. Evidence: raw/m001-t08-urls.txt (derived from m001-t08-body.json; 29,273 lines)
Command
jq -r '.[1:][] | .[0]' m001-t08-body.json > m001-t08-urls.txt
wc -l m001-t08-urls.txt
grep -ci '\.sit\.hqx$' m001-t08-urls.txt # also .cpt.hqx, .sea.hqx, .bin.hqx
grep -i '\.sit$' m001-t08-urls.txt
awk -F/ '{print $4}' m001-t08-urls.txt | sort | uniq -c | sort -rn | head -20
Result: 29,273 lines. Double extensions: .sit.hqx 7; .cpt.hqx 0; .sea.hqx 0; .bin.hqx 0. Top-level directories (top 20): _Communication 3157, _Game 2527, game 2371, comm 1899, dev 1561, _User_Interface 1273, _Internet 1252, _Development 1226, inet 1082, gui 1028, Graphic&_Sound_Tool 1024, _Application 739, _Text_Processing 674, app 667, cfg 613, _Configuration 583, gst 578, Art&_Info 568, art 534, text 515.
Observations
.sit.hqx URLs: most .hqx files are plain name.hqx._Game/game, _Communication/comm, _Development/dev, _User_Interface/gui, _Internet/inet, _Graphic_&_Sound_Tool/gst, _Application/app, _Configuration/cfg, _Text_Processing/text, _Art_&_Info/art)..sit URLs are the same filename under both schemes (_Game/_Cards/ and game/crd/), one on http and one on https.Corrections to earlier entries
.sit.hqx is refuted (7 of 29,273). The 29k vs 9k discrepancy now has a candidate explanation (duplicate trees), not yet verified.Conclusion: The 29,273 count is a count of URLs, not necessarily of distinct files. Digest comparison is needed before treating it as a file count. Open: distinct digests; which files exist in both trees; length semantics; capture history; the full directory list.
Date: 2026 – 11-26 Tools: curl 8.18.0, jq 1.8.2, sort, uniq, awk (WSL) Evidence: raw/m001-t10-headers.txt, raw/m001-t10-body.json (3,834,175 bytes)
Command
curl -sG 'https://web.archive.org/cdx/search/cdx' \
--data-urlencode 'url=archive.info-mac.org/*' \
--data-urlencode 'filter=statuscode:200' \
--data-urlencode 'filter=original:(?i).*\.(sit|sitx|hqx|sea)$' \
--data-urlencode 'collapse=urlkey' \
--data-urlencode 'fl=original,timestamp,digest,length' \
--data-urlencode 'output=json' \
-D m001-t10-headers.txt -o m001-t10-body.json
jq -r '.[1:][] | .[2]' m001-t10-body.json | sort -u | wc -l
jq -r '.[1:][] | .[2]' m001-t10-body.json | sort | uniq -c | awk '{print $1}' | sort -n | uniq -c
Result: HTTP/2 200. jq 'length' = 29274 (29,273 records). Distinct digests: 9,145.
| URLs per digest | Digests |
|---|---|
| 1 | 72 |
| 2 | 4,412 |
| 3 | 1,708 |
| 4 | 1,295 |
| 5 | 826 |
| 6 | 466 |
| 7 | 257 |
| 8 | 2 |
| 10 | 2 |
| 11 | 13 |
| 12 | 44 |
| 13 | 47 |
| 30 | 1 |
Histogram reconciles: 9,145 digests, 29,273 URLs.
Observations
csmp-digest-v3-121.hqx) has six paths: _Development/_Information/_C.S.M._Programmer/, _Information/_Development/_C.S.M._Programmer/, _Periodical/csmp/, dev/info/_C.S.M._Programmer/, info/_Development/_C.S.M._Programmer/, per/_C.S.M._Programmer/.info/_Development).Corrections to earlier entries
Conclusion: The census is 29,273 URLs but about 9,145 distinct files. Retrieval should be planned per digest, with one canonical URL chosen for each. Open: the 30-path digest; length semantics; capture years; whether one digest ever has differing lengths; how to choose the canonical URL; capture history beyond the first capture.
length? One digest covers 30 addresses (probably a stub), nearly all captures date from 2014 – 2015, and length is not the file size.
Date: 2026 – 11-26 Tools: jq 1.8.2, sort, uniq, awk (WSL). No requests to archive.org. Evidence: raw/m001-t10-body.json (analysed locally)
Command
d=$(jq -r '.[1:][] | .[2]' m001-t10-body.json | sort | uniq -c | awk '$1==30{print $2}')
jq -r --arg d "$d" '.[1:][] | select(.[2]==$d) | .[0]' m001-t10-body.json
jq -r '.[1:][] | .[1][0:4]' m001-t10-body.json | sort | uniq -c
jq -r '.[1:] | unique_by(.[2]) | map(.[3]|tonumber) | sort | "min \(.[0]) median \(.[length/2|floor]) max \(.[-1]) total \(add)"' m001-t10-body.json
jq -r '.[1:] | group_by(.[2]) | map(map(.[3]) | unique | length) | map(select(.>1)) | length' m001-t10-body.json
Result
Observations
length is not file size and not comparable between URLs.Corrections to earlier entries
length is not the original file size; it varies for identical content. Probably the stored record size including headers. Not verified.length should not be used as file size anywhere.Conclusion: Use digest for identity and a HEAD request or download for real size. Any digest with a tiny length needs inspection before it counts as software. Open: how many digests are tiny stubs; what the 462-byte body contains; the 2022 – 2025 captures; capture history beyond the first capture; choosing the canonical URL per digest.
Date: 2026 – 11-26 Tools: jq 1.8.2 (WSL). No requests to archive.org. Evidence: raw/m001-t10-body.json (analysed locally)
Command
jq -r '.[1:] | unique_by(.[2]) | map({d:.[2], l:(.[3]|tonumber), u:.[0]}) | sort_by(.l) | .[0:15][] | "\(.l) \(.d) \(.u)"' m001-t10-body.json
jq -r '.[1:] | unique_by(.[2]) | map(select((.[3]|tonumber) < 1000)) | length' m001-t10-body.json
jq -r '.[1:][] | select(.[1][0:4] | tonumber >= 2022) | "\(.[1]) \(.[3]) \(.[0])"' m001-t10-body.json | head -20
Result
eudora-unix-navs.hqx etc.).-src, -rsrc, -ext files.Observations
Corrections to earlier entries
Conclusion: Stub contamination is limited. The capture-history question is now the main unknown, since collapse=urlkey hides it. Open: which capture collapse=urlkey keeps; whether 2022+ URLs have earlier captures; the content of the 462-byte stub; the remaining 99 post-2022 URLs.
- captures, revisit pointers and one identical digest from 2014 to 2025, so the status-200 filter was too strict.
Date: 2026 – 11-26 Tools: curl 8.18.0 (WSL) Evidence: raw/m001-t13-body.txt (response bodies only, three URLs concatenated; separators and headers were not saved)
Command
for u in \
'archive.info-mac.org/_Anti-Virus/bscan-2.hqx' \
'archive.info-mac.org/_Application/fat-tracker-40.hqx' \
'archive.info-mac.org/_Communication/inet/mac-waveout-14b5.hqx'
do
curl -sG 'https://web.archive.org/cdx/search/cdx' \
--data-urlencode "url=$u" \
--data-urlencode 'fl=timestamp,original,mimetype,statuscode,digest,length' \
| tee -a m001-t13-body.txt
sleep 2
done
Result (no filter, no collapse; timestamp / scheme / mimetype / status / digest / length)
bscan-2.hqx
20140910233300 http application/mac-binhex40 200 WSRZN4CU... 386423
20220717115553 https warc/revisit - WSRZN4CU... 586
20250309230727 https application/mac-binhex40 200 WSRZN4CU... 494231
fat-tracker-40.hqx
20140910233250 http unk - AAYRM7WH... 4792982
20150320181528 http warc/revisit - AAYRM7WH... 526
20220717115614 https application/mac-binhex40 200 AAYRM7WH... 4792888
mac-waveout-14b5.hqx (the 462-byte stub digest)
20150320182058 http application/mac-binhex40 200 3I42H3S6... 462
Observations
fat-tracker-40.hqx has a 2014 capture with mimetype unk and status -.warc/revisit rows have status -, length 526 – 586 and the same digest as an original capture.length is not a content size. The 108 KB gap is unexplained.- and mimetype unk come from older or incomplete capture metadata, not failed downloads.Corrections to earlier entries
-.--only URLs would push it up.unk.length is a record size (supported by T13); revisit records have very small lengths.Conclusion: The status-200 filter is too strict for a complete census, and capture status needs to be examined directly before choosing which capture to retrieve. Revisit records are not downloadable files in their own right. Open: how many URLs have no status-200 capture; whether status-- captures replay correctly; which capture collapse=urlkey keeps; what the 462-byte stub contains.
collapse=urlkey keep? The earliest one that passes the filters, judging from two URLs, so the census is not a capture history.
Date: 2026 – 11-26 Tools: jq 1.8.2 (WSL). No requests to archive.org. Evidence: raw/m001-t10-body.json (analysed locally)
Command
jq -r '.[1:][] | select(.[0] | test("/_Anti-Virus/bscan-2[.]hqx$|/_Application/fat-tracker-40[.]hqx$|/mac-waveout-14b5[.]hqx$")) | "\(.[1]) \(.[0]) \(.[3])"' m001-t10-body.json
Result (timestamp, URL, recorded length)
20140910233300 .../_Anti-Virus/bscan-2.hqx 386423
20220717115614 .../_Application/fat-tracker-40.hqx 4792888
20150320182058 .../_Communication/inet/mac-waveout-14b5.hqx 462
20140911002432 .../_Communication/tcp/mac-waveout-14b5.hqx 605
20140911000718 .../_Internet/mac-waveout-14b5.hqx 602
20140911003045 .../comm/inet/mac-waveout-14b5.hqx 602
20140910235832 .../inet/mac-waveout-14b5.hqx 597
Observations
-) was excluded.mac-waveout-14b5.hqx are in the census, all under the 30-path digest. Their recorded lengths are 462, 605, 602, 602, 597.Corrections to earlier entries
Conclusion: The census is a list of URLs with a first status-200 capture, not a capture history. Any capture-level decision needs a query without collapse. Open: what the stub contains; how many URLs have no status-200 capture; whether status-- captures replay.
Date: 2026 – 11-26 Tools: curl 8.18.0, file, sha256sum (WSL) Evidence: raw/m001-t15-headers.txt, raw/m001-t15-body.bin (0 bytes)
Command
curl -sS -D m001-t15-headers.txt -o m001-t15-body.bin \
'https://web.archive.org/web/20150320182058id_/http://archive.info-mac.org/_Communication/inet/mac-waveout-14b5.hqx'
ls -l m001-t15-body.bin; file m001-t15-body.bin; sha256sum m001-t15-body.bin
Result: HTTP/2 200, content-type application/mac-binhex40, content-length 0. Body empty. SHA-256 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 (SHA-256 of empty input).
Observations
x-archive-orig-content-length: 0; original server Apache, last-modified 1999 – 02-26. The original file was zero bytes when captured.length is record overhead around an empty payload.id_ replay returns the raw payload with x-archive-orig-* headers preserved.x-archive-src names the source WARC (provenance).x-nid header present.Corrections to earlier entries
length includes capture overhead, confirmed by an empty file showing 462.Conclusion: A 200 status plus a CDX entry does not guarantee a usable file. The download tool needs a non-zero-size check. Open: whether the digest is the empty-content SHA-1; non-200 census gap; whether status - captures replay.
Date: 2026 – 11-26 Tools: python3, curl 8.18.0 (WSL) Evidence: raw/m001-t16-headers.txt, raw/m001-t16-body.txt
Command
python3 -c "import hashlib,base64;print(base64.b32encode(hashlib.sha1(b'').digest()).decode())"
curl -sG 'https://web.archive.org/cdx/search/cdx' \
--data-urlencode 'url=archive.info-mac.org/*' \
--data-urlencode 'filter=!statuscode:200' \
--data-urlencode 'filter=original:(?i).*\.(sit|sitx|hqx|sea)$' \
--data-urlencode 'fl=timestamp,original,mimetype,statuscode,digest,length' \
--data-urlencode 'limit=10' \
-D m001-t16-headers.txt -o m001-t16-body.txt
Result
3I42H3S6NNFQ2MSVX7XZKYAYSCX5QBYJ (equals the 30-path digest).!statuscode:200 returned 10 rows, all warc/revisit, status -, 2022 – 07-17, lengths 585 – 598, under /_Anti-Virus/.Observations
unk).Corrections to earlier entries
Conclusion: Validation must include: non-zero size, empty-digest check, size consistency per digest, and a SHA-256 recorded locally. Open: non-200 population (revisit vs other); whether unk/- originals replay; cause of previous wrong-size downloads; whether BinHex CRC checking is feasible.
Date: 2026 – 11-27 Tools: jq 1.8.2 (WSL). No requests to archive.org. Evidence: raw/m001-t10-body.json (analysed locally)
Command
jq -r '.[1:][] | select(.[2]=="3I42H3S6NNFQ2MSVX7XZKYAYSCX5QBYJ") | .[0]' m001-t10-body.json | wc -l
Result: 30.
Observations
Corrections to earlier entries
Conclusion: Empty files can be excluded using the CDX digest alone, before any download. Open: non-200, non-revisit population; whether unk/- originals replay; cause of earlier wrong-size downloads; BinHex CRC checking.
- and mimetype unk, which the census missed.
Date: 2026 – 11-27 Tools: curl 8.18.0 (WSL) Evidence: raw/m001-t18-headers.txt, raw/m001-t18-body.txt
Command
curl -sG 'https://web.archive.org/cdx/search/cdx' \
--data-urlencode 'url=archive.info-mac.org/*' \
--data-urlencode 'filter=!statuscode:200' \
--data-urlencode 'filter=!mimetype:warc/revisit' \
--data-urlencode 'filter=original:(?i).*\.(sit|sitx|hqx|sea)$' \
--data-urlencode 'fl=timestamp,original,mimetype,statuscode,digest,length' \
--data-urlencode 'limit=20' \
-D m001-t18-headers.txt -o m001-t18-body.txt
Result: HTTP/2 200, 20 rows. All mimetype unk, status -, captured 2014 – 09-11 00:40 – 00:45. Recorded lengths 4,044,285 to 13,850,702. Paths under /_Application/_Business_&_Finance/, /_Application/_Time_&_Date/, /_Application/bus/.
Observations
_Business_&_Finance/ and bus/), as in T10.Corrections to earlier entries
unk/- example (fat-tracker-40) is not an oddity; it is a class of captures.Conclusion: Capture status - with mimetype unk marks a class of real, large files that the status-200 filter excluded. The census undercounts. Open: size of the gap; whether unk/- captures replay correctly; whether any of these URLs also have a 200 capture.
Date: 2026 – 11-27 Tools: curl 8.18.0, jq 1.8.2, sort, comm (WSL) Evidence: raw/m001-t19-headers.txt, raw/m001-t19-body.json (67,878 bytes), raw/census-digests.txt, raw/gap-digests.txt
Command
curl -sG 'https://web.archive.org/cdx/search/cdx' \
--data-urlencode 'url=archive.info-mac.org/*' \
--data-urlencode 'filter=!statuscode:200' \
--data-urlencode 'filter=!mimetype:warc/revisit' \
--data-urlencode 'filter=original:(?i).*\.(sit|sitx|hqx|sea)$' \
--data-urlencode 'collapse=urlkey' \
--data-urlencode 'fl=original,digest' \
--data-urlencode 'output=json' \
-D m001-t19-headers.txt -o m001-t19-body.json
jq -r '.[1:][] | .[2]' m001-t10-body.json | sort -u > census-digests.txt
jq -r '.[1:][] | .[1]' m001-t19-body.json | sort -u > gap-digests.txt
comm -13 census-digests.txt gap-digests.txt | wc -l
Result: HTTP/2 200. jq 'length' = 673 (672 URLs). Distinct digests in the gap: 269. Gap digests not in the census: 173.
Observations
unk / -.Corrections to earlier entries
Conclusion: The status-200 census is a good but incomplete picture. A complete catalogue must include the non-200 captures, with capture status recorded per row. Open: status/mimetype mix of the 672 rows; size
- and mimetype unk), plus 180 redirects and server errors.
Date: 2026 – 11-27 Tools: curl 8.18.0, jq 1.8.2, awk (WSL) Evidence: raw/m001-t20-headers.txt, raw/m001-t20-body.json, raw/gap-by-digest.tsv, raw/gap-new.tsv
Command
curl -sG 'https://web.archive.org/cdx/search/cdx' \
--data-urlencode 'url=archive.info-mac.org/*' \
--data-urlencode 'filter=!statuscode:200' \
--data-urlencode 'filter=!mimetype:warc/revisit' \
--data-urlencode 'filter=original:(?i).*\.(sit|sitx|hqx|sea)$' \
--data-urlencode 'collapse=urlkey' \
--data-urlencode 'fl=timestamp,original,mimetype,statuscode,digest,length' \
--data-urlencode 'output=json' \
-D m001-t20-headers.txt -o m001-t20-body.json
Result: HTTP/2 200, 672 records.
| mimetype | status | rows |
|---|---|---|
| unk | - | 492 |
| unk | 301 | 29 |
| text/html | 302 | 139 |
| text/html | 301 | 8 |
| text/html | 503 | 4 |
Capture years: 2011: 45; 2012: 14; 2013: 56; 2014: 504; 2015: 10; 2016: 1; 2018: 2; 2019: 2; 2020: 31; 2021: 3; 2022: 1; 2023: 1; 2024: 2. Rows with the empty-content digest: 28. New digests (not in the census): 173. Recorded length of one row per new digest: min 393, median 4,142,400, max 13,850,702.
Observations
unk / -.unk / -”) was wrong: 73%.Corrections to earlier entries
unk / - rows.unk / - class but not of the whole gap.Conclusion: The gap contains real files (492 rows) and non-software responses (180 rows). Retrieval candidates must be selected by status and mimetype as well as extension. Open: recount of new digests among unk / - rows; whether unk / - captures replay; whether downloaded content matches the CDX digest.
- one, matched the CDX digest exactly, and the gap recount gives about 9,244 files.
Date: 2026 – 11-27 Tools: curl 8.18.0, sha256sum, python3, jq, comm (WSL) Evidence: raw/m001-t20-bscan-2.hqx (+ .headers.txt), raw/m001-t20-fat-tracker-40.hqx (+ .headers.txt), raw/gap-unk-digests.txt (File names carry the t20 prefix because they were saved before this entry was renumbered.)
Command
dl () {
ts="$1"; url="$2"; out="$3"
curl -sS -D "$out.headers.txt" -o "$out" "https://web.archive.org/web/${ts}id_/${url}"
head -n 1 "$out.headers.txt"; ls -l "$out"; sha256sum "$out"
python3 -c "import hashlib,base64,sys;print('base32 sha1:',base64.b32encode(hashlib.sha1(open(sys.argv[1],'rb').read()).digest()).decode())" "$out"
}
dl 20140910233300 'http://archive.info-mac.org/_Anti-Virus/bscan-2.hqx' m001-t20-bscan-2.hqx
dl 20140910233250 'http://archive.info-mac.org/_Application/fat-tracker-40.hqx' m001-t20-fat-tracker-40.hqx
jq -r '.[1:][] | select(.[2]=="unk" and .[3]=="-") | .[4]' m001-t20-body.json | sort -u > gap-unk-digests.txt
comm -13 census-digests.txt gap-unk-digests.txt | wc -l
Result
| File | Capture | CDX status | Downloaded | Base32 SHA-1 vs CDX digest | SHA-256 |
|---|---|---|---|---|---|
| bscan-2.hqx | 2014 – 09-10 | 200 | 508,420 B | match (WSRZN4CU…) | bf94204392a9dd97…a007c |
| fat-tracker-40.hqx | 2014 – 09-10 | - / unk |
6,319,072 B | match (AAYRM7WH…) | 42f1c9791265ccd9…6db5 |
Recount: unk / - rows have 195 distinct digests; 100 are not in the census.
Observations
unk / - capture replays correctly (one file tested).Corrections to earlier entries
unk / - rows).unk / - captures is confirmed for one file.Conclusion: The digest gives a built-in integrity check and the gap captures are recoverable. Downloads should be verified by SHA-1 against the CDX digest and stored with a SHA-256. Open: whether all unk / - captures replay; the unk / 301 rows; behaviour under thousands of sequential requests; BinHex CRC checking; pagination (untested).
Objective: Establish how the live CDX service behaves before relying on it for software discovery.
Established
output=json is best for scripting. All values are strings, and row 0 is the header.url=host/* matches paths below the root. Without the wildcard, only the exact URL matches.filter=original: regexes work, including (?i) and $. Negated filters (!) work and can be combined.collapse=urlkey applies after the filters and keeps the earliest remaining capture (two URLs tested).showNumPages ignores filters and collapse, so it is not a size estimate..hqx/.sit URLs on archive.info-mac.org with status 200, which map to 9,145 distinct digests.3I42H3S6NNFQ2MSVX7XZKYAYSCX5QBYJ, 30 URLs) can be excluded without downloading.length is not file size. The best current explanation is compressed record size (inference, not verified).unk and status -, so status-200 and mimetype filters miss them. The census gap is 672 URLs, of which 492 are unk / -; about 100 digests are not in the census.warc/revisit records are pointers to earlier content, not downloadable files.unk / - capture replayed correctly (one file tested).id_ replay form returns the original bytes and preserves x-archive-orig-* headers.Working estimate: about 9,244 distinct non-empty files (9,144 census + 100 gap). Approximate.
Not yet tested
page=, resumeKey).unk / - captures replay.unk / 301 and other redirect rows.bscan-2.hqx length difference between 2014 and 2025.Next: Phase 3, the SQLite catalogue, built from one request with no collapse and no status filter so that all captures are kept.
- means, how digests work or why files are duplicated; those rest on our own tests.
Date: 2026 – 11-27 Source: Wayback CDX Server API README (github.com/internetarchive/wayback)
Findings that match earlier tests
/* = matchType=prefix; ! negation and Java regex filters; JSON header row; fl=; collapse works on adjacent lines.Not covered by the docs (empirical results stand)
- / unk; digest = base32 SHA-1; length; duplicate paths; empty files; replay of unk / - captures.Corrections to earlier entries
Design implications
showResumeKey / resumeKey or page= for the discovery run.showDupeCount, from / to, pageSize.Date: 2026 – 11-28 Sources: IA blog (2026 – 09-15), wayback Python package docs/PyPI, IA Wayback APIs page
Findings
wayback 0.5.x, 2026) supports CDX options; the interface is in use.Corrections to earlier entries
Design implications
Objective: Obtain every capture of the target extensions on archive.info-mac.org (no collapse, no status filter) using the documented resume key, at a deliberately light request rate, and keep the raw pages as evidence for the SQLite catalogue.
Footprint rules: one request at a time, small pages, pauses between requests, stop at the first 429, no repeats of large requests.
Note: D01 and D02 above were written after the Milestone 001 summary and apply to this milestone too.
Date: 2026 – 11-28 Tools: curl 8.18.0, jq 1.8.2 (WSL) Evidence: raw/m002-t01-headers.txt, raw/m002-t01-body.json
Command
curl -sG 'https://web.archive.org/cdx/search/cdx' \
--data-urlencode 'url=archive.info-mac.org/*' \
--data-urlencode 'filter=original:(?i).*\.(sit|sitx|hqx|sea)$' \
--data-urlencode 'fl=timestamp,original,mimetype,statuscode,digest,length' \
--data-urlencode 'output=json' \
--data-urlencode 'limit=200' \
--data-urlencode 'showResumeKey=true' \
-D m002-t01-headers.txt -o m002-t01-body.json
Result: HTTP/2 200. jq 'length' = 203: 1 header + 200 records + [] + one-element array holding the resume key.
Observations
warc/revisit for calc-it-11.hqx, status -, length 538)./_Application/_Calculator/; the full result set is much larger than the 29,273-row census (size unknown).Corrections to earlier entries
Conclusion: The resume key is issued as documented. Resumption itself must be tested before the paged run.
Date: 2026 – 11-28 Tools: curl 8.18.0, jq 1.8.2 (WSL) Evidence: raw/m002-t02-headers.txt, raw/m002-t02-body.json
Command
key=$(jq -r '.[-1][0]' m002-t01-body.json)
curl -sG 'https://web.archive.org/cdx/search/cdx' \
--data-urlencode 'url=archive.info-mac.org/*' \
--data-urlencode 'filter=original:(?i).*\.(sit|sitx|hqx|sea)$' \
--data-urlencode 'fl=timestamp,original,mimetype,statuscode,digest,length' \
--data-urlencode 'output=json' \
--data-urlencode 'limit=200' \
--data-urlencode 'showResumeKey=true' \
--data-urlencode "resumeKey=$key" \
-D m002-t02-headers.txt -o m002-t02-body.json
Result: HTTP/2 200. Key length 106. jq 'length' = 203 (same structure as page 1). Last row of page 1: calc-it-11.hqx (2015, warc/revisit, -). First row of page 2: calculator-ii-15.hqx (2014 – 09-11, application/mac-binhex40, 200, length 77794). Rows appearing in both pages: 0.
Observations
Corrections to earlier entries
Conclusion: The resume key works as documented, so a paged discovery run is feasible. Completeness check is deferred to the end of the run.
m002-discover.sh (version 1)Date: 2026 – 11-28 File: ~/buriedbits/cdx/m002-discover.sh SHA-256 of the file: [run: sha256sum ~/buriedbits/cdx/m002-discover.sh and paste the first 16 characters]
Purpose: Page through every capture of .sit/.sitx/.hqx/.sea URLs on archive.info-mac.org using the CDX resume key (confirmed in M002-T01/T02), slowly and with built-in stops. Saves one raw JSON file per request.
Safeguards
Retry-After is shown if sent. An answer that is not the expected JSON is not saved.UA variable adds a User-Agent (not required by the Archive as far as we know).Testing: Tested only against a simulated curl in Claude’s workspace (the workspace cannot reach archive.org). Verified there: per-run cap, continuation across runs, detection of a finished run, recovery after a deleted page, stop on HTTP 429 with Retry-After shown, and the continuation pause (5 s). Not yet run against the real service.
Source (version 1)
#!/usr/bin/env bash
# M002 discovery: page through every capture of the target extensions on
# archive.info-mac.org using the CDX resume key, slowly and politely.
#
# - One request at a time, PAUSE seconds apart (minimum 5).
# - At most MAX_PAGES requests per run (default 5). Re-run to continue.
# - Stops at the first non-200 answer (no retries). 429/503: wait and try later.
# - State lives in the saved pages: re-running continues from the last page.
# - Optional: UA="BuriedBits-research/0.1 (contact: you@example.com)" to identify the project.
#
# Usage: MAX_PAGES=1 ./m002-discover.sh (one request, as a pilot)
# ./m002-discover.sh (up to 5 requests)
set -u
HOST_URL='archive.info-mac.org/*'
EXT_REGEX='original:(?i).*\.(sit|sitx|hqx|sea)$'
FIELDS='timestamp,original,mimetype,statuscode,digest,length'
PAGE_LIMIT=5000
PAUSE=${PAUSE:-10}
MAX_PAGES=${MAX_PAGES:-5}
[ "$PAUSE" -lt 5 ] && PAUSE=5
DIR="$HOME/buriedbits/cdx/raw/m002-pages"
LOG="$DIR/m002-log.txt"
mkdir -p "$DIR"
cd "$DIR" || exit 1
UA_ARGS=()
if [ -n "${UA:-}" ]; then UA_ARGS=(-A "$UA"); fi
# Print the resume key stored at the end of a saved page (empty if none).
extract_key() {
jq -r 'if (length>=2 and .[-2]==[] and (.[-1]|length)==1) then .[-1][0] else "" end' "$1"
}
key=""
last=$(ls page-*.json 2>/dev/null | sort | tail -1)
if [ -n "$last" ]; then
key=$(extract_key "$last")
if [ -z "$key" ]; then
echo "The last saved page ($last) has no resume key: discovery is already complete."
exit 0
fi
fi
n=$(( $(ls page-*.json 2>/dev/null | wc -l) + 1 ))
# When continuing an earlier run, pause first so back-to-back runs stay spaced out.
if [ -n "$last" ]; then sleep "$PAUSE"; fi
count=0
while [ "$count" -lt "$MAX_PAGES" ]; do
page=$(printf 'page-%04d' "$n")
args=(-sG 'https://web.archive.org/cdx/search/cdx'
--data-urlencode "url=$HOST_URL"
--data-urlencode "filter=$EXT_REGEX"
--data-urlencode "fl=$FIELDS"
--data-urlencode 'output=json'
--data-urlencode "limit=$PAGE_LIMIT"
--data-urlencode 'showResumeKey=true')
if [ -n "$key" ]; then args+=(--data-urlencode "resumeKey=$key"); fi
code=$(curl "${args[@]}" ${UA_ARGS[@]+"${UA_ARGS[@]}"} --max-time 180 \
-D "$page.headers.txt" -o "$page.tmp" -w '%{http_code}')
if [ "$code" != "200" ]; then
rm -f "$page.tmp"
echo "$(date -Is) $page http=$code STOPPED" | tee -a "$LOG"
echo "Stopped: HTTP $code. No retry. Headers saved in $DIR/$page.headers.txt"
if grep -qi '^retry-after' "$page.headers.txt" 2>/dev/null; then
grep -i '^retry-after' "$page.headers.txt"
fi
echo "If this is 429 or 503, wait (hours, not minutes) before running again."
exit 1
fi
if ! jq -e 'type=="array" and length>=1 and .[0][0]=="timestamp"' "$page.tmp" >/dev/null 2>&1; then
rm -f "$page.tmp"
echo "$(date -Is) $page http=200 BAD-JSON STOPPED" | tee -a "$LOG"
echo "Stopped: the answer was not the expected JSON. Nothing saved."
exit 1
fi
next=$(extract_key "$page.tmp")
if [ -n "$next" ]; then
rows=$(jq 'length-3' "$page.tmp")
else
rows=$(jq 'length-1' "$page.tmp")
fi
mv "$page.tmp" "$page.json"
echo "$(date -Is) $page http=200 rows=$rows bytes=$(stat -c%s "$page.json") more=$([ -n "$next" ] && echo yes || echo no)" | tee -a "$LOG"
if [ -z "$next" ]; then
echo "Last page reached. Discovery complete."
exit 0
fi
key="$next"
n=$((n+1))
count=$((count+1))
if [ "$count" -lt "$MAX_PAGES" ]; then sleep "$PAUSE"; fi
done
echo "Stopped after $MAX_PAGES request(s) (per-run cap). Run again to continue."
Corrections to earlier entries
Open: real page size and request time; total number of pages; whether the full result set matches all 29,273 census URLs (completeness check after the run).
Date: 2026 – 11-28 Tools: m002-discover.sh v1 (M002-S01), curl, jq (WSL) Evidence: raw/m002-pages/page-0001.json, raw/m002-pages/page-0001.headers.txt, raw/m002-pages/m002-log.txt
Command
cd ~/buriedbits/cdx/raw
MAX_PAGES=1 ~/buriedbits/cdx/m002-discover.sh
cat m002-pages/m002-log.txt
Result: page-0001 http=200 rows=5000 bytes=833504 more=yes. Stopped by the per-run cap, as designed.
Observations
Corrections to earlier entries
Conclusion: The script works against the live service for one page. Continue in small batches and watch the log for any change.
Date: 2026 – 11-28 Tools: m002-discover.sh v1 (M002-S01), jq (WSL) Evidence: raw/m002-pages/page-0001.json to page-0004.json (+ .headers.txt), raw/m002-pages/m002-log.txt
Command
cd ~/buriedbits/cdx/raw/m002-pages
jq -c '.[0]' page-0001.json
jq -c '.[1]' page-0001.json
jq -c '.[5000]' page-0001.json
jq -r '.[1:5001][] | "\(.[2]) \(.[3])"' page-0001.json | sort | uniq -c | sort -rn | head
cd ~/buriedbits/cdx/raw
time MAX_PAGES=3 ~/buriedbits/cdx/m002-discover.sh
Result
["timestamp","original","mimetype","statuscode","digest","length"]..../_Anti-Virus/alternate-sam-35-install.hqx, 2014 – 09-10, 200, digest 3FGHQ5OO..., length 5969 (same as T05 row 1). Row 5000: .../_Communication/tcp/html/simple-text-2-html.hqx.-: 1,147; unk -: 47.real 0m37.275s.Observations
Corrections to earlier entries
Conclusion: The script behaves as designed on the live service. Continue in small batches.
Date: 2026 – 11-28 Tools: m002-discover.sh v1 (M002-S01) Evidence: raw/m002-pages/page-0005.json to page-0008.json (+ .headers.txt), m002-log.txt
Command
cd ~/buriedbits/cdx/raw
time MAX_PAGES=4 ~/buriedbits/cdx/m002-discover.sh
Result: pages 5 – 8, all http=200, 5,000 rows each; bytes 805,277 / 765,015 / 774,257 / 751,667; more=yes after page 8. real 0m53.452s.
Observations
Corrections to earlier entries
Conclusion: Steady behaviour over eight requests. Continue in small batches.
Date: 2026 – 11-28 Tools: m002-discover.sh v1 (M002-S01) Evidence: raw/m002-pages/page-0009.json, page-0010.json (+ .headers.txt), m002-log.txt
Command
cd ~/buriedbits/cdx/raw
time MAX_PAGES=4 ~/buriedbits/cdx/m002-discover.sh
Result: page-0009: http=200, rows=5000, bytes=757006, more=yes. page-0010: http=200, rows=89, bytes=12983, more=no. “Last page reached. Discovery complete.” real 0m23.179s.
Observations
Corrections to earlier entries
Conclusion: The paged run completed within the planned footprint. Completeness is not yet verified (see M002-T07).
Date: 2026 – 11-28 Tools: jq, awk, sort, comm (WSL). No requests to archive.org. Evidence: raw/m002-all-rows.tsv (45,089 rows), raw/census-triples.tsv, raw/gap-triples.tsv, raw/paged-triples.tsv
Command
cd ~/buriedbits/cdx/raw
export LC_ALL=C
for f in m002-pages/page-*.json; do
jq -r '.[1:] | map(select(length==6))[] | @tsv' "$f"
done > m002-all-rows.tsv
jq -r '.[1:][] | [.[0], .[1], .[2]] | @tsv' m001-t10-body.json | sort > census-triples.tsv
awk -F'\t' '{print $2"\t"$1"\t"$5}' m002-all-rows.tsv | sort > paged-triples.tsv
comm -23 census-triples.tsv paged-triples.tsv | wc -l
jq -r '.[1:][] | [.[1], .[0], .[4]] | @tsv' m001-t20-body.json | sort > gap-triples.tsv
comm -23 gap-triples.tsv paged-triples.tsv | wc -l
cut -f3,4 m002-all-rows.tsv | sort | uniq -c | sort -rn
cut -f5 m002-all-rows.tsv | sort -u | wc -l
Result
| rows | mimetype | status |
|---|---|---|
| 31,057 | application/mac-binhex40 | 200 |
| 13,259 | warc/revisit | - |
| 494 | unk | - |
| 204 | text/html | 302 |
| 36 | unk | 301 |
| 20 | text/html | 301 |
| 14 | text/html | 503 |
| 3 | text/html | 403 |
| 2 | application/x-stuffit | 200 |
Observations
application/x-stuffit rows are probably the 2 .sit URLs from T09 (not checked).Corrections to earlier entries
Conclusion: The paged discovery is consistent with both earlier extractions. m002-all-rows.tsv is the input for the catalogue.
Discovery of all captures of .sit/.sitx/.hqx/.sea URLs on archive.info-mac.org is complete: 10 pages, 45,089 rows, 10 requests at about 10 s spacing, no errors or 429s. The paged data contains all 29,273 census rows and all 672 gap rows (M002-T07). Results are in raw/m002-pages/ and raw/m002-all-rows.tsv.
Objective: Store every discovered capture in a local SQLite catalogue that works for any site, group captures into distinct files by digest, and record download status separately, so that discovery never has to be repeated and downloads can be planned from the catalogue.
build_catalogue.py (version 1)Date: 2026 – 11-28 File: ~/buriedbits/cdx/build_catalogue.py Database: ~/buriedbits/cdx/catalogue.sqlite SHA-256 of the file: [run: sha256sum ~/buriedbits/cdx/build_catalogue.py and paste the first 16 characters]
Purpose: Read the saved CDX pages of any site and build or update the catalogue. No requests to any server.
Design
sources (one row per site and extension set), captures (one row per CDX row, nothing discarded), downloads (never touched by the importer).ok, unknown_status, revisit, redirect or error.files: one row per distinct digest with a verdict (candidate, empty, revisit_only, not_a_file) and a chosen capture (prefer ok, then unknown_status, earliest date).download_queue: the candidates with their download status.Testing: Tested only on simulated pages in Claude’s workspace: counts and verdicts, re-import without duplicates, download records surviving re-import, a second site in the same catalogue, a warning for unfinished discovery, and clear errors for a missing page, a header without a required field, and an empty folder. Not yet run on real data.
Source (version 1): save as ~/buriedbits/cdx/build_catalogue.py
#!/usr/bin/env python3
"""
build_catalogue.py - build or update the BuriedBits catalogue (SQLite) from saved CDX pages.
Works for any site. The host and the extensions are labels for the discovery run;
the pages folder holds the saved responses written by the paged discovery script.
Safe to re-run: re-importing a site replaces that site's captures only. The
`downloads` table is never touched by this script. No requests are made to any server.
Example:
python3 build_catalogue.py --host archive.info-mac.org --extensions sit,sitx,hqx,sea \
--pages ~/buriedbits/cdx/raw/m002-pages
"""
import argparse
import datetime
import glob
import json
import os
import re
import sqlite3
import sys
from urllib.parse import urlsplit
EMPTY_DIGEST = "3I42H3S6NNFQ2MSVX7XZKYAYSCX5QBYJ" # base32 SHA-1 of empty content
REQUIRED = ["timestamp", "original", "mimetype", "statuscode", "digest", "length"]
SCHEMA = """
CREATE TABLE IF NOT EXISTS sources (
id INTEGER PRIMARY KEY,
host TEXT NOT NULL,
extensions TEXT NOT NULL,
pages INTEGER,
rows INTEGER,
complete INTEGER,
imported_at TEXT,
UNIQUE (host, extensions)
);
CREATE TABLE IF NOT EXISTS captures (
id INTEGER PRIMARY KEY,
source_id INTEGER NOT NULL REFERENCES sources(id),
timestamp TEXT NOT NULL,
original TEXT NOT NULL,
url_host TEXT,
path TEXT,
ext TEXT,
mimetype TEXT,
statuscode TEXT,
digest TEXT,
length INTEGER,
class TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS captures_digest ON captures(digest);
CREATE INDEX IF NOT EXISTS captures_class ON captures(class);
CREATE INDEX IF NOT EXISTS captures_source ON captures(source_id);
CREATE TABLE IF NOT EXISTS downloads (
digest TEXT PRIMARY KEY,
status TEXT NOT NULL DEFAULT 'not_downloaded',
local_path TEXT,
sha256 TEXT,
bytes INTEGER,
downloaded_at TEXT,
note TEXT
);
"""
VIEWS = """
DROP VIEW IF EXISTS download_queue;
DROP VIEW IF EXISTS files;
CREATE VIEW files AS
WITH ranked AS (
SELECT digest, original, timestamp, class, length,
ROW_NUMBER() OVER (
PARTITION BY digest
ORDER BY CASE class WHEN 'ok' THEN 0 WHEN 'unknown_status' THEN 1
WHEN 'revisit' THEN 2 ELSE 3 END,
timestamp, LENGTH(original), original
) AS rn
FROM captures
), best AS (SELECT * FROM ranked WHERE rn = 1)
SELECT c.digest AS digest,
COUNT(DISTINCT c.original) AS n_urls,
COUNT(*) AS n_captures,
MAX(c.class = 'ok') AS has_ok,
MAX(c.class = 'unknown_status') AS has_unknown_status,
MAX(c.class = 'revisit') AS has_revisit,
CASE WHEN c.digest = '__EMPTY__' THEN 'empty'
WHEN MAX(c.class IN ('ok', 'unknown_status')) = 1 THEN 'candidate'
WHEN MAX(c.class = 'revisit') = 1 THEN 'revisit_only'
ELSE 'not_a_file' END AS verdict,
b.original AS best_url,
b.timestamp AS best_timestamp,
b.class AS best_class,
b.length AS best_record_length
FROM captures c JOIN best b ON b.digest = c.digest
GROUP BY c.digest;
CREATE VIEW download_queue AS
SELECT f.*, COALESCE(d.status, 'not_downloaded') AS download_status
FROM files f LEFT JOIN downloads d ON d.digest = f.digest
WHERE f.verdict = 'candidate';
""".replace("__EMPTY__", EMPTY_DIGEST)
def classify(mimetype, status):
if mimetype == "warc/revisit":
return "revisit"
if status.startswith("3"):
return "redirect"
if status.startswith(("4", "5")):
return "error"
if status == "200":
return "ok"
return "unknown_status" # for example status "-" with mimetype "unk"
def ext_of(url):
name = urlsplit(url).path.rsplit("/", 1)[-1]
return name.rsplit(".", 1)[1].lower() if "." in name else ""
def norm_host(h):
h = h.strip().lower()
h = re.sub(r"^https?://", "", h)
return re.sub(r"(/\*|/)+$", "", h)
def norm_exts(s):
parts = [p.strip().lstrip(".").lower() for p in re.split(r"[,\s]+", s)]
return ",".join(sorted({p for p in parts if p}))
def read_pages(pages_dir):
paths = sorted(glob.glob(os.path.join(pages_dir, "page-*.json")))
if not paths:
sys.exit("No page-*.json files found in %s" % pages_dir)
numbers = [int(re.search(r"page-(\d+)\.json$", p).group(1)) for p in paths]
if numbers != list(range(1, len(paths) + 1)):
sys.exit("The page files are not consecutive (page-0001...): a page is missing.")
header0 = None
rows = []
complete = True
for p in paths:
with open(p, encoding="utf-8") as fh:
data = json.load(fh)
if not data or not isinstance(data[0], list):
sys.exit("%s: not a CDX JSON page" % p)
header = data[0]
missing = [f for f in REQUIRED if f not in header]
if missing:
sys.exit("%s: header lacks fields %s" % (p, missing))
if header0 is None:
header0 = header
elif header != header0:
sys.exit("%s: header differs from the first page" % p)
ix = {name: i for i, name in enumerate(header)}
for row in data[1:]:
if not (isinstance(row, list) and len(row) == len(header)):
continue # the trailing [] and [resume key] arrays
original = row[ix["original"]]
status = row[ix["statuscode"]]
mimetype = row[ix["mimetype"]]
try:
length = int(row[ix["length"]])
except (TypeError, ValueError):
length = None
sp = urlsplit(original)
rows.append((row[ix["timestamp"]], original, sp.hostname or "", sp.path,
ext_of(original), mimetype, status, row[ix["digest"]],
length, classify(mimetype, status)))
if p == paths[-1]:
complete = not (len(data) >= 3 and data[-2] == [] and len(data[-1]) == 1)
return rows, len(paths), complete
def report(con, sid, host, exts, pages, complete):
q = lambda sql, *a: con.execute(sql, a).fetchall()
n = q("SELECT COUNT(*) FROM captures WHERE source_id=?", sid)[0][0]
print("\n=== %s (extensions: %s) ===" % (host, exts))
print("pages: %d captures: %d discovery complete: %s" % (pages, n, "yes" if complete else "NO"))
print("\ncaptures by class:")
for cls, c in q("SELECT class, COUNT(*) FROM captures WHERE source_id=? GROUP BY class ORDER BY 2 DESC", sid):
print(" %7d %s" % (c, cls))
print("\ncaptures by file extension (top 10):")
for e, c in q("SELECT ext, COUNT(*) FROM captures WHERE source_id=? GROUP BY ext ORDER BY 2 DESC LIMIT 10", sid):
print(" %7d .%s" % (c, e))
scope = "digest IN (SELECT digest FROM captures WHERE source_id=%d)" % sid
print("\ndistinct files (by digest) and what they are:")
total = 0
for v, c in q("SELECT verdict, COUNT(*) FROM files WHERE %s GROUP BY verdict ORDER BY 2 DESC" % scope):
total += c
print(" %7d %s" % (c, v))
print(" %7d total distinct digests" % total)
cand, urls, recl = q("SELECT COUNT(*), COALESCE(SUM(n_urls),0), COALESCE(SUM(best_record_length),0) "
"FROM files WHERE verdict='candidate' AND %s" % scope)[0]
print("\ndownload candidates: %d files, listed under %d addresses" % (cand, urls))
print(" (downloading by digest means %d files instead of %d addresses)" % (cand, urls))
print(" recorded length of the chosen captures: about %.1f MB" % (recl / 1e6))
print(" (approximate: the recorded length is the stored record size, not the file size)")
def main():
ap = argparse.ArgumentParser(description="Build or update the BuriedBits catalogue from saved CDX pages.")
ap.add_argument("--host", required=True, help="site the discovery run was for, e.g. archive.info-mac.org")
ap.add_argument("--extensions", required=True, help="comma-separated extensions, e.g. sit,hqx")
ap.add_argument("--pages", required=True, help="folder holding page-0001.json, page-0002.json, ...")
ap.add_argument("--db", default="~/buriedbits/cdx/catalogue.sqlite", help="catalogue file")
args = ap.parse_args()
host = norm_host(args.host)
exts = norm_exts(args.extensions)
if not host or not exts:
sys.exit("Both --host and --extensions need a value.")
pages_dir = os.path.expanduser(args.pages)
db = os.path.expanduser(args.db)
rows, pages, complete = read_pages(pages_dir)
if not complete:
print("WARNING: the last page still has a resume key, so discovery is not finished. "
"Importing what is there; run the discovery script again and re-import to complete it.")
os.makedirs(os.path.dirname(db), exist_ok=True)
con = sqlite3.connect(db)
con.executescript(SCHEMA)
with con:
found = con.execute("SELECT id FROM sources WHERE host=? AND extensions=?", (host, exts)).fetchone()
if found:
sid = found[0]
con.execute("DELETE FROM captures WHERE source_id=?", (sid,))
else:
sid = con.execute("INSERT INTO sources(host, extensions) VALUES (?, ?)", (host, exts)).lastrowid
con.executemany(
"INSERT INTO captures(source_id, timestamp, original, url_host, path, ext, mimetype, "
"statuscode, digest, length, class) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
[(sid,) + r for r in rows])
con.execute("UPDATE sources SET pages=?, rows=?, complete=?, imported_at=? WHERE id=?",
(pages, len(rows), 1 if complete else 0,
datetime.datetime.now().astimezone().isoformat(timespec="seconds"), sid))
con.executescript(VIEWS)
report(con, sid, host, exts, pages, complete)
con.close()
print("\nCatalogue: %s" % db)
if __name__ == "__main__":
main()
To check that the saved file is valid Python:
python3 -c "import ast,sys; ast.parse(open('$HOME/buriedbits/cdx/build_catalogue.py').read()); print('script saved, syntax ok')"
Corrections to earlier entries
Date: 2026 – 11-28 Tools: build_catalogue.py v1 (M003-S01), sqlite3 (WSL). No requests to archive.org. Evidence: ~/buriedbits/cdx/catalogue.sqlite
Command
python3 ~/buriedbits/cdx/build_catalogue.py \
--host archive.info-mac.org --extensions sit,sitx,hqx,sea \
--pages ~/buriedbits/cdx/raw/m002-pages
sqlite3 -header -column ~/buriedbits/cdx/catalogue.sqlite "SELECT verdict, COUNT(*) FROM files GROUP BY verdict;"
Result: 10 pages, 45,089 captures, discovery complete.
Observations
unk / -).unk / - files; the 26 digests unexplained in M002-T07 are therefore among the 99 non-candidates (arithmetic; not inspected individually).original strings); the earlier 29,273 merged them (collapse=urlkey).Corrections to earlier entries
Conclusion: The catalogue reproduces every earlier figure and gives a defined download list. Not yet tested: whether the chosen captures replay, and how the Archive responds to a sustained series of downloads.
Question: Of the distinct files, how many are real download candidates, and what are the ones that are not?
Result (from catalogue.sqlite, no request to archive.org):
| Verdict | Best capture class | Files |
|---|---|---|
| candidate | ok (status 200) | 9,144 |
| candidate | unknown_status (status -, mimetype unk) |
100 |
| revisit_only | revisit pointer only | 5 |
| not_a_file | redirect | 77 |
| not_a_file | error (4xx/5xx) | 17 |
The five revisit-only addresses (the Archive holds only a pointer for them in this extract):
http://archive.info-mac.org/game/word-find-15.hqxhttp://archive.info-mac.org/cmp/uu-undo-10.hqxhttp://archive.info-mac.org/game/brd/quarto-101r.hqxhttp://archive.info-mac.org/comm/inet/newswatcher-216.hqxhttp://archive.info-mac.org/comm/inet/mail/edr/eudora-light-155.hqxConclusion: 9,244 candidates, as before. The 100 unknown-status files are included deliberately, because earlier tests showed real files with status -. Whether the revisit-only five can be fetched is untested (see M003-T04).
Corrections to earlier entries: none.
download_batch.py (verified, gentle batch downloader)Purpose: Downloads a small batch of files chosen from the catalogue, one request at a time, and checks each against the CDX digest.
Safety rules built in: dry run unless --go; minimum 5 s between requests (default 10 s), also across separate runs via files/.last-request; at most 100 files per run; stops on the first problem; no retries; redirects not followed; 429/5xx records nothing; digest mismatch sets the file aside in _mismatch/.
Where things go: ~/buriedbits/cdx/files/<digest>/<filename>, plus files/download-log.txt. Status is kept in the downloads table of the catalogue.
Tested on simulated data first (local server): dry run makes no requests; verification; resume; 429, 503, 404, 302, digest mismatch; hard cap; pause floor; --retry-failed; --verdict revisit_only.
SHA-256 of the frozen script: (run sha256sum ~/buriedbits/cdx/download_batch.py and paste it here)
Source: save as ~/buriedbits/cdx/download_batch.py
#!/usr/bin/env python3
"""
download_batch.py - download a small, verified batch of files chosen from the catalogue.
Gentle by design:
* Nothing is downloaded unless you add --go. Without it, only the plan is printed.
* One request at a time, at least 5 s apart (default 10 s), also across separate runs.
* At most --count files per run (default 10, hard limit 100).
* Any problem stops the run at once. There are no automatic retries.
* Every file is checked against the Archive's own fingerprint (the CDX digest, a
base32 SHA-1 of the file). Files that do not match are set aside, never kept as good.
* It never queries the CDX index; it only fetches the captures already chosen in the catalogue.
Examples:
python3 download_batch.py --pilot # show the plan for the 10-file pilot
python3 download_batch.py --pilot --go # run the pilot
python3 download_batch.py --count 20 --go # 20 smallest files not yet downloaded
python3 download_batch.py --verdict revisit_only --count 5 --go
"""
import argparse
import base64
import datetime
import hashlib
import os
import re
import shutil
import sqlite3
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
DEFAULT_BASE = "https://web.archive.org"
HARD_CAP = 100
MAX_BYTES = 200 * 1024 * 1024 # safety limit for one file
MIN_PAUSE = 5
DEFAULT_UA = "BuriedBits-research/0.1 (personal software-preservation project; slow, sequential requests)"
class NoRedirect(urllib.request.HTTPRedirectHandler):
"""Do not follow redirects: a redirect is treated as something to look at."""
def redirect_request(self, *args, **kwargs):
return None
def safe_name(url):
name = urllib.parse.unquote(urllib.parse.urlsplit(url).path.rsplit("/", 1)[-1])
name = re.sub(r'[\x00-\x1f/\\:*?"<>|]', "_", name).strip(" .")
return name[:150] or "file"
def now():
return datetime.datetime.now().astimezone().isoformat(timespec="seconds")
def pick_pilot(rows):
"""rows are sorted by recorded length (smallest first)."""
ok = [r for r in rows if r["best_class"] == "ok"]
unk = [r for r in rows if r["best_class"] == "unknown_status"]
chosen = ok[:2] + unk[:3]
if ok:
m = len(ok) // 2
chosen += ok[max(m - 1, 0):m + 2][:3]
chosen += ok[-2:]
seen, out = set(), []
for r in chosen:
if r["digest"] not in seen:
seen.add(r["digest"])
out.append(r)
return out[:10]
def wait_for_gap(path, pause):
try:
with open(path) as fh:
last = float(fh.read().strip())
except (OSError, ValueError):
last = 0.0
remaining = last + pause - time.time()
if remaining > 0:
time.sleep(remaining)
def stamp(path):
with open(path, "w") as fh:
fh.write(str(time.time()))
def fetch(opener, url, tmp_path, ua, timeout):
req = urllib.request.Request(url, headers={"User-Agent": ua, "Accept-Encoding": "identity"})
sha1, sha256, size = hashlib.sha1(), hashlib.sha256(), 0
with opener.open(req, timeout=timeout) as resp, open(tmp_path, "wb") as out:
if resp.status != 200:
raise urllib.error.HTTPError(url, resp.status, "unexpected status", resp.headers, None)
while True:
chunk = resp.read(65536)
if not chunk:
break
size += len(chunk)
if size > MAX_BYTES:
raise ValueError("file is larger than the safety limit")
sha1.update(chunk)
sha256.update(chunk)
out.write(chunk)
return size, base64.b32encode(sha1.digest()).decode(), sha256.hexdigest()
def record(con, digest, status, local_path=None, sha256=None, nbytes=None, note=None):
with con:
con.execute(
"INSERT INTO downloads(digest, status, local_path, sha256, bytes, downloaded_at, note) "
"VALUES (?,?,?,?,?,?,?) ON CONFLICT(digest) DO UPDATE SET status=excluded.status, "
"local_path=excluded.local_path, sha256=excluded.sha256, bytes=excluded.bytes, "
"downloaded_at=excluded.downloaded_at, note=excluded.note",
(digest, status, local_path, sha256, nbytes, now(), note))
def main():
ap = argparse.ArgumentParser(description="Download a small, verified batch of files chosen from the catalogue.")
ap.add_argument("--db", default="~/buriedbits/cdx/catalogue.sqlite")
ap.add_argument("--out", default="~/buriedbits/cdx/files", help="where downloaded files are kept")
ap.add_argument("--count", type=int, default=10, help="files per run (default 10, hard limit %d)" % HARD_CAP)
ap.add_argument("--pilot", action="store_true", help="a 10-file spread: smallest, unknown-status, middle, largest")
ap.add_argument("--verdict", default="candidate", help="which catalogue verdict to take files from")
ap.add_argument("--max-mb", type=float, default=25.0, help="skip files whose recorded length is above this")
ap.add_argument("--pause", type=float, default=10.0, help="seconds between requests (minimum %d)" % MIN_PAUSE)
ap.add_argument("--retry-failed", action="store_true", help="also pick files marked failed earlier")
ap.add_argument("--go", action="store_true", help="actually download (otherwise only the plan is shown)")
ap.add_argument("--base-url", default=DEFAULT_BASE, help=argparse.SUPPRESS) # for testing only
args = ap.parse_args()
if args.count < 1 or args.count > HARD_CAP:
sys.exit("--count must be between 1 and %d. (The limit is deliberate; change the script to raise it.)" % HARD_CAP)
min_pause = MIN_PAUSE if args.base_url == DEFAULT_BASE else 0
pause = max(args.pause, min_pause)
ua = os.environ.get("UA") or DEFAULT_UA
db = os.path.expanduser(args.db)
out_dir = os.path.expanduser(args.out)
if not os.path.exists(db):
sys.exit("Catalogue not found: %s (run build_catalogue.py first)" % db)
con = sqlite3.connect(db)
con.row_factory = sqlite3.Row
statuses = ("not_downloaded", "failed") if args.retry_failed else ("not_downloaded",)
marks = ",".join("?" * len(statuses))
rows = con.execute(
"SELECT f.digest, f.best_url, f.best_timestamp, f.best_class, f.best_record_length, f.n_urls "
"FROM files f LEFT JOIN downloads d ON d.digest = f.digest "
"WHERE f.verdict = ? AND COALESCE(d.status, 'not_downloaded') IN (%s) "
"AND COALESCE(f.best_record_length, 0) <= ? "
"ORDER BY f.best_record_length, f.digest" % marks,
(args.verdict, *statuses, int(args.max_mb * 1e6))).fetchall()
selected = pick_pilot(rows) if args.pilot else rows[:args.count]
selected = selected[:HARD_CAP]
print("Files waiting (verdict '%s', not yet downloaded, up to %.0f MB recorded): %d" % (args.verdict, args.max_mb, len(rows)))
print("This run: %d file(s). Pause between requests: %.0f s%s." % (
len(selected), pause, " (minimum)" if args.pause < min_pause else ""))
total = 0
for i, r in enumerate(selected, 1):
total += r["best_record_length"] or 0
print(" %2d. %-15s %8.2f MB %s [%s]" % (
i, r["best_class"], (r["best_record_length"] or 0) / 1e6, r["best_url"], r["digest"][:8]))
print("Recorded length of this batch: about %.1f MB (approximate)." % (total / 1e6))
if not args.go:
print("\nNothing was requested (no --go). Add --go to download these files.")
return
if not selected:
print("Nothing to do.")
return
os.makedirs(os.path.join(out_dir, "_tmp"), exist_ok=True)
gap_file = os.path.join(out_dir, ".last-request")
log_file = os.path.join(out_dir, "download-log.txt")
opener = urllib.request.build_opener(NoRedirect)
def log(msg):
line = "%s %s" % (now(), msg)
print(line)
with open(log_file, "a") as fh:
fh.write(line + "\n")
done = 0
for i, r in enumerate(selected, 1):
digest, best_url, ts = r["digest"], r["best_url"], r["best_timestamp"]
url = "%s/web/%sid_/%s" % (args.base_url.rstrip("/"), ts, best_url.replace(" ", "%20"))
name = safe_name(best_url)
tmp = os.path.join(out_dir, "_tmp", digest + ".part")
wait_for_gap(gap_file, pause)
try:
size, got, sha256 = fetch(opener, url, tmp, ua, 60)
except urllib.error.HTTPError as e:
code = e.code
if os.path.exists(tmp):
os.remove(tmp)
if code == 429 or code >= 500:
log("[%d/%d] %s HTTP %d STOPPED (nothing recorded; wait hours before trying again)" % (i, len(selected), digest[:8], code))
ra = e.headers.get("Retry-After") if e.headers else None
if ra:
print("Retry-After: %s" % ra)
else:
loc = e.headers.get("Location") if e.headers else None
record(con, digest, "failed", note="HTTP %d%s at %s %s" % (code, " -> " + loc if loc else "", ts, best_url))
log("[%d/%d] %s HTTP %d FAILED, recorded as failed; STOPPED" % (i, len(selected), digest[:8], code))
stamp(gap_file)
sys.exit(1)
except (urllib.error.URLError, OSError, ValueError) as e:
if os.path.exists(tmp):
os.remove(tmp)
log("[%d/%d] %s problem during download: %s STOPPED (nothing recorded)" % (i, len(selected), digest[:8], e))
stamp(gap_file)
sys.exit(1)
except KeyboardInterrupt:
if os.path.exists(tmp):
os.remove(tmp)
print("\nInterrupted; partial file removed.")
sys.exit(130)
stamp(gap_file)
if got == digest:
dest_dir = os.path.join(out_dir, digest)
os.makedirs(dest_dir, exist_ok=True)
dest = os.path.join(dest_dir, name)
shutil.move(tmp, dest)
record(con, digest, "verified", dest, sha256, size, "capture %s %s" % (ts, best_url))
log("[%d/%d] %s verified %d bytes %s" % (i, len(selected), digest[:8], size, name))
done += 1
else:
dest_dir = os.path.join(out_dir, "_mismatch", digest)
os.makedirs(dest_dir, exist_ok=True)
dest = os.path.join(dest_dir, name)
shutil.move(tmp, dest)
record(con, digest, "digest_mismatch", dest, sha256, size, "expected %s got %s (capture %s %s)" % (digest, got, ts, best_url))
log("[%d/%d] %s DIGEST MISMATCH (got %s), file set aside; STOPPED" % (i, len(selected), digest[:8], got[:8]))
sys.exit(1)
print("\nDone: %d file(s) downloaded and verified. Files are in %s" % (done, out_dir))
if __name__ == "__main__":
main()
To check that the saved file is valid Python:
python3 -m py_compile ~/buriedbits/cdx/download_batch.py && echo "syntax ok"
Question: Do the captures the catalogue chose actually replay as the right files, including the awkward kinds, and how fast does the Archive serve them when we go slowly?
Method: download_batch.py --pilot --go (M003-S02): one request at a time, 10 s pause, stop at the first problem. The pilot is a spread: 2 smallest, 3 smallest unknown-status, 3 around the median, 2 largest under the 25 MB limit. Dry run first (no requests), then the real run, 00:54 to 00:58 (about 4 minutes in total).
Result: 10 of 10 verified. For each file the SHA-1 of the downloaded bytes, converted to base32, equals the CDX digest. No HTTP errors, no redirects, no 429/503.
| # | Class in catalogue | Recorded length | Actual size | Ratio |
|---|---|---|---|---|
| 1 | ok | ~0 MB | 663 B | n/a |
| 2 | ok | ~0 MB | 650 B | n/a |
| 3 | unknown_status | 3.99 MB | 5,257,040 B | 0.76 |
| 4 | unknown_status | 4.03 MB | 5,304,424 B | 0.76 |
| 5 | unknown_status | 4.04 MB | 5,357,709 B | 0.75 |
| 6 | ok | 0.20 MB | 257,433 B | n/a |
| 7 | ok | 0.20 MB | 258,041 B | n/a |
| 8 | ok | 0.20 MB | 274,335 B | n/a |
| 9 | ok | 16.80 MB | 22,069,248 B | 0.76 |
| 10 | ok | 18.51 MB | 24,310,770 B | 0.76 |
Observations:
- and mimetype unk verified exactly. Filtering them out would have lost 100 genuine files.length is the stored record size, not the file size. Real sizes will be roughly 1.3 times the catalogue figures.cross-country-usa-2-x.hqx appears twice with different digests, one of them over 25 MB (https://archive.info-mac.org/edu/...) and one that was downloaded here under _Education/. Storing by digest keeps them apart; storing by filename would have overwritten one.~/buriedbits/cdx/files/<digest>/<filename>, with one folder per digest, plus download-log.txt in files/. Ten folders were created in this pilot.Corrections to earlier entries:
Open items: revisit_only captures are still untested for replay; the three files over 25 MB are excluded by default; behaviour under longer sustained downloads is unknown.
Question: Can a file whose only capture is a warc/revisit pointer be fetched with the same replay URL?
Method: (1) download_batch.py --verdict revisit_only --count 5 --go, which stops at the first problem. (2) One manual request to the redirect target it reported.
Result:
http://archive.info-mac.org/cmp/uu-undo-10.hqx (digest ANPPPPTV…): HTTP 302. The script does not follow redirects, so it recorded the file as failed and stopped. The other four files were not requested.http://www.info-mac.org/archive_download.php?file=cmp/uu-undo-10.hqx (2013 – 08-17), the old website’s download script, on a different host.3I42H3S6NNFQ2MSVX7XZKYAYSCX5QBYJ). Nothing was recovered.Interpretation: Download scripts of this kind (.php) answer with a redirect to the real file, and replay returns that redirect, not the file. This is consistent with one test, not proven for all .php addresses. The five revisit-only files are treated as not recoverable by replay.
Decision: No more requests spent on the other four. The tool will list revisit-only files in its final report as “pointer only, not recovered”.
Corrections to earlier entries: I wrote that the redirect target is “where the real file is stored”. That was wrong; it was a redirect, not a file.
Question: Does the downloader stay clean and verified over a longer run?
Method: download_batch.py --count 30 --go, 10 s pause, 01:26:43 to 01:32:00 (5 min 17 s).
Result: 30 of 30 verified. No HTTP errors, no redirects, no throttling. Average 10.9 s per file, almost entirely the 10 s pause. Sizes 467 B to 3,937 B. Total requests to the Archive by the downloader so far: 41 (10 pilot, 1 revisit, 30 here), plus 1 manual.
Observation: This batch was the 30 smallest files, so it says little about large-file speed. Very small files that fail verification are the signature of a saved redirect or error page, which the old downloader could produce unnoticed. Here every small file matched its digest.
Open question: Whether to shorten the pause from 10 s toward the 5 s minimum. Decision pending.
Corrections to earlier entries: none.
Question: Does a 5 s pause (the script’s minimum) cause any difference compared with 10 s?
Method: download_batch.py --count 100 --pause 5 --go, after a dry run.
Result: 100 of 100 verified. No HTTP errors, no redirects, no throttling. The last log entries are 6 s apart (5 s pause plus about 1 s transfer), against about 11 s per file at a 10 s pause.
Totals so far (from the catalogue): 140 verified files, 63,461,269 bytes (about 63 MB); 1 failed (the revisit file, M003-T04). The 130 files after the pilot average about 2.9 KB, because the downloader takes the smallest files first.
Requests to the Archive by the downloader so far: 141 (140 verified, 1 redirect), plus 1 manual request (M003-T04).
Observation: The shorter pause caused no visible change. Over 141 requests this says little about what the Archive tolerates over thousands; the limits remain unpublished. The tool will stay stop-on-first-problem.
Corrections to earlier entries: none.
Goal: Replace the separate scripts and the old scraping downloader with a single tool that anyone can point at a website and a set of file types, and that recovers the files from the Wayback Machine slowly, safely and verifiably. It is not tied to one site or one platform: the person can type one site, or optionally refer to a text file with one site per line, and the file types are always chosen by the person.
What the tool will do, in four stages:
| Stage | What it does | Why |
|---|---|---|
| 1. Discovery for any site | Lists every capture of the chosen file types on any site, gently and in small pieces, one folder of saved results per site. | The discovery script is currently fixed to Info-Mac. Saved results mean discovery never has to be repeated. |
| 2. The front-end | Asks for a site address, or a .txt file with one address per line (invalid lines skipped with a warning), then for the file types (for example .hqx, .sit). It runs discovery and builds the catalogue. |
The tool should work for any site without anyone editing a script. |
| 3. Summary and confirmation | Shows how many distinct files and addresses were found, with an estimated size and time, and waits for a yes. | The person decides before anything is downloaded. |
| 4. Resumable downloading | Downloads the confirmed files slowly, verifies each against its digest, and can continue across sessions within a limit per session that the person chooses. | A full run takes many hours; it must be safe to stop and restart. |
Flowchart of the tool: gate check, site and file-type questions, discovery, catalogue import, summary and confirmation, then one verified download at a time, with two stop levels: stop this site, and stop the whole run.
Flowchart of the rules after every request: a good reply continues; a 429 or 503 stops the whole run with a saved cool-down; a timeout is retried once; any other problem stops that site.
The Archive says it has “put protections in place to keep the service running” against “waves of high-volume automated traffic” (An Update on Wayback Machine Access, 15 September 2026).
What the Archive said. On 15 September 2026, Mark Graham published “An Update on Wayback Machine Access” on the Internet Archive’s blog. It says the Wayback Machine “has been hit by waves of high-volume automated traffic”, and that the Archive has “put protections in place to keep the service running”. It also says it rewrote the message people see when a request is blocked with a 429 error, the HTTP code that means “too many requests”.
What it says about the cost to ordinary users. The protections “sometimes catch real people by mistake”. The post apologises for this and says the Archive is working to reduce the errors. Anyone who thinks they were blocked in error is asked to email info@archive.org with their operating system, browser and IP address.
What it does not say. The post gives no request rates, no limits and no guidance for researchers or developers, and it does not describe how the protections work. It does not name the source of the traffic. So the pace this project uses (one request at a time, a pause of at least 5 seconds, a speed cap) is our own choice. It is not a published limit.
Timeline. The notice came about ten weeks before our first experiments (26 to 29 November 2026). In all of our requests to the Archive, 141 downloads plus the discovery runs, we received no 429 or 503. We cannot say whether that is because of our pace, because of luck or because of how the protections work.
How this shapes the tool.
A 429 is the Archive asking for less traffic. This tool treats it as an instruction: it stops, waits, and resumes more slowly. It never makes more than one request at a time.
The tool does not try to work around a 429. It stops, saves a cool-down so that it cannot be restarted too soon, and resumes with a longer pause. It makes one request at a time and never in parallel. Apart from a single retry after a timeout, it never repeats a request on its own. The design follows the Archive’s stated aim of keeping the service running, and it asks for no more than that.
Source read for this section: the Archive’s post above, in full. Commentary on it from other websites was not used.
Retry-After, or one hour if none) is saved to disk and the tool refuses to start until it has passed. The next run uses a longer pause, which steps back down only after a long clean stretch, and never below the pause the person chose. The tool never speeds up beyond that setting on its own.S entry (the script) and T entries (the live runs).Decoding or opening the files; a readable folder tree that mirrors each site’s paths (possible later as an optional extra); sites that block the Archive’s crawler.
Date: 2026 – 11-30
What it is: A frozen copy of bb_common.py, version 1. It makes no requests itself. Every tool that contacts the Archive imports it, so the rules are written once.
What it enforces:
.last-request file).activity-log.txt.SHA-256: 526173f31a91823777faae1f8b136c1a1c8e9f5236608fb8411ccfd26bd5ae08
Source:
#!/usr/bin/env python3
"""
bb_common.py - safety rules shared by all BuriedBits tools.
This file makes no requests by itself. It holds the rules that every tool must follow
when it talks to the Internet Archive:
* Only one copy of a tool runs at a time (a lock file).
* One request at a time, with a pause between requests (at least 5 s), also across
separate runs and across different tools (a shared "last request" time).
* HTTP 429 or 503 (the Archive asking for less traffic) stops the whole run. A cool-down
is saved to disk and the tools refuse to start until it has passed. The next runs use a
longer pause, which steps back down only after 50 clean requests in a row, and never
below the pause the person chose. The tools never speed up on their own.
* A timeout is retried once after a longer wait; a second failure stops the whole run.
* Any other problem (404, a redirect, a wrong kind of reply) stops that one site only.
* Every decision is appended to an activity log, with a timestamp and a reason.
State lives in one folder (default ~/buriedbits/state):
pace.json pause multiplier, clean-request streak, cool-down, recent pressure events
activity-log.txt append-only record of what the tools did and why
.last-request time of the most recent request
running.lock present while a tool is running
"""
import atexit
import datetime
import email.utils
import json
import os
import re
import socket
import time
import urllib.error
import urllib.request
ARCHIVE = "https://web.archive.org"
MIN_PAUSE = 5 # seconds; never go below this when talking to the Archive
PACE_CAP = 8 # the pause is never multiplied by more than this
CLEAN_STEP = 50 # clean requests in a row before the pause steps back down
COOLDOWN_DEFAULT = 3600 # seconds, when the Archive sends no Retry-After
COOLDOWN_CAP = 24 * 3600
DEFAULT_UA = "BuriedBits-research/0.1 (personal software-preservation project; slow, sequential requests)"
DEFAULT_STATE_DIR = "~/buriedbits/state"
DEFAULT_SITES_DIR = "~/buriedbits/sites"
def now():
return datetime.datetime.now().astimezone()
def iso(dt):
return dt.isoformat(timespec="seconds")
class NoRedirect(urllib.request.HTTPRedirectHandler):
"""A redirect is never followed. It is reported as a problem to look at."""
def redirect_request(self, *args, **kwargs):
return None
# ----------------------------------------------------------------------------------------
# Input checking (used by the tools that ask for a site and for file types)
# ----------------------------------------------------------------------------------------
_HOST_RE = re.compile(r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$")
_PATH_RE = re.compile(r"^[A-Za-z0-9._~%/-]*$")
_EXT_RE = re.compile(r"^[a-z0-9]{1,10}$")
def parse_site(text):
"""Return (host, path) from something like 'archive.info-mac.org' or
'https://example.com/files/'. The path is '' or starts with '/'. Raises ValueError
with a plain explanation if the text is not a usable site address."""
s = (text or "").strip()
if not s:
raise ValueError("empty line")
s = re.sub(r"^[a-zA-Z][a-zA-Z0-9+.-]*://", "", s)
if re.search(r"[\s?#*]", s):
raise ValueError("contains spaces, '?', '#' or '*': %r" % text)
s = s.rstrip("/")
host, _, rest = s.partition("/")
host = host.lower()
if not _HOST_RE.match(host):
raise ValueError("%r does not look like a site name (for example example.com)" % host)
path = ("/" + rest) if rest else ""
path = re.sub(r"/+", "/", path)
if not _PATH_RE.match(path):
raise ValueError("the path contains unusual characters: %r" % path)
return host, path
def parse_extensions(text):
"""Return a sorted, comma-separated string such as 'hqx,sit' from '.hqx, .SIT'."""
parts = [p.strip().lstrip(".").lower() for p in re.split(r"[,\s]+", text or "")]
parts = [p for p in parts if p]
if not parts:
raise ValueError("no file types given (for example: .hqx, .sit)")
bad = [p for p in parts if not _EXT_RE.match(p)]
if bad:
raise ValueError("not usable as file types (letters and digits only, up to 10): %s" % ", ".join(bad))
return ",".join(sorted(set(parts)))
def parse_retry_after(value):
"""Seconds to wait from a Retry-After header (a number of seconds or a date), or None."""
if not value:
return None
value = value.strip()
if value.isdigit():
return int(value)
try:
when = email.utils.parsedate_to_datetime(value)
if when.tzinfo is None:
when = when.replace(tzinfo=datetime.timezone.utc)
return max(0, int((when - now()).total_seconds()))
except (TypeError, ValueError):
return None
# ----------------------------------------------------------------------------------------
# Shared state
# ----------------------------------------------------------------------------------------
class State:
def __init__(self, state_dir=DEFAULT_STATE_DIR):
self.dir = os.path.expanduser(state_dir)
os.makedirs(self.dir, exist_ok=True)
self.pace_file = os.path.join(self.dir, "pace.json")
self.log_file = os.path.join(self.dir, "activity-log.txt")
self.gap_file = os.path.join(self.dir, ".last-request")
self.lock_file = os.path.join(self.dir, "running.lock")
self._locked = False
# ---- activity log ----------------------------------------------------------------
def log(self, event, site="", exts="", message=""):
line = "%s | %-9s | %s | %s | %s" % (iso(now()), event.upper(), site or "-", exts or "-", message)
with open(self.log_file, "a", encoding="utf-8") as fh:
fh.write(line + "\n")
return line
# ---- one copy at a time ----------------------------------------------------------
def acquire(self):
"""Return True if this copy may run, False if another copy is running."""
for _ in range(2):
try:
fd = os.open(self.lock_file, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
except FileExistsError:
pid = self._lock_pid()
if pid and self._alive(pid):
return False
try:
os.remove(self.lock_file) # stale lock from a copy that is no longer running
except FileNotFoundError:
pass
continue
with os.fdopen(fd, "w") as fh:
fh.write(str(os.getpid()))
self._locked = True
atexit.register(self.release)
return True
return False
def release(self):
if self._locked:
try:
os.remove(self.lock_file)
except FileNotFoundError:
pass
self._locked = False
def _lock_pid(self):
try:
with open(self.lock_file) as fh:
return int(fh.read().strip())
except (OSError, ValueError):
return None
@staticmethod
def _alive(pid):
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except PermissionError:
return True
return True
# ---- pace and cool-down ----------------------------------------------------------
def _load_pace(self):
default = {"multiplier": 1, "clean_streak": 0, "cooldown_until": None, "pressure_events": []}
try:
with open(self.pace_file, encoding="utf-8") as fh:
data = json.load(fh)
if not isinstance(data, dict):
raise ValueError
default.update(data)
return default
except FileNotFoundError:
return default
except (OSError, ValueError):
try:
os.replace(self.pace_file, self.pace_file + ".unreadable")
except OSError:
pass
self.log("warning", message="pace.json could not be read; it was set aside as pace.json.unreadable")
return default
def _save_pace(self, pace):
tmp = self.pace_file + ".tmp"
with open(tmp, "w", encoding="utf-8") as fh:
json.dump(pace, fh, indent=2)
os.replace(tmp, self.pace_file)
def cooldown_until(self):
"""The time before which no request may be made, or None."""
value = self._load_pace().get("cooldown_until")
if not value:
return None
try:
when = datetime.datetime.fromisoformat(value)
except ValueError:
return None
return when if when > now() else None
def multiplier(self):
return int(self._load_pace().get("multiplier", 1) or 1)
def effective_pause(self, chosen, min_pause=MIN_PAUSE):
"""The pause to use: what the person chose (never below the minimum), times the
slow-down multiplier. The tools never go below what the person chose."""
return max(chosen, min_pause) * self.multiplier()
def note_pressure(self, retry_after=None):
"""The Archive asked for less traffic (429/503). Save a cool-down and slow down."""
pace = self._load_pace()
cutoff = now() - datetime.timedelta(hours=24)
events = []
for e in pace.get("pressure_events", []):
try:
if datetime.datetime.fromisoformat(e) > cutoff:
events.append(e)
except ValueError:
pass
events.append(iso(now()))
base = retry_after if (retry_after and retry_after > 0) else COOLDOWN_DEFAULT
cooldown = min(base * (2 ** (len(events) - 1)), COOLDOWN_CAP)
pace["pressure_events"] = events
pace["multiplier"] = min(int(pace.get("multiplier", 1) or 1) * 2, PACE_CAP)
pace["clean_streak"] = 0
pace["cooldown_until"] = iso(now() + datetime.timedelta(seconds=cooldown))
self._save_pace(pace)
return {"cooldown_seconds": int(cooldown), "cooldown_until": pace["cooldown_until"],
"multiplier": pace["multiplier"], "events_in_24h": len(events)}
def note_clean(self):
"""A request went well. After CLEAN_STEP in a row, step the pause back down."""
pace = self._load_pace()
pace["clean_streak"] = int(pace.get("clean_streak", 0)) + 1
stepped = None
if pace["clean_streak"] >= CLEAN_STEP:
pace["clean_streak"] = 0
if int(pace.get("multiplier", 1)) > 1:
pace["multiplier"] = max(1, int(pace["multiplier"]) // 2)
stepped = pace["multiplier"]
self._save_pace(pace)
if stepped is not None:
self.log("pace", message="%d clean requests in a row: pause multiplier stepped down to x%d" % (CLEAN_STEP, stepped))
return stepped
# ---- the pause between requests --------------------------------------------------
def wait_gap(self, pause):
try:
with open(self.gap_file) as fh:
last = float(fh.read().strip())
except (OSError, ValueError):
last = 0.0
remaining = last + pause - time.time()
if remaining > 0:
time.sleep(remaining)
def stamp(self):
with open(self.gap_file, "w") as fh:
fh.write(str(time.time()))
# ----------------------------------------------------------------------------------------
# One polite request
# ----------------------------------------------------------------------------------------
class Outcome:
"""kind is one of:
'ok' the request worked; value holds what fn returned
'pressure' HTTP 429 or 503 (or another server error): stop the whole run, cool-down saved
'network' timeout or connection trouble twice in a row: stop the whole run
'site' any other problem (404, a redirect, ...): stop this site only
"""
def __init__(self, kind, value=None, code=None, detail="", retry_after=None, cooldown=None):
self.kind = kind
self.value = value
self.code = code
self.detail = detail
self.retry_after = retry_after
self.cooldown = cooldown
def polite_call(st, fn, chosen_pause, min_pause=MIN_PAUSE, retry_wait=60.0):
"""Wait for the pause, make one request by calling fn(), and sort out what happened.
fn() makes the request and returns its result, or raises urllib.error.HTTPError / URLError
/ OSError. A timeout is tried once more after retry_wait seconds. Nothing else is retried."""
for attempt in (1, 2):
st.wait_gap(st.effective_pause(chosen_pause, min_pause))
try:
value = fn()
except urllib.error.HTTPError as e:
st.stamp()
code = e.code
if code == 429 or code >= 500:
ra = parse_retry_after(e.headers.get("Retry-After") if e.headers else None)
cool = st.note_pressure(ra)
return Outcome("pressure", code=code, detail="HTTP %d" % code, retry_after=ra, cooldown=cool)
loc = e.headers.get("Location") if e.headers else None
return Outcome("site", code=code, detail="HTTP %d%s" % (code, (" -> " + loc) if loc else ""))
except (socket.timeout, TimeoutError, urllib.error.URLError, ConnectionError, OSError) as e:
st.stamp()
if attempt == 1:
time.sleep(retry_wait)
continue
return Outcome("network", detail="%s (twice in a row)" % (getattr(e, "reason", None) or e))
st.stamp()
st.note_clean()
return Outcome("ok", value=value)
return Outcome("network", detail="unknown")
Corrections to earlier entries: none.
Date: 2026 – 11-30
What it is: A frozen copy of discover.py, version 1. It replaces the hard-coded bash script of M002-S01. It asks the CDX index which files of the given types a site has, and saves the raw pages. Nothing is downloaded.
Usage: Dry run by default (no requests). --go contacts the Archive.
python3 discover.py --site archive.info-mac.org --extensions hqx,sit
python3 discover.py --site archive.info-mac.org --extensions hqx,sit --go --max-pages 5
Behaviour:
~/buriedbits/sites/<site>/<types>/pages/page-NNNN.json, plus discovery.json (progress and next resume key).--refresh.--refresh moves the old pages to pages-<timestamp>; nothing is deleted.[] replies are recorded as “no results” and the site is finished.SHA-256: 24633150518400897b922aa82f448f3fc89852fb74213ed6dc385a8023436f24
Source:
#!/usr/bin/env python3
"""
discover.py - stage 1 of BuriedBits: ask the Wayback Machine CDX index which files of the
given types it has captured for one site. Nothing is downloaded here, only the list.
python3 discover.py --site archive.info-mac.org --extensions hqx,sit (dry run)
python3 discover.py --site archive.info-mac.org --extensions hqx,sit --go (real run)
Rules (see bb_common.py): one request at a time, pause of at least 5 s, stop at the first
sign of trouble, cool-down saved to disk after a 429/503. Saved pages are never overwritten:
a stopped run resumes from them. --refresh moves the old pages aside and starts again.
Exit codes: 0 ok (complete, page cap reached, skipped, or dry run)
1 stopped the whole run (Archive pressure or network trouble)
2 refused to start (cool-down running, or another copy is running)
3 stopped for this site (unexpected reply)
"""
import argparse
import json
import os
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
import bb_common as bb
FIELDS = ["urlkey", "timestamp", "original", "mimetype", "statuscode", "digest", "length"]
PAGE_LIMIT = 5000
HARD_MAX_PAGES = 500
def slug(text):
return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-") or "x"
def build_url(base, host, path, exts, resume_key):
alt = "|".join(re.escape(e) for e in exts.split(","))
q = [("url", host + path + "/*"),
("filter", r"original:(?i).*\.(%s)$" % alt),
("fl", ",".join(FIELDS)),
("output", "json"),
("limit", str(PAGE_LIMIT)),
("showResumeKey", "true")]
if resume_key:
q.append(("resumeKey", resume_key))
return base.rstrip("/") + "/cdx/search/cdx?" + urllib.parse.urlencode(q, quote_via=urllib.parse.quote)
def parse_page(text):
"""Return (rows, resume_key). rows excludes the header. Raises ValueError on a bad reply."""
text = text.strip()
if not text:
return [], ""
data = json.loads(text)
if not isinstance(data, list):
raise ValueError("reply is not a JSON list")
if not data:
return [], ""
key = ""
if len(data) >= 2 and data[-2] == [] and isinstance(data[-1], list) and len(data[-1]) == 1:
key = str(data[-1][0])
data = data[:-2]
if data == []:
return [], key
if data[0] != FIELDS:
raise ValueError("unexpected header row: %r" % (data[0],))
rows = data[1:]
for r in rows:
if not isinstance(r, list) or len(r) != len(FIELDS):
raise ValueError("a row does not have %d fields" % len(FIELDS))
return rows, key
def save_atomic(path, text):
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as fh:
fh.write(text)
os.replace(tmp, path)
def main():
ap = argparse.ArgumentParser(description="Discover captured files of given types for one site (no downloads).")
ap.add_argument("--site", required=True, help="site address, e.g. archive.info-mac.org or example.com/files")
ap.add_argument("--extensions", required=True, help="comma-separated file types, e.g. hqx,sit")
ap.add_argument("--pause", type=float, default=10, help="seconds between requests (minimum 5, default 10)")
ap.add_argument("--max-pages", type=int, default=5, help="pages to request in this run (1-50, default 5; 5000 rows each)")
ap.add_argument("--refresh", action="store_true", help="start over: move the saved pages aside and ask again")
ap.add_argument("--go", action="store_true", help="really contact the Archive (without it: dry run)")
ap.add_argument("--sites-dir", default=bb.DEFAULT_SITES_DIR)
ap.add_argument("--state-dir", default=bb.DEFAULT_STATE_DIR)
ap.add_argument("--base-url", default=bb.ARCHIVE, help=argparse.SUPPRESS)
ap.add_argument("--timeout", type=float, default=60, help=argparse.SUPPRESS)
ap.add_argument("--retry-wait", type=float, default=60, help=argparse.SUPPRESS)
a = ap.parse_args()
if a.pause < bb.MIN_PAUSE:
print("Pause raised to the minimum of %d seconds." % bb.MIN_PAUSE)
a.pause = bb.MIN_PAUSE
if not 1 <= a.max_pages <= 50:
print("--max-pages must be between 1 and 50.")
return 2
try:
host, path = bb.parse_site(a.site)
exts = bb.parse_extensions(a.extensions)
except ValueError as e:
print("Cannot use that input: %s" % e)
return 2
site_label = host + path
folder = os.path.join(os.path.expanduser(a.sites_dir), slug(site_label), slug(exts))
pages_dir = os.path.join(folder, "pages")
info_file = os.path.join(folder, "discovery.json")
info = None
if os.path.exists(info_file):
try:
with open(info_file, encoding="utf-8") as fh:
info = json.load(fh)
except (OSError, ValueError):
print("discovery.json in %s is unreadable. Move it aside and run again." % folder)
return 3
st = bb.State(a.state_dir)
# ---- what would happen -------------------------------------------------------------
if info and info.get("complete") and not a.refresh:
print("Already discovered: %s (%s) was completed on %s with %d page(s), %d row(s)."
% (site_label, exts, info.get("finished"), info.get("pages", 0), info.get("rows", 0)))
print("Nothing to do. Use --refresh to ask again; a refresh keeps the old pages aside "
"and adds to what is known, because captures never disappear from the index.")
st.log("skipped", site_label, exts, "already complete; --refresh not given")
return 0
have = info.get("pages", 0) if (info and not a.refresh) else 0
next_key = info.get("next_key", "") if (info and not a.refresh) else ""
pause_now = st.effective_pause(a.pause)
print("Site: %s" % site_label)
print("File types: %s" % exts)
print("Saved in: %s" % folder)
print("Pages saved: %d%s" % (have, " (resuming)" if have else ""))
print("This run: up to %d request(s), %.0f s apart%s" %
(a.max_pages, pause_now, " (slowed x%d after earlier pressure)" % st.multiplier() if st.multiplier() > 1 else ""))
if a.refresh and info:
print("Refresh: old pages will be moved aside, not deleted.")
if not a.go:
print("\nDRY RUN: nothing was requested. Add --go to run it.")
return 0
# ---- gates -------------------------------------------------------------------------
if not st.acquire():
print("Another copy is already running. One request at a time: not starting.")
return 2
until = st.cooldown_until()
if until:
print("The Archive asked for less traffic earlier. Cool-down until %s. Not starting." % bb.iso(until))
st.log("refused", site_label, exts, "cool-down until %s" % bb.iso(until))
return 2
os.makedirs(pages_dir, exist_ok=True)
stamp = bb.now().strftime("%Y%m%d-%H%M%S")
if a.refresh and info:
os.replace(pages_dir, os.path.join(folder, "pages-" + stamp))
os.replace(info_file, os.path.join(folder, "discovery-%s.json" % stamp))
os.makedirs(pages_dir, exist_ok=True)
info, have, next_key = None, 0, ""
st.log("refresh", site_label, exts, "old pages moved to pages-" + stamp)
seen = set(info.get("keys_seen", [])) if info else set()
rows_total = info.get("rows", 0) if info else 0
started = info.get("started") if info else bb.iso(bb.now())
def write_info(complete, **extra):
d = {"site": site_label, "extensions": exts, "started": started, "pages": have,
"rows": rows_total, "complete": complete, "next_key": next_key,
"keys_seen": sorted(seen), "zero_results": extra.pop("zero", False)}
if complete:
d["finished"] = bb.iso(bb.now())
d.update(extra)
save_atomic(info_file, json.dumps(d, indent=2))
st.log("start", site_label, exts, "resuming after page %d" % have if have else "new discovery")
opener = urllib.request.build_opener(bb.NoRedirect)
requests = 0
while requests < a.max_pages:
if have >= HARD_MAX_PAGES:
print("Reached the hard limit of %d pages. Stopping this site." % HARD_MAX_PAGES)
st.log("site-stop", site_label, exts, "hard page limit")
return 3
url = build_url(a.base_url, host, path, exts, next_key)
def fetch():
req = urllib.request.Request(url, headers={"User-Agent": bb.DEFAULT_UA})
with opener.open(req, timeout=a.timeout) as r:
if r.status != 200:
raise urllib.error.HTTPError(url, r.status, "unexpected status", r.headers, None)
return r.read().decode("utf-8", "replace")
out = bb.polite_call(st, fetch, a.pause, retry_wait=a.retry_wait)
requests += 1
if out.kind == "pressure":
c = out.cooldown
print("STOP: the Archive replied %s. Whole run stopped. Cool-down %d s (until %s); "
"next runs will be x%d slower." % (out.code, c["cooldown_seconds"], c["cooldown_until"], c["multiplier"]))
st.log("pressure", site_label, exts, "%s; cool-down until %s; multiplier x%d" % (out.detail, c["cooldown_until"], c["multiplier"]))
write_info(False)
return 1
if out.kind == "network":
print("STOP: no answer after one retry (%s). Whole run stopped; no cool-down saved." % out.detail)
st.log("network", site_label, exts, out.detail)
write_info(False)
return 1
if out.kind == "site":
print("STOP THIS SITE: %s. Not retrying." % out.detail)
st.log("site-stop", site_label, exts, out.detail)
write_info(False)
return 3
try:
rows, key = parse_page(out.value)
except ValueError as e:
print("STOP THIS SITE: the reply was not a CDX page (%s). Not saved." % e)
st.log("site-stop", site_label, exts, "bad reply: %s" % e)
write_info(False)
return 3
if not rows and have == 0 and not key:
print("No results: the index has no captures of %s files for %s." % (exts, site_label))
st.log("zero", site_label, exts, "no captures found")
write_info(True, zero=True)
return 0
have += 1
rows_total += len(rows)
save_atomic(os.path.join(pages_dir, "page-%04d.json" % have), out.value)
print("page %d saved: %d rows%s" % (have, len(rows), "" if not key else ", more to come"))
st.log("page", site_label, exts, "page %d, %d rows" % (have, len(rows)))
if key:
if key in seen:
print("STOP THIS SITE: the Archive repeated a resume key (loop guard).")
st.log("site-stop", site_label, exts, "resume key repeated")
next_key = key
write_info(False)
return 3
seen.add(key)
next_key = key
if not key:
write_info(True)
print("Discovery complete: %d page(s), %d row(s)." % (have, rows_total))
st.log("complete", site_label, exts, "%d pages, %d rows" % (have, rows_total))
return 0
write_info(False)
print("Page cap for this run reached (%d). %d page(s) saved so far; run again to continue." % (a.max_pages, have))
st.log("cap", site_label, exts, "run page cap; %d pages saved" % have)
return 0
if __name__ == "__main__":
sys.exit(main())
Corrections to earlier entries: M002-S01 (bash) is superseded for new work. It is kept as evidence of what was run.
Date: 2026 – 11-30
Why a simulation: The rules about 429, 503 and timeouts should be proven before the tool meets the real Archive. The server ran on 127.0.0.1 and could be switched to return paged data, 429 with Retry-After, 503, a timeout, a 302, bad JSON, [], a blank reply, or a repeating resume key. For speed, the test runner set the 5 s minimum pause to 0. The delivered code keeps 5 s.
| Check | Result |
|---|---|
| Dry run | 0 requests |
--max-pages 2, then resume |
page cap stops it; resume completes (3 pages, 9 rows) |
| Run again when complete | skipped, with a reason |
--refresh |
old pages and discovery.json moved aside, new pages saved |
[] reply, blank reply |
recorded as no results, exit 0 |
| Bad JSON, 302 | stops that site only, nothing saved, exit 3 |
| Repeated resume key | loop guard stops that site |
| 429 with Retry-After 120 | whole run stops, 120 s cool-down, multiplier x2 |
| Next run during cool-down | refused, 0 requests made, exit 2 |
| 503 within 24 h | cool-down 7200 s (1 h doubled), multiplier x4 |
| 50th clean request | multiplier steps down x4 to x2 |
| Timeout | one retry, then whole run stops, no cool-down (5 requests counted at the server over the timeout tests) |
| Lock held by a live process | refused, exit 2 |
| Lock held by a dead process | cleared, run proceeds |
| Gap across runs (2 s) | waited 2.0 s |
| Invalid site or file type | rejected with an explanation |
Limits: A simulation shows the code follows the rules. It does not show how the real Archive behaves under load. The first real run should be small (--max-pages 1).
Corrections to earlier entries: none.
Date: 2026 – 11-30
What was run: A dry run first (no requests), then one real request:
python3 discover.py --site archive.info-mac.org --extensions hqx,sit
python3 discover.py --site archive.info-mac.org --extensions hqx,sit --go --max-pages 1
What happened:
activity-log.txt recorded START, PAGE and CAP, and the request took about 2 s (it was the first one, so there was no gap to wait for).pace.json after the run: multiplier 1, clean streak 1, no cool-down, no pressure events.Comparison with the old script: The old M002 page 1 and the new page 1 were each reduced to timestamp, original URL and digest, one line per capture, and sorted. Both had 5,000 lines and diff printed nothing:
jq -r '.[0] as $h | .[1:][] | select(type=="array" and length==($h|length)) | [.[$h|index("timestamp")], .[$h|index("original")], .[$h|index("digest")]] | @tsv' <page-file> | sort
Limits: Only three fields were compared (timestamp, original, digest), and only page 1. One request does not show how the Archive reacts to a longer run. The paging, resume and pressure rules have so far been proven on the simulated server only (M004-T01).
Corrections to earlier entries: none.
Date: 2026 – 11-30
Why: In M004-T01 the resume key was tested only on a simulated server with short keys. The Archive’s real key is an opaque string of about 106 characters, so it had to be shown that the tool sends it back correctly.
What was run: The SHA-256 of page 1 was recorded, then one more request was made, then the SHA-256 was checked again:
sha256sum sites/archive-info-mac-org/hqx-sit/pages/page-0001.json
python3 discover.py --site archive.info-mac.org --extensions hqx,sit --go --max-pages 1
sha256sum sites/archive-info-mac-org/hqx-sit/pages/page-0001.json
What happened:
page-0001.json was the same before and after (03a3931d0dd094732c2eecaac1b8162dc8990ca68c50203bce54ca44abed8f62).page-0001.json and page-0002.json.jq -r '.[1:][] | select(length==7) | .[1]+" "+.[2]' <page-file> | sort
comm -12 /tmp/p1.txt /tmp/p2.txt | wc -l
Limits: Two pages are now saved. In M002 this site ran to 10 pages (45,089 captures), and the remaining pages have not been requested by this tool. Resuming after a stop in the middle of a run (rather than at a page cap) was proven only on the simulated server.
Corrections to earlier entries: none.
Date: 2026 – 11-30
What it is: A frozen copy of parts/catalogue.py, version 1. It replaces build_catalogue.py (M003-S01) for new work. It makes no requests.
What changed from M003-S01:
pages-<timestamp>/ folders (set aside by --refresh) and then pages/.zero_results) is recorded with 0 captures.downloads table is never touched.SHA-256: 8fcb4efcd63f80b3402b2f876f40e8f131f5d223fcf8c91ed7f2629439cba5aa
Source:
#!/usr/bin/env python3
"""
catalogue.py - add the saved discovery pages of one site to the BuriedBits catalogue (SQLite).
No requests are made to any server. Safe to re-run.
* A re-import ADDS captures that are new and keeps every existing record. Nothing is
deleted or replaced. (The Archive's index only grows, so old records stay true.)
* Pages are read from <site folder>/pages-<timestamp>/ (older rounds, set aside by
--refresh) and then <site folder>/pages/ (the latest round).
* A site whose discovery found nothing (zero_results) is recorded with 0 captures.
* The `downloads` table is never touched.
Standalone use:
python3 catalogue.py --host archive.info-mac.org --extensions hqx,sit \
--folder ~/buriedbits/sites/archive-info-mac-org/hqx-sit
python3 catalogue.py --host archive.info-mac.org --extensions sit,hqx --pages ~/old/page-folder
"""
import argparse
import datetime
import glob
import json
import os
import re
import sqlite3
import sys
from urllib.parse import urlsplit
EMPTY_DIGEST = "3I42H3S6NNFQ2MSVX7XZKYAYSCX5QBYJ" # base32 SHA-1 of empty content
REQUIRED = ["timestamp", "original", "mimetype", "statuscode", "digest", "length"]
DEFAULT_DB = "~/buriedbits/cdx/catalogue.sqlite"
class CatalogueError(Exception):
pass
SCHEMA = """
CREATE TABLE IF NOT EXISTS sources (
id INTEGER PRIMARY KEY,
host TEXT NOT NULL,
extensions TEXT NOT NULL,
pages INTEGER,
rows INTEGER,
complete INTEGER,
imported_at TEXT,
UNIQUE (host, extensions)
);
CREATE TABLE IF NOT EXISTS captures (
id INTEGER PRIMARY KEY,
source_id INTEGER NOT NULL REFERENCES sources(id),
timestamp TEXT NOT NULL,
original TEXT NOT NULL,
url_host TEXT,
path TEXT,
ext TEXT,
mimetype TEXT,
statuscode TEXT,
digest TEXT,
length INTEGER,
class TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS captures_digest ON captures(digest);
CREATE INDEX IF NOT EXISTS captures_class ON captures(class);
CREATE INDEX IF NOT EXISTS captures_source ON captures(source_id);
CREATE TABLE IF NOT EXISTS downloads (
digest TEXT PRIMARY KEY,
status TEXT NOT NULL DEFAULT 'not_downloaded',
local_path TEXT,
sha256 TEXT,
bytes INTEGER,
downloaded_at TEXT,
note TEXT
);
"""
VIEWS = """
DROP VIEW IF EXISTS download_queue;
DROP VIEW IF EXISTS files;
CREATE VIEW files AS
WITH ranked AS (
SELECT digest, original, timestamp, class, length,
ROW_NUMBER() OVER (
PARTITION BY digest
ORDER BY CASE class WHEN 'ok' THEN 0 WHEN 'unknown_status' THEN 1
WHEN 'revisit' THEN 2 ELSE 3 END,
timestamp, LENGTH(original), original
) AS rn
FROM captures
), best AS (SELECT * FROM ranked WHERE rn = 1)
SELECT c.digest AS digest,
COUNT(DISTINCT c.original) AS n_urls,
COUNT(*) AS n_captures,
MAX(c.class = 'ok') AS has_ok,
MAX(c.class = 'unknown_status') AS has_unknown_status,
MAX(c.class = 'revisit') AS has_revisit,
CASE WHEN c.digest = '__EMPTY__' THEN 'empty'
WHEN MAX(c.class IN ('ok', 'unknown_status')) = 1 THEN 'candidate'
WHEN MAX(c.class = 'revisit') = 1 THEN 'revisit_only'
ELSE 'not_a_file' END AS verdict,
b.original AS best_url,
b.timestamp AS best_timestamp,
b.class AS best_class,
b.length AS best_record_length
FROM captures c JOIN best b ON b.digest = c.digest
GROUP BY c.digest;
CREATE VIEW download_queue AS
SELECT f.*, COALESCE(d.status, 'not_downloaded') AS download_status
FROM files f LEFT JOIN downloads d ON d.digest = f.digest
WHERE f.verdict = 'candidate';
""".replace("__EMPTY__", EMPTY_DIGEST)
def classify(mimetype, status):
if mimetype == "warc/revisit":
return "revisit"
if status.startswith("3"):
return "redirect"
if status.startswith(("4", "5")):
return "error"
if status == "200":
return "ok"
return "unknown_status" # for example status "-" with mimetype "unk"
def ext_of(url):
name = urlsplit(url).path.rsplit("/", 1)[-1]
return name.rsplit(".", 1)[1].lower() if "." in name else ""
def norm_host(h):
h = h.strip().lower()
h = re.sub(r"^https?://", "", h)
return re.sub(r"(/\*|/)+$", "", h)
def norm_exts(s):
parts = [p.strip().lstrip(".").lower() for p in re.split(r"[,\s]+", s)]
return ",".join(sorted({p for p in parts if p}))
def read_page_set(pages_dir):
"""Read page-0001.json, page-0002.json, ... of one folder. Returns (rows, n_pages, last_page_has_key)."""
paths = sorted(glob.glob(os.path.join(pages_dir, "page-*.json")))
if not paths:
return [], 0, False
numbers = [int(re.search(r"page-(\d+)\.json$", p).group(1)) for p in paths]
if numbers != list(range(1, len(paths) + 1)):
raise CatalogueError("%s: the page files are not consecutive (page-0001...): a page is missing." % pages_dir)
header0 = None
rows = []
more = False
for p in paths:
with open(p, encoding="utf-8") as fh:
try:
data = json.load(fh)
except ValueError:
raise CatalogueError("%s: not valid JSON" % p)
if not data or not isinstance(data[0], list):
raise CatalogueError("%s: not a CDX JSON page" % p)
header = data[0]
missing = [f for f in REQUIRED if f not in header]
if missing:
raise CatalogueError("%s: header lacks fields %s" % (p, missing))
if header0 is None:
header0 = header
elif header != header0:
raise CatalogueError("%s: header differs from the first page" % p)
ix = {name: i for i, name in enumerate(header)}
for row in data[1:]:
if not (isinstance(row, list) and len(row) == len(header)):
continue # the trailing [] and [resume key] arrays
original = row[ix["original"]]
status = row[ix["statuscode"]]
mimetype = row[ix["mimetype"]]
try:
length = int(row[ix["length"]])
except (TypeError, ValueError):
length = None
sp = urlsplit(original)
rows.append((row[ix["timestamp"]], original, sp.hostname or "", sp.path,
ext_of(original), mimetype, status, row[ix["digest"]],
length, classify(mimetype, status)))
if p == paths[-1]:
more = len(data) >= 3 and data[-2] == [] and len(data[-1]) == 1
return rows, len(paths), more
def read_site_folder(folder):
"""All saved rounds of one site/type folder, oldest first.
Returns (rows, n_pages, complete, zero_results)."""
folder = os.path.expanduser(folder)
if not os.path.isdir(folder):
raise CatalogueError("Folder not found: %s" % folder)
info = {}
info_file = os.path.join(folder, "discovery.json")
if os.path.exists(info_file):
try:
with open(info_file, encoding="utf-8") as fh:
info = json.load(fh)
except (OSError, ValueError):
raise CatalogueError("%s is unreadable." % info_file)
sets = sorted(glob.glob(os.path.join(folder, "pages-*"))) + [os.path.join(folder, "pages")]
rows, pages, last_more = [], 0, False
for s in sets:
if os.path.isdir(s):
r, n, more = read_page_set(s)
rows += r
pages += n
last_more = more
zero = bool(info.get("zero_results"))
if info:
complete = bool(info.get("complete"))
else:
complete = pages > 0 and not last_more
if pages == 0 and not zero:
raise CatalogueError("No saved pages in %s. Run discovery first." % folder)
return rows, pages, complete, zero
def add_to_catalogue(db_path, host, exts, rows, pages, complete):
"""Add rows that are not already known. Returns (source_id, added, already_known)."""
host, exts = norm_host(host), norm_exts(exts)
db_path = os.path.expanduser(db_path)
os.makedirs(os.path.dirname(db_path), exist_ok=True)
con = sqlite3.connect(db_path)
try:
con.executescript(SCHEMA)
with con:
found = con.execute("SELECT id FROM sources WHERE host=? AND extensions=?", (host, exts)).fetchone()
sid = found[0] if found else con.execute(
"INSERT INTO sources(host, extensions) VALUES (?, ?)", (host, exts)).lastrowid
known = set(con.execute("SELECT timestamp, original, digest FROM captures WHERE source_id=?", (sid,)))
new, distinct = [], set()
for r in rows:
distinct.add((r[0], r[1], r[7]))
key = (r[0], r[1], r[7])
if key not in known:
known.add(key)
new.append(r)
con.executemany(
"INSERT INTO captures(source_id, timestamp, original, url_host, path, ext, mimetype, "
"statuscode, digest, length, class) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
[(sid,) + r for r in new])
total = con.execute("SELECT COUNT(*) FROM captures WHERE source_id=?", (sid,)).fetchone()[0]
con.execute("UPDATE sources SET pages=?, rows=?, complete=?, imported_at=? WHERE id=?",
(pages, total, 1 if complete else 0,
datetime.datetime.now().astimezone().isoformat(timespec="seconds"), sid))
con.executescript(VIEWS)
finally:
con.close()
return sid, len(new), len(distinct) - len(new)
def summary(db_path, host, exts):
"""Return a dict of plain numbers about one site, from the catalogue."""
con = sqlite3.connect(os.path.expanduser(db_path))
try:
sid = con.execute("SELECT id, pages, complete FROM sources WHERE host=? AND extensions=?",
(norm_host(host), norm_exts(exts))).fetchone()
if not sid:
return None
sid, pages, complete = sid
q = lambda sql, *a: con.execute(sql, a).fetchall()
scope = "digest IN (SELECT digest FROM captures WHERE source_id=%d)" % sid
d = {"pages": pages, "complete": bool(complete),
"captures": q("SELECT COUNT(*) FROM captures WHERE source_id=?", sid)[0][0],
"by_class": dict(q("SELECT class, COUNT(*) FROM captures WHERE source_id=? GROUP BY class", sid)),
"verdicts": dict(q("SELECT verdict, COUNT(*) FROM files WHERE %s GROUP BY verdict" % scope)),
"by_ext": q("SELECT ext, COUNT(*) FROM captures WHERE source_id=? GROUP BY ext ORDER BY 2 DESC LIMIT 10", sid)}
cand, urls, recl = q("SELECT COUNT(*), COALESCE(SUM(n_urls),0), COALESCE(SUM(best_record_length),0) "
"FROM files WHERE verdict='candidate' AND %s" % scope)[0]
d.update(candidates=cand, addresses=urls, record_bytes=recl)
d["already_verified"] = q("SELECT COUNT(*) FROM download_queue WHERE download_status='verified' AND %s" % scope)[0][0]
return d
finally:
con.close()
def print_summary(host, exts, s, added=None, known=None):
print("\n=== %s (file types: %s) ===" % (host, exts))
if s is None or s["captures"] == 0:
print("No captures: the Archive's index has no files of these types for this site.")
return
print("pages: %d captures: %d discovery complete: %s" % (s["pages"], s["captures"], "yes" if s["complete"] else "NO (run again to continue)"))
if added is not None:
print("this import: %d new capture(s) added, %d already known" % (added, known))
print("\ncaptures by class:")
for cls, c in sorted(s["by_class"].items(), key=lambda kv: -kv[1]):
print(" %7d %s" % (c, cls))
print("\ndistinct files (by digest) and what they are:")
for v, c in sorted(s["verdicts"].items(), key=lambda kv: -kv[1]):
print(" %7d %s" % (c, v))
print(" %7d total distinct digests" % sum(s["verdicts"].values()))
print("\ndownload candidates: %d files, listed under %d addresses" % (s["candidates"], s["addresses"]))
print(" already downloaded and verified: %d" % s["already_verified"])
print(" recorded length of the chosen captures: about %.1f MB" % (s["record_bytes"] / 1e6))
print(" (approximate: the recorded length is the stored record size, not the file size)")
if s["verdicts"].get("revisit_only"):
print(" %d file(s) are pointer only, not recovered (see M003-T04)" % s["verdicts"]["revisit_only"])
def main():
ap = argparse.ArgumentParser(description="Add saved discovery pages to the BuriedBits catalogue (no requests).")
ap.add_argument("--host", required=True)
ap.add_argument("--extensions", required=True)
g = ap.add_mutually_exclusive_group(required=True)
g.add_argument("--folder", help="site/type folder made by discover.py")
g.add_argument("--pages", help="a single folder holding page-0001.json, ... (older layout)")
ap.add_argument("--db", default=DEFAULT_DB)
a = ap.parse_args()
try:
if a.folder:
rows, pages, complete, zero = read_site_folder(a.folder)
else:
rows, pages, more = read_page_set(os.path.expanduser(a.pages))
if pages == 0:
raise CatalogueError("No page-*.json files found in %s" % a.pages)
complete, zero = not more, False
if not complete:
print("WARNING: discovery is not finished for this site. Importing what is saved; "
"run discovery again and re-import to add the rest.")
sid, added, known = add_to_catalogue(a.db, a.host, a.extensions, rows, pages, complete)
except CatalogueError as e:
print("Cannot import: %s" % e)
return 1
print_summary(norm_host(a.host), norm_exts(a.extensions), summary(a.db, a.host, a.extensions), added, known)
print("\nCatalogue: %s" % os.path.expanduser(a.db))
return 0
if __name__ == "__main__":
sys.exit(main())
Corrections to earlier entries: none.
Date: 2026 – 11-30
What it is: A frozen copy of buriedbits.py, version 1, plus README.md. It asks for a site (or a .txt file with one site per line), then file types; shows a plan; waits for “yes”; runs parts/discover.py for each site that needs it, one after another; adds the saved pages to the catalogue; and prints a session report. --status shows what is known without making any requests. It makes no requests itself and downloads nothing.
How the stop rules show up here:
Not done yet: the downloader still uses the old cdx/ folder and download_batch.py (M003-S02). The cdx/ folder is not moved yet, because the catalogue stores full file paths for the 140 verified files. The move comes with stage 4, together with a path repair.
SHA-256: d6d6f1410286ff9216fc81ab80a7e5b0de09a8a6d711316bfb24b6cec405c2f7
Source:
#!/usr/bin/env python3
"""
buriedbits.py - the one command you run.
python3 buriedbits.py ask for a site (or a .txt list), file types, then discover and catalogue
python3 buriedbits.py --status show what is known and whether a cool-down is running (no requests)
It asks, shows the plan, and waits for a clear "yes" before the Archive is contacted. Discovery
saves the Archive's lists untouched; the catalogue groups them into distinct files. Nothing is
downloaded by this command (stage 4 does that, later).
The pieces it uses live in the parts/ folder next to this file. You never run those directly.
"""
import argparse
import glob
import json
import os
import sqlite3
import subprocess
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
PARTS = os.path.join(HERE, "parts")
sys.path.insert(0, PARTS)
import bb_common as bb # noqa: E402
import catalogue as cat # noqa: E402
from discover import slug # noqa: E402
def ask(prompt):
try:
return input(prompt).strip()
except (EOFError, KeyboardInterrupt):
print("\nNo answer given. Nothing was requested. Stopping.")
sys.exit(0)
def read_site_list(path, st):
"""One site per line. Blank lines and lines starting with # are ignored. Lines that are not a
usable site are skipped with a warning and recorded in the activity log."""
sites, seen = [], set()
with open(path, encoding="utf-8", errors="replace") as fh:
for n, line in enumerate(fh, 1):
text = line.strip()
if not text or text.startswith("#"):
continue
try:
host, p = bb.parse_site(text)
except ValueError as e:
print(" line %d skipped: %s" % (n, e))
st.log("skipped", "-", "-", "%s line %d: %s" % (os.path.basename(path), n, e))
continue
if (host, p) in seen:
print(" line %d skipped: %s is already in the list" % (n, host + p))
continue
seen.add((host, p))
sites.append((host, p))
return sites
def ask_sites(st):
while True:
text = ask("Site address, or the path to a .txt file with one site per line: ")
if not text:
continue
if text.lower().endswith(".txt"):
path = os.path.expanduser(text)
if not os.path.isfile(path):
print(" I can't find that file. Check the path and try again.")
continue
print("Reading %s" % path)
sites = read_site_list(path, st)
if not sites:
print(" No usable sites in that file.")
continue
return sites
try:
return [bb.parse_site(text)]
except ValueError as e:
print(" Can't use that: %s" % e)
def ask_extensions():
for _ in range(5):
text = ask("File types to look for, comma-separated (for example: hqx, sit, sea): ")
try:
return bb.parse_extensions(text)
except ValueError as e:
print(" Can't use that: %s" % e)
print("Too many tries. Nothing was requested. Stopping.")
sys.exit(0)
def site_folder(a, host, path, exts):
return os.path.join(os.path.expanduser(a.sites_dir), slug(host + path), slug(exts))
def read_info(folder):
try:
with open(os.path.join(folder, "discovery.json"), encoding="utf-8") as fh:
return json.load(fh)
except (OSError, ValueError):
return None
def plan_line(a, host, path, exts):
info = read_info(site_folder(a, host, path, exts))
if info is None:
return "new", "new: will be discovered"
if info.get("complete") and a.refresh:
return "refresh", "discovered before (%s): will be asked again; old pages are set aside, not deleted" % info.get("finished", "?")
if info.get("complete"):
return "done", ("already discovered on %s (%d pages): not asked again. Use --refresh to ask again."
% (info.get("finished", "?"), info.get("pages", 0)))
return "resume", "partly discovered (%d pages saved): will continue" % info.get("pages", 0)
def status(a, st):
print("BuriedBits status (no requests are made)\n")
until = st.cooldown_until()
print("Cool-down: %s" % ("running until %s" % bb.iso(until) if until else "none"))
print("Pause: %d s between requests (you chose %d s, slow-down x%d)"
% (st.effective_pause(a.pause), a.pause, st.multiplier()))
print("\nDiscovered sites (%s):" % os.path.expanduser(a.sites_dir))
found = sorted(glob.glob(os.path.join(os.path.expanduser(a.sites_dir), "*", "*", "discovery.json")))
if not found:
print(" none yet")
for f in found:
try:
with open(f, encoding="utf-8") as fh:
i = json.load(fh)
except (OSError, ValueError):
print(" %s: unreadable" % f)
continue
state = ("no captures" if i.get("zero_results") else "complete" if i.get("complete") else "NOT finished")
print(" %-40s %-12s %3d pages %s" % (i.get("site", "?"), i.get("extensions", "?"), i.get("pages", 0), state))
db = os.path.expanduser(a.db)
print("\nCatalogue (%s):" % db)
if not os.path.exists(db):
print(" none yet")
else:
con = sqlite3.connect(db)
try:
n = con.execute("SELECT COUNT(*) FROM captures").fetchone()[0]
c = con.execute("SELECT COUNT(*) FROM files WHERE verdict='candidate'").fetchone()[0]
v = con.execute("SELECT COUNT(*) FROM downloads WHERE status='verified'").fetchone()[0]
print(" %d captures, %d candidate files, %d downloaded and verified" % (n, c, v))
except sqlite3.Error:
print(" present, but not readable as a catalogue")
finally:
con.close()
print("\nLast activity (%s):" % st.log_file)
try:
with open(st.log_file, encoding="utf-8") as fh:
for line in fh.readlines()[-5:]:
print(" " + line.rstrip())
except OSError:
print(" none yet")
def run_discovery(a, host, path, exts, refresh):
cmd = [sys.executable, os.path.join(PARTS, "discover.py"), "--site", host + path, "--extensions", exts,
"--pause", str(a.pause), "--max-pages", str(a.max_pages), "--sites-dir", a.sites_dir,
"--state-dir", a.state_dir, "--go"]
if refresh:
cmd.append("--refresh")
if a.base_url:
cmd += ["--base-url", a.base_url]
if a.timeout is not None:
cmd += ["--timeout", str(a.timeout)]
if a.retry_wait is not None:
cmd += ["--retry-wait", str(a.retry_wait)]
return subprocess.run(cmd).returncode
def import_site(a, st, host, path, exts):
label = host + path
try:
rows, pages, complete, zero = cat.read_site_folder(site_folder(a, host, path, exts))
sid, added, known = cat.add_to_catalogue(a.db, label, exts, rows, pages, complete)
except cat.CatalogueError as e:
print("Catalogue: cannot import %s: %s" % (label, e))
st.log("warning", label, exts, "catalogue import failed: %s" % e)
return False
st.log("catalogue", label, exts, "%d new captures, %d already known" % (added, known))
cat.print_summary(label, exts, cat.summary(a.db, label, exts), added, known)
return True
def main():
ap = argparse.ArgumentParser(description="Discover and catalogue archived files for one or more sites.")
ap.add_argument("--status", action="store_true", help="show what is known; make no requests")
ap.add_argument("--refresh", action="store_true", help="ask again for sites already discovered (old pages are set aside)")
ap.add_argument("--pause", type=float, default=10, help="seconds between requests (minimum 5, default 10)")
ap.add_argument("--max-pages", type=int, default=5, help="pages per site in this session (1-50, default 5)")
ap.add_argument("--sites-dir", default=bb.DEFAULT_SITES_DIR)
ap.add_argument("--state-dir", default=bb.DEFAULT_STATE_DIR)
ap.add_argument("--db", default=cat.DEFAULT_DB)
ap.add_argument("--base-url", default=None, help=argparse.SUPPRESS)
ap.add_argument("--timeout", type=float, default=None, help=argparse.SUPPRESS)
ap.add_argument("--retry-wait", type=float, default=None, help=argparse.SUPPRESS)
a = ap.parse_args()
if a.pause < bb.MIN_PAUSE:
print("Pause raised to the minimum of %d seconds." % bb.MIN_PAUSE)
a.pause = bb.MIN_PAUSE
if not 1 <= a.max_pages <= 50:
print("--max-pages must be between 1 and 50.")
return 2
st = bb.State(a.state_dir)
if a.status:
status(a, st)
return 0
until = st.cooldown_until()
if until:
print("The Archive asked for less traffic earlier. Cool-down until %s." % bb.iso(until))
print("Nothing will be requested before then. (python3 buriedbits.py --status shows the details.)")
st.log("refused", "-", "-", "front-end: cool-down until %s" % bb.iso(until))
return 2
print("BuriedBits: find and catalogue archived files. Nothing is requested until you say yes.\n")
sites = ask_sites(st)
exts = ask_extensions()
todo = []
print("\nPlan: %d site(s), file types: %s" % (len(sites), exts))
for host, p in sites:
kind, text = plan_line(a, host, p, exts)
print(" %-36s %s" % (host + p, text))
todo.append((host, p, kind))
asks = sum(1 for _, _, k in todo if k != "done")
if asks:
print("\nPause between requests: %d s%s. One request at a time. Up to %d page request(s) per site, "
"up to %d in this session." % (st.effective_pause(a.pause),
" (slowed x%d after earlier pressure)" % st.multiplier() if st.multiplier() > 1 else "",
a.max_pages, asks * a.max_pages))
if asks == 0:
print("No site needs the Archive. Saved lists will only be added to the catalogue.")
elif ask("\nContact the Archive now? Type yes to go on: ").lower() not in ("yes", "y"):
print("Not confirmed. Nothing was requested.")
return 0
st.log("session", "-", exts, "%d site(s)" % len(sites))
results = []
stopped = None
for host, p, kind in todo:
label = host + p
print("\n--- %s ---" % label)
if kind == "done":
print("Already discovered; no request needed.")
ok = import_site(a, st, host, p, exts)
results.append((label, "already discovered" if ok else "catalogue problem"))
continue
rc = run_discovery(a, host, p, exts, kind == "refresh")
if rc == 0:
info = read_info(site_folder(a, host, p, exts)) or {}
import_site(a, st, host, p, exts)
results.append((label, "complete" if info.get("complete") else "NOT finished: run again to continue"))
elif rc == 3:
results.append((label, "stopped for this site; see the message above; no import"))
print("Going on to the next site.")
else:
stopped = "the whole run was stopped (%s)" % ("cool-down or another copy running" if rc == 2 else "Archive pressure or no answer")
results.append((label, "stopped"))
break
print("\n=== Session report ===")
for label, text in results:
print(" %-36s %s" % (label, text))
left = [h + p for h, p, _ in todo[len(results):]]
if left:
print(" not reached: %s" % ", ".join(left))
if stopped:
print("\nSTOPPED: %s. Nothing more was requested. Run `python3 buriedbits.py --status` before trying again." % stopped)
return 1
print("\nDone. Downloads are a separate step and have not been started.")
return 0
if __name__ == "__main__":
sys.exit(main())
README.md SHA-256: df827f8b8e87a9128858e42ee5c7cae9129d14aa55db556d85441b0dda83d27a
Corrections to earlier entries: none. parts/bb_common.py and parts/discover.py are unchanged copies of M004-S01 and M004-S02 (same SHA-256).
Date: 2026 – 11-30
Setup: The same simulated CDX server as M004-T01, extended so that sites whose name starts with bad. answer 302, p429. answer 429 with Retry-After, and none. answer []. The test runner set the 5 s minimum pause to 0. Answers were typed in through standard input.
| Check | Result |
|---|---|
| Answering “no” at the confirmation | 0 requests |
| One new site | 3 pages, 9 captures added to the catalogue |
| Same site again | “already discovered”, 0 requests, 0 new captures |
.txt list with a comment, a blank line, an invalid line and a repeated site |
the invalid line and the repeat were skipped with line numbers; the rest were planned |
Site with no captures ([]) |
recorded as “no captures”, the run went on |
| Site answering 302 | stopped for that site only, nothing imported, the next site went ahead |
--refresh |
old pages and discovery.json set aside; 0 duplicate captures in the catalogue |
| Site answering 429 in the middle of a list | whole session stopped, the later site was “not reached”, cool-down saved |
| Next run during the cool-down | refused before any question was asked |
--status |
listed sites with their state, catalogue counts, cool-down and the last log lines |
| Requests counted at the server | 12, exactly those expected; declining and skipping made none |
Also checked: an invalid site, a missing .txt file, and invalid or empty file types were each refused with an explanation and asked again; end of input stopped the program with no requests.
Limits: As in M004-T01, this shows that the code follows the rules, not how the real Archive behaves. The first real run of buriedbits.py should be one small site.
Corrections to earlier entries: none.
Date: 2026 – 12-01
What happened: The first run of buriedbits.py on the real machine was made with a deliberately misspelled address (archive.info-mac.orr). Nothing was requested from the Archive in that run. Two problems showed up.
bb_common.py and discover.py had not yet been moved into parts/. The front-end still started, because Python found the copies next to it, and then failed when it tried to start parts/discover.py. Python’s own “cannot open file” error has the exit code 2, which the front-end read as “cool-down or another copy running”. The message was wrong.parts/bb_common.py, parts/discover.py and parts/catalogue.py exist. If not, it says which are missing and gives the exact mv command when they are next to buriedbits.py. It does this before anything else..orr) is not one the tool recognises, with the closest match (.org). The list is not the official one (it could not be downloaded here); it holds the older generic endings, two-letter country endings including some that no longer exist, and a few newer ones. The warning never blocks anything, because old sites can have endings that no longer exist."<site>" was not found, asks to check the spelling, and offers to try a corrected address straight away. A corrected address is shown in a plan again and needs a new “yes”. A site that was not found is asked again on a later run (one request), instead of being skipped as “already discovered”.SHA-256: e34367d0d256fa43bda241e0c19910ef3ff083698d73e738e984700a9a27e0b7
Source:
#!/usr/bin/env python3
"""
buriedbits.py - the one command you run.
python3 buriedbits.py ask for a site (or a .txt list), file types, then discover and catalogue
python3 buriedbits.py --status show what is known and whether a cool-down is running (no requests)
It asks, shows the plan, and waits for a clear "yes" before the Archive is contacted. Discovery
saves the Archive's lists untouched; the catalogue groups them into distinct files. Nothing is
downloaded by this command (stage 4 does that, later).
The pieces it uses live in the parts/ folder next to this file. You never run those directly.
"""
import argparse
import difflib
import glob
import json
import os
import sqlite3
import subprocess
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
PARTS = os.path.join(HERE, "parts")
sys.path.insert(0, PARTS)
NEEDED_PARTS = ["bb_common.py", "discover.py", "catalogue.py"]
def check_parts():
"""Stop early, in plain words, if a piece is not where it should be."""
missing = [n for n in NEEDED_PARTS if not os.path.isfile(os.path.join(PARTS, n))]
if not missing:
return True
print("The parts folder is incomplete. Missing in %s: %s" % (PARTS, ", ".join(missing)))
stray = [n for n in missing if os.path.isfile(os.path.join(HERE, n))]
if stray:
print("These are next to buriedbits.py instead: %s" % ", ".join(stray))
print("Move them with: cd %s && mkdir -p parts && mv %s parts/" % (HERE, " ".join(stray)))
print("Nothing was requested.")
return False
if not check_parts():
sys.exit(2)
import bb_common as bb # noqa: E402
import catalogue as cat # noqa: E402
from discover import slug # noqa: E402
# Endings (top-level domains) we recognise. This is NOT the full official list: it is the old
# generic endings, the two-letter country endings (including some that no longer exist, because
# the Archive holds old sites), and a few newer ones. It is only used to warn about typos.
KNOWN_TLDS = set("""
com org net edu gov mil int info biz name pro mobi aero coop museum asia tel travel jobs cat xxx post arpa
app dev blog online site store tech shop club xyz top
ac ad ae af ag ai al am ao aq ar as at au aw ax az ba bb bd be bf bg bh bi bj bm bn bo br bs bt bw by bz
ca cc cd cf cg ch ci ck cl cm cn co cr cu cv cw cx cy cz de dj dk dm do dz ec ee eg er es et eu fi fj fk
fm fo fr ga gd ge gf gg gh gi gl gm gn gp gq gr gs gt gu gw gy hk hm hn hr ht hu id ie il im in io iq ir is
it je jm jo jp ke kg kh ki km kn kp kr kw ky kz la lb lc li lk lr ls lt lu lv ly ma mc md me mg mh mk ml
mm mn mo mp mq mr ms mt mu mv mw mx my mz na nc ne nf ng ni nl no np nr nu nz om pa pe pf pg ph pk pl pm
pn pr ps pt pw py qa re ro rs ru rw sa sb sc sd se sg sh si sk sl sm sn so sr ss st su sv sx sy sz tc td
tf tg th tj tk tl tm tn to tr tt tv tw tz ua ug uk us uy uz va vc ve vg vi vn vu wf ws ye yt za zm zw
yu dd zr tp an cs bu
""".split())
def spelling_warning(host):
"""A warning if the ending of the address is not one we recognise, otherwise None."""
tld = host.rsplit(".", 1)[-1]
if tld in KNOWN_TLDS or tld.startswith("xn--"):
return None
guess = difflib.get_close_matches(tld, sorted(KNOWN_TLDS), n=1, cutoff=0.6)
return "check the spelling: I don't recognise the ending '.%s'%s" % (
tld, " (did you mean '.%s'?)" % guess[0] if guess else "")
def ask(prompt, default=None):
"""Ask a question. With a default, running out of input returns it; without one it stops the program."""
try:
return input(prompt).strip()
except (EOFError, KeyboardInterrupt):
if default is not None:
print()
return default
print("\nNo answer given. Nothing was requested. Stopping.")
sys.exit(0)
def read_site_list(path, st):
"""One site per line. Blank lines and lines starting with # are ignored. Lines that are not a
usable site are skipped with a warning and recorded in the activity log."""
sites, seen = [], set()
with open(path, encoding="utf-8", errors="replace") as fh:
for n, line in enumerate(fh, 1):
text = line.strip()
if not text or text.startswith("#"):
continue
try:
host, p = bb.parse_site(text)
except ValueError as e:
print(" line %d skipped: %s" % (n, e))
st.log("skipped", "-", "-", "%s line %d: %s" % (os.path.basename(path), n, e))
continue
if (host, p) in seen:
print(" line %d skipped: %s is already in the list" % (n, host + p))
continue
seen.add((host, p))
sites.append((host, p))
return sites
def ask_sites(st):
while True:
text = ask("Site address, or the path to a .txt file with one site per line: ")
if not text:
continue
if text.lower().endswith(".txt"):
path = os.path.expanduser(text)
if not os.path.isfile(path):
print(" I can't find that file. Check the path and try again.")
continue
print("Reading %s" % path)
sites = read_site_list(path, st)
if not sites:
print(" No usable sites in that file.")
continue
return sites
try:
return [bb.parse_site(text)]
except ValueError as e:
print(" Can't use that: %s" % e)
def ask_extensions():
for _ in range(5):
text = ask("File types to look for, comma-separated (for example: hqx, sit, sea): ")
try:
return bb.parse_extensions(text)
except ValueError as e:
print(" Can't use that: %s" % e)
print("Too many tries. Nothing was requested. Stopping.")
sys.exit(0)
def site_folder(a, host, path, exts):
return os.path.join(os.path.expanduser(a.sites_dir), slug(host + path), slug(exts))
def read_info(folder):
try:
with open(os.path.join(folder, "discovery.json"), encoding="utf-8") as fh:
return json.load(fh)
except (OSError, ValueError):
return None
def plan_line(a, host, path, exts):
info = read_info(site_folder(a, host, path, exts))
if info is None:
return "new", "new: will be discovered"
if info.get("complete") and a.refresh:
return "refresh", "discovered before (%s): will be asked again; old pages are set aside, not deleted" % info.get("finished", "?")
if info.get("complete") and info.get("zero_results"):
return "retry", ("asked on %s and nothing was found; will be asked again (one request)"
% info.get("finished", "?"))
if info.get("complete"):
return "done", ("already discovered on %s (%d pages): not asked again. Use --refresh to ask again."
% (info.get("finished", "?"), info.get("pages", 0)))
return "resume", "partly discovered (%d pages saved): will continue" % info.get("pages", 0)
def status(a, st):
print("BuriedBits status (no requests are made)\n")
until = st.cooldown_until()
print("Cool-down: %s" % ("running until %s" % bb.iso(until) if until else "none"))
print("Pause: %d s between requests (you chose %d s, slow-down x%d)"
% (st.effective_pause(a.pause), a.pause, st.multiplier()))
print("\nDiscovered sites (%s):" % os.path.expanduser(a.sites_dir))
found = sorted(glob.glob(os.path.join(os.path.expanduser(a.sites_dir), "*", "*", "discovery.json")))
if not found:
print(" none yet")
for f in found:
try:
with open(f, encoding="utf-8") as fh:
i = json.load(fh)
except (OSError, ValueError):
print(" %s: unreadable" % f)
continue
state = ("no captures" if i.get("zero_results") else "complete" if i.get("complete") else "NOT finished")
print(" %-40s %-12s %3d pages %s" % (i.get("site", "?"), i.get("extensions", "?"), i.get("pages", 0), state))
db = os.path.expanduser(a.db)
print("\nCatalogue (%s):" % db)
if not os.path.exists(db):
print(" none yet")
else:
con = sqlite3.connect(db)
try:
n = con.execute("SELECT COUNT(*) FROM captures").fetchone()[0]
c = con.execute("SELECT COUNT(*) FROM files WHERE verdict='candidate'").fetchone()[0]
v = con.execute("SELECT COUNT(*) FROM downloads WHERE status='verified'").fetchone()[0]
print(" %d captures, %d candidate files, %d downloaded and verified" % (n, c, v))
except sqlite3.Error:
print(" present, but not readable as a catalogue")
finally:
con.close()
print("\nLast activity (%s):" % st.log_file)
try:
with open(st.log_file, encoding="utf-8") as fh:
for line in fh.readlines()[-5:]:
print(" " + line.rstrip())
except OSError:
print(" none yet")
def run_discovery(a, host, path, exts, refresh):
cmd = [sys.executable, os.path.join(PARTS, "discover.py"), "--site", host + path, "--extensions", exts,
"--pause", str(a.pause), "--max-pages", str(a.max_pages), "--sites-dir", a.sites_dir,
"--state-dir", a.state_dir, "--go"]
if refresh:
cmd.append("--refresh")
if a.base_url:
cmd += ["--base-url", a.base_url]
if a.timeout is not None:
cmd += ["--timeout", str(a.timeout)]
if a.retry_wait is not None:
cmd += ["--retry-wait", str(a.retry_wait)]
return subprocess.run(cmd).returncode
def import_site(a, st, host, path, exts):
label = host + path
try:
rows, pages, complete, zero = cat.read_site_folder(site_folder(a, host, path, exts))
sid, added, known = cat.add_to_catalogue(a.db, label, exts, rows, pages, complete)
except cat.CatalogueError as e:
print("Catalogue: cannot import %s: %s" % (label, e))
st.log("warning", label, exts, "catalogue import failed: %s" % e)
return False
st.log("catalogue", label, exts, "%d new captures, %d already known" % (added, known))
cat.print_summary(label, exts, cat.summary(a.db, label, exts), added, known)
return True
def process_site(a, st, host, p, exts, kind):
"""Discover one site and add it to the catalogue. Returns (result text, stop reason or None, not_found)."""
label = host + p
print("\n--- %s ---" % label)
if kind == "done":
print("Already discovered; no request needed.")
ok = import_site(a, st, host, p, exts)
return ("already discovered" if ok else "catalogue problem"), None, False
rc = run_discovery(a, host, p, exts, kind in ("refresh", "retry"))
if rc == 0:
info = read_info(site_folder(a, host, p, exts)) or {}
import_site(a, st, host, p, exts)
if info.get("zero_results"):
print('\n"%s" was not found: the Archive has no files of these types for it.' % label)
print("Check the spelling and try again.")
return "NOT FOUND (check the spelling)", None, True
return ("complete" if info.get("complete") else "NOT finished: run again to continue"), None, False
if rc == 3:
print("Going on to the next site.")
return "stopped for this site; see the message above; no import", None, False
if rc == 1:
return "stopped", "discovery stopped the whole run (the Archive asked for less traffic, or did not answer)", False
if rc == 2:
return "stopped", "discovery refused to start or could not run (a cool-down, another copy running, or an error shown above)", False
return "stopped", "discovery ended with an unexpected error (code %s; see the message above)" % rc, False
def main():
ap = argparse.ArgumentParser(description="Discover and catalogue archived files for one or more sites.")
ap.add_argument("--status", action="store_true", help="show what is known; make no requests")
ap.add_argument("--refresh", action="store_true", help="ask again for sites already discovered (old pages are set aside)")
ap.add_argument("--pause", type=float, default=10, help="seconds between requests (minimum 5, default 10)")
ap.add_argument("--max-pages", type=int, default=5, help="pages per site in this session (1-50, default 5)")
ap.add_argument("--sites-dir", default=bb.DEFAULT_SITES_DIR)
ap.add_argument("--state-dir", default=bb.DEFAULT_STATE_DIR)
ap.add_argument("--db", default=cat.DEFAULT_DB)
ap.add_argument("--base-url", default=None, help=argparse.SUPPRESS)
ap.add_argument("--timeout", type=float, default=None, help=argparse.SUPPRESS)
ap.add_argument("--retry-wait", type=float, default=None, help=argparse.SUPPRESS)
a = ap.parse_args()
if a.pause < bb.MIN_PAUSE:
print("Pause raised to the minimum of %d seconds." % bb.MIN_PAUSE)
a.pause = bb.MIN_PAUSE
if not 1 <= a.max_pages <= 50:
print("--max-pages must be between 1 and 50.")
return 2
st = bb.State(a.state_dir)
if a.status:
status(a, st)
return 0
until = st.cooldown_until()
if until:
print("The Archive asked for less traffic earlier. Cool-down until %s." % bb.iso(until))
print("Nothing will be requested before then. (python3 buriedbits.py --status shows the details.)")
st.log("refused", "-", "-", "front-end: cool-down until %s" % bb.iso(until))
return 2
print("BuriedBits: find and catalogue archived files. Nothing is requested until you say yes.\n")
sites = ask_sites(st)
exts = ask_extensions()
todo = []
print("\nPlan: %d site(s), file types: %s" % (len(sites), exts))
for host, p in sites:
kind, text = plan_line(a, host, p, exts)
print(" %-36s %s" % (host + p, text))
warn = spelling_warning(host)
if warn:
print(" %-36s WARNING: %s" % ("", warn))
todo.append((host, p, kind))
asks = sum(1 for _, _, k in todo if k != "done")
if asks:
print("\nPause between requests: %d s%s. One request at a time. Up to %d page request(s) per site, "
"up to %d in this session." % (st.effective_pause(a.pause),
" (slowed x%d after earlier pressure)" % st.multiplier() if st.multiplier() > 1 else "",
a.max_pages, asks * a.max_pages))
if asks == 0:
print("No site needs the Archive. Saved lists will only be added to the catalogue.")
elif ask("\nContact the Archive now? Type yes to go on (anything else cancels): ").lower() not in ("yes", "y"):
print("Not confirmed. Nothing was requested.")
return 0
st.log("session", "-", exts, "%d site(s)" % len(sites))
results = []
stopped = None
not_found = []
for host, p, kind in todo:
text, stopped, nf = process_site(a, st, host, p, exts, kind)
results.append((host + p, text))
if nf:
not_found.append((host, p))
if stopped:
break
# A site that was not found: offer to try a corrected address straight away.
for host, p in not_found:
while not stopped:
label = host + p
fixed = ask("\nTry again for %s? Type the corrected address, or press Enter to leave it: " % label, default="")
if not fixed:
break
try:
nhost, npath = bb.parse_site(fixed)
except ValueError as e:
print(" Can't use that: %s" % e)
continue
kind, text = plan_line(a, nhost, npath, exts)
print(" %-36s %s" % (nhost + npath, text))
warn = spelling_warning(nhost)
if warn:
print(" %-36s WARNING: %s" % ("", warn))
if kind != "done" and ask("Contact the Archive now? Type yes to go on (anything else cancels): ", default="").lower() not in ("yes", "y"):
print("Not confirmed. Nothing was requested.")
continue
text, stopped, nf = process_site(a, st, nhost, npath, exts, kind)
results.append((nhost + npath, text))
if not nf:
break
host, p = nhost, npath
print("\n=== Session report ===")
for label, text in results:
print(" %-36s %s" % (label, text))
done_labels = [l for l, _ in results]
left = [h + p for h, p, _ in todo if (h + p) not in done_labels]
if left:
print(" not reached: %s" % ", ".join(left))
if stopped:
print("\nSTOPPED: %s.\nNothing more was requested. Run `python3 buriedbits.py --status` before trying again." % stopped)
return 1
print("\nDone. Downloads are a separate step and have not been started.")
return 0
if __name__ == "__main__":
sys.exit(main())
Corrections to earlier entries: M004-S04: the stop message for exit code 2 (“cool-down or another copy running”) could appear for any failure to start discovery, and the front-end did not check that its parts were in place. M004-S04 also recorded a site with no captures as “already discovered”; it is now asked again. parts/bb_common.py, parts/discover.py and parts/catalogue.py are unchanged (same SHA-256 as M004-S01, S02 and S03).
Date: 2026 – 12-01
What was run: python3 buriedbits.py --max-pages 1, answering archive.info-mac.org, file types hqx, sit, sitx, sea, and yes. These are the same types as in M002 (the tool sorts them to hqx,sea,sit,sitx).
What happened:
sites/archive-info-mac-org/hqx-sea-sit-sitx/.Findings:
sources table with this run’s own page count and completeness. The summary printed “pages: 1 … discovery complete: NO” next to 45,089 captures. The captures are intact; the note about them is misleading. An import must not downgrade what the catalogue already knows.To change: the plan checks the catalogue first and skips a site it already holds completely, with the reason; the importer keeps the larger page count and a “complete” flag that was already set.
Corrections to earlier entries: none.
Date: 2026 – 12-01
What was run: python3 buriedbits.py --max-pages 1, answering archive.info-mac.orr (a deliberate misspelling of .org), file type hqx, and yes.
What happened:
yes: one request. The tool printed “No results: the index has no captures of hqx files for archive.info-mac.orr.” and then:"archive.info-mac.orr" was not found: the Archive has no files of these types for it.
Check the spelling and try again.
Try again for archive.info-mac.orr? Type the corrected address, or press Enter to leave it:
Findings: The real Archive treats an unknown address like a site with no captures: it returns an empty result, not an error. The tool handles it. The reply is not saved, so this run does not record whether the body was blank or []; the tool treats both the same.
Limits: The tool cannot tell a misspelled address from a real site that has no captures of the chosen types; the message says so by asking the person to check the spelling. For a .txt list the tool should not ask for a corrected address for every site; it should list the sites not found at the end and point to the log. That is not built yet.
Corrections to earlier entries: none.
Date: 2026 – 12-01
What was run: python3 buriedbits.py --max-pages 1, answering archive.info-mac.org, file type dmg, and yes.
What happened:
Findings: This is the first time the real Archive ended a discovery for the new tool: the last page has no resume key, and the tool treats that as complete. The summary shows a different scope from M004-T05: it covers only the captures of this file-type run, not the whole catalogue.
Limits: dmg was not part of the earlier discovery for this site, so these 3 files are new. Nothing has been downloaded.
Corrections to earlier entries: none.